code
stringlengths
2
1.05M
'use strict'; require('babel/register'); import logger from './log'; import * as Async from 'async'; import parse from 'parse-link-header'; import * as GithubAPI from 'octonode'; import * as Database from './database'; import merge from 'lodash-node/modern/object/merge'; import pick from 'lodash-node/modern/object/pick'; const ORGS = require('../../app').organizations; const ACCESS_TOKEN = require('../../app').githubAccessToken; const PUBLIC_TYPE = 'public'; const STATE_OPEN = 'open'; var client = GithubAPI.client(ACCESS_TOKEN); client.requestDefaults['headers'] = { 'user-agent': 'Gander' }; function getAllRepos(org, withOptions, whenDone) { logger.info({ method: 'getAllRepos', args: arguments }); var attrsToPick = [ 'id', 'name', 'full_name', 'html_url', 'description', 'created_at', 'updated_at', 'pushed_at', 'stargazers_count', 'watchers_count', 'language', 'has_issues', 'forks_count', 'open_issues_count', 'watchers' ]; getAll('/orgs/' + org + '/repos', withOptions, attrsToPick, whenDone); } function getAllIssues(org, withOptions, whenDone) { logger.info({ method: 'getAllIssues', args: arguments }); var attrsToPick = [ 'title', 'created_at', 'updated_at', 'comments', 'repository', 'pull_request', 'description' ]; getAll('/orgs/' + org + '/issues', withOptions, attrsToPick, whenDone); } function getAll(url, withOptions, attrsToPick, whenDone) { logger.info({ method: 'getAll', args: arguments }); var results = []; var defaultOptions = { per_page: 100, page: 0 }; function pickedResults() { return results.map(function(result) { return pick(result, attrsToPick); }); } var options = merge(defaultOptions, withOptions); function get(done) { options.page += 1; logger.info({ method: 'getAll:get', page: options.page }); client.get(url, options, done); } function handler(err, statusCode, data, headers) { logger.info({ method: 'getAll:handler', args: arguments }); if (err) { return whenDone(err); } results = results.concat(data); if (!headers.link) { return whenDone(null, pickedResults()); } if (typeof parse(headers.link).last === 'undefined') { whenDone(null, pickedResults()); } else { get(handler); } } get(handler); } function getRepoAndIssues(org, done) { logger.info({ method: 'getRepoAndIssues', args: arguments }); Async.parallel([ function(callback) { getAllRepos(org, { type: PUBLIC_TYPE }, callback); }, function(callback) { getAllIssues(org, { state: STATE_OPEN, filter: 'all' }, callback); } ], done); } function mashReposWithIssues(repos, issues) { // init the computed property repos.map(function(repo) { repo.computed = { issues: [], pull_requests: [] }; }); issues.map(function(issue) { let index = repos.findIndex(function(repo) { return repo.name === issue.repository.name; }); // happens when the repository is private if (index === -1) { logger.error({ type: 'CANNOT_FIND_REPO_FOR_ISSUE', issue: issue }); return; } let repo = repos[index]; delete issue.repository; // push the issue into the appropriate bucket repo.computed[issue.pull_request ? 'pull_requests' : 'issues'].push(issue); }); return repos; } export function sync() { function iterator(org, callback) { getRepoAndIssues(org, function(err, results) { if (err) { logger.info(err); return callback(err); } Database.saveReposWithIssues(org, mashReposWithIssues(results[0], results[1]), callback); }); } Async.eachSeries(ORGS, iterator, function(err) { if (err) { return logger.error(err); } }); } export function fetch(org, callback) { logger.info({ method: 'fetch', args: arguments }); Database.readReposWithIssues(org, callback); } export function fetchAll(callback) { var results = []; function iterator(org, itCallback) { fetch(org, function(err, obj) { if (err) { logger.info(err); return itCallback(err); } results.push(obj); itCallback(); }); } Async.eachSeries(ORGS, iterator, function(err) { callback(err, results); }); } export function fetchAllIssues(callback) { fetchAll(function(err, results) { if (err) { logger.info(err); return callback(err); } results = results.map(function(result) { delete result.repos; return result; }); callback(null, results); }); }
import React, { Component, PropTypes } from 'react'; import { Provider } from 'react-redux'; import { Router } from 'react-router'; import routes from '../routes'; export default class Root extends Component { render() { const { store, history } = this.props; return ( <Provider store={store}> <div> <Router history={history} routes={routes} /> </div> </Provider> ); } } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired };
function AbstractObjectPlacementHelper() { } AbstractObjectPlacementHelper.prototype = { execute: function(plugin) { // place in front of current camera if we're in VR view if (E2.app.worldEditor.isVRCamera()) { var cam = E2.app.worldEditor.getCamera() var worldPos = new THREE.Vector3(0, 0, -2) worldPos.applyMatrix4(cam.matrixWorld) var oldPos = new THREE.Vector3(plugin.state.position.x, plugin.state.position.y, plugin.state.position.z) plugin.undoableSetState('position', worldPos, oldPos) } } } // Objects function ObjectPlacementHelper() { AbstractObjectPlacementHelper.apply(this, arguments) } ObjectPlacementHelper.prototype = Object.create(AbstractObjectPlacementHelper.prototype) ObjectPlacementHelper.prototype.execute = function(plugin) { // scale to unit size plugin.scaleToUnitSize() AbstractObjectPlacementHelper.prototype.execute.apply(this, arguments) } // Textures function TexturePlacementHelper() { AbstractObjectPlacementHelper.apply(this, arguments) } TexturePlacementHelper.prototype = Object.create(AbstractObjectPlacementHelper.prototype) TexturePlacementHelper.prototype.execute = function(plugin) { AbstractObjectPlacementHelper.prototype.execute.apply(this, arguments) }
/** * AccessMap allows configuration of different access control rules for * specific parts of the website. * * @memberOf Jymfony.Component.Security.Authorization */ class AccessMapInterface { /** * Returns security attributes and required channel for the supplied request. * * @returns {[string[], undefined|string]} A tuple of security attributes and the required channel */ getPatterns(request) { } } export default getInterface(AccessMapInterface);
/*--------------------------------------------------------------------------------------------- * Copyright (c) Artyom Shalkhakov. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Based on the ATS/Postiats lexer by Hongwei Xi. *--------------------------------------------------------------------------------------------*/ define(["require", "exports"], function (require, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.conf = { comments: { lineComment: '//', blockComment: ['(*', '*)'], }, brackets: [['{', '}'], ['[', ']'], ['(', ')'], ['<', '>']], autoClosingPairs: [ { open: '"', close: '"', notIn: ['string', 'comment'] }, { open: '{', close: '}', notIn: ['string', 'comment'] }, { open: '[', close: ']', notIn: ['string', 'comment'] }, { open: '(', close: ')', notIn: ['string', 'comment'] }, ] }; exports.language = { tokenPostfix: '.pats', // TODO: staload and dynload are followed by a special kind of string literals // with {$IDENTIFER} variables, and it also may make sense to highlight // the punctuation (. and / and \) differently. // Set defaultToken to invalid to see what you do not tokenize yet defaultToken: 'invalid', // keyword reference: https://github.com/githwxi/ATS-Postiats/blob/master/src/pats_lexing_token.dats keywords: [ // "abstype", "abst0ype", "absprop", "absview", "absvtype", "absviewtype", "absvt0ype", "absviewt0ype", // "as", // "and", // "assume", // "begin", // /* "case", // CASE */ // "classdec", // "datasort", // "datatype", "dataprop", "dataview", "datavtype", "dataviewtype", // "do", // "end", // "extern", "extype", "extvar", // "exception", // "fn", "fnx", "fun", // "prfn", "prfun", // "praxi", "castfn", // "if", "then", "else", // "ifcase", // "in", // "infix", "infixl", "infixr", "prefix", "postfix", // "implmnt", "implement", // "primplmnt", "primplement", // "import", // /* "lam", // LAM "llam", // LLAM "fix", // FIX */ // "let", // "local", // "macdef", "macrodef", // "nonfix", // "symelim", "symintr", "overload", // "of", "op", // "rec", // "sif", "scase", // "sortdef", /* // HX: [sta] is now deprecated */ "sta", "stacst", "stadef", "static", /* "stavar", // T_STAVAR */ // "staload", "dynload", // "try", // "tkindef", // /* "type", // TYPE */ "typedef", "propdef", "viewdef", "vtypedef", "viewtypedef", // /* "val", // VAL */ "prval", // "var", "prvar", // "when", "where", // /* "for", // T_FOR "while", // T_WHILE */ // "with", // "withtype", "withprop", "withview", "withvtype", "withviewtype", ], keywords_dlr: [ "$delay", "$ldelay", // "$arrpsz", "$arrptrsize", // "$d2ctype", // "$effmask", "$effmask_ntm", "$effmask_exn", "$effmask_ref", "$effmask_wrt", "$effmask_all", // "$extern", "$extkind", "$extype", "$extype_struct", // "$extval", "$extfcall", "$extmcall", // "$literal", // "$myfilename", "$mylocation", "$myfunction", // "$lst", "$lst_t", "$lst_vt", "$list", "$list_t", "$list_vt", // "$rec", "$rec_t", "$rec_vt", "$record", "$record_t", "$record_vt", // "$tup", "$tup_t", "$tup_vt", "$tuple", "$tuple_t", "$tuple_vt", // "$break", "$continue", // "$raise", // "$showtype", // "$vcopyenv_v", "$vcopyenv_vt", // "$tempenver", // "$solver_assert", "$solver_verify", ], keywords_srp: [ // "#if", "#ifdef", "#ifndef", // "#then", // "#elif", "#elifdef", "#elifndef", // "#else", "#endif", // "#error", // "#prerr", "#print", // "#assert", // "#undef", "#define", // "#include", "#require", // "#pragma", "#codegen2", "#codegen3", ], irregular_keyword_list: [ "val+", "val-", "val", "case+", "case-", "case", "addr@", "addr", "fold@", "free@", "fix@", "fix", "lam@", "lam", "llam@", "llam", "viewt@ype+", "viewt@ype-", "viewt@ype", "viewtype+", "viewtype-", "viewtype", "view+", "view-", "view@", "view", "type+", "type-", "type", "vtype+", "vtype-", "vtype", "vt@ype+", "vt@ype-", "vt@ype", "viewt@ype+", "viewt@ype-", "viewt@ype", "viewtype+", "viewtype-", "viewtype", "prop+", "prop-", "prop", "type+", "type-", "type", "t@ype", "t@ype+", "t@ype-", "abst@ype", "abstype", "absviewt@ype", "absvt@ype", "for*", "for", "while*", "while" ], keywords_types: [ 'bool', 'double', 'byte', 'int', 'short', 'char', 'void', 'unit', 'long', 'float', 'string', 'strptr' ], // TODO: reference for this? keywords_effects: [ "0", "fun", "clo", "prf", "funclo", "cloptr", "cloref", "ref", "ntm", "1" // all effects ], operators: [ "@", "!", "|", "`", ":", "$", ".", "=", "#", "~", // "..", "...", // "=>", // "=<", // T_EQLT "=<>", "=/=>", "=>>", "=/=>>", // "<", ">", // "><", // ".<", ">.", // ".<>.", // "->", //"-<", // T_MINUSLT "-<>", ], brackets: [ { open: ',(', close: ')', token: 'delimiter.parenthesis' }, { open: '`(', close: ')', token: 'delimiter.parenthesis' }, { open: '%(', close: ')', token: 'delimiter.parenthesis' }, { open: '\'(', close: ')', token: 'delimiter.parenthesis' }, { open: '\'{', close: '}', token: 'delimiter.parenthesis' }, { open: '@(', close: ')', token: 'delimiter.parenthesis' }, { open: '@{', close: '}', token: 'delimiter.brace' }, { open: '@[', close: ']', token: 'delimiter.square' }, { open: '#[', close: ']', token: 'delimiter.square' }, { open: '{', close: '}', token: 'delimiter.curly' }, { open: '[', close: ']', token: 'delimiter.square' }, { open: '(', close: ')', token: 'delimiter.parenthesis' }, { open: '<', close: '>', token: 'delimiter.angle' } ], // we include these common regular expressions symbols: /[=><!~?:&|+\-*\/\^%]+/, IDENTFST: /[a-zA-Z_]/, IDENTRST: /[a-zA-Z0-9_'$]/, symbolic: /[%&+-./:=@~`^|*!$#?<>]/, digit: /[0-9]/, digitseq0: /@digit*/, xdigit: /[0-9A-Za-z]/, xdigitseq0: /@xdigit*/, INTSP: /[lLuU]/, FLOATSP: /[fFlL]/, fexponent: /[eE][+-]?[0-9]+/, fexponent_bin: /[pP][+-]?[0-9]+/, deciexp: /\.[0-9]*@fexponent?/, hexiexp: /\.[0-9a-zA-Z]*@fexponent_bin?/, irregular_keywords: /val[+-]?|case[+-]?|addr\@?|fold\@|free\@|fix\@?|lam\@?|llam\@?|prop[+-]?|type[+-]?|view[+-@]?|viewt@?ype[+-]?|t@?ype[+-]?|v(iew)?t@?ype[+-]?|abst@?ype|absv(iew)?t@?ype|for\*?|while\*?/, ESCHAR: /[ntvbrfa\\\?'"\(\[\{]/, start: 'root', // The main tokenizer for ATS/Postiats // reference: https://github.com/githwxi/ATS-Postiats/blob/master/src/pats_lexing.dats tokenizer: { root: [ // lexing_blankseq0 { regex: /[ \t\r\n]+/, action: { token: '' } }, // NOTE: (*) is an invalid ML-like comment! { regex: /\(\*\)/, action: { token: 'invalid' } }, { regex: /\(\*/, action: { token: 'comment', next: 'lexing_COMMENT_block_ml' } }, { regex: /\(/, action: '@brackets' /*{ token: 'delimiter.parenthesis' }*/ }, { regex: /\)/, action: '@brackets' /*{ token: 'delimiter.parenthesis' }*/ }, { regex: /\[/, action: '@brackets' /*{ token: 'delimiter.bracket' }*/ }, { regex: /\]/, action: '@brackets' /*{ token: 'delimiter.bracket' }*/ }, { regex: /\{/, action: '@brackets' /*{ token: 'delimiter.brace' }*/ }, { regex: /\}/, action: '@brackets' /*{ token: 'delimiter.brace' }*/ }, // lexing_COMMA { regex: /,\(/, action: '@brackets' /*{ token: 'delimiter.parenthesis' }*/ }, { regex: /,/, action: { token: 'delimiter.comma' } }, { regex: /;/, action: { token: 'delimiter.semicolon' } }, // lexing_AT { regex: /@\(/, action: '@brackets' /* { token: 'delimiter.parenthesis' }*/ }, { regex: /@\[/, action: '@brackets' /* { token: 'delimiter.bracket' }*/ }, { regex: /@\{/, action: '@brackets' /*{ token: 'delimiter.brace' }*/ }, // lexing_COLON { regex: /:</, action: { token: 'keyword', next: '@lexing_EFFECT_commaseq0' } }, /* lexing_DOT: . // SYMBOLIC => lexing_IDENT_sym . FLOATDOT => lexing_FLOAT_deciexp . DIGIT => T_DOTINT */ { regex: /\.@symbolic+/, action: { token: 'identifier.sym' } }, // FLOATDOT case { regex: /\.@digit*@fexponent@FLOATSP*/, action: { token: 'number.float' } }, { regex: /\.@digit+/, action: { token: 'number.float' } }, // lexing_DOLLAR: // '$' IDENTFST IDENTRST* => lexing_IDENT_dlr, _ => lexing_IDENT_sym { regex: /\$@IDENTFST@IDENTRST*/, action: { cases: { '@keywords_dlr': { token: 'keyword.dlr' }, '@default': { token: 'namespace' }, } } }, // lexing_SHARP: // '#' IDENTFST IDENTRST* => lexing_ident_srp, _ => lexing_IDENT_sym { regex: /\#@IDENTFST@IDENTRST*/, action: { cases: { '@keywords_srp': { token: 'keyword.srp' }, '@default': { token: 'identifier' }, } } }, // lexing_PERCENT: { regex: /%\(/, action: { token: 'delimiter.parenthesis' } }, { regex: /^%{(#|\^|\$)?/, action: { token: 'keyword', next: '@lexing_EXTCODE', nextEmbedded: 'text/javascript' } }, { regex: /^%}/, action: { token: 'keyword' } }, // lexing_QUOTE { regex: /'\(/, action: { token: 'delimiter.parenthesis' } }, { regex: /'\[/, action: { token: 'delimiter.bracket' } }, { regex: /'\{/, action: { token: 'delimiter.brace' } }, [/(')(\\@ESCHAR|\\[xX]@xdigit+|\\@digit+)(')/, ['string', 'string.escape', 'string']], [/'[^\\']'/, 'string'], // lexing_DQUOTE [/"/, 'string.quote', '@lexing_DQUOTE'], // lexing_BQUOTE { regex: /`\(/, action: '@brackets' /* { token: 'delimiter.parenthesis' }*/ }, // TODO: otherwise, try lexing_IDENT_sym { regex: /\\/, action: { token: 'punctuation' } }, // lexing_IDENT_alp: // NOTE: (?!regex) is syntax for "not-followed-by" regex // to resolve ambiguity such as foreach$fwork being incorrectly lexed as [for] [each$fwork]! { regex: /@irregular_keywords(?!@IDENTRST)/, action: { token: 'keyword' } }, { regex: /@IDENTFST@IDENTRST*[<!\[]?/, action: { cases: { // TODO: dynload and staload should be specially parsed // dynload whitespace+ "special_string" // this special string is really: // '/' '\\' '.' => punctuation // ({\$)([a-zA-Z_][a-zA-Z_0-9]*)(}) => punctuation,keyword,punctuation // [^"] => identifier/literal '@keywords': { token: 'keyword' }, '@keywords_types': { token: 'type' }, '@default': { token: 'identifier' } } } }, // lexing_IDENT_sym: { regex: /\/\/\/\//, action: { token: 'comment', next: '@lexing_COMMENT_rest' } }, { regex: /\/\/.*$/, action: { token: 'comment' } }, { regex: /\/\*/, action: { token: 'comment', next: '@lexing_COMMENT_block_c' } }, // AS-20160627: specifically for effect annotations { regex: /-<|=</, action: { token: 'keyword', next: '@lexing_EFFECT_commaseq0' } }, { regex: /@symbolic+/, action: { cases: { '@operators': 'keyword', '@default': 'operator' } } }, // lexing_ZERO: // FIXME: this one is quite messy/unfinished yet // TODO: lexing_INT_hex // - testing_hexiexp => lexing_FLOAT_hexiexp // - testing_fexponent_bin => lexing_FLOAT_hexiexp // - testing_intspseq0 => T_INT_hex // lexing_INT_hex: { regex: /0[xX]@xdigit+(@hexiexp|@fexponent_bin)@FLOATSP*/, action: { token: 'number.float' } }, { regex: /0[xX]@xdigit+@INTSP*/, action: { token: 'number.hex' } }, { regex: /0[0-7]+(?![0-9])@INTSP*/, action: { token: 'number.octal' } }, //{regex: /0/, action: { token: 'number' } }, // INTZERO // lexing_INT_dec: // - testing_deciexp => lexing_FLOAT_deciexp // - testing_fexponent => lexing_FLOAT_deciexp // - otherwise => intspseq0 ([0-9]*[lLuU]?) { regex: /@digit+(@fexponent|@deciexp)@FLOATSP*/, action: { token: 'number.float' } }, { regex: /@digit@digitseq0@INTSP*/, action: { token: 'number.decimal' } }, // DIGIT, if followed by digitseq0, is lexing_INT_dec { regex: /@digit+@INTSP*/, action: { token: 'number' } }, ], lexing_COMMENT_block_ml: [ [/[^\(\*]+/, 'comment'], [/\(\*/, 'comment', '@push'], [/\(\*/, 'comment.invalid'], [/\*\)/, 'comment', '@pop'], [/\*/, 'comment'] ], lexing_COMMENT_block_c: [ [/[^\/*]+/, 'comment'], // [/\/\*/, 'comment', '@push' ], // nested C-style block comments not allowed // [/\/\*/, 'comment.invalid' ], // NOTE: this breaks block comments in the shape of /* //*/ [/\*\//, 'comment', '@pop'], [/[\/*]/, 'comment'] ], lexing_COMMENT_rest: [ [/$/, 'comment', '@pop'], [/.*/, 'comment'] ], // NOTE: added by AS, specifically for highlighting lexing_EFFECT_commaseq0: [ { regex: /@IDENTFST@IDENTRST+|@digit+/, action: { cases: { '@keywords_effects': { token: 'type.effect' }, '@default': { token: 'identifier' } } } }, { regex: /,/, action: { token: 'punctuation' } }, { regex: />/, action: { token: '@rematch', next: '@pop' } }, ], lexing_EXTCODE: [ { regex: /^%}/, action: { token: '@rematch', next: '@pop', nextEmbedded: '@pop' } }, { regex: /[^%]+/, action: '' }, ], lexing_DQUOTE: [ { regex: /"/, action: { token: 'string.quote', next: '@pop' } }, // AS-20160628: additional hi-lighting for variables in staload/dynload strings { regex: /(\{\$)(@IDENTFST@IDENTRST*)(\})/, action: [{ token: 'string.escape' }, { token: 'identifier' }, { token: 'string.escape' }] }, { regex: /\\$/, action: { token: 'string.escape' } }, { regex: /\\(@ESCHAR|[xX]@xdigit+|@digit+)/, action: { token: 'string.escape' } }, { regex: /[^\\"]+/, action: { token: 'string' } } ], }, }; });
// Greek 'use strict'; var el = function() {} el.code = 'el'; el.data = { /* Sign Message */ NAV_SignMsg: 'Sign Message', MSG_message: 'Message', MSG_date: 'Date', MSG_signature: 'Signature', MSG_verify: 'Verify Message', MSG_info1: 'Include the current date so the signature cannot be reused on a different date.', MSG_info2: 'Include your nickname and where you use the nickname so someone else cannot use it.', MSG_info3: 'Inlude a specific reason for the message so it cannot be reused for a different purpose.', /* Mnemonic Additions */ MNEM_1: 'Please select the address you would like to interact with.', MNEM_2: 'Your single HD mnemonic phrase can access a number of wallets / addresses. Please select the address you would like to interact with at this time.', MNEM_more: 'More Addresses', MNEM_prev: 'Previous Addresses', x_Mnemonic: 'Mnemonic Phrase (MetaMask / Jaxx / ether.cards)', ADD_Radio_5: 'Paste/Type Your Mnemonic', SEND_custom: 'Add Custom Token', TOKEN_show: 'Show All Tokens', TOKEN_hide: 'Hide Tokens', ERROR_21: ' is not a valid ERC-20 token. If other tokens are loading, please remove this token and try again.', ERROR_22: 'Could not estimate gas. There are not enough funds in the account, or the receiving contract address would throw an error. Feel free to manually set the gas and proceed. The error message upon sending may be more informative.', WARN_Send_Link: 'You arrived via a link that has the address, value, gas, data fields, or transaction type (send mode) filled in for you. You can change any information before sending. Unlock your wallet to get started.', /* Hardware wallets */ x_Ledger: 'Ledger Nano S', ADD_Ledger_1: 'Connect your Ledger Nano S', ADD_Ledger_2: 'Open the Ethereum application (or a contract application)', ADD_Ledger_3: 'Verify that Browser Support is enabled in Settings', ADD_Ledger_4: 'If no Browser Support is found in settings, verify that you have [Firmware >1.2](https://www.ledgerwallet.com/apps/manager)', ADD_Ledger_0a: 'Re-open MyEtherWallet on a secure (SSL) connection', ADD_Ledger_0b: 'Re-open MyEtherWallet using [Chrome](https://www.google.com/chrome/browser/desktop/) or [Opera](https://www.opera.com/)', ADD_Ledger_scan: 'Connect to Ledger Nano S', /* Geth Error Messages */ GETH_InvalidSender: 'Invalid sender', GETH_Nonce: 'Nonce too low', GETH_Cheap: 'Gas price too low for acceptance', GETH_Balance: 'Insufficient balance', GETH_NonExistentAccount: 'Account does not exist or account balance too low', GETH_InsufficientFunds: 'Insufficient funds for gas * price + value', GETH_IntrinsicGas: 'Intrinsic gas too low', GETH_GasLimit: 'Exceeds block gas limit', GETH_NegativeValue: 'Negative value', HELP_12_Desc_15b: 'If you are on a PC:', SUCCESS_5: 'File Selected: ', FOOTER_4: 'Disclaimer', /* New - Deploy Contracts */ NAV_DeployContract: 'Deploy Contract', NAV_InteractContract: 'Interact with Contract', NAV_Contracts: 'Contracts', NAV_Multisig: 'Multisig', DEP_generate: 'Generate Bytecode', DEP_generated: 'Generated Bytecode', DEP_signtx: 'Sign Transaction', DEP_interface: 'Generated Interface', /* Navigation*/ NAV_YourWallets: 'Τα Πορτοφόλια σας', NAV_AddWallet: 'Προσθήκη Πορτοφολιού', NAV_GenerateWallet: 'Δημηουργία Πορτοφολιού', NAV_BulkGenerate: 'Δημιουργία Πολλών Πορτοφολιών', NAV_SendEther: 'Αποστολή Ether και Tokens', NAV_SendTokens: 'Αποστολή Tokens', NAV_Offline: 'Αποστολή εκτός Σύνδεσης', NAV_MyWallets: 'Τα Πορτοφόλια μου', NAV_ViewWallet: 'Προβολή Πληροφοριών Πορτοφολιού', NAV_Help: 'Βοήθεια', NAV_Contact: 'Επικοινωνία', /* General */ x_Wallet: 'Πορτοφόλι', x_Password: 'Κωδικός', x_Download: 'Λήψη', x_Address: 'Η Διεύθυνσή σας', x_Save: 'Αποθήκευση', x_Cancel: 'Ακύρωση', x_AddessDesc: 'Γνωστή και ως "Αριθμός Λογαριασμού" σας ή "Δημόσιο Κλειδί" σας. Αυτή δίνετε σε όσους επιθυμούν να σας στείλουν ether. Το εικονίδιο είναι ένας εύκολος τρόπος αναγνώρισης της διεύθυνσής σας.', x_PrivKey: 'Ιδιωτικό Κλειδί (μη κρυπτογραφημένο)', x_PrivKey2: 'Ιδιωτικό Κλειδί', x_PrivKeyDesc: 'Αυτό το κείμενο είναι η μη κρυπτογραφημένη εκδοχή του Ιδιωτικού Κλειδιού σας που σημαίνει ότι δεν απαιτείται κωδικός. Στην περίπτωση που κάποιος βρει το μη κρυπτογραφημένο Ιδιωτικό Κλειδί σας, έχει πρόσβαση στο πορτοφόλι σας χωρίς κωδικό. Για αυτόν τον λόγο, συνήθως συνιστώνται οι κρυπτογραφημένες εκδοχές.', x_Keystore: 'Αρχείο Keystore (UTC / JSON · Συνιστάται · Κρυπτογραφημένο · Μορφή Mist)', x_Keystore2: 'Αρχείο Keystore (UTC / JSON)', x_KeystoreDesc: 'Αυτό το Αρχείο Keystore έχει την ίδια μορφή που χρησιμοποιείται από το Mist ώστε να μπορείτε εύκολα να το εισάγετε στο μέλλον. Είναι το συνιστώμενο αρχείο για λήψη και δημιουργία αντιγράφου ασφαλείας.', x_Json: 'Αρχείο JSON (μη κρυπτογραφημένο)', x_JsonDesc: 'Αυτή είναι η μη κρυπτογραφημένη, JSON μορφή του Ιδιωτικού Κλειδιού σας. Αυτό σημαίνει ότι δεν απαιτείται κωδικός όμως οποιοσδήποτε βρει το JSON σας έχει πρόσβαση στο πορτοφόλι και τα Ether σας χωρίς κωδικό.', x_PrintShort: 'Εκτύπωση', x_Print: 'Εκτύπωση Χάρτινου Πορτοφολιού', x_PrintDesc: 'Συμβουλή: Κλικάρετε "Εκτύπωση και Αποθήκευση ως PDF" ακόμη κι αν δεν έχετε εκτυπωτή!', x_CSV: 'Αρχείο CSV (μη κρυπτογραφημένο)', x_TXT: 'Αρχείο TXT (μη κρυπτογραφημένο)', /* Header */ MEW_Warning_1: 'Πάντα να ελέγχετε την διεύθυνση URL προτού μπείτε στο πορτοφόλι σας ή δημιουργήσετε καινούριο πορτοφόλι. Προσοχή στις σελίδες ηλεκτρονικού ψαρέματος!', CX_Warning_1: 'Σιγουρευτείτε ότι έχετε **εξωτερικά αντίγραφα ασφαλείας** όλων των πορτοφολιών που αποθηκεύετε εδώ. Μπορούν να συμβούν διάφορα που θα προκαλούσαν απώλεια των δεδομένων σας σε αυτήν την επέκταση Chrome, συμπεριλαμβανομένης απεγκατάστασης και επανεγκατάστασης της επέκτασης. Αυτή η επέκταση είναι ένας τρόπος εύκολης πρόσβασης στα πορτοφόλια σας και **όχι** ένας τρόπος να δημηιουργήσετε αντίγραφα ασφαλείας τους.', MEW_Tagline: 'Ασφαλές Πορτοφόλι Ether Ανοιχτού Κώδικα JavaScript από την πλευρά του Πελάτη', CX_Tagline: 'Επέκταση Chrome για Ασφαλές Πορτοφόλι Ether Ανοιχτού Κώδικα JavaScript από την πλευρά του Πελάτη', /* Footer */ FOOTER_1: 'Ένα εργαλείο ανοιχτού κώδικα, javascript, από πλευράς πελάτη για την δημιουργία Πορτοφολιών Ethereum & αποστολή συναλλαγών.', FOOTER_1b: 'Δημιουργήθηκε από', FOOTER_2: 'Εκτιμούμε πολύ τις δωρεές σας:', FOOTER_3: 'Δημιουργία Πορτοφολιών από πλευράς πελάτη από', /* Sidebar */ sidebar_AccountInfo: 'Πληροφορίες Λογαριασμού: ', sidebar_AccountAddr: 'Διεύθυνση Λογαριασμού: ', sidebar_AccountBal: 'Υπόλοιπο Λογαριασμού: ', sidebar_TokenBal: 'Υπόλοιπο Token: ', sidebar_Equiv: 'Ισότιμες Αξίες: ', sidebar_TransHistory: 'Ιστορικό Συναλλαγών', sidebar_donation: 'Το MyEtherWallet είναι μία δωρεάν υπηρεσία ανοιχτού κώδικα αφοσιωμένη στην ιδιωτικότητα και την ασφάλεια σας. Όσο περισσότερες δωρεές λαμβάνουμε, τόσο περισσότερο χρόνο αφιερώνουμε στη δημιουργία νέων χαρακτηριστικών καθώς και την αξιολόγηση και εφαρμογή όσων μας προτείνετε. Είμαστε απλά δύο άνθρωποι που προσπαθούν να αλλάξουν τον κόσμο. Θα μας βοηθήσετε; ', sidebar_donate: 'Δωρεά', sidebar_thanks: 'ΣΑΣ ΕΥΧΑΡΙΣΤΟΥΜΕ!!!', /* Decrypt Panel */ decrypt_Access: 'Πώς θα θέλατε να έχετε πρόσβαση στο Πορτοφόλι σας;', decrypt_Title: 'Επιλέξτε την μορφή του Ιδιωτικού Κλειδιού σας:', decrypt_Select: 'Επιλέξτε Πορτοφόλι:', /* Add Wallet */ ADD_Label_1: 'Τι θα θέλατε να κάνετε;', ADD_Radio_1: 'Δημιουργία Νέου Πορτοφολιού', ADD_Radio_2: 'Επιλέξτε το αρχείο Πορτοφολιού σας (Keystore / JSON)', ADD_Radio_2_short: 'ΕΠΙΛΕΞΤΕ ΑΡΧΕΙΟ ΠΟΡΤΟΦΟΛΙΟΥ...', ADD_Radio_3: 'Επικολλήστε/Πληκτρολογήστε το Ιδιωτικό Κλειδί σας', ADD_Radio_4: 'Προσθήκη Λογαριασμού προς Παρακολούθηση', ADD_Label_2: 'Δημιουργία Ψευδωνύμου:', ADD_Label_3: 'Το πορτοφόλι σας είναι κρυπτογραφημένο. Παρακαλώ εισάγετε τον κωδικό: ', ADD_Label_4: 'Προσθήκη Λογαριασμού προς Παρακολούθηση', ADD_Warning_1: 'Μπορείτε να προσθέσετε έναν λογαριασμό προς "παρακολούθηση" στην καρτέλα πορτοφολιών χωρίς να ανεβάσετε ιδιωτικό κλειδί. Αυτό ** δεν ** σημαίνει ότι έχετε πρόσβαση στο πορτοφόλι, ούτε ότι μπορείτε να μεταφέρετε Ether από αυτό.', ADD_Label_5: 'Εισάγετε την Διεύθυνση: ', ADD_Label_6: 'Ξεκλειδώστε το Πορτοφόλι σας', ADD_Label_6_short: 'Ξεκλείδωμα', ADD_Label_7: 'Προσθήκη Λογαριασμού', /* Generate Wallets */ GEN_desc: 'Αν επιθυμείτε να δημιουργήσετε πολλά πορτοφόλια, μπορείτε να το κάνετε εδώ:', GEN_Label_1: 'Εισάγετε ισχυρό κωδικό (τουλάχιστον 9 χαρακτήρες)', GEN_Placeholder_1: 'ΜΗΝ ξεχάσετε να τον αποθηκεύσετε!', GEN_SuccessMsg: 'Επιτυχία! Το πορτοφόλι σας δημιουργήθηκε.', GEN_Warning: 'Προκειμένου να έχετε πρόσβαση σε αυτό το πορτοφόλι στο μέλλον **είναι απαραίτητο το αρχείο Keystore/JSON & ο κωδικός ή το Ιδιωτικό Κλειδί σας**. Παρακαλούμε κρατήστε ένα εξωτερικό αντίγραφο ασφαλείας! Δεν υπάρχει τρόπος ανάκτησης ενός πορτοφολιού άν δεν το αποθηκέυσετε. Διαβάστε την σελίδα [Βοήθειας](https://www.myetherwallet.com/#help) για οδηγίες.', GEN_Label_2: 'Αποθηκεύστε το αρχέιο Keystore/JSON ή το Ιδιωτικό Κλειδί. Μην ξεχάσετε τον παραπάνω κωδικό.', GEN_Label_3: 'Αποθηκέυστε την Διεύθυνση σας.', GEN_Label_4: 'Εκτυπώστε το χάρτινο Πορτοφόλι σας ή αποθηκέυστε την εκδοχή με QR code. (προαιρετικό)', /* Bulk Generate Wallets */ BULK_Label_1: 'Αριθμός Πορτοφολιών για Δημιουργία', BULK_Label_2: 'Δημιουργία Πορτοφολιών', BULK_SuccessMsg: 'Επιτυχία! Τα πορτοφόλια σας δημιουργήθηκαν.', /* Sending Ether and Tokens */ SEND_addr: 'Προς Διεύθυνση: ', SEND_amount: 'Ποσό για αποστολή: ', SEND_amount_short: 'Ποσό', SEND_custom: 'Custom', SEND_gas: 'Gas', SEND_generate: 'Δημιουργία Υπογεγραμμένης Συναλλαγής', SEND_raw: 'Ακατέργαστη Συναλλαγή', SEND_signed: 'Υπογεγραμμένη Συναλλαγή', SEND_trans: 'Αποστολή Συναλλαγής', SEND_TransferTotal: 'Μεταφορά συνολικού διαθέσιμου υπολοίπου', SENDModal_Title: 'Προσοχή! ', /* full sentence reads "You are about to send "10 ETH" to address "0x1234". Are you sure you want to do this? " */ SENDModal_Content_1: 'Πρόκειται να στείλετε', SENDModal_Content_2: 'στη διεύθυνση', SENDModal_Content_3: 'Είστε σίγουροι ότι θέλετε να το κάνετε;', SENDModal_Content_4: 'ΣΗΜΕΙΩΣΗ: Αν αντιμετωπίσετε σφάλμα, το πιο πιθανό χρειάζεται να προσθέσετε ether στον λογαριασμό σας για να καλύψετε το κόστος gas για την αποστολή token. Το gas πληρώνεται σε ether.', SENDModal_No: 'Όχι, θέλω να φύγω από εδώ!', SENDModal_Yes: 'Ναι, είμαι σίγουρος/η! Εκτελέστε την συναλλαγή.', SEND_TransferTotal: 'Μεταφορά όλου του υπάρχοντος υπολοίπου', /* Tokens */ TOKEN_Addr: 'Διεύθυνση: ', TOKEN_Symbol: 'Σύμβολο Token: ', TOKEN_Dec: 'Δεκαδικά: ', /* Send Transaction */ TRANS_desc: 'Άν επιθυμείτε να στείλετε Tokens, παρακαλώ χρησιμοποιήστε την σελίδα "Αποστολή Token".', TRANS_warning: 'Άν χρησιμοποιείτε τις λειτουργίες "Μόνο ETH" ή "Μόνο ETC", η αποστολή γίνεται μέσω contracts. Ορισμένες υπηρεσίες παρουσιάζουν προβλήματα με την αποδοχή τέτοιων συναλλαγών. Διαβάστε περισσότερα.', TRANS_advanced: '+Για προχωρημένους: Προσθήκη Data ', TRANS_data: 'Data: ', TRANS_gas: 'Gas Limit: ', TRANS_sendInfo: 'Μία standard συναλλαγή που χρησιμοποιεί 21000 gas θα κοστίσει 0,000441 ETH. Χρησιμοποιούμε για τιμή gas 0.000000021 ETH που είναι λίγο πάνω απο την ελάχιστη ώστε διασφαλίσουμε οτι θα επικυρωθεί γρήγορα. Δεν παίρνουμε προμήθεια για την συναλλαγή.', /* Send Transaction Modals */ TRANSModal_Title: 'Συναλλαγές "Μόνο ETH" και "Μόνο ETC"', TRANSModal_Content_0: 'Μια σημείωση για τις διάφορετικές συναλλαγές και διαφορετικές υπηρεσίες συναλλαγών:', TRANSModal_Content_1: '**ETH (Standard Συναλλαγή): ** This generates a default transaction directly from one address to another. It has a default gas of 21000. It is likely that any ETH sent via this method will be replayed onto the ETC chain.', TRANSModal_Content_2: '**Μόνο ETH: ** This sends via [Timon Rapp\'s replay protection contract (as recommended by VB)](https://blog.ethereum.org/2016/07/26/onward_from_the_hard_fork/) so that you only send on the **ETH** chain.', TRANSModal_Content_3: '**Μόνο ETC: ** This sends via [Timon Rapp\'s replay protection contract (as recommended by VB)](https://blog.ethereum.org/2016/07/26/onward_from_the_hard_fork/) so that you only send on the **ETC** chain. ', TRANSModal_Content_4: '**Coinbase & ShapeShift: ** Αποστέλλετε μόνο με Standard Συναλλαγή. Αν στείλετε με τα "Μόνο" contracts, θα χρεαιστεί να έρθετε σε επφή με το προσωπικό υποστήριξης τους ώστε να σας βοηθήσουν με χειροκίνητη μεταφορά υπολοίπων ή επιστροφή χρημάτων.[Μπορείτε επίσης να δοκιμάσετε το εργαλείο "διαχωρισμού" του Shapeshift](https://split.shapeshift.io/)', TRANSModal_Content_5: '**Kraken & Poloniex:** Δεν υπάρχουν γνωστά προβλήματα. Αποστέλλετε με οποιαδήποτε μέθοδο.', TRANSModal_Yes: 'Τέλεια, το κατάλαβα.', TRANSModal_No: 'Πωπω, μπερδεύτηκα ακόμη περισσότερο. Βοηθήστε με.', /* Offline Transaction */ OFFLINE_Title: 'Δημιουργία και Αποστολή Συναλλαγής εκτός Σύνδεσης', OFFLINE_Desc: 'Η δημιουργία συναλλαγών εκτός σύνδεσης μπορεί να γίνει σε τρία βήματα. Θα προβείτε στα βήματα 1 και 3 σε έναν συνδεδεμένο υπολογιστή και το βήμα 2 σε έναν εκτός σύνδεσης/αποκομμένο υπολογιστή. Αυτό εξασφαλίζει ότι τα ιδιωτικά κλειδιά σας δεν έρχονται σε επαφή με συσκευή συνδεδεμένη στο διαδίκτυο.', OFFLLINE_Step1_Title: 'Βήμα 1: Δημιουργία Πληροφοριών (Συνδεδεμένος Υπολογιστής)', OFFLINE_Step1_Button: 'Δημιουργία Πληροφοριών', OFFLINE_Step1_Label_1: 'Από Διεύθυνση:', OFFLINE_Step1_Label_2: 'Σημείωση: Αυτή είναι η Διεύθυνση ΑΠΟΣΤΟΛΕΑ, ΟΧΙ η Διεύθυνση. Το nonce δημιουργείται απο τον λογαριασμό προέλευσης. Αν χρησιμοποιείται αποκομμένο υπολογιστή, πρόκειται για την διεύθυνση του λογαριασμού σε cold-storage.', OFFLINE_Step2_Title: 'Step 2: Δημιουργία Συναλλαγής (εκτός Σύνδεσης Υπολογιστής)', OFFLINE_Step2_Label_1: 'Προς Διεύθυνση: ', OFFLINE_Step2_Label_2: 'Αξία / Ποσό για Αποστολή', OFFLINE_Step2_Label_3: 'Τιμή Gas ', OFFLINE_Step2_Label_3b: 'Εμφανίστηκε στο Βήμα 1 στον συνδεδεμένο υπολογιστή σας.', OFFLINE_Step2_Label_4: 'Όριο Gas ', OFFLINE_Step2_Label_4b: '21000 είναι το προεπιλεγμένο όριο gas. When you send contracts or add\'l data, this may need to be different. Any unused gas will be returned to you.', OFFLINE_Step2_Label_5: 'Nonce', OFFLINE_Step2_Label_5b: 'Εμφανίστηκε στο Βήμα 1 στον συνδεδεμένο υπολογιστή σας.', OFFLINE_Step2_Label_6: 'Data', OFFLINE_Step2_Label_6b: 'Αυτό είναι προαιρετικό. Data συνήθως χρησιμοποιούνται όταν αποστέλλονται συναλλαγές σε contracts.', OFFLINE_Step2_Label_7: 'Εισαγωγή / Επιλογή του Ιδιωτικού Κλειδιού / JSON.', OFFLINE_Step3_Title: 'Βήμα 3: Δημοσίευση Συναλλαγής (Συνδεδεμένος Υπολογιστής)', OFFLINE_Step3_Label_1: 'Επικολλήστε την υπογεγραμμένη συναλλαγή εδώ και πατήστε το κουμπί "ΑΠΟΣΤΟΛΗ ΣΥΝΑΛΛΑΓΗΣ".', /* My Wallet */ MYWAL_Nick: 'Ψευδώνυμο Πορτοφολιού', MYWAL_Address: 'Διεύθυνση Πορτοφολιού', MYWAL_Bal: 'Υπόλοιπο', MYWAL_Edit: 'Επεξεργασία', MYWAL_View: 'Προβολή', MYWAL_Remove: 'Αφαίρεση', MYWAL_RemoveWal: 'Αφαίρεση Πορτοφολιού:', MYWAL_WatchOnly: 'Οι Μόνο-προς-παρακολούθηση-Λογαριασμοί', MYWAL_Viewing: 'Προβάλλεται το Πορτοφόλι: ', MYWAL_Hide: 'Απόκρυψη Πληροφοριών Πορτοφολιού', MYWAL_Edit: 'Επεξεργασία Πορτοφολιού: ', MYWAL_Name: 'Όνομα Πορτοφολιού', MYWAL_Content_1: 'Προσοχή! Πρόκειται να αφαιρέσετε το πορτοφόλι σας.', MYWAL_Content_2: 'Σιγουρευτείτε ότι έχετε **αποθηκεύσει το αρχέιο Keystore/JSON και τον κωδικό** του πορτοφολιού αυτού πριν το αφαιρέσετε.', MYWAL_Content_3: 'Αν θέλετε να χρησιμοποιήσετε το ποροτοφόλι αυτό με το MyEtherWalletCX στο μέλλον, θα χρειαστεί να το ξαναπροσθέσετε χειροκίνητα χρησιμοποιώντας το Ιδιωτικό Κλειδί/JSON και τον κωδικό.', /* View Wallet Details */ VIEWWALLET_Subtitle: 'Αυτό σας επιτρέπει να κατεβάσετε διαφορετικές εκδοχές των ιδιωτικών κλειδιών σας και να επανεκτυπώσετε το χάρτινο πορτοφόλι σας. Ίσως επιθυμείτε να το κάνετε προκειμένου να [εισάγετε τον Λογαριασμό σας στο Geth/Mist](http://ethereum.stackexchange.com/questions/465/how-to-import-a-plain-private-key-into-geth/). Αν επιθυμείτε να ελέγξετε το υπόλοιπό σας, συνιστούμε να χρησιμοποιήσετε ένα εργαλείο εξερεύνησης blockchain όπως το [etherscan.io](http://etherscan.io/).', VIEWWALLET_Subtitle_Short: 'Αυτό σας επιτρέπει να κατεβάσετε διαφορετικές εκδοχές των ιδιωτικών κλειδιών σας και να επανεκτυπώσετε το χάρτινο πορτοφόλι σας.', VIEWWALLET_SuccessMsg: 'Επιτυχία! Εδώ είναι οι πληροφορίες για το πορτοφόλι σας.', /* CX */ CX_error_1: 'Δεν έχετε αποθηκευμένα πορτοφόλια. Κάντε κλικ στο ["Προσθήκη Πορτοφολιού"](/cx-wallet.html#add-wallet) για να προσθεσετε ένα!', CX_quicksend: 'ΤαχυΑποστολή', /* Error Messages */ ERROR_1: 'Παρακαλώ εισάγετε έγκυρο ποσό.', ERROR_2: 'Ο κωδικός σας πρέπει να αποτελείται απο τουλάχιστον 9 χαρακτήρες. Παρακαλώ σιγουρευτείτε ότι είναι ισχυρός κωδικός. ', ERROR_3: 'Συγγνώμη! Δεν αναγνωρίζουμε αυτού του είδους αρχεία πορτοφολιού ', ERROR_4: 'Αυτό δεν είναι έγκυρο αρχείο πορτοφολιού. ', ERROR_5: 'Αυτή η μονάδα δεν υπάρχει, παρακαλώ χρησιμοποιήστε μία απο τις ακόλουθες μονάδες:', ERROR_6: 'Λάθος Διεύθυνση. ', ERROR_7: 'Λάθος κωδικός. ', ERROR_8: 'Λάθος ποσό. ', ERROR_9: 'Λάθος όριο gas. ', ERROR_10: 'Λάθος data value. ', ERROR_11: 'Λάθος ποσό gas. ', ERROR_12: 'Λάθος nonce. ', ERROR_13: 'Λάθος υπογεγραμμένη συναλλαγή. ', ERROR_14: 'Υπάρχει ήδη πορτοφόλι με αυτό το ψευδώνυμο. ', ERROR_15: 'Δεν βρέθηκε πορτοφόλι. ', ERROR_16: 'Φαίνετα να μην υπάρχει ακόμη πρόταση με αυτό το ID ή υπήρξε σφάλμα κατά την ανάγνωση της πρότασης αυτής. ', ERROR_17: 'Υπάρχει ήδη αποθηκευμένο πορτοφόλι με αυτή την διεύθυνση. Παρακαλώ ελέγξτε την σελίδα πορτοφολιών σας. ', ERROR_18: 'Πρέπει να έχετε τουλάχιστον 0.001 ETH στον λογαριασμό σας για να καλύψετε το κόστος του gas. Παρακαλώ προσθέστε μερικά ether και δοκιμάστε ξανά. ', ERROR_19: 'Όλο το gas θα είχε δαπανηθεί στην συναλλαγή αυτή. Αυτό σημαίνει ότι έχετε ήδη ψηφίσει στην πρόταση αυτή ή ότι η περίοδος συζήτησης έχει λήξει.', ERROR_20: 'Λάθος σύμβολο', SUCCESS_1: 'Έγκυρη διεύθυνση', SUCCESS_2: 'Το πορτοφόλι αποκρυπτογραφήθηκε επιτυχώς', SUCCESS_3: 'Η συναλλαγή υποβλήθηκε. TX ID: ', SUCCESS_4: 'Το πορτοφόλι σας προστέθηκε επιτυχώς: ', /* Parity Error Messages */ PARITY_AlreadyImported: "Transaction with the same hash was already imported.", PARITY_Old: "Transaction nonce is too low. Try incrementing the nonce.", PARITY_TooCheapToReplace: "Transaction fee is too low. There is another transaction with same nonce in the queue. Try increasing the fee or incrementing the nonce.", PARITY_LimitReached: "There are too many transactions in the queue. Your transaction was dropped due to limit. Try increasing the fee.", PARITY_InsufficientGasPrice: "Transaction fee is too low. It does not satisfy your node's minimal fee (minimal: {}, got: {}). Try increasing the fee.", PARITY_InsufficientBalance: "Insufficient funds. Account you try to send transaction from does not have enough funds. Required {} and got: {}.", PARITY_GasLimitExceeded: "Transaction cost exceeds current gas limit. Limit: {}, got: {}. Try decreasing supplied gas.", PARITY_InvalidGasLimit: "Supplied gas is beyond limit.", /* Tranlsation Info */ translate_version: '0.3', Translator_Desc: 'Ευχαριστούμε τους μεταφραστές μας: ', TranslatorName_1: '[VitalikFanBoy#117](https://www.myetherwallet.com/?gaslimit=21000&to=0x245f27796a44d7e3d30654ed62850ff09ee85656&value=1.0#send-transaction) · ', TranslatorAddr_1: '0x245f27796a44d7e3d30654ed62850ff09ee85656', /* Translator 1: Insert Comments Here */ TranslatorName_2: 'LefterisJP · ', TranslatorAddr_2: '', /* Translator 2: Insert Comments Here */ TranslatorName_3: '[Nikos Vavoulas](https://www.myetherwallet.com/?gaslimit=21000&to=0x062711C89Bd46E9765CfF0b743Cb83a9dBA2d2d2&value=1.0#send-transaction) · ', TranslatorAddr_3: '0x062711C89Bd46E9765CfF0b743Cb83a9dBA2d2d2', /* Translator 3: Insert Comments Here */ TranslatorName_4: ' ', TranslatorAddr_4: ' ', /* Translator 4: Insert Comments Here */ TranslatorName_5: ' ', TranslatorAddr_5: ' ', /* Translator 5: Insert Comments Here */ /* Help - Nothing after this point has to be translated. If you feel like being extra helpful, go for it. */ HELP_Warning: 'If you created a wallet -or- downloaded the repo before **Dec. 31st, 2015**, please check your wallets &amp; download a new version of the repo. Click for details.', HELP_Desc: 'Do you see something missing? Have another question? [Get in touch with us](mailto:myetherwallet@gmail.com), and we will not only answer your question, we will update this page to be more useful to people in the future!', HELP_Remind_Title: 'Some reminders', HELP_Remind_Desc_1: '**Ethereum, MyEtherWallet.com & MyEtherWallet CX, and some of the underlying Javascript libraries we use are under active development.** While we have thoroughly tested & tens of thousands of wallets have been successfully created by people all over the globe, there is always the remote possibility that something unexpected happens that causes your ETH to be lost. Please do not invest more than you are willing to lose, and please be careful. If something were to happen, we are sorry, but **we are not responsible for the lost Ether**.', HELP_Remind_Desc_2: 'MyEtherWallet.com & MyEtherWallet CX are not "web wallets". You do not create an account or give us your Ether to hold onto. All data never leaves your computer/your browser. We make it easy for you to create, save, and access your information and interact with the blockchain.', HELP_Remind_Desc_3: 'If you do not save your private key & password, there is no way to recover access to your wallet or the funds it holds. Back them up in multiple physical locations &ndash; not just on your computer!', HELP_0_Title: '0) Είμαι νέος χρήστης. Τι κάνω?', HELP_0_Desc_1: 'Το MyEtherWallet σας δίνει την δυνατότητα να δημιουργήσετε νέα πορτοφόλια ώστε να μπορείτε να αποθηκεύσετε το Ether σας μόνοι σας, και όχι σε κάποιο ανταλλακτήριο (exchange provider). Αυτή η διαδικασία συμβαίνει εξ\'ολοκλήρου στον υπολογιστή σας, και όχι στους servers μας. Γι\'αυτό, όταν δημιουργείτε ένα νέο πορτοφόλι, **εσείς είστε υπεύθυνοι να κρατήσετε αντίγραφα ασφαλείας**.', HELP_0_Desc_2: 'Δημιουργήστε ένα νέο πορτοφόλι.', HELP_0_Desc_3: 'Κρατήστε αντίγραφο ασφαλείας ποτοφολιού.', HELP_0_Desc_4: 'Επιβεβαιώστε ότι έχετε πρόσβαση στο νέο αυτό πορτοφόλι και ότι αποθηκεύσατε σωστά όλες τις απαραίτητες πληροφορίες.', HELP_0_Desc_5: 'Μεταφέρετε Ether στο νέο αυτό πορτοφόλι.', HELP_1_Title: '1) Πως φτιάχνω ένα νέο πορτοφόλι? ', HELP_1_Desc_1: 'Πηγαίνετε στην σελίδα "Δημιουργία Πορτοφολιού".', HELP_1_Desc_2: 'Πηγαίνετε στην σελίδα "Προσθήκη Πορτοφολιού" & επιλέξτε "Δημιουργία Νέου Πορτοφολιού"', HELP_1_Desc_3: 'Οληκτρολογήστε ένα δυνατό συνθηματικό (password). Αν νομίζετε ότι μπορεί να το ξεχάσετε, αποθηκεύστε το κάπου που να είναι ασφαλές. Θα χρειαστείτε αυτό το password για τις εξερχόμενες συναλλαγές σας.', HELP_1_Desc_4: 'Κάντε κλικ στο "ΔΗΜΙΟΥΡΓΙΑ".', HELP_1_Desc_5: 'Το πορτοφόλι σας δημιοθργήθηκε με επιτυχία.', HELP_2a_Title: '2a) How do I save/backup my wallet?', HELP_2a_Desc_1: 'You should always back up your wallet externally and in multiple physical locations - like on a USB drive and/or a piece of paper.', HELP_2a_Desc_2: 'Save the address. You can keep it to yourself or share it with others. That way, others can transfer ether to you.', HELP_2a_Desc_3: 'Save versions of the private key. Do not share it with anyone else. Your private key is necessary when you want to access your Ether to send it! There are 3 types of private keys:', HELP_2a_Desc_4: 'Place your address, versions of the private key, and the PDF version of your paper wallet in a folder. Save this on your computer and a USB drive.', HELP_2a_Desc_5: 'Print the wallet if you have a printer. Otherwise, write down your private key and address on a piece of paper. Store this as a secure location, separate from your computer and the USB drive.', HELP_2a_Desc_6: 'Keep in mind, you must prevent loss of the keys and password due to loss or failure of you hard drive failure, or USB drive, or piece of paper. You also must keep in mind physical loss / damage of an entire area (think fire or flood).', HELP_2b_Title: '2b) How do I safely / offline / cold storage with MyEtherWallet?', HELP_2b_Desc_1: 'Go to [https://github.com/kvhnuke/etherwallet/releases/latest](https://github.com/kvhnuke/etherwallet/releases/latest).', HELP_2b_Desc_2: 'Click on `dist-vX.X.X.X.zip`.', HELP_2b_Desc_3: 'Move zip to an airgapped computer.', HELP_2b_Desc_4: 'Unzip it and double-click `index.html`.', HELP_2b_Desc_5: 'Generate a wallet with a strong password.', HELP_2b_Desc_6: 'Save the address. Save versions of the private key. Save the password if you might not remember it forever.', HELP_2b_Desc_7: 'Store these papers / USBs in multiple physically separate locations.', HELP_2b_Desc_8: 'Go to the "View Wallet Info" page and type in your private key / password to ensure they are correct and access your wallet. Check that the address you wrote down is the same.', HELP_3_Title: '3) How do I verify I have access to my new wallet?', HELP_3_Desc_1: '**Before you send any Ether to your new wallet**, you should ensure you have access to it.', HELP_3_Desc_2: 'Navigate to the "View Wallet Info" page.', HELP_3_Desc_3: 'Navigate to the MyEtherWallet.com "View Wallet Info" page.', HELP_3_Desc_4: 'Select your wallet file -or- your private key and unlock your wallet.', HELP_3_Desc_5: 'If the wallet is encrypted, a text box will automatically appear. Enter the password.', HELP_3_Desc_6: 'Click the "Unlock Wallet" button.', HELP_3_Desc_7: 'Your wallet information should show up. Find your account address, next to a colorful, circular icon. This icon visually represents your address. Be certain that the address is the address you have saved to your text document and is on your paper wallet.', HELP_3_Desc_8: 'If you are planning on holding a large amount of ether, we recommend that send a small amount of ether from new wallet before depositing a large amount. Send 0.001 ether to your new wallet, access that wallet, send that 0.001 ether to another address, and ensure everything works smoothly.', HELP_4_Title: '4) How do I send Ether from one wallet to another?', HELP_4_Desc_1: 'If you plan to move a large amount of ether, you should test sending a small amount to your wallet first to ensure everything goes as planned.', HELP_4_Desc_2: 'Navigate to the "Αποστολή Ether και Tokens" page.', HELP_4_Desc_3: 'Select your wallet file -or- your private key and unlock your wallet.', HELP_4_Desc_4: 'If the wallet is encrypted, a text box will automatically appear. Enter the password.', HELP_4_Desc_5: 'Click the "Unlock Wallet" button.', HELP_4_Desc_6: 'Enter the address you would like to send to in the "To Address:" field.', HELP_4_Desc_7: 'Enter the amount you would like to send. You can also click the "Send Entire Balance" link if you would like the transfer the entire balance.', HELP_4_Desc_9: 'Click "Generate Transaction".', HELP_4_Desc_10: 'A couple more fields will appear. This is your browser generating the transaction.', HELP_4_Desc_11: 'Click the blue "Send Transaction" button below that.', HELP_4_Desc_12: 'A pop-up will appear. Verify that the amount and the address you are sending to are correct. Then click "Yes, I am sure! Make transaction." button.', HELP_4_Desc_13: 'The transaction will be submitted. The TX ID will display. You can click that TX ID to see it on the blockchain. ', HELP_4CX_Title: '4) How do I send Ether using MyEtherWallet CX?', HELP_4CX_Desc_1: 'First, you need to add a wallet. Once you have done that, you have 2 options: the "QuickSend" functionality from the Chrome Extension icon or the "Αποστολή Ether και Tokens" page.', HELP_4CX_Desc_2: 'QuickSend:', HELP_4CX_Desc_3: 'Click the Chrome Extension Icon.', HELP_4CX_Desc_4: 'Click the "QuickSend" button.', HELP_4CX_Desc_5: 'Select the wallet you wish to send from.', HELP_4CX_Desc_6: 'Enter the address you would like to send to in the "To Address:" field.', HELP_4CX_Desc_7: 'Enter the amount you would like to send. You can also click the "Send Entire Balance" link if you would like the transfer the entire balance.', HELP_4CX_Desc_8: 'Click "Send Transaction". ', HELP_4CX_Desc_9: 'Verify the address and the amount you are sending is correct.', HELP_4CX_Desc_10: 'Enter the password for that wallet.', HELP_4CX_Desc_11: 'Click "Send Transaction."', HELP_4CX_Desc_12: 'Using "Αποστολή Ether και Tokens" Page: ', HELP_5_Title: '5) How do I run MyEtherWallet.com offline/locally? ', HELP_5_Desc_1: 'You can run MyEtherWallet.com on your computer instead of from the GitHub servers. You can generate a wallet completely offline and send transactions from the "Offline Transaction" page.', HELP_5_Desc_7: 'MyEtherWallet.com is now running entirely on your computer.', HELP_5_Desc_8: 'In case you are not familiar, you need to keep the entire folder in order to run the website, not just `index.html`. Don\'t touch or move anything around in the folder. If you are storing a backup of the MyEtherWallet repo for the future, we recommend just storing the ZIP so you can be sure the folder contents stay intact.', HELP_5_Desc_9: 'As we are constantly updating MyEtherWallet.com, we recommend you periodically update your saved version of the repo.', HELP_5CX_Title: '5) How can I install this extension from the repo instead of the Chrome Store? ', HELP_5CX_Desc_2: 'Click on `chrome-extension-vX.X.X.X.zip` and unzip it.', HELP_5CX_Desc_3: 'Go to Google Chrome and find you settings (in the menu in the upper right).', HELP_5CX_Desc_4: 'Click "Extensions" on the left.', HELP_5CX_Desc_5: 'Check the "Developer Mode" button at the top of that page.', HELP_5CX_Desc_6: 'Click the "Load unpacked extension..." button.', HELP_5CX_Desc_7: 'Navigate to the now-unzipped folder that you downloaded earlier. Click "select".', HELP_5CX_Desc_8: 'The extension should now show up in your extensions and in your Chrome Extension bar.', HELP_7_Title: '7) How do I send Tokens & add custom tokens?', HELP_7_Desc_0: '[Ethplorer.io](https://ethplorer.io/) is a great way to explore tokens and find the decimals of a token.', HELP_7_Desc_1: 'Navigate to the "Αποστολή Ether και Tokens" page.', HELP_7_Desc_2: 'Unlock your wallet.', HELP_7_Desc_3: 'Enter the address you would like to send to in the "To Address:" field.', HELP_7_Desc_4: 'Enter the amount you would like to send.', HELP_7_Desc_5: 'Select which token you would like to send.', HELP_7_Desc_6: 'If you do not see the token listed:', HELP_7_Desc_7: 'Click "Custom".', HELP_7_Desc_8: 'Enter the address, name, and decimals of the token. These are provided by the developers of the token and are also needed when you "Add a Watch Token" to Mist.', HELP_7_Desc_9: 'Click "Save".', HELP_7_Desc_10: 'You can now send that token as well as see it\'s balance in the sidebar.', HELP_7_Desc_11: 'Click "Generate Transaction".', HELP_7_Desc_12: 'A couple more fields will appear. This is your browser generating the transaction.', HELP_7_Desc_13: 'Click the blue "Send Transaction" button below that.', HELP_7_Desc_14: 'A pop-up will appear. Verify that the amount and the address you are sending to are correct. Then click "Yes, I am sure! Make transaction." button.', HELP_7_Desc_15: 'The transaction will be submitted. The TX ID will display. You can click that TX ID to see it on the blockchain.', HELP_8_Title: '8) What happens if your site goes down?', HELP_8_Desc_1: 'MyEtherWallet is not a web wallet. You don\'t have a login and nothing ever gets saved to our servers. It is simply an interface that allows you interact with the blockchain.', HELP_8_Desc_2: 'If MyEtherWallet.com goes down, you would have to find another way (like geth or Ethereum Wallet / Mist) to do what we are doing. But you wouldn\'t have to "get" your Ether out of MyEtherWallet because it\'s not in MyEtherWallet. It\'s in whatever wallet your generated via our site.', HELP_8_Desc_3: 'You can import your unencrypted private key and your Geth/Mist Format (encrypted) files directly into geth / Ethereum Wallet / Mist very easily now. See question #12 below.', HELP_8_Desc_4: 'In addition, the likelihood of us taking MyEtherWallet down is slim to none. It costs us almost nothing to maintain as we aren\'t storing any information. If we do take the domain down, it still is, and always will be, publicly available at [https://github.com/kvhnuke/etherwallet](https://github.com/kvhnuke/etherwallet/tree/gh-pages). You can download the ZIP there and run it locally. ', HELP_8CX_Title: '8) What happens if MyEtherWallet CX disappears?', HELP_8CX_Desc_1: 'First, all data is saved on your computer, not our servers. I know it can be confusing, but when you look at the Chrome Extension, you are NOT looking at stuff saved on our servers somewhere - it\'s all saved on your own computer.', HELP_8CX_Desc_2: 'That said, it is **very important** that you back up all your information for any new wallets generated with MyEtherWallet CX. That way if anything happens to MyEtherWallet CX or your computer, you still have all the information necessary to access your Ether. See the #2a for how to back up your wallets.', HELP_8CX_Desc_3: 'If for some reason MyEtherWallet CX disappears from the Chrome Store, you can find the source on Github and load it manually. See #5 above.', HELP_9_Title: '9) Is the "Αποστολή Ether και Tokens" page offline?', HELP_9_Desc_1: 'No. It needs the internet in order to get the current gas price, nonce of your account, and broadcast the transaction (aka "send"). However, it only sends the signed transaction. Your private key safely stays with you. We also now provide an "Offline Transaction" page so that you can ensure your private keys are on an offline/airgapped computer at all times.', HELP_10_Title: '10) How do I make an offline transaction?', HELP_10_Desc_1: 'Navigate to the "Offline Transaction" page via your online computer.', HELP_10_Desc_2: 'Enter the "From Address". Please note, this is the address you are sending FROM, not TO. This generates the nonce and gas price.', HELP_10_Desc_3: 'Move to your offline computer. Enter the "TO ADDRESS" and the "AMOUNT" you wish to send.', HELP_10_Desc_4: 'Enter the "GAS PRICE" as it was displayed to you on your online computer in step #1.', HELP_10_Desc_5: 'Enter the "NONCE" as it was displayed to you on your online computer in step #1.', HELP_10_Desc_6: 'The "GAS LIMIT" has a default value of 21000. This will cover a standard transaction. If you are sending to a contract or are including additional data with your transaction, you will need to increase the gas limit. Any excess gas will be returned to you.', HELP_10_Desc_7: 'If you wish, enter some data. If you enter data, you will need to include more than the 21000 default gas limit. All data is in HEX format.', HELP_10_Desc_8: 'Select your wallet file -or- your private key and unlock your wallet.', HELP_10_Desc_9: 'Press the "GENERATE SIGNED TRANSACTION" button.', HELP_10_Desc_10: 'The data field below this button will populate with your signed transaction. Copy this and move it back to your online computer. ', HELP_10_Desc_11: 'On your online computer, paste the signed transaction into the text field in step #3 and click send. This will broadcast your transaction.', HELP_12_Title: '12) How do I import a wallet created with MyEtherWallet into geth / Ethereum Wallet / Mist?', HELP_12_Desc_1: 'Using an Geth/Mist JSON file from MyEtherWallet v2+....', HELP_12_Desc_2: 'Go to the "View Wallet Info" page.', HELP_12_Desc_3: 'Unlock your wallet using your **encrypted** private key or JSON file. ', HELP_12_Desc_4: 'Go to the "My Wallets" page.', HELP_12_Desc_5: 'Select the wallet you want to import into Mist, click the "View" icon, enter your password, and access your wallet. ', HELP_12_Desc_6: 'Find the "Download JSON file - Geth/Mist Format (encrypted)" section. Press the "Download" button below that. You now have your keystore file.', HELP_12_Desc_7: 'Open the Ethereum Wallet application. ', HELP_12_Desc_8: 'In the menu bar, go "Accounts" -> "Backup" -> "Accounts"', HELP_12_Desc_9: 'This will open your keystore folder. Copy the file you just downloaded (`UTC--2016-04-14......../`) into that keystore folder.', HELP_12_Desc_10: 'Your account should show up immediately under "Accounts."', HELP_12_Desc_11: 'Using your unencrypted private key...', HELP_12_Desc_12: 'If you do not already have your unencrypted private key, navigate to the "View Wallet Details" page.', HELP_12_Desc_13: 'Select your wallet file -or- enter/paste your private key to unlock your wallet.', HELP_12_Desc_14: 'Copy Your Private Key (μη κρυπτογραφημένο).', HELP_12_Desc_15: 'If you are on a Mac:', HELP_12_Desc_15b: 'If you are on a PC:', HELP_12_Desc_16: 'Open Text Edit and paste this private key.', HELP_12_Desc_17: 'Go to the menu bar and click "Format" -> "Make Plain Text".', HELP_12_Desc_18: 'Save this file to your `desktop/` as `nothing_special_delete_me.txt`. Make sure it says "UTF-8" and "If no extension is provided use .txt" in the save dialog.', HELP_12_Desc_19: 'Open terminal and run the following command: `geth account import ~/Desktop/nothing_special_delete_me.txt`', HELP_12_Desc_20: 'This will prompt you to make a new password. This is the password you will use in geth / Ethereum Wallet / Mist whenever you send a transaction, so don\'t forget it. ', HELP_12_Desc_21: 'After successful import, delete `nothing_special_delete_me.txt`', HELP_12_Desc_22: 'The next time you open the Ethereum Wallet application, your account will be listed under "Accounts".', HELP_12_Desc_23: 'Open Notepad & paste the private key', HELP_12_Desc_24: 'Save the file as `nothing_special_delete_me.txt` at `C:`', HELP_12_Desc_25: 'Run the command, `geth account import C:\\nothing_special_delete_me.txt`', HELP_12_Desc_26: 'This will prompt you to make a new password. This is the password you will use in geth / Ethereum Wallet / Mist whenever you send a transaction, so don\'t forget it.', HELP_12_Desc_27: 'After successful import, delete `nothing_special_delete_me.txt`', HELP_12_Desc_28: 'The next time you open the Ethereum Wallet application, your account will be listed under "Accounts". ', HELP_13_Title: '13) What does "Insufficient funds. Account you try to send transaction from does not have enough funds. Required XXXXXXXXXXXXXXXXXXX and got: XXXXXXXXXXXXXXXX." Mean?', HELP_13_Desc_1: 'This means you do not have enough Ether in your account to cover the cost of gas. Each transaction (including token and contract transactions) require gas and that gas is paid in Ether. The number displayed is the amount required to cover the cost of the transaction in Wei. Take that number, divide by `1000000000000000000`, and subtract the amount of Ether you were trying to send (if you were attempting to send Ether). This will give you the amount of Ether you need to send to that account to make the transaction.', HELP_14_Title: '14) Some sites randomize (seed) the private key generation via mouse movements. MyEtherWallet.com doesn\'t do this. Is the random number generation for MyEtherWallet safe?', HELP_14_Desc_1: 'While the mouse moving thing is clever and we understand why people like it, the reality is window.crypto ensures more entropy than your mouse movements. The mouse movements aren\'t unsafe, it\'s just that we (and tons of other crypto experiments) believe in window.crypto. In addition, MyEtherWallet.com can be used on touch devices. Here\'s a [conversation between an angry redditor and Vitalik Buterin regarding mouse movements v. window.crypto](https://www.reddit.com/r/ethereum/comments/2bilqg/note_there_is_a_paranoid_highsecurity_way_to/cj5sgrm) and here is the [the window.crypto w3 spec](https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto).', HELP_15_Title: '15) Why hasn\'t the account I just created show up in the blockchain explorer? (ie: etherchain, etherscan)', HELP_15_Desc_1: 'Accounts will only show up in a blockchain explorer once the account has activity on it&mdash;for example, once you have transferred some Ether to it.', HELP_16_Title: '16) How do I check the balance of my account? ', HELP_16_Desc_1: 'You can use a blockchain explorer like [etherscan.io](http://etherscan.io/). Paste your address into the search bar and it will pull up your address and transaction history. For example, here\'s what our [donation account](http://etherscan.io/address/0x7cb57b5a97eabe94205c07890be4c1ad31e486a8) looks like on etherscan.io', HELP_17_Title: '17) Why isn\'t my balance showing up when I unlock my wallet? ', HELP_17_Desc_1: ' This is most likely due to the fact that you are behind a firewall. The API that we use to get the balance and convert said balance is often blocked by firewalls for whatever reason. You will still be able to send transactions, you just need to use a different method to see said balance, like etherscan.io', HELP_18_Title: '18) Where is my geth wallet file?', HELP_19_Title: '19) Where is my Mist wallet file? ', HELP_19_Desc_1: 'Mist files are typically found in the file locations above, but it\'s much easier to open Mist, select "Accounts" in the top bar, select "Backup", and select "Accounts". This will open the folder where your files are stored.', HELP_20_Title: '20) Where is my pre-sale wallet file?', HELP_20_Desc_1: 'Wherever you saved it. ;) It also was emailed to you, so check there. Look for the file called `"ethereum_wallet_backup.json"` and select that file. This wallet file will be encrypted with a password that you created during the purchase of the pre-sale.', HELP_21_Title: '21) Couldn\'t everybody put in random private keys, look for a balance, and send to their own address? ', HELP_21_Desc_1: 'Short version: yes, but finding an account with a balance would take longer than the universe...so...no.', HELP_21_Desc_2: 'Long ELI5 Version: So Ethereum is based on [Public Key Cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography), specifically [Elliptic curve cryptography](https://eprint.iacr.org/2013/734.pdf) which is very widely used, not just in Ethereum. Most servers are protected via ECC. Bitcoin uses the same, as well as SSH and TLS and a lot of other stuff. The Ethereum keys specifically are 256-bit keys, which are stronger than 128-bit and 192-bit, which are also widely used and still considered secure by experts.', HELP_21_Desc_3: 'In this you have a private key and a public key. The private key can derive the public key, but the public key cannot be turned back into the private key. The fact that the internet and the world’s secrets are using this cryptography means that if there is a way to go from public key to private key, your lost ether is the least of everyone’s problems.', HELP_21_Desc_4: 'Now, that said, YES if someone else has your private key then they can indeed send ether from your account. Just like if someone has your password to your email, they can read and send your email, or the password to your bank account, they could make transfers. You could download the Keystore version of your private key which is the private key that is encrypted with a password. This is like having a password that is also protected by another password.', HELP_21_Desc_5: 'And YES, in theory you could just type in a string of 64 hexadecimal characters until you got one that matched. In fact, smart people could write a program to very quickly check random private keys. This is known as "brute-forcing" or "mining" private keys. People have thought about this long and hard. With a few very high end servers, they may be able to check 1M+ keys / second. However, even checking that many per second would not yield access to make the cost of running those servers even close to worthwhile - it is more likely you, and your great-grandchildren, will die before getting a match.', HELP_21_Desc_6: 'If you know anything about Bitcoin, [this will put it in perspective:](http://bitcoin.stackexchange.com/questions/32331/two-people-with-same-public-address-how-will-people-network-know-how-to-deliver) *To illustrate how unlikely this is: suppose every satoshi of every bitcoin ever to be generated was sent to its own unique private keys. The probability that among those keys there could be two that would correspond to the same address is roughly one in 100 quintillion.', HELP_21_Desc_7: '[If you want something a bit more technical:](http://security.stackexchange.com/questions/25375/why-not-use-larger-cipher-keys/25392#25392) *These numbers have nothing to do with the technology of the devices; they are the maximums that thermodynamics will allow. And they strongly imply that brute-force attacks against 256-bit keys will be infeasible until computers are built from something other than matter and occupy something other than space.', HELP_21_Desc_8: 'Of course, this all assumes that keys are generated in a truly random way & with sufficient entropy. The keys generated here meet that criteria, as do Jaxx and Mist/geth. The Ethereum wallets are all pretty good. Keys generated by brainwallets do not, as a person\'s brain is not capable of creating a truly random seed. There have been a number of other issues regarding lack of entropy or seeds not being generated in a truly random way in Bitcoin-land, but that\'s a separate issue that can wait for another day.', HELP_SecCX_Title: 'Security - MyEtherWallet CX ', HELP_SecCX_Desc_1: 'Where is this extension saving my information?', HELP_SecCX_Desc_2: 'The information you store in this Chrome Extension is saved via [chrome.storage](http://chrome.storage/). - this is the same place your passwords are saved when you save your password in Chrome.', HELP_SecCX_Desc_3: 'What information is saved? ', HELP_SecCX_Desc_4: 'The address, nickname, private key is stored in chrome.storage. The private key is encrypted using the password you set when you added the wallet. The nickname and wallet address is not encrypted.', HELP_SecCX_Desc_5: 'Why aren\'t the nickname and wallet address encrypted? ', HELP_SecCX_Desc_6: 'If we were to encrypt these items, you would need to enter a password each time you wanted to view your account balance or view the nicknames. If this concerns you, we recommend you use MyEtherWallet.com instead of this Chrome Extension.', HELP_Sec_Title: 'Security', HELP_Sec_Desc_1: 'If one of your first questions is "Why should I trust these people?", that is a good thing. Hopefully the following will help ease your fears. ', HELP_Sec_Desc_2: 'We\'ve been up and running since August 2015. If you search for ["myetherwallet" on reddit](https://www.reddit.com/search?q=myetherwallet), you can see numerous people who use us with great success.', HELP_Sec_Desc_3: 'We aren\'t going to take your money or steal your private key(s). There is no malicious code on this site. In fact the "GENERATE WALLET" pages are completely client-side. That means that all the code is executed on ** your computer** and it is never saved and transmitted anywhere.', HELP_Sec_Desc_4: 'Check the URL -- This site is being served through GitHub and you can see the source code here: [https://github.com/kvhnuke/etherwallet/tree/gh-pages](https://github.com/kvhnuke/etherwallet/tree/gh-pages) to [https://www.myetherwallet.com](https://www.myetherwallet.com).', HELP_Sec_Desc_5: 'For generating wallets, you can download the [source code and run it locally](https://github.com/kvhnuke/etherwallet/releases/latest). See #5 above.', HELP_Sec_Desc_6: 'Generate a test wallet and check and see what network activity is happening. The easiest way for you to do this is to right click on the page and click "inspect element". Go to the "Network" tab. Generate a test wallet. You will see there is no network activity. You may see something happening that looks like data:image/gif and data:image/png. Those are the QR codes being generated...on your computer...by your computer. No bytes were transferred.', HELP_Sec_Desc_8: 'If you do not feel comfortable using this tool, then by all means, do not use it. We created this tool as a helpful way for people to generate wallets and make transactions without needing to dive into command line or run a full node. Again, feel free to reach out if you have concerns and we will respond as quickly as possible. Thanks! ', HELP_FAQ_Title: 'More Helpful Answers to Frequent Questions', HELP_Contact_Title: 'Ways to Get in Touch' }; module.exports = el;
/****************************** * 协同云BIM模块的元数据配置 *******************************/ var md = md || {}; (function (u, undefined) { var unit = { //单体对象 typeAlias: 'ObjModelUnit', classAlias: 'ClassModelUnit', ownerAlias: null, propDefs: { NameOrTitle: "0" //名称或标题 } }; var floor = {//楼层 typeAlias: 'ObjFloor', classAlias: 'ClassFloor', ownerAlias: 'ObjModelUnit', propDefs: { NameOrTitle: '0' //名称或标题 } }; var discipline = {//模型专业 typeAlias: 'ObjModelDiscipline', classAlias: 'ClassModelDiscipline', ownerAlias: 'ObjFloor', propDefs: { NameOrTitle: '0' //名称或标题 } }; var componentClasses = {//构件类别 typeAlias: 'ObjComponentClasses', classAlias: 'ClassComponentClasses', ownerAlias: 'ObjModelDiscipline', propDefs: { NameOrTitle: '0', //名称或标题 ID: 'PropID' } }; var componentType = {//构件类型 typeAlias: 'ObjComponentType', classAlias: 'ClassComponentType', ownerAlias: 'ObjComponentClasses', propDefs: { NameOrTitle: '0', //名称或标题 ID: 'PropID' } }; var componentModel = {//构件模型 typeAlias: 'ObjComponentModel', classAlias: 'ClassComponentModel', ownerAlias: 'ObjComponentType', propDefs: { NameOrTitle: '0', //名称或标题 ID: 'PropID', GUID: 'PropGUID' } }; //文档类型相关 var bimModelDoc = {//BIM模型文件(模型策划) typeAlias: '0', classAlias: 'ClassBimModelDoc', ownerAlias: null, propDefs: { ModelName: 'PropModelName', //模型名称 UnitAt: 'PropModelUnitAt', //所在单体 FloorAt: 'PropFloorAt', //所在楼层 DisciplineAt: 'PropDisciplineAt', //所在专业 TemplateAt: 'PropTemplateAt', //模板 ModelNumber: 'PropModelNumber', //编号 ModelCreator: 'PropModelCreator', //建模人 DisciLeader: 'PropDisciLeader', //专业负责人 Deadline: 'PropExpectedDeadline', //预计完成时间 ActualFinishDate: 'PropActualFinishDate' //实际完成时间 } }; var previewModel = { typeAlias: '0', classAlias: 'ClassPreviewModel', ownerAlias: null, propDefs: { NameOrTitle: '0', //名称或标题 ModelName: 'PropModelName', //模型名称 UnitAt: 'PropModelUnitAt', //所在单体 FloorAt: 'PropFloorAt', //所在楼层 DisciplineAt: 'PropDisciplineAt', //所在专业 ComponentClassAt: 'PropComponentClassAt', //所在构件类别 ComponentTypeAt: 'PropComponentTypeAt', //所在构件类型 ComponentAt: 'PropComponentAt' //构件 } }; var attachments = { //构件附件 typeAlias: 'ObjectTypeElement', classAlias: 'ClassElement', ownerAlias: null, propDefs: { "PropComponentModelLU": "PropComponentModelLU", //构件模型 "PropDoc": "PropDoc", //文档 "PropType": "PropType", //分类 "PropAnnexDescription": "PropAnnexDescription" //描述 } } u.unit = unit; //单体对象 u.floor = floor;//楼层 u.discipline = discipline;//模型专业 u.componentClasses = componentClasses;//构件类别 u.componentType = componentType;//构件类型 u.componentModel = componentModel;//构件模型 u.attachments = attachments; //构件附件 u.bimModelDoc = bimModelDoc;//BIM模型文件(模型策划) u.previewModel = previewModel;//模型预览文件 })(md);
'use strict'; // Use applicaion configuration module to register a new module ApplicationConfiguration.registerModule('etc-products');
import React from 'react'; import PropTypes from 'prop-types'; import { AppBar } from 'react-toolbox'; import { Link } from 'react-router'; import Logo from '../logo'; import Navigation from '../navigation'; import style from './style.css'; const MainAppBar = (props) => { let className = style.appbar; if (props.className) className += ` ${props.className}`; return ( <AppBar className={className} flat fixed> <Link to="/"> <Logo className={style.logo} /> </Link> <Navigation activeClassName={style.active} className={style.navigation} /> </AppBar> ); }; MainAppBar.propTypes = { className: PropTypes.string }; MainAppBar.defaultProps = { className: '' }; export default MainAppBar;
const fs = require('fs'); class WriteDllStatsPlugin { constructor({ filePath='./dll/stats.json', dllName='lib' }={}) { this.filePath = filePath this.dllName = dllName } apply(compile){ compile.hooks.emit.tap('WriteDllStats', compile => { try { const stats = compile.getStats().toJson(); fs.writeFileSync( this.filePath, JSON.stringify({ [this.dllName]: stats.assetsByChunkName[this.dllName] }, null, 4) ) } catch(err){ console.log(err.message) } }) } } module.exports = WriteDllStatsPlugin
import React, { Component, PropTypes } from 'react'; import classSet from 'classnames'; class PageButton extends Component { constructor(props) { super(props); } pageBtnClick = e => { e.preventDefault(); this.props.changePage(e.currentTarget.textContent); } render() { const classes = classSet({ 'active': this.props.active, 'disabled': this.props.disable, 'hidden': this.props.hidden }); return ( <li className={ classes }> <a href='#' onClick={ this.pageBtnClick }>{ this.props.children }</a> </li> ); } } PageButton.propTypes = { changePage: PropTypes.func, active: PropTypes.bool, disable: PropTypes.bool, hidden: PropTypes.bool, children: PropTypes.node }; export default PageButton;
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // 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. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],3:[function(require,module,exports){ module.exports = require('./lib/ReactWithAddons'); },{"./lib/ReactWithAddons":94}],4:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusMixin * @typechecks static-only */ "use strict"; var focusNode = require("./focusNode"); var AutoFocusMixin = { componentDidMount: function() { if (this.props.autoFocus) { focusNode(this.getDOMNode()); } } }; module.exports = AutoFocusMixin; },{"./focusNode":128}],5:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var SyntheticInputEvent = require("./SyntheticInputEvent"); var keyOf = require("./keyOf"); var canUseTextInputEvent = ( ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !('documentMode' in document || isPresto()) ); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return ( typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12 ); } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({onBeforeInput: null}), captured: keyOf({onBeforeInputCapture: null}) }, dependencies: [ topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste ] } }; // Track characters inserted via keypress and composition events. var fallbackChars = null; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return ( (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey) ); } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var chars; if (canUseTextInputEvent) { switch (topLevelType) { case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return; } hasSpaceKeypress = true; chars = SPACEBAR_CHAR; break; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return; } // Otherwise, carry on. break; default: // For other native event types, do nothing. return; } } else { switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. fallbackChars = null; break; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { fallbackChars = String.fromCharCode(nativeEvent.which); } break; case topLevelTypes.topCompositionEnd: fallbackChars = nativeEvent.data; break; } // If no changes have occurred to the fallback string, no relevant // event has fired and we're done. if (fallbackChars === null) { return; } chars = fallbackChars; } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return; } var event = SyntheticInputEvent.getPooled( eventTypes.beforeInput, topLevelTargetID, nativeEvent ); event.data = chars; fallbackChars = null; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = BeforeInputEventPlugin; },{"./EventConstants":19,"./EventPropagators":24,"./ExecutionEnvironment":25,"./SyntheticInputEvent":104,"./keyOf":150}],6:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSCore * @typechecks */ var invariant = require("./invariant"); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function(element, className) { ("production" !== process.env.NODE_ENV ? invariant( !/\s/.test(className), 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ) : invariant(!/\s/.test(className))); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function(element, className) { ("production" !== process.env.NODE_ENV ? invariant( !/\s/.test(className), 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ) : invariant(!/\s/.test(className))); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1') .replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to set the class on * @param {string} className the CSS className * @return {boolean} true if the element has the class, false if not */ hasClass: function(element, className) { ("production" !== process.env.NODE_ENV ? invariant( !/\s/.test(className), 'CSS.hasClass takes only a single class name.' ) : invariant(!/\s/.test(className))); if (element.classList) { return !!className && element.classList.contains(className); } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; } }; module.exports = CSSCore; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],7:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ "use strict"; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { columnCount: true, fillOpacity: true, flex: true, flexGrow: true, flexShrink: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function(prop) { prefixes.forEach(function(prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundImage: true, backgroundPosition: true, backgroundRepeat: true, backgroundColor: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],8:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations * @typechecks static-only */ "use strict"; var CSSProperty = require("./CSSProperty"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var camelizeStyleName = require("./camelizeStyleName"); var dangerousStyleValue = require("./dangerousStyleValue"); var hyphenateStyleName = require("./hyphenateStyleName"); var memoizeStringOnly = require("./memoizeStringOnly"); var warning = require("./warning"); var processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }); var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("production" !== process.env.NODE_ENV) { var warnedStyleNames = {}; var warnHyphenatedStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; ("production" !== process.env.NODE_ENV ? warning( false, 'Unsupported style property ' + name + '. Did you mean ' + camelizeStyleName(name) + '?' ) : null); }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function(styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("production" !== process.env.NODE_ENV) { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } } var styleValue = styles[styleName]; if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("production" !== process.env.NODE_ENV) { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; }).call(this,require('_process')) },{"./CSSProperty":7,"./ExecutionEnvironment":25,"./camelizeStyleName":115,"./dangerousStyleValue":122,"./hyphenateStyleName":141,"./memoizeStringOnly":152,"./warning":163,"_process":2}],9:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ "use strict"; var PooledClass = require("./PooledClass"); var assign = require("./Object.assign"); var invariant = require("./invariant"); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function(callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function() { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { ("production" !== process.env.NODE_ENV ? invariant( callbacks.length === contexts.length, "Mismatched list of contexts in callback queue" ) : invariant(callbacks.length === contexts.length)); this._callbacks = null; this._contexts = null; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; }).call(this,require('_process')) },{"./Object.assign":31,"./PooledClass":32,"./invariant":143,"_process":2}],10:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var ReactUpdates = require("./ReactUpdates"); var SyntheticEvent = require("./SyntheticEvent"); var isEventSupported = require("./isEventSupported"); var isTextInputElement = require("./isTextInputElement"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { return ( elem.nodeName === 'SELECT' || (elem.nodeName === 'INPUT' && elem.type === 'file') ); } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && ( !('documentMode' in document) || document.documentMode > 8 ); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled( eventTypes.change, activeElementID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && ( !('documentMode' in document) || document.documentMode > 9 ); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function() { return activeElementValueProp.get.call(this); }, set: function(val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor( target.constructor.prototype, 'value' ); Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return ( elem.nodeName === 'INPUT' && (elem.type === 'checkbox' || elem.type === 'radio') ); } function getTargetIDForClickEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc( topLevelType, topLevelTarget, topLevelTargetID ); if (targetID) { var event = SyntheticEvent.getPooled( eventTypes.change, targetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc( topLevelType, topLevelTarget, topLevelTargetID ); } } }; module.exports = ChangeEventPlugin; },{"./EventConstants":19,"./EventPluginHub":21,"./EventPropagators":24,"./ExecutionEnvironment":25,"./ReactUpdates":93,"./SyntheticEvent":102,"./isEventSupported":144,"./isTextInputElement":146,"./keyOf":150}],11:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ "use strict"; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function() { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],12:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CompositionEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var ReactInputSelection = require("./ReactInputSelection"); var SyntheticCompositionEvent = require("./SyntheticCompositionEvent"); var getTextContentAccessor = require("./getTextContentAccessor"); var keyOf = require("./keyOf"); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var useCompositionEvent = ( ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window ); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. In Korean, for example, // the compositionend event contains only one character regardless of // how many characters have been composed since compositionstart. // We therefore use the fallback data while still using the native // events as triggers. var useFallbackData = ( !useCompositionEvent || ( 'documentMode' in document && document.documentMode > 8 && document.documentMode <= 11 ) ); var topLevelTypes = EventConstants.topLevelTypes; var currentComposition = null; // Events and their corresponding property names. var eventTypes = { compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({onCompositionEnd: null}), captured: keyOf({onCompositionEndCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({onCompositionStart: null}), captured: keyOf({onCompositionStartCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({onCompositionUpdate: null}), captured: keyOf({onCompositionUpdateCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] } }; /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackStart(topLevelType, nativeEvent) { return ( topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE ); } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1); case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return (nativeEvent.keyCode !== START_KEYCODE); case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Helper class stores information about selection and document state * so we can figure out what changed at a later date. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this.root = root; this.startSelection = ReactInputSelection.getSelection(root); this.startValue = this.getText(); } /** * Get current text of input. * * @return {string} */ FallbackCompositionState.prototype.getText = function() { return this.root.value || this.root[getTextContentAccessor()]; }; /** * Text that has changed since the start of composition. * * @return {string} */ FallbackCompositionState.prototype.getData = function() { var endValue = this.getText(); var prefixLength = this.startSelection.start; var suffixLength = this.startValue.length - this.startSelection.end; return endValue.substr( prefixLength, endValue.length - suffixLength - prefixLength ); }; /** * This plugin creates `onCompositionStart`, `onCompositionUpdate` and * `onCompositionEnd` events on inputs, textareas and contentEditable * nodes. */ var CompositionEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var eventType; var data; if (useCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (useFallbackData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = new FallbackCompositionState(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { data = currentComposition.getData(); currentComposition = null; } } } if (eventType) { var event = SyntheticCompositionEvent.getPooled( eventType, topLevelTargetID, nativeEvent ); if (data) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = data; } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } }; module.exports = CompositionEventPlugin; },{"./EventConstants":19,"./EventPropagators":24,"./ExecutionEnvironment":25,"./ReactInputSelection":67,"./SyntheticCompositionEvent":100,"./getTextContentAccessor":138,"./keyOf":150}],13:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations * @typechecks static-only */ "use strict"; var Danger = require("./Danger"); var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes"); var getTextContentAccessor = require("./getTextContentAccessor"); var invariant = require("./invariant"); /** * The DOM property to use when setting text content. * * @type {string} * @private */ var textContentAccessor = getTextContentAccessor(); /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ function insertChildAt(parentNode, childNode, index) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. parentNode.insertBefore( childNode, parentNode.childNodes[index] || null ); } var updateTextContent; if (textContentAccessor === 'textContent') { /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ updateTextContent = function(node, text) { node.textContent = text; }; } else { /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ updateTextContent = function(node, text) { // In order to preserve newlines correctly, we can't use .innerText to set // the contents (see #1080), so we empty the element then append a text node while (node.firstChild) { node.removeChild(node.firstChild); } if (text) { var doc = node.ownerDocument || document; node.appendChild(doc.createTextNode(text)); } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: updateTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function(updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; update = updates[i]; 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; ("production" !== process.env.NODE_ENV ? 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 ) : invariant(updatedChild)); initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; update = updates[k]; 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: updateTextContent( update.parentNode, update.textContent ); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; module.exports = DOMChildrenOperations; }).call(this,require('_process')) },{"./Danger":16,"./ReactMultiChildUpdateTypes":74,"./getTextContentAccessor":138,"./invariant":143,"_process":2}],14:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ "use strict"; var invariant = require("./invariant"); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function(domPropertyConfig) { var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push( domPropertyConfig.isCustomAttribute ); } for (var propName in Properties) { ("production" !== process.env.NODE_ENV ? invariant( !DOMProperty.isStandardName.hasOwnProperty(propName), 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName ) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName))); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; DOMProperty.getPossibleStandardName[attributeName] = propName; DOMProperty.getAttributeName[propName] = attributeName; } else { DOMProperty.getAttributeName[propName] = lowerCased; } DOMProperty.getPropertyName[propName] = DOMPropertyNames.hasOwnProperty(propName) ? DOMPropertyNames[propName] : propName; if (DOMMutationMethods.hasOwnProperty(propName)) { DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; } else { DOMProperty.getMutationMethod[propName] = null; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); DOMProperty.mustUseProperty[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); DOMProperty.hasSideEffects[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); DOMProperty.hasBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); DOMProperty.hasNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); DOMProperty.hasPositiveNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); DOMProperty.hasOverloadedBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE); ("production" !== process.env.NODE_ENV ? invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ) : invariant(!DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName])); ("production" !== process.env.NODE_ENV ? invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ) : invariant(DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName])); ("production" !== process.env.NODE_ENV ? invariant( !!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName ) : invariant(!!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1)); } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be numeric or parse as a * numeric and should be removed when set to a falsey value. * @type {Object} */ hasNumericValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * Whether the property can be used as a flag as well as with a value. Removed * when strictly equal to false; present without a value when strictly equal * to true; present with a value otherwise. * @type {Object} */ hasOverloadedBooleanValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],15:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations * @typechecks static-only */ "use strict"; var DOMProperty = require("./DOMProperty"); var escapeTextForBrowser = require("./escapeTextForBrowser"); var memoizeStringOnly = require("./memoizeStringOnly"); var warning = require("./warning"); function shouldIgnoreValue(name, value) { return value == null || (DOMProperty.hasBooleanValue[name] && !value) || (DOMProperty.hasNumericValue[name] && isNaN(value)) || (DOMProperty.hasPositiveNumericValue[name] && (value < 1)) || (DOMProperty.hasOverloadedBooleanValue[name] && value === false); } var processAttributeNameAndPrefix = memoizeStringOnly(function(name) { return escapeTextForBrowser(name) + '="'; }); if ("production" !== process.env.NODE_ENV) { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function(name) { if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = ( DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null ); // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. ("production" !== process.env.NODE_ENV ? warning( standardName == null, 'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?' ) : null); }; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function(id) { return processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) + escapeTextForBrowser(id) + '"'; }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function(name, value) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { if (shouldIgnoreValue(name, value)) { return ''; } var attributeName = DOMProperty.getAttributeName[name]; if (DOMProperty.hasBooleanValue[name] || (DOMProperty.hasOverloadedBooleanValue[name] && value === true)) { return escapeTextForBrowser(attributeName); } return processAttributeNameAndPrefix(attributeName) + escapeTextForBrowser(value) + '"'; } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return processAttributeNameAndPrefix(name) + escapeTextForBrowser(value) + '"'; } else if ("production" !== process.env.NODE_ENV) { warnUnknownProperty(name); } return null; }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function(node, name, value) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(name, value)) { this.deleteValueForProperty(node, name); } else if (DOMProperty.mustUseAttribute[name]) { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. node.setAttribute(DOMProperty.getAttributeName[name], '' + value); } else { var propName = DOMProperty.getPropertyName[name]; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== ('' + value)) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } } else if ("production" !== process.env.NODE_ENV) { warnUnknownProperty(name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function(node, name) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, undefined); } else if (DOMProperty.mustUseAttribute[name]) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { var propName = DOMProperty.getPropertyName[name]; var defaultValue = DOMProperty.getDefaultValueForProperty( node.nodeName, propName ); if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if ("production" !== process.env.NODE_ENV) { warnUnknownProperty(name); } } }; module.exports = DOMPropertyOperations; }).call(this,require('_process')) },{"./DOMProperty":14,"./escapeTextForBrowser":126,"./memoizeStringOnly":152,"./warning":163,"_process":2}],16:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger * @typechecks static-only */ /*jslint evil: true, sub: true */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var createNodesFromMarkup = require("./createNodesFromMarkup"); var emptyFunction = require("./emptyFunction"); var getMarkupWrap = require("./getMarkupWrap"); var invariant = require("./invariant"); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function(markupList) { ("production" !== process.env.NODE_ENV ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== process.env.NODE_ENV ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. for (var resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (i = 0; i < renderNodes.length; ++i) { var renderNode = renderNodes[i]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== process.env.NODE_ENV ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== process.env.NODE_ENV) { console.error( "Danger: Discarding unexpected node:", renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== process.env.NODE_ENV ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== process.env.NODE_ENV ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) { ("production" !== process.env.NODE_ENV ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== process.env.NODE_ENV ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup)); ("production" !== process.env.NODE_ENV ? invariant( oldChild.tagName.toLowerCase() !== 'html', 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See renderComponentToString().' ) : invariant(oldChild.tagName.toLowerCase() !== 'html')); var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; }).call(this,require('_process')) },{"./ExecutionEnvironment":25,"./createNodesFromMarkup":120,"./emptyFunction":124,"./getMarkupWrap":135,"./invariant":143,"_process":2}],17:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ "use strict"; var keyOf = require("./keyOf"); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [ keyOf({ResponderEventPlugin: null}), keyOf({SimpleEventPlugin: null}), keyOf({TapEventPlugin: null}), keyOf({EnterLeaveEventPlugin: null}), keyOf({ChangeEventPlugin: null}), keyOf({SelectEventPlugin: null}), keyOf({CompositionEventPlugin: null}), keyOf({BeforeInputEventPlugin: null}), keyOf({AnalyticsEventPlugin: null}), keyOf({MobileSafariClickEventPlugin: null}) ]; module.exports = DefaultEventPluginOrder; },{"./keyOf":150}],18:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var SyntheticMouseEvent = require("./SyntheticMouseEvent"); var ReactMount = require("./ReactMount"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({onMouseEnter: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] }, mouseLeave: { registrationName: keyOf({onMouseLeave: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] } }; var extractedEvents = [null, null]; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from, to; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) || win; } else { from = win; to = topLevelTarget; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromID = from ? ReactMount.getID(from) : ''; var toID = to ? ReactMount.getID(to) : ''; var leave = SyntheticMouseEvent.getPooled( eventTypes.mouseLeave, fromID, nativeEvent ); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled( eventTypes.mouseEnter, toID, nativeEvent ); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; },{"./EventConstants":19,"./EventPropagators":24,"./ReactMount":72,"./SyntheticMouseEvent":106,"./keyOf":150}],19:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ "use strict"; var keyMirror = require("./keyMirror"); var PropagationPhases = keyMirror({bubbled: null, captured: null}); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topBlur: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topReset: null, topScroll: null, topSelectionChange: null, topSubmit: null, topTextInput: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"./keyMirror":149}],20:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventListener * @typechecks */ var emptyFunction = require("./emptyFunction"); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function(target, eventType, callback) { if (!target.addEventListener) { if ("production" !== process.env.NODE_ENV) { console.error( 'Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.' ); } return { remove: emptyFunction }; } else { target.addEventListener(eventType, callback, true); return { remove: function() { target.removeEventListener(eventType, callback, true); } }; } }, registerDefault: function() {} }; module.exports = EventListener; }).call(this,require('_process')) },{"./emptyFunction":124,"_process":2}],21:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ "use strict"; var EventPluginRegistry = require("./EventPluginRegistry"); var EventPluginUtils = require("./EventPluginUtils"); var accumulateInto = require("./accumulateInto"); var forEachAccumulated = require("./forEachAccumulated"); var invariant = require("./invariant"); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ var executeDispatchesAndRelease = function(event) { if (event) { var executeDispatch = EventPluginUtils.executeDispatch; // Plugins can provide custom behavior when dispatching events. var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event); if (PluginModule && PluginModule.executeDispatch) { executeDispatch = PluginModule.executeDispatch; } EventPluginUtils.executeDispatchesInOrder(event, executeDispatch); if (!event.isPersistent()) { event.constructor.release(event); } } }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var invalid = !InstanceHandle|| !InstanceHandle.traverseTwoPhase || !InstanceHandle.traverseEnterLeave; if (invalid) { throw new Error('InstanceHandle not injected before use!'); } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function(InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if ("production" !== process.env.NODE_ENV) { validateInstanceHandle(); } }, getInstanceHandle: function() { if ("production" !== process.env.NODE_ENV) { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function(id, registrationName, listener) { ("production" !== process.env.NODE_ENV ? invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function(id) { for (var registrationName in listenerBank) { delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0, l = plugins.length; i < l; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function(events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function() { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; forEachAccumulated(processingEventQueue, executeDispatchesAndRelease); ("production" !== process.env.NODE_ENV ? invariant( !eventQueue, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.' ) : invariant(!eventQueue)); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; }).call(this,require('_process')) },{"./EventPluginRegistry":22,"./EventPluginUtils":23,"./accumulateInto":112,"./forEachAccumulated":129,"./invariant":143,"_process":2}],22:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry * @typechecks static-only */ "use strict"; var invariant = require("./invariant"); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); ("production" !== process.env.NODE_ENV ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== process.env.NODE_ENV ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== process.env.NODE_ENV ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { ("production" !== process.env.NODE_ENV ? invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName))); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName ); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { ("production" !== process.env.NODE_ENV ? invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName ) : invariant(!EventPluginRegistry.registrationNameModules[registrationName])); EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function(InjectedEventPluginOrder) { ("production" !== process.env.NODE_ENV ? invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.' ) : invariant(!EventPluginOrder)); // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function(injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { ("production" !== process.env.NODE_ENV ? invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName ) : invariant(!namesToPlugins[pluginName])); namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function(event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[ dispatchConfig.phasedRegistrationNames[phase] ]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function() { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],23:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ "use strict"; var EventConstants = require("./EventConstants"); var invariant = require("./invariant"); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function(InjectedMount) { injection.Mount = InjectedMount; if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? invariant( InjectedMount && InjectedMount.getNode, 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' + 'is missing getNode.' ) : invariant(InjectedMount && InjectedMount.getNode)); } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("production" !== process.env.NODE_ENV) { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; ("production" !== process.env.NODE_ENV ? invariant( idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.' ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen)); }; } /** * Invokes `cb(event, listener, id)`. Avoids using call if no scope is * provided. The `(listener,id)` pair effectively forms the "dispatch" but are * kept separate to conserve memory. */ function forEachEventDispatch(event, cb) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== process.env.NODE_ENV) { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. cb(event, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { cb(event, dispatchListeners, dispatchIDs); } } /** * Default implementation of PluginModule.executeDispatch(). * @param {SyntheticEvent} SyntheticEvent to handle * @param {function} Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, listener, domID) { event.currentTarget = injection.Mount.getNode(domID); var returnValue = listener(event, domID); event.currentTarget = null; return returnValue; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, executeDispatch) { forEachEventDispatch(event, executeDispatch); event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return id of the first dispatch execution who's listener returns true, or * null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== process.env.NODE_ENV) { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("production" !== process.env.NODE_ENV) { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; ("production" !== process.env.NODE_ENV ? invariant( !Array.isArray(dispatchListener), 'executeDirectDispatch(...): Invalid `event`.' ) : invariant(!Array.isArray(dispatchListener))); var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {bool} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatch: executeDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, injection: injection, useTouchEvents: false }; module.exports = EventPluginUtils; }).call(this,require('_process')) },{"./EventConstants":19,"./invariant":143,"_process":2}],24:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var accumulateInto = require("./accumulateInto"); var forEachAccumulated = require("./forEachAccumulated"); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(domID, upwards, event) { if ("production" !== process.env.NODE_ENV) { if (!domID) { throw new Error('Dispatching id must not be null'); } } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We can not perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase( event.dispatchMarker, accumulateDirectionalDispatches, event ); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave( fromID, toID, accumulateDispatches, leave, enter ); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; }).call(this,require('_process')) },{"./EventConstants":19,"./EventPluginHub":21,"./accumulateInto":112,"./forEachAccumulated":129,"_process":2}],25:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],26:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = require("./DOMProperty"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var hasSVG; if (ExecutionEnvironment.canUseDOM) { var implementation = document.implementation; hasSVG = ( implementation && implementation.hasFeature && implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1' ) ); } var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, acceptCharset: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusMixin // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, coords: null, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, frameBorder: MUST_USE_ATTRIBUTE, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, label: null, lang: null, list: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, manifest: MUST_USE_ATTRIBUTE, max: null, maxLength: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, noValidate: HAS_BOOLEAN_VALUE, open: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, tabIndex: null, target: null, title: null, type: null, useMap: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ autoCapitalize: null, // Supported in Mobile Safari for keyboard hints autoCorrect: null, // Supported in Mobile Safari for keyboard hints itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html property: null // Supports OG in meta tags }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', encType: 'enctype', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; },{"./DOMProperty":14,"./ExecutionEnvironment":25}],27:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedStateMixin * @typechecks static-only */ "use strict"; var ReactLink = require("./ReactLink"); var ReactStateSetters = require("./ReactStateSetters"); /** * A simple mixin around ReactLink.forState(). */ var LinkedStateMixin = { /** * Create a ReactLink that's linked to part of this component's state. The * ReactLink will have the current value of this.state[key] and will call * setState() when a change is requested. * * @param {string} key state key to update. Note: you may want to use keyOf() * if you're using Google Closure Compiler advanced mode. * @return {ReactLink} ReactLink instance linking to the state. */ linkState: function(key) { return new ReactLink( this.state[key], ReactStateSetters.createStateKeySetter(this, key) ); } }; module.exports = LinkedStateMixin; },{"./ReactLink":70,"./ReactStateSetters":87}],28:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils * @typechecks static-only */ "use strict"; var ReactPropTypes = require("./ReactPropTypes"); var invariant = require("./invariant"); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(input) { ("production" !== process.env.NODE_ENV ? invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.' ) : invariant(input.props.checkedLink == null || input.props.valueLink == null)); } function _assertValueLink(input) { _assertSingleLink(input); ("production" !== process.env.NODE_ENV ? invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.' ) : invariant(input.props.value == null && input.props.onChange == null)); } function _assertCheckedLink(input) { _assertSingleLink(input); ("production" !== process.env.NODE_ENV ? invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink' ) : invariant(input.props.checked == null && input.props.onChange == null)); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedValueChange(e) { /*jshint validthis:true */ this.props.valueLink.requestChange(e.target.value); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { Mixin: { propTypes: { value: function(props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return; } return new Error( 'You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); }, checked: function(props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return; } return new Error( 'You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); }, onChange: ReactPropTypes.func } }, /** * @param {ReactComponent} input Form component * @return {*} current value of the input either from value prop or link. */ getValue: function(input) { if (input.props.valueLink) { _assertValueLink(input); return input.props.valueLink.value; } return input.props.value; }, /** * @param {ReactComponent} input Form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { _assertValueLink(input); return _handleLinkedValueChange; } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; } return input.props.onChange; } }; module.exports = LinkedValueUtils; }).call(this,require('_process')) },{"./ReactPropTypes":81,"./invariant":143,"_process":2}],29:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LocalEventTrapMixin */ "use strict"; var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var accumulateInto = require("./accumulateInto"); var forEachAccumulated = require("./forEachAccumulated"); var invariant = require("./invariant"); function remove(event) { event.remove(); } var LocalEventTrapMixin = { trapBubbledEvent:function(topLevelType, handlerBaseName) { ("production" !== process.env.NODE_ENV ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted())); var listener = ReactBrowserEventEmitter.trapBubbledEvent( topLevelType, handlerBaseName, this.getDOMNode() ); this._localEventListeners = accumulateInto(this._localEventListeners, listener); }, // trapCapturedEvent would look nearly identical. We don't implement that // method because it isn't currently needed. componentWillUnmount:function() { if (this._localEventListeners) { forEachAccumulated(this._localEventListeners, remove); } } }; module.exports = LocalEventTrapMixin; }).call(this,require('_process')) },{"./ReactBrowserEventEmitter":35,"./accumulateInto":112,"./forEachAccumulated":129,"./invariant":143,"_process":2}],30:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule MobileSafariClickEventPlugin * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var emptyFunction = require("./emptyFunction"); var topLevelTypes = EventConstants.topLevelTypes; /** * Mobile Safari does not fire properly bubble click events on non-interactive * elements, which means delegated click listeners do not fire. The workaround * for this bug involves attaching an empty click listener on the target node. * * This particular plugin works around the bug by attaching an empty click * listener on `touchstart` (which does fire on every element). */ var MobileSafariClickEventPlugin = { eventTypes: null, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topTouchStart) { var target = nativeEvent.target; if (target && !target.onclick) { target.onclick = emptyFunction; } } } }; module.exports = MobileSafariClickEventPlugin; },{"./EventConstants":19,"./emptyFunction":124}],31:[function(require,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; }; module.exports = assign; },{}],32:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ "use strict"; var invariant = require("./invariant"); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function(a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function(a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fiveArgumentPooler = function(a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function(instance) { var Klass = this; ("production" !== process.env.NODE_ENV ? invariant( instance instanceof Klass, 'Trying to release an instance into a pool of a different type.' ) : invariant(instance instanceof Klass)); if (instance.destructor) { instance.destructor(); } if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function(CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],33:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ "use strict"; var DOMPropertyOperations = require("./DOMPropertyOperations"); var EventPluginUtils = require("./EventPluginUtils"); var ReactChildren = require("./ReactChildren"); var ReactComponent = require("./ReactComponent"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactDOM = require("./ReactDOM"); var ReactDOMComponent = require("./ReactDOMComponent"); var ReactDefaultInjection = require("./ReactDefaultInjection"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactLegacyElement = require("./ReactLegacyElement"); var ReactMount = require("./ReactMount"); var ReactMultiChild = require("./ReactMultiChild"); var ReactPerf = require("./ReactPerf"); var ReactPropTypes = require("./ReactPropTypes"); var ReactServerRendering = require("./ReactServerRendering"); var ReactTextComponent = require("./ReactTextComponent"); var assign = require("./Object.assign"); var deprecated = require("./deprecated"); var onlyChild = require("./onlyChild"); ReactDefaultInjection.inject(); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; if ("production" !== process.env.NODE_ENV) { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; } // TODO: Drop legacy elements once classes no longer export these factories createElement = ReactLegacyElement.wrapCreateElement( createElement ); createFactory = ReactLegacyElement.wrapCreateFactory( createFactory ); var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, only: onlyChild }, DOM: ReactDOM, PropTypes: ReactPropTypes, initializeTouchEvents: function(shouldUseTouch) { EventPluginUtils.useTouchEvents = shouldUseTouch; }, createClass: ReactCompositeComponent.createClass, createElement: createElement, createFactory: createFactory, constructAndRenderComponent: ReactMount.constructAndRenderComponent, constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID, render: render, renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, unmountComponentAtNode: ReactMount.unmountComponentAtNode, isValidClass: ReactLegacyElement.isValidClass, isValidElement: ReactElement.isValidElement, withContext: ReactContext.withContext, // Hook for JSX spread, don't use this for anything else. __spread: assign, // Deprecations (remove for 0.13) renderComponent: deprecated( 'React', 'renderComponent', 'render', this, render ), renderComponentToString: deprecated( 'React', 'renderComponentToString', 'renderToString', this, ReactServerRendering.renderToString ), renderComponentToStaticMarkup: deprecated( 'React', 'renderComponentToStaticMarkup', 'renderToStaticMarkup', this, ReactServerRendering.renderToStaticMarkup ), isValidComponent: deprecated( 'React', 'isValidComponent', 'isValidElement', this, ReactElement.isValidElement ) }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ Component: ReactComponent, CurrentOwner: ReactCurrentOwner, DOMComponent: ReactDOMComponent, DOMPropertyOperations: DOMPropertyOperations, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, MultiChild: ReactMultiChild, TextComponent: ReactTextComponent }); } if ("production" !== process.env.NODE_ENV) { var ExecutionEnvironment = require("./ExecutionEnvironment"); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // If we're in Chrome, look for the devtools marker and provide a download // link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { console.debug( 'Download the React DevTools for a better development experience: ' + 'http://fb.me/react-devtools' ); } } var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze ]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error( 'One or more ES5 shim/shams expected by React are not available: ' + 'http://fb.me/react-warning-polyfills' ); break; } } } } // Version exists only in the open-source version of React, not in Facebook's // internal version. React.version = '0.12.1'; module.exports = React; }).call(this,require('_process')) },{"./DOMPropertyOperations":15,"./EventPluginUtils":23,"./ExecutionEnvironment":25,"./Object.assign":31,"./ReactChildren":38,"./ReactComponent":39,"./ReactCompositeComponent":42,"./ReactContext":43,"./ReactCurrentOwner":44,"./ReactDOM":45,"./ReactDOMComponent":47,"./ReactDefaultInjection":57,"./ReactElement":60,"./ReactElementValidator":61,"./ReactInstanceHandles":68,"./ReactLegacyElement":69,"./ReactMount":72,"./ReactMultiChild":73,"./ReactPerf":77,"./ReactPropTypes":81,"./ReactServerRendering":85,"./ReactTextComponent":89,"./deprecated":123,"./onlyChild":154,"_process":2}],34:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserComponentMixin */ "use strict"; var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactMount = require("./ReactMount"); var invariant = require("./invariant"); var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function() { ("production" !== process.env.NODE_ENV ? invariant( this.isMounted(), 'getDOMNode(): A component must be mounted to have a DOM node.' ) : invariant(this.isMounted())); if (ReactEmptyComponent.isNullComponentID(this._rootNodeID)) { return null; } return ReactMount.getNode(this._rootNodeID); } }; module.exports = ReactBrowserComponentMixin; }).call(this,require('_process')) },{"./ReactEmptyComponent":62,"./ReactMount":72,"./invariant":143,"_process":2}],35:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPluginRegistry = require("./EventPluginRegistry"); var ReactEventEmitterMixin = require("./ReactEventEmitterMixin"); var ViewportMetrics = require("./ViewportMetrics"); var assign = require("./Object.assign"); var isEventSupported = require("./isEventSupported"); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled() ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!( isListening.hasOwnProperty(dependency) && isListening[dependency] )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'mousewheel', mountAt ); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topBlur, 'blur', mountAt ); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topBlur, 'focusout', mountAt ); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function(){ if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter; },{"./EventConstants":19,"./EventPluginHub":21,"./EventPluginRegistry":22,"./Object.assign":31,"./ReactEventEmitterMixin":64,"./ViewportMetrics":111,"./isEventSupported":144}],36:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroup */ "use strict"; var React = require("./React"); var assign = require("./Object.assign"); var ReactTransitionGroup = React.createFactory( require("./ReactTransitionGroup") ); var ReactCSSTransitionGroupChild = React.createFactory( require("./ReactCSSTransitionGroupChild") ); var ReactCSSTransitionGroup = React.createClass({ displayName: 'ReactCSSTransitionGroup', propTypes: { transitionName: React.PropTypes.string.isRequired, transitionEnter: React.PropTypes.bool, transitionLeave: React.PropTypes.bool }, getDefaultProps: function() { return { transitionEnter: true, transitionLeave: true }; }, _wrapChild: function(child) { // We need to provide this childFactory so that // ReactCSSTransitionGroupChild can receive updates to name, enter, and // leave while it is leaving. return ReactCSSTransitionGroupChild( { name: this.props.transitionName, enter: this.props.transitionEnter, leave: this.props.transitionLeave }, child ); }, render: function() { return ( ReactTransitionGroup( assign({}, this.props, {childFactory: this._wrapChild}) ) ); } }); module.exports = ReactCSSTransitionGroup; },{"./Object.assign":31,"./React":33,"./ReactCSSTransitionGroupChild":37,"./ReactTransitionGroup":92}],37:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroupChild */ "use strict"; var React = require("./React"); var CSSCore = require("./CSSCore"); var ReactTransitionEvents = require("./ReactTransitionEvents"); var onlyChild = require("./onlyChild"); // We don't remove the element from the DOM until we receive an animationend or // transitionend event. If the user screws up and forgets to add an animation // their node will be stuck in the DOM forever, so we detect if an animation // does not start and if it doesn't, we just call the end listener immediately. var TICK = 17; var NO_EVENT_TIMEOUT = 5000; var noEventListener = null; if ("production" !== process.env.NODE_ENV) { noEventListener = function() { console.warn( 'transition(): tried to perform an animation without ' + 'an animationend or transitionend event after timeout (' + NO_EVENT_TIMEOUT + 'ms). You should either disable this ' + 'transition in JS or add a CSS animation/transition.' ); }; } var ReactCSSTransitionGroupChild = React.createClass({ displayName: 'ReactCSSTransitionGroupChild', transition: function(animationType, finishCallback) { var node = this.getDOMNode(); var className = this.props.name + '-' + animationType; var activeClassName = className + '-active'; var noEventTimeout = null; var endListener = function(e) { if (e && e.target !== node) { return; } if ("production" !== process.env.NODE_ENV) { clearTimeout(noEventTimeout); } CSSCore.removeClass(node, className); CSSCore.removeClass(node, activeClassName); ReactTransitionEvents.removeEndEventListener(node, endListener); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. finishCallback && finishCallback(); }; ReactTransitionEvents.addEndEventListener(node, endListener); CSSCore.addClass(node, className); // Need to do this to actually trigger a transition. this.queueClass(activeClassName); if ("production" !== process.env.NODE_ENV) { noEventTimeout = setTimeout(noEventListener, NO_EVENT_TIMEOUT); } }, queueClass: function(className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this.flushClassNameQueue, TICK); } }, flushClassNameQueue: function() { if (this.isMounted()) { this.classNameQueue.forEach( CSSCore.addClass.bind(CSSCore, this.getDOMNode()) ); } this.classNameQueue.length = 0; this.timeout = null; }, componentWillMount: function() { this.classNameQueue = []; }, componentWillUnmount: function() { if (this.timeout) { clearTimeout(this.timeout); } }, componentWillEnter: function(done) { if (this.props.enter) { this.transition('enter', done); } else { done(); } }, componentWillLeave: function(done) { if (this.props.leave) { this.transition('leave', done); } else { done(); } }, render: function() { return onlyChild(this.props.children); } }); module.exports = ReactCSSTransitionGroupChild; }).call(this,require('_process')) },{"./CSSCore":6,"./React":33,"./ReactTransitionEvents":91,"./onlyChild":154,"_process":2}],38:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ "use strict"; var PooledClass = require("./PooledClass"); var traverseAllChildren = require("./traverseAllChildren"); var warning = require("./warning"); var twoArgumentPooler = PooledClass.twoArgumentPooler; var threeArgumentPooler = PooledClass.threeArgumentPooler; /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.forEachFunction = forEachFunction; this.forEachContext = forEachContext; } PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(traverseContext, child, name, i) { var forEachBookKeeping = traverseContext; forEachBookKeeping.forEachFunction.call( forEachBookKeeping.forEachContext, child, i); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, mapFunction, mapContext) { this.mapResult = mapResult; this.mapFunction = mapFunction; this.mapContext = mapContext; } PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler); function mapSingleChildIntoContext(traverseContext, child, name, i) { var mapBookKeeping = traverseContext; var mapResult = mapBookKeeping.mapResult; var keyUnique = !mapResult.hasOwnProperty(name); ("production" !== process.env.NODE_ENV ? warning( keyUnique, 'ReactChildren.map(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); if (keyUnique) { var mappedChild = mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i); mapResult[name] = mappedChild; } } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * TODO: This may likely break any calls to `ReactChildren.map` that were * previously relying on the fact that we guarded against null children. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var mapResult = {}; var traverseContext = MapBookKeeping.getPooled(mapResult, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); return mapResult; } function forEachSingleChildDummy(traverseContext, child, name, i) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } var ReactChildren = { forEach: forEachChildren, map: mapChildren, count: countChildren }; module.exports = ReactChildren; }).call(this,require('_process')) },{"./PooledClass":32,"./traverseAllChildren":161,"./warning":163,"_process":2}],39:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ "use strict"; var ReactElement = require("./ReactElement"); var ReactOwner = require("./ReactOwner"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); /** * Every React component is in one of these life cycles. */ var ComponentLifeCycle = keyMirror({ /** * Mounted components have a DOM node representation and are capable of * receiving new props. */ MOUNTED: null, /** * Unmounted components are inactive and cannot receive new props. */ UNMOUNTED: null }); var injected = false; /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. * * @private */ var unmountIDFromEnvironment = null; /** * The "image" of a component tree, is the platform specific (typically * serialized) data that represents a tree of lower level UI building blocks. * On the web, this "image" is HTML markup which describes a construction of * low level `div` and `span` nodes. Other platforms may have different * encoding of this "image". This must be injected. * * @private */ var mountImageIntoNode = null; /** * Components are the basic units of composition in React. * * Every component accepts a set of keyed input parameters known as "props" that * are initialized by the constructor. Once a component is mounted, the props * can be mutated using `setProps` or `replaceProps`. * * Every component is capable of the following operations: * * `mountComponent` * Initializes the component, renders markup, and registers event listeners. * * `receiveComponent` * Updates the rendered DOM nodes to match the given component. * * `unmountComponent` * Releases any resources allocated by this component. * * Components can also be "owned" by other components. Being owned by another * component means being constructed by that component. This is different from * being the child of a component, which means having a DOM representation that * is a child of the DOM representation of that component. * * @class ReactComponent */ var ReactComponent = { injection: { injectEnvironment: function(ReactComponentEnvironment) { ("production" !== process.env.NODE_ENV ? invariant( !injected, 'ReactComponent: injectEnvironment() can only be called once.' ) : invariant(!injected)); mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode; unmountIDFromEnvironment = ReactComponentEnvironment.unmountIDFromEnvironment; ReactComponent.BackendIDOperations = ReactComponentEnvironment.BackendIDOperations; injected = true; } }, /** * @internal */ LifeCycle: ComponentLifeCycle, /** * Injected module that provides ability to mutate individual properties. * Injected into the base class because many different subclasses need access * to this. * * @internal */ BackendIDOperations: null, /** * Base functionality for every ReactComponent constructor. Mixed into the * `ReactComponent` prototype, but exposed statically for easy access. * * @lends {ReactComponent.prototype} */ Mixin: { /** * Checks whether or not this component is mounted. * * @return {boolean} True if mounted, false otherwise. * @final * @protected */ isMounted: function() { return this._lifeCycleState === ComponentLifeCycle.MOUNTED; }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public */ setProps: function(partialProps, callback) { // Merge with the pending element if it exists, otherwise with existing // element props. var element = this._pendingElement || this._currentElement; this.replaceProps( assign({}, element.props, partialProps), callback ); }, /** * Replaces all of the props. * * @param {object} props New props. * @param {?function} callback Called after props are updated. * @final * @public */ replaceProps: function(props, callback) { ("production" !== process.env.NODE_ENV ? invariant( this.isMounted(), 'replaceProps(...): Can only update a mounted component.' ) : invariant(this.isMounted())); ("production" !== process.env.NODE_ENV ? invariant( this._mountDepth === 0, 'replaceProps(...): You called `setProps` or `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(this._mountDepth === 0)); // This is a deoptimized path. We optimize for always having a element. // This creates an extra internal element. this._pendingElement = ReactElement.cloneAndReplaceProps( this._pendingElement || this._currentElement, props ); ReactUpdates.enqueueUpdate(this, callback); }, /** * Schedule a partial update to the props. Only used for internal testing. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @internal */ _setPropsInternal: function(partialProps, callback) { // This is a deoptimized path. We optimize for always having a element. // This creates an extra internal element. var element = this._pendingElement || this._currentElement; this._pendingElement = ReactElement.cloneAndReplaceProps( element, assign({}, element.props, partialProps) ); ReactUpdates.enqueueUpdate(this, callback); }, /** * Base constructor for all React components. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.construct.call(this, ...)`. * * @param {ReactElement} element * @internal */ construct: function(element) { // This is the public exposed props object after it has been processed // with default props. The element's props represents the true internal // state of the props. this.props = element.props; // Record the component responsible for creating this component. // This is accessible through the element but we maintain an extra // field for compatibility with devtools and as a way to make an // incremental update. TODO: Consider deprecating this field. this._owner = element._owner; // All components start unmounted. this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; // See ReactUpdates. this._pendingCallbacks = null; // We keep the old element and a reference to the pending element // to track updates. this._currentElement = element; this._pendingElement = null; }, /** * Initializes the component, renders markup, and registers event listeners. * * NOTE: This does not insert any nodes into the DOM. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.mountComponent.call(this, ...)`. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy. * @return {?string} Rendered markup to be inserted into the DOM. * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ("production" !== process.env.NODE_ENV ? invariant( !this.isMounted(), 'mountComponent(%s, ...): Can only mount an unmounted component. ' + 'Make sure to avoid storing components between renders or reusing a ' + 'single component instance in multiple places.', rootID ) : invariant(!this.isMounted())); var ref = this._currentElement.ref; if (ref != null) { var owner = this._currentElement._owner; ReactOwner.addComponentAsRefTo(this, ref, owner); } this._rootNodeID = rootID; this._lifeCycleState = ComponentLifeCycle.MOUNTED; this._mountDepth = mountDepth; // Effectively: return ''; }, /** * Releases any resources allocated by `mountComponent`. * * NOTE: This does not remove any nodes from the DOM. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.unmountComponent.call(this)`. * * @internal */ unmountComponent: function() { ("production" !== process.env.NODE_ENV ? invariant( this.isMounted(), 'unmountComponent(): Can only unmount a mounted component.' ) : invariant(this.isMounted())); var ref = this._currentElement.ref; if (ref != null) { ReactOwner.removeComponentAsRefFrom(this, ref, this._owner); } unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; }, /** * Given a new instance of this component, updates the rendered DOM nodes * as if that instance was rendered instead. * * Subclasses that override this method should make sure to invoke * `ReactComponent.Mixin.receiveComponent.call(this, ...)`. * * @param {object} nextComponent Next set of properties. * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextElement, transaction) { ("production" !== process.env.NODE_ENV ? invariant( this.isMounted(), 'receiveComponent(...): Can only update a mounted component.' ) : invariant(this.isMounted())); this._pendingElement = nextElement; this.performUpdateIfNecessary(transaction); }, /** * If `_pendingElement` is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { if (this._pendingElement == null) { return; } var prevElement = this._currentElement; var nextElement = this._pendingElement; this._currentElement = nextElement; this.props = nextElement.props; this._owner = nextElement._owner; this._pendingElement = null; this.updateComponent(transaction, prevElement); }, /** * Updates the component's currently mounted representation. * * @param {ReactReconcileTransaction} transaction * @param {object} prevElement * @internal */ updateComponent: function(transaction, prevElement) { var nextElement = this._currentElement; // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. if (nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref) { if (prevElement.ref != null) { ReactOwner.removeComponentAsRefFrom( this, prevElement.ref, prevElement._owner ); } // Correct, even if the owner is the same, and only the ref has changed. if (nextElement.ref != null) { ReactOwner.addComponentAsRefTo( this, nextElement.ref, nextElement._owner ); } } }, /** * Mounts this component and inserts it into the DOM. * * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup * @final * @internal * @see {ReactMount.render} */ mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( this._mountComponentIntoNode, this, rootID, container, transaction, shouldReuseMarkup ); ReactUpdates.ReactReconcileTransaction.release(transaction); }, /** * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup * @final * @private */ _mountComponentIntoNode: function( rootID, container, transaction, shouldReuseMarkup) { var markup = this.mountComponent(rootID, transaction, 0); mountImageIntoNode(markup, container, shouldReuseMarkup); }, /** * Checks if this component is owned by the supplied `owner` component. * * @param {ReactComponent} owner Component to check. * @return {boolean} True if `owners` owns this component. * @final * @internal */ isOwnedBy: function(owner) { return this._owner === owner; }, /** * Gets another component, that shares the same owner as this one, by ref. * * @param {string} ref of a sibling Component. * @return {?ReactComponent} the actual sibling Component. * @final * @internal */ getSiblingByRef: function(ref) { var owner = this._owner; if (!owner || !owner.refs) { return null; } return owner.refs[ref]; } } }; module.exports = ReactComponent; }).call(this,require('_process')) },{"./Object.assign":31,"./ReactElement":60,"./ReactOwner":76,"./ReactUpdates":93,"./invariant":143,"./keyMirror":149,"_process":2}],40:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ /*jslint evil: true */ "use strict"; var ReactDOMIDOperations = require("./ReactDOMIDOperations"); var ReactMarkupChecksum = require("./ReactMarkupChecksum"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var ReactReconcileTransaction = require("./ReactReconcileTransaction"); var getReactRootElementInContainer = require("./getReactRootElementInContainer"); var invariant = require("./invariant"); var setInnerHTML = require("./setInnerHTML"); var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** * Abstracts away all functionality of `ReactComponent` requires knowledge of * the browser context. */ var ReactComponentBrowserEnvironment = { ReactReconcileTransaction: ReactReconcileTransaction, BackendIDOperations: ReactDOMIDOperations, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function(rootNodeID) { ReactMount.purgeID(rootNodeID); }, /** * @param {string} markup Markup string to place into the DOM Element. * @param {DOMElement} container DOM Element to insert markup into. * @param {boolean} shouldReuseMarkup Should reuse the existing markup in the * container if possible. */ mountImageIntoNode: ReactPerf.measure( 'ReactComponentBrowserEnvironment', 'mountImageIntoNode', function(markup, container, shouldReuseMarkup) { ("production" !== process.env.NODE_ENV ? invariant( container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ), 'mountComponentIntoNode(...): Target container is not valid.' ) : invariant(container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ))); if (shouldReuseMarkup) { if (ReactMarkupChecksum.canReuseMarkup( markup, getReactRootElementInContainer(container))) { return; } else { ("production" !== process.env.NODE_ENV ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); if ("production" !== process.env.NODE_ENV) { console.warn( 'React attempted to use reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server.' ); } } } ("production" !== process.env.NODE_ENV ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See renderComponentToString() for server rendering.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); setInnerHTML(container, markup); } ) }; module.exports = ReactComponentBrowserEnvironment; }).call(this,require('_process')) },{"./ReactDOMIDOperations":49,"./ReactMarkupChecksum":71,"./ReactMount":72,"./ReactPerf":77,"./ReactReconcileTransaction":83,"./getReactRootElementInContainer":137,"./invariant":143,"./setInnerHTML":157,"_process":2}],41:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ "use strict"; var shallowEqual = require("./shallowEqual"); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this Mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; },{"./shallowEqual":158}],42:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactErrorUtils = require("./ReactErrorUtils"); var ReactLegacyElement = require("./ReactLegacyElement"); var ReactOwner = require("./ReactOwner"); var ReactPerf = require("./ReactPerf"); var ReactPropTransferer = require("./ReactPropTransferer"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var instantiateReactComponent = require("./instantiateReactComponent"); var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); var keyOf = require("./keyOf"); var monitorCodeUse = require("./monitorCodeUse"); var mapObject = require("./mapObject"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); var warning = require("./warning"); var MIXINS_KEY = keyOf({mixins: null}); /** * Policies that describe methods in `ReactCompositeComponentInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base ReactCompositeComponent class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactCompositeComponent`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will available on the prototype. * * @interface ReactCompositeComponentInterface * @internal */ var ReactCompositeComponentInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); Constructor.childContextTypes = assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.context ); Constructor.contextTypes = assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); Constructor.propTypes = assign( {}, Constructor.propTypes, propTypes ); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); } }; function getDeclarationErrorAddendum(component) { var owner = component._owner || null; if (owner && owner.constructor && owner.constructor.displayName) { return ' Check the render method of `' + owner.constructor.displayName + '`.'; } return ''; } function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { ("production" !== process.env.NODE_ENV ? invariant( typeof typeDef[propName] == 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactCompositeComponent', ReactPropTypeLocationNames[location], propName ) : invariant(typeof typeDef[propName] == 'function')); } } } function validateMethodOverride(proto, name) { var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ? ReactCompositeComponentInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactCompositeComponentMixin.hasOwnProperty(name)) { ("production" !== process.env.NODE_ENV ? invariant( specPolicy === SpecPolicy.OVERRIDE_BASE, 'ReactCompositeComponentInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE)); } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { ("production" !== process.env.NODE_ENV ? invariant( specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED, 'ReactCompositeComponentInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED)); } } function validateLifeCycleOnReplaceState(instance) { var compositeLifeCycleState = instance._compositeLifeCycleState; ("production" !== process.env.NODE_ENV ? invariant( instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'replaceState(...): Can only update a mounted or mounting component.' ) : invariant(instance.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== process.env.NODE_ENV ? invariant( ReactCurrentOwner.current == null, 'replaceState(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.' ) : invariant(ReactCurrentOwner.current == null)); ("production" !== process.env.NODE_ENV ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, 'replaceState(...): Cannot update while unmounting component. This ' + 'usually means you called setState() on an unmounted component.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING)); } /** * Mixin helper which handles policy validation and reserved * specification keys when building `ReactCompositeComponent` classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } ("production" !== process.env.NODE_ENV ? invariant( !ReactLegacyElement.isValidFactory(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(!ReactLegacyElement.isValidFactory(spec))); ("production" !== process.env.NODE_ENV ? invariant( !ReactElement.isValidElement(spec), 'ReactCompositeComponent: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactElement.isValidElement(spec))); var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactCompositeComponent methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isCompositeComponentMethod = ReactCompositeComponentInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isCompositeComponentMethod && !isAlreadyDefined && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactCompositeComponentInterface[name]; // These cases should already be caught by validateMethodOverride ("production" !== process.env.NODE_ENV ? invariant( isCompositeComponentMethod && ( specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY ), 'ReactCompositeComponent: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ) : invariant(isCompositeComponentMethod && ( specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY ))); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("production" !== process.env.NODE_ENV) { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; ("production" !== process.env.NODE_ENV ? invariant( !isReserved, 'ReactCompositeComponent: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ) : invariant(!isReserved)); var isInherited = name in Constructor; ("production" !== process.env.NODE_ENV ? invariant( !isInherited, 'ReactCompositeComponent: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ) : invariant(!isInherited)); Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeObjectsWithNoDuplicateKeys(one, two) { ("production" !== process.env.NODE_ENV ? invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects' ) : invariant(one && two && typeof one === 'object' && typeof two === 'object')); mapObject(two, function(value, key) { ("production" !== process.env.NODE_ENV ? invariant( one[key] === undefined, 'mergeObjectsWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ) : invariant(one[key] === undefined)); one[key] = value; }); return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } return mergeObjectsWithNoDuplicateKeys(a, b); }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * `ReactCompositeComponent` maintains an auxiliary life cycle state in * `this._compositeLifeCycleState` (which can be null). * * This is different from the life cycle state maintained by `ReactComponent` in * `this._lifeCycleState`. The following diagram shows how the states overlap in * time. There are times when the CompositeLifeCycle is null - at those times it * is only meaningful to look at ComponentLifeCycle alone. * * Top Row: ReactComponent.ComponentLifeCycle * Low Row: ReactComponent.CompositeLifeCycle * * +-------+---------------------------------+--------+ * | UN | MOUNTED | UN | * |MOUNTED| | MOUNTED| * +-------+---------------------------------+--------+ * | ^--------+ +-------+ +--------^ | * | | | | | | | | * | 0--|MOUNTING|-0-|RECEIVE|-0-| UN |--->0 | * | | | |PROPS | |MOUNTING| | * | | | | | | | | * | | | | | | | | * | +--------+ +-------+ +--------+ | * | | | | * +-------+---------------------------------+--------+ */ var CompositeLifeCycle = keyMirror({ /** * Components in the process of being mounted respond to state changes * differently. */ MOUNTING: null, /** * Components in the process of being unmounted are guarded against state * changes. */ UNMOUNTING: null, /** * Components that are mounted and receiving new props respond to state * changes differently. */ RECEIVING_PROPS: null }); /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function(element) { // Children can be either an array or more than one argument ReactComponent.Mixin.construct.apply(this, arguments); ReactOwner.Mixin.construct.apply(this, arguments); this.state = null; this._pendingState = null; // This is the public post-processed context. The real context and pending // context lives on the element. this.context = null; this._compositeLifeCycleState = null; }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { return ReactComponent.Mixin.isMounted.call(this) && this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: ReactPerf.measure( 'ReactCompositeComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; if (this.__reactAutoBindMap) { this._bindAutoBindMethods(); } this.context = this._processContext(this._currentElement._context); this.props = this._processProps(this.props); this.state = this.getInitialState ? this.getInitialState() : null; ("production" !== process.env.NODE_ENV ? invariant( typeof this.state === 'object' && !Array.isArray(this.state), '%s.getInitialState(): must return an object or null', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof this.state === 'object' && !Array.isArray(this.state))); this._pendingState = null; this._pendingForceUpdate = false; if (this.componentWillMount) { this.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingState` without triggering a re-render. if (this._pendingState) { this.state = this._pendingState; this._pendingState = null; } } this._renderedComponent = instantiateReactComponent( this._renderValidatedComponent(), this._currentElement.type // The wrapping type ); // Done with mounting, `setState` will now trigger UI changes. this._compositeLifeCycleState = null; var markup = this._renderedComponent.mountComponent( rootID, transaction, mountDepth + 1 ); if (this.componentDidMount) { transaction.getReactMountReady().enqueue(this.componentDidMount, this); } return markup; } ), /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function() { this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING; if (this.componentWillUnmount) { this.componentWillUnmount(); } this._compositeLifeCycleState = null; this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); // Some existing components rely on this.props even after they've been // destroyed (in event handlers). // TODO: this.props = null; // TODO: this.state = null; }, /** * Sets a subset of the state. Always use this or `replaceState` to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after state is updated. * @final * @protected */ setState: function(partialState, callback) { ("production" !== process.env.NODE_ENV ? invariant( typeof partialState === 'object' || partialState == null, 'setState(...): takes an object of state variables to update.' ) : invariant(typeof partialState === 'object' || partialState == null)); if ("production" !== process.env.NODE_ENV){ ("production" !== process.env.NODE_ENV ? warning( partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ) : null); } // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( assign({}, this._pendingState || this.state, partialState), callback ); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {object} completeState Next state. * @param {?function} callback Called after state is updated. * @final * @protected */ replaceState: function(completeState, callback) { validateLifeCycleOnReplaceState(this); this._pendingState = completeState; if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) { // If we're in a componentWillMount handler, don't enqueue a rerender // because ReactUpdates assumes we're in a browser context (which is wrong // for server rendering) and we're about to do a render anyway. // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. ReactUpdates.enqueueUpdate(this, callback); } }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function(context) { var maskedContext = null; var contextTypes = this.constructor.contextTypes; if (contextTypes) { maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } if ("production" !== process.env.NODE_ENV) { this._checkPropTypes( contextTypes, maskedContext, ReactPropTypeLocations.context ); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function(currentContext) { var childContext = this.getChildContext && this.getChildContext(); var displayName = this.constructor.displayName || 'ReactCompositeComponent'; if (childContext) { ("production" !== process.env.NODE_ENV ? invariant( typeof this.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', displayName ) : invariant(typeof this.constructor.childContextTypes === 'object')); if ("production" !== process.env.NODE_ENV) { this._checkPropTypes( this.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { ("production" !== process.env.NODE_ENV ? invariant( name in this.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', displayName, name ) : invariant(name in this.constructor.childContextTypes)); } return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { if ("production" !== process.env.NODE_ENV) { var propTypes = this.constructor.propTypes; if (propTypes) { this._checkPropTypes(propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.constructor.displayName; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName, location); if (error instanceof Error) { // We may want to extend this logic for similar errors in // renderComponent calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); ("production" !== process.env.NODE_ENV ? warning(false, error.message + addendum) : null); } } } }, /** * If any of `_pendingElement`, `_pendingState`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { var compositeLifeCycleState = this._compositeLifeCycleState; // Do not trigger a state transition if we are in the middle of mounting or // receiving props because both of those will already be doing this. if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING || compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) { return; } if (this._pendingElement == null && this._pendingState == null && !this._pendingForceUpdate) { return; } var nextContext = this.context; var nextProps = this.props; var nextElement = this._currentElement; if (this._pendingElement != null) { nextElement = this._pendingElement; nextContext = this._processContext(nextElement._context); nextProps = this._processProps(nextElement.props); this._pendingElement = null; this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS; if (this.componentWillReceiveProps) { this.componentWillReceiveProps(nextProps, nextContext); } } this._compositeLifeCycleState = null; var nextState = this._pendingState || this.state; this._pendingState = null; var shouldUpdate = this._pendingForceUpdate || !this.shouldComponentUpdate || this.shouldComponentUpdate(nextProps, nextState, nextContext); if ("production" !== process.env.NODE_ENV) { if (typeof shouldUpdate === "undefined") { console.warn( (this.constructor.displayName || 'ReactCompositeComponent') + '.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.' ); } } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( nextElement, nextProps, nextState, nextContext, transaction ); } else { // If it's determined that a component should not update, we still want // to set props and state. this._currentElement = nextElement; this.props = nextProps; this.state = nextState; this.context = nextContext; // Owner cannot change because shouldUpdateReactComponent doesn't allow // it. TODO: Remove this._owner completely. this._owner = nextElement._owner; } }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @private */ _performComponentUpdate: function( nextElement, nextProps, nextState, nextContext, transaction ) { var prevElement = this._currentElement; var prevProps = this.props; var prevState = this.state; var prevContext = this.context; if (this.componentWillUpdate) { this.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this.props = nextProps; this.state = nextState; this.context = nextContext; // Owner cannot change because shouldUpdateReactComponent doesn't allow // it. TODO: Remove this._owner completely. this._owner = nextElement._owner; this.updateComponent( transaction, prevElement ); if (this.componentDidUpdate) { transaction.getReactMountReady().enqueue( this.componentDidUpdate.bind(this, prevProps, prevState, prevContext), this ); } }, receiveComponent: function(nextElement, transaction) { if (nextElement === this._currentElement && nextElement._owner != null) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for a element created outside a composite to be // deeply mutated and reused. return; } ReactComponent.Mixin.receiveComponent.call( this, nextElement, transaction ); }, /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactCompositeComponent', 'updateComponent', function(transaction, prevParentElement) { ReactComponent.Mixin.updateComponent.call( this, transaction, prevParentElement ); var prevComponentInstance = this._renderedComponent; var prevElement = prevComponentInstance._currentElement; var nextElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevElement, nextElement)) { prevComponentInstance.receiveComponent(nextElement, transaction); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; prevComponentInstance.unmountComponent(); this._renderedComponent = instantiateReactComponent( nextElement, this._currentElement.type ); var nextMarkup = this._renderedComponent.mountComponent( thisID, transaction, this._mountDepth + 1 ); ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID( prevComponentID, nextMarkup ); } } ), /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldUpdateComponent`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ forceUpdate: function(callback) { var compositeLifeCycleState = this._compositeLifeCycleState; ("production" !== process.env.NODE_ENV ? invariant( this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING, 'forceUpdate(...): Can only force an update on mounted or mounting ' + 'components.' ) : invariant(this.isMounted() || compositeLifeCycleState === CompositeLifeCycle.MOUNTING)); ("production" !== process.env.NODE_ENV ? invariant( compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING && ReactCurrentOwner.current == null, 'forceUpdate(...): Cannot force an update while unmounting component ' + 'or within a `render` function.' ) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING && ReactCurrentOwner.current == null)); this._pendingForceUpdate = true; ReactUpdates.enqueueUpdate(this, callback); }, /** * @private */ _renderValidatedComponent: ReactPerf.measure( 'ReactCompositeComponent', '_renderValidatedComponent', function() { var renderedComponent; var previousContext = ReactContext.current; ReactContext.current = this._processChildContext( this._currentElement._context ); ReactCurrentOwner.current = this; try { renderedComponent = this.render(); if (renderedComponent === null || renderedComponent === false) { renderedComponent = ReactEmptyComponent.getEmptyComponent(); ReactEmptyComponent.registerNullComponentID(this._rootNodeID); } else { ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID); } } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.constructor.displayName || 'ReactCompositeComponent' ) : invariant(ReactElement.isValidElement(renderedComponent))); return renderedComponent; } ), /** * @private */ _bindAutoBindMethods: function() { for (var autoBindKey in this.__reactAutoBindMap) { if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { continue; } var method = this.__reactAutoBindMap[autoBindKey]; this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard( method, this.constructor.displayName + '.' + autoBindKey )); } }, /** * Binds a method to the component. * * @param {function} method Method to be bound. * @private */ _bindAutoBindMethod: function(method) { var component = this; var boundMethod = method.bind(component); if ("production" !== process.env.NODE_ENV) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): React component methods may only be bound to the ' + 'component instance. See ' + componentName ); } else if (!args.length) { monitorCodeUse('react_bind_warning', { component: componentName }); console.warn( 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See ' + componentName ); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } }; var ReactCompositeComponentBase = function() {}; assign( ReactCompositeComponentBase.prototype, ReactComponent.Mixin, ReactOwner.Mixin, ReactPropTransferer.Mixin, ReactCompositeComponentMixin ); /** * Module for creating composite components. * * @class ReactCompositeComponent * @extends ReactComponent * @extends ReactOwner * @extends ReactPropTransferer */ var ReactCompositeComponent = { LifeCycle: CompositeLifeCycle, Base: ReactCompositeComponentBase, /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function(props) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. This will later be used // by the stand-alone class implementation. }; Constructor.prototype = new ReactCompositeComponentBase(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } ("production" !== process.env.NODE_ENV ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== process.env.NODE_ENV) { if (Constructor.prototype.componentShouldUpdate) { monitorCodeUse( 'react_component_should_update_warning', { component: spec.displayName } ); console.warn( (spec.displayName || 'A component') + ' has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.' ); } } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactCompositeComponentInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } if ("production" !== process.env.NODE_ENV) { return ReactLegacyElement.wrapFactory( ReactElementValidator.createFactory(Constructor) ); } return ReactLegacyElement.wrapFactory( ReactElement.createFactory(Constructor) ); }, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactCompositeComponent; }).call(this,require('_process')) },{"./Object.assign":31,"./ReactComponent":39,"./ReactContext":43,"./ReactCurrentOwner":44,"./ReactElement":60,"./ReactElementValidator":61,"./ReactEmptyComponent":62,"./ReactErrorUtils":63,"./ReactLegacyElement":69,"./ReactOwner":76,"./ReactPerf":77,"./ReactPropTransferer":78,"./ReactPropTypeLocationNames":79,"./ReactPropTypeLocations":80,"./ReactUpdates":93,"./instantiateReactComponent":142,"./invariant":143,"./keyMirror":149,"./keyOf":150,"./mapObject":151,"./monitorCodeUse":153,"./shouldUpdateReactComponent":159,"./warning":163,"_process":2}],43:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ "use strict"; var assign = require("./Object.assign"); /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: {}, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; },{"./Object.assign":31}],44:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ "use strict"; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],45:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM * @typechecks static-only */ "use strict"; var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactLegacyElement = require("./ReactLegacyElement"); var mapObject = require("./mapObject"); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if ("production" !== process.env.NODE_ENV) { return ReactLegacyElement.markNonLegacyFactory( ReactElementValidator.createFactory(tag) ); } return ReactLegacyElement.markNonLegacyFactory( ReactElement.createFactory(tag) ); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOM = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', hr: 'hr', html: 'html', i: 'i', iframe: 'iframe', img: 'img', input: 'input', ins: 'ins', kbd: 'kbd', keygen: 'keygen', label: 'label', legend: 'legend', li: 'li', link: 'link', main: 'main', map: 'map', mark: 'mark', menu: 'menu', menuitem: 'menuitem', meta: 'meta', meter: 'meter', nav: 'nav', noscript: 'noscript', object: 'object', ol: 'ol', optgroup: 'optgroup', option: 'option', output: 'output', p: 'p', param: 'param', picture: 'picture', pre: 'pre', progress: 'progress', q: 'q', rp: 'rp', rt: 'rt', ruby: 'ruby', s: 's', samp: 'samp', script: 'script', section: 'section', select: 'select', small: 'small', source: 'source', span: 'span', strong: 'strong', style: 'style', sub: 'sub', summary: 'summary', sup: 'sup', table: 'table', tbody: 'tbody', td: 'td', textarea: 'textarea', tfoot: 'tfoot', th: 'th', thead: 'thead', time: 'time', title: 'title', tr: 'tr', track: 'track', u: 'u', ul: 'ul', 'var': 'var', video: 'video', wbr: 'wbr', // SVG circle: 'circle', defs: 'defs', ellipse: 'ellipse', g: 'g', line: 'line', linearGradient: 'linearGradient', mask: 'mask', path: 'path', pattern: 'pattern', polygon: 'polygon', polyline: 'polyline', radialGradient: 'radialGradient', rect: 'rect', stop: 'stop', svg: 'svg', text: 'text', tspan: 'tspan' }, createDOMFactory); module.exports = ReactDOM; }).call(this,require('_process')) },{"./ReactElement":60,"./ReactElementValidator":61,"./ReactLegacyElement":69,"./mapObject":151,"_process":2}],46:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); var keyMirror = require("./keyMirror"); // Store a reference to the <button> `ReactDOMComponent`. TODO: use string var button = ReactElement.createFactory(ReactDOM.button.type); var mouseListenerNames = keyMirror({ onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = ReactCompositeComponent.createClass({ displayName: 'ReactDOMButton', mixins: [AutoFocusMixin, ReactBrowserComponentMixin], render: function() { var props = {}; // Copy the props; except the mouse listeners if we're disabled for (var key in this.props) { if (this.props.hasOwnProperty(key) && (!this.props.disabled || !mouseListenerNames[key])) { props[key] = this.props[key]; } } return button(props, this.props.children); } }); module.exports = ReactDOMButton; },{"./AutoFocusMixin":4,"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60,"./keyMirror":149}],47:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent * @typechecks static-only */ "use strict"; var CSSPropertyOperations = require("./CSSPropertyOperations"); var DOMProperty = require("./DOMProperty"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactComponent = require("./ReactComponent"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactMount = require("./ReactMount"); var ReactMultiChild = require("./ReactMultiChild"); var ReactPerf = require("./ReactPerf"); var assign = require("./Object.assign"); var escapeTextForBrowser = require("./escapeTextForBrowser"); var invariant = require("./invariant"); var isEventSupported = require("./isEventSupported"); var keyOf = require("./keyOf"); var monitorCodeUse = require("./monitorCodeUse"); var deleteListener = ReactBrowserEventEmitter.deleteListener; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; var STYLE = keyOf({style: null}); var ELEMENT_NODE_TYPE = 1; /** * @param {?object} props */ function assertValidProps(props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. ("production" !== process.env.NODE_ENV ? invariant( props.children == null || props.dangerouslySetInnerHTML == null, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.' ) : invariant(props.children == null || props.dangerouslySetInnerHTML == null)); if ("production" !== process.env.NODE_ENV) { if (props.contentEditable && props.children != null) { console.warn( 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of those '+ 'nodes are unexpectedly modified or duplicated. This is probably not ' + 'intentional.' ); } } ("production" !== process.env.NODE_ENV ? invariant( props.style == null || typeof props.style === 'object', 'The `style` prop expects a mapping from style properties to values, ' + 'not a string.' ) : invariant(props.style == null || typeof props.style === 'object')); } function putListener(id, registrationName, listener, transaction) { if ("production" !== process.env.NODE_ENV) { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. if (registrationName === 'onScroll' && !isEventSupported('scroll', true)) { monitorCodeUse('react_no_scroll_event'); console.warn('This browser doesn\'t support the `onScroll` event'); } } var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getPutListenerQueue().enqueuePutListener( id, registrationName, listener ); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // We accept any tag to be rendered but since this gets injected into abitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { ("production" !== process.env.NODE_ENV ? invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag) : invariant(VALID_TAG_REGEX.test(tag))); validatedTagCache[tag] = true; } } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag; this.tagName = tag.toUpperCase(); } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {string} The computed markup. */ mountComponent: ReactPerf.measure( 'ReactDOMComponent', 'mountComponent', function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); assertValidProps(this.props); var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>'; return ( this._createOpenTagMarkupAndPutListeners(transaction) + this._createContentMarkup(transaction) + closeTag ); } ), /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction) { var props = this.props; var ret = '<' + this._tag; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { putListener(this._rootNodeID, propKey, propValue, transaction); } else { if (propKey === STYLE) { if (propValue) { propValue = props.style = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret + '>'; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID + '>'; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Content markup. */ _createContentMarkup: function(transaction) { // Intentional use of != to avoid catching zero/false. var innerHTML = this.props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof this.props.children] ? this.props.children : null; var childrenToUse = contentToUse != null ? null : this.props.children; if (contentToUse != null) { return escapeTextForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren( childrenToUse, transaction ); return mountImages.join(''); } } return ''; }, receiveComponent: function(nextElement, transaction) { if (nextElement === this._currentElement && nextElement._owner != null) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for a element created outside a composite to be // deeply mutated and reused. return; } ReactComponent.Mixin.receiveComponent.call( this, nextElement, transaction ); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @internal * @overridable */ updateComponent: ReactPerf.measure( 'ReactDOMComponent', 'updateComponent', function(transaction, prevElement) { assertValidProps(this._currentElement.props); ReactComponent.Mixin.updateComponent.call( this, transaction, prevElement ); this._updateDOMProperties(prevElement.props, transaction); this._updateDOMChildren(prevElement.props, transaction); } ), /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMProperties: function(lastProps, transaction) { var nextProps = this.props; var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[propKey]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } } else if (registrationNameModules.hasOwnProperty(propKey)) { deleteListener(this._rootNodeID, propKey); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.BackendIDOperations.deletePropertyByID( this._rootNodeID, propKey ); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { nextProp = nextProps.style = assign({}, nextProp); } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { putListener(this._rootNodeID, propKey, nextProp, transaction); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.BackendIDOperations.updatePropertyByID( this._rootNodeID, propKey, nextProp ); } } if (styleUpdates) { ReactComponent.BackendIDOperations.updateStylesByID( this._rootNodeID, styleUpdates ); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMChildren: function(lastProps, transaction) { var nextProps = this.props; var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { ReactComponent.BackendIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function() { this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponent.Mixin.unmountComponent.call(this); } }; assign( ReactDOMComponent.prototype, ReactComponent.Mixin, ReactDOMComponent.Mixin, ReactMultiChild.Mixin, ReactBrowserComponentMixin ); module.exports = ReactDOMComponent; }).call(this,require('_process')) },{"./CSSPropertyOperations":8,"./DOMProperty":14,"./DOMPropertyOperations":15,"./Object.assign":31,"./ReactBrowserComponentMixin":34,"./ReactBrowserEventEmitter":35,"./ReactComponent":39,"./ReactMount":72,"./ReactMultiChild":73,"./ReactPerf":77,"./escapeTextForBrowser":126,"./invariant":143,"./isEventSupported":144,"./keyOf":150,"./monitorCodeUse":153,"_process":2}],48:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMForm */ "use strict"; var EventConstants = require("./EventConstants"); var LocalEventTrapMixin = require("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); // Store a reference to the <form> `ReactDOMComponent`. TODO: use string var form = ReactElement.createFactory(ReactDOM.form.type); /** * Since onSubmit doesn't bubble OR capture on the top level in IE8, we need * to capture it on the <form> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <form> a * composite component and use `componentDidMount` to attach the event handlers. */ var ReactDOMForm = ReactCompositeComponent.createClass({ displayName: 'ReactDOMForm', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { // TODO: Instead of using `ReactDOM` directly, we should use JSX. However, // `jshint` fails to parse JSX so in order for linting to work in the open // source repo, we need to just use `ReactDOM.form`. return form(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset'); this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit'); } }); module.exports = ReactDOMForm; },{"./EventConstants":19,"./LocalEventTrapMixin":29,"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60}],49:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ /*jslint evil: true */ "use strict"; var CSSPropertyOperations = require("./CSSPropertyOperations"); var DOMChildrenOperations = require("./DOMChildrenOperations"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var invariant = require("./invariant"); var setInnerHTML = require("./setInnerHTML"); /** * Errors for properties that should not be updated with `updatePropertyById()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactComponent.BackendIDOperations`. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updatePropertyByID', function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== process.env.NODE_ENV ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } } ), /** * Updates a DOM node to remove a property. This should only be used to remove * DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A property name to remove, see `DOMProperty`. * @internal */ deletePropertyByID: ReactPerf.measure( 'ReactDOMIDOperations', 'deletePropertyByID', function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== process.env.NODE_ENV ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); DOMPropertyOperations.deleteValueForProperty(node, name, value); } ), /** * Updates a DOM node with new style values. If a value is specified as '', * the corresponding style property will be unset. * * @param {string} id ID of the node to update. * @param {object} styles Mapping from styles to values. * @internal */ updateStylesByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateStylesByID', function(id, styles) { var node = ReactMount.getNode(id); CSSPropertyOperations.setValueForStyles(node, styles); } ), /** * Updates a DOM node's innerHTML. * * @param {string} id ID of the node to update. * @param {string} html An HTML string. * @internal */ updateInnerHTMLByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateInnerHTMLByID', function(id, html) { var node = ReactMount.getNode(id); setInnerHTML(node, html); } ), /** * Updates a DOM node's text content set by `props.content`. * * @param {string} id ID of the node to update. * @param {string} content Text content. * @internal */ updateTextContentByID: ReactPerf.measure( 'ReactDOMIDOperations', 'updateTextContentByID', function(id, content) { var node = ReactMount.getNode(id); DOMChildrenOperations.updateTextContent(node, content); } ), /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: ReactPerf.measure( 'ReactDOMIDOperations', 'dangerouslyReplaceNodeWithMarkupByID', function(id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); } ), /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: ReactPerf.measure( 'ReactDOMIDOperations', 'dangerouslyProcessChildrenUpdates', function(updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } ) }; module.exports = ReactDOMIDOperations; }).call(this,require('_process')) },{"./CSSPropertyOperations":8,"./DOMChildrenOperations":13,"./DOMPropertyOperations":15,"./ReactMount":72,"./ReactPerf":77,"./invariant":143,"./setInnerHTML":157,"_process":2}],50:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMImg */ "use strict"; var EventConstants = require("./EventConstants"); var LocalEventTrapMixin = require("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); // Store a reference to the <img> `ReactDOMComponent`. TODO: use string var img = ReactElement.createFactory(ReactDOM.img.type); /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <img> element itself. There are lots of hacks we could do * to accomplish this, but the most reliable is to make <img> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMImg = ReactCompositeComponent.createClass({ displayName: 'ReactDOMImg', tagName: 'IMG', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { return img(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load'); this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error'); } }); module.exports = ReactDOMImg; },{"./EventConstants":19,"./LocalEventTrapMixin":29,"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60}],51:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); var ReactMount = require("./ReactMount"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var invariant = require("./invariant"); // Store a reference to the <input> `ReactDOMComponent`. TODO: use string var input = ReactElement.createFactory(ReactDOM.input.type); var instancesByReactID = {}; function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = ReactCompositeComponent.createClass({ displayName: 'ReactDOMInput', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; return { initialChecked: this.props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.defaultChecked = null; props.defaultValue = null; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.initialValue; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.initialChecked; props.onChange = this._handleChange; return input(props, this.props.children); }, componentDidMount: function() { var id = ReactMount.getID(this.getDOMNode()); instancesByReactID[id] = this; }, componentWillUnmount: function() { var rootNode = this.getDOMNode(); var id = ReactMount.getID(rootNode); delete instancesByReactID[id]; }, componentDidUpdate: function(prevProps, prevState, prevContext) { var rootNode = this.getDOMNode(); if (this.props.checked != null) { DOMPropertyOperations.setValueForProperty( rootNode, 'checked', this.props.checked || false ); } var value = LinkedValueUtils.getValue(this); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = this.props.name; if (this.props.type === 'radio' && name != null) { var rootNode = this.getDOMNode(); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll( 'input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0, groupLen = group.length; i < groupLen; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherID = ReactMount.getID(otherNode); ("production" !== process.env.NODE_ENV ? invariant( otherID, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.' ) : invariant(otherID)); var otherInstance = instancesByReactID[otherID]; ("production" !== process.env.NODE_ENV ? invariant( otherInstance, 'ReactDOMInput: Unknown radio button ID %s.', otherID ) : invariant(otherInstance)); // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } }); module.exports = ReactDOMInput; }).call(this,require('_process')) },{"./AutoFocusMixin":4,"./DOMPropertyOperations":15,"./LinkedValueUtils":28,"./Object.assign":31,"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60,"./ReactMount":72,"./ReactUpdates":93,"./invariant":143,"_process":2}],52:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ "use strict"; var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); var warning = require("./warning"); // Store a reference to the <option> `ReactDOMComponent`. TODO: use string var option = ReactElement.createFactory(ReactDOM.option.type); /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = ReactCompositeComponent.createClass({ displayName: 'ReactDOMOption', mixins: [ReactBrowserComponentMixin], componentWillMount: function() { // TODO (yungsters): Remove support for `selected` in <option>. if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( this.props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ) : null); } }, render: function() { return option(this.props, this.props.children); } }); module.exports = ReactDOMOption; }).call(this,require('_process')) },{"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60,"./warning":163,"_process":2}],53:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); // Store a reference to the <select> `ReactDOMComponent`. TODO: use string var select = ReactElement.createFactory(ReactDOM.select.type); function updateWithPendingValueIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.setState({value: this._pendingValue}); this._pendingValue = 0; } } /** * Validation function for `value` and `defaultValue`. * @private */ function selectValueType(props, propName, componentName) { if (props[propName] == null) { return; } if (props.multiple) { if (!Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be an array if ") + ("`multiple` is true.") ); } } else { if (Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be a scalar ") + ("value if `multiple` is false.") ); } } } /** * If `value` is supplied, updates <option> elements on mount and update. * @param {ReactComponent} component Instance of ReactDOMSelect * @param {?*} propValue For uncontrolled components, null/undefined. For * controlled components, a string (or with `multiple`, a list of strings). * @private */ function updateOptions(component, propValue) { var multiple = component.props.multiple; var value = propValue != null ? propValue : component.state.value; var options = component.getDOMNode().options; var selectedValue, i, l; if (multiple) { selectedValue = {}; for (i = 0, l = value.length; i < l; ++i) { selectedValue['' + value[i]] = true; } } else { selectedValue = '' + value; } for (i = 0, l = options.length; i < l; i++) { var selected = multiple ? selectedValue.hasOwnProperty(options[i].value) : options[i].value === selectedValue; if (selected !== options[i].selected) { options[i].selected = selected; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * string. If `multiple` is true, the prop must be an array of strings. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = ReactCompositeComponent.createClass({ displayName: 'ReactDOMSelect', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], propTypes: { defaultValue: selectValueType, value: selectValueType }, getInitialState: function() { return {value: this.props.defaultValue || (this.props.multiple ? [] : '')}; }, componentWillMount: function() { this._pendingValue = null; }, componentWillReceiveProps: function(nextProps) { if (!this.props.multiple && nextProps.multiple) { this.setState({value: [this.state.value]}); } else if (this.props.multiple && !nextProps.multiple) { this.setState({value: this.state.value[0]}); } }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.onChange = this._handleChange; props.value = null; return select(props, this.props.children); }, componentDidMount: function() { updateOptions(this, LinkedValueUtils.getValue(this)); }, componentDidUpdate: function(prevProps) { var value = LinkedValueUtils.getValue(this); var prevMultiple = !!prevProps.multiple; var multiple = !!this.props.multiple; if (value != null || prevMultiple !== multiple) { updateOptions(this, value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } var selectedValue; if (this.props.multiple) { selectedValue = []; var options = event.target.options; for (var i = 0, l = options.length; i < l; i++) { if (options[i].selected) { selectedValue.push(options[i].value); } } } else { selectedValue = event.target.value; } this._pendingValue = selectedValue; ReactUpdates.asap(updateWithPendingValueIfMounted, this); return returnValue; } }); module.exports = ReactDOMSelect; },{"./AutoFocusMixin":4,"./LinkedValueUtils":28,"./Object.assign":31,"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60,"./ReactUpdates":93}],54:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var getNodeForCharacterOffset = require("./getNodeForCharacterOffset"); var getTextContentAccessor = require("./getTextContentAccessor"); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed( selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset ); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed( tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset ); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && document.selection; var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"./ExecutionEnvironment":25,"./getNodeForCharacterOffset":136,"./getTextContentAccessor":138}],55:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ "use strict"; var AutoFocusMixin = require("./AutoFocusMixin"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var ReactDOM = require("./ReactDOM"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var warning = require("./warning"); // Store a reference to the <textarea> `ReactDOMComponent`. TODO: use string var textarea = ReactElement.createFactory(ReactDOM.textarea.type); function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = ReactCompositeComponent.createClass({ displayName: 'ReactDOMTextarea', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = this.props.children; if (children != null) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.' ) : null); } ("production" !== process.env.NODE_ENV ? invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.' ) : invariant(defaultValue == null)); if (Array.isArray(children)) { ("production" !== process.env.NODE_ENV ? invariant( children.length <= 1, '<textarea> can only have at most one child.' ) : invariant(children.length <= 1)); children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(this); return { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue) }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); ("production" !== process.env.NODE_ENV ? invariant( props.dangerouslySetInnerHTML == null, '`dangerouslySetInnerHTML` does not make sense on <textarea>.' ) : invariant(props.dangerouslySetInnerHTML == null)); props.defaultValue = null; props.value = null; props.onChange = this._handleChange; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. return textarea(props, this.state.initialValue); }, componentDidUpdate: function(prevProps, prevState, prevContext) { var value = LinkedValueUtils.getValue(this); if (value != null) { var rootNode = this.getDOMNode(); // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } }); module.exports = ReactDOMTextarea; }).call(this,require('_process')) },{"./AutoFocusMixin":4,"./DOMPropertyOperations":15,"./LinkedValueUtils":28,"./Object.assign":31,"./ReactBrowserComponentMixin":34,"./ReactCompositeComponent":42,"./ReactDOM":45,"./ReactElement":60,"./ReactUpdates":93,"./invariant":143,"./warning":163,"_process":2}],56:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ "use strict"; var ReactUpdates = require("./ReactUpdates"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function() { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } assign( ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; } } ); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, a, b) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b); } else { transaction.perform(callback, null, a, b); } } }; module.exports = ReactDefaultBatchingStrategy; },{"./Object.assign":31,"./ReactUpdates":93,"./Transaction":110,"./emptyFunction":124}],57:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ "use strict"; var BeforeInputEventPlugin = require("./BeforeInputEventPlugin"); var ChangeEventPlugin = require("./ChangeEventPlugin"); var ClientReactRootIndex = require("./ClientReactRootIndex"); var CompositionEventPlugin = require("./CompositionEventPlugin"); var DefaultEventPluginOrder = require("./DefaultEventPluginOrder"); var EnterLeaveEventPlugin = require("./EnterLeaveEventPlugin"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var HTMLDOMPropertyConfig = require("./HTMLDOMPropertyConfig"); var MobileSafariClickEventPlugin = require("./MobileSafariClickEventPlugin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactComponentBrowserEnvironment = require("./ReactComponentBrowserEnvironment"); var ReactDefaultBatchingStrategy = require("./ReactDefaultBatchingStrategy"); var ReactDOMComponent = require("./ReactDOMComponent"); var ReactDOMButton = require("./ReactDOMButton"); var ReactDOMForm = require("./ReactDOMForm"); var ReactDOMImg = require("./ReactDOMImg"); var ReactDOMInput = require("./ReactDOMInput"); var ReactDOMOption = require("./ReactDOMOption"); var ReactDOMSelect = require("./ReactDOMSelect"); var ReactDOMTextarea = require("./ReactDOMTextarea"); var ReactEventListener = require("./ReactEventListener"); var ReactInjection = require("./ReactInjection"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var SelectEventPlugin = require("./SelectEventPlugin"); var ServerReactRootIndex = require("./ServerReactRootIndex"); var SimpleEventPlugin = require("./SimpleEventPlugin"); var SVGDOMPropertyConfig = require("./SVGDOMPropertyConfig"); var createFullPageComponent = require("./createFullPageComponent"); function inject() { ReactInjection.EventEmitter.injectReactEventListener( ReactEventListener ); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, CompositionEventPlugin: CompositionEventPlugin, MobileSafariClickEventPlugin: MobileSafariClickEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass( ReactDOMComponent ); ReactInjection.NativeComponent.injectComponentClasses({ 'button': ReactDOMButton, 'form': ReactDOMForm, 'img': ReactDOMImg, 'input': ReactDOMInput, 'option': ReactDOMOption, 'select': ReactDOMSelect, 'textarea': ReactDOMTextarea, 'html': createFullPageComponent('html'), 'head': createFullPageComponent('head'), 'body': createFullPageComponent('body') }); // This needs to happen after createFullPageComponent() otherwise the mixin // gets double injected. ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction( ReactComponentBrowserEnvironment.ReactReconcileTransaction ); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if ("production" !== process.env.NODE_ENV) { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = require("./ReactDefaultPerf"); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; }).call(this,require('_process')) },{"./BeforeInputEventPlugin":5,"./ChangeEventPlugin":10,"./ClientReactRootIndex":11,"./CompositionEventPlugin":12,"./DefaultEventPluginOrder":17,"./EnterLeaveEventPlugin":18,"./ExecutionEnvironment":25,"./HTMLDOMPropertyConfig":26,"./MobileSafariClickEventPlugin":30,"./ReactBrowserComponentMixin":34,"./ReactComponentBrowserEnvironment":40,"./ReactDOMButton":46,"./ReactDOMComponent":47,"./ReactDOMForm":48,"./ReactDOMImg":50,"./ReactDOMInput":51,"./ReactDOMOption":52,"./ReactDOMSelect":53,"./ReactDOMTextarea":55,"./ReactDefaultBatchingStrategy":56,"./ReactDefaultPerf":58,"./ReactEventListener":65,"./ReactInjection":66,"./ReactInstanceHandles":68,"./ReactMount":72,"./SVGDOMPropertyConfig":95,"./SelectEventPlugin":96,"./ServerReactRootIndex":97,"./SimpleEventPlugin":98,"./createFullPageComponent":119,"_process":2}],58:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf * @typechecks static-only */ "use strict"; var DOMProperty = require("./DOMProperty"); var ReactDefaultPerfAnalysis = require("./ReactDefaultPerfAnalysis"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var performanceNow = require("./performanceNow"); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _injected: false, start: function() { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function() { ReactPerf.enableMeasure = false; }, getLastMeasurements: function() { return ReactDefaultPerf._allMeasurements; }, printExclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, printInclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, getMeasurementsSummaryMap: function(measurements) { var summary = ReactDefaultPerfAnalysis.getInclusiveSummary( measurements, true ); return summary.map(function(item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printDOM: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function(item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result['type'] = item.type; result['args'] = JSON.stringify(item.args); return result; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, _recordWrite: function(id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf ._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1] .writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function(moduleName, fnName, func) { return function() {for (var args=[],$__0=0,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0 }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ].totalTime = performanceNow() - start; return rv; } else if (moduleName === 'ReactDOMIDOperations' || moduleName === 'ReactComponentBrowserEnvironment') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === 'mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function(update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite( update.parentID, update.type, totalTime, writeArgs ); }); } else { // basic format ReactDefaultPerf._recordWrite( args[0], fnName, totalTime, Array.prototype.slice.call(args, 1) ); } return rv; } else if (moduleName === 'ReactCompositeComponent' && ( fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.constructor.displayName, owner: this._owner ? this._owner.constructor.displayName : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; },{"./DOMProperty":14,"./ReactDefaultPerfAnalysis":59,"./ReactMount":72,"./ReactPerf":77,"./performanceNow":156}],59:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ var assign = require("./Object.assign"); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { 'mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', TEXT_CONTENT: 'set textContent', 'updatePropertyByID': 'update attribute', 'deletePropertyByID': 'delete attribute', 'updateStylesByID': 'update styles', 'updateInnerHTMLByID': 'set innerHTML', 'dangerouslyReplaceNodeWithMarkupByID': 'replace' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var id; for (id in measurement.writes) { measurement.writes[id].forEach(function(write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); } } return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function(a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function(a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; },{"./Object.assign":31}],60:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ "use strict"; var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var warning = require("./warning"); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set the ' + key + ' property of the component. ' + 'Mutate the existing props object instead.' ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = { validated: false, props: props }; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== process.env.NODE_ENV) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( config.key !== null, 'createElement(...): Encountered component with a `key` of null. In ' + 'a future version, this will be treated as equivalent to the string ' + '\'null\'; instead, provide an explicit key or use undefined.' ) : null); } // TODO: Change this back to `config.key === undefined` key = config.key == null ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== process.env.NODE_ENV) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; }).call(this,require('_process')) },{"./ReactContext":43,"./ReactCurrentOwner":44,"./warning":163,"_process":2}],61:[function(require,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ "use strict"; var ReactElement = require("./ReactElement"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var monitorCodeUse = require("./monitorCodeUse"); /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = { 'react_key_warning': {}, 'react_numeric_key_warning': {} }; var ownerHasMonitoredObjectMap = {}; var loggedTypeFailures = {}; var NUMERIC_PROPERTY_REGEX = /^\d+$/; /** * Gets the current owner's displayName for use in warnings. * * @internal * @return {?string} Display name or undefined */ function getCurrentOwnerDisplayName() { var current = ReactCurrentOwner.current; return current && current.constructor.displayName || undefined; } /** * Warn if the component doesn't have an explicit key assigned to it. * This component is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactComponent} component Component that requires a key. * @param {*} parentType component's parent's type. */ function validateExplicitKey(component, parentType) { if (component._store.validated || component.key != null) { return; } component._store.validated = true; warnAndMonitorForKeyUse( 'react_key_warning', 'Each child in an array should have a unique "key" prop.', component, parentType ); } /** * Warn if the key is being defined as an object property but has an incorrect * value. * * @internal * @param {string} name Property name of the key. * @param {ReactComponent} component Component that requires a key. * @param {*} parentType component's parent's type. */ function validatePropertyKey(name, component, parentType) { if (!NUMERIC_PROPERTY_REGEX.test(name)) { return; } warnAndMonitorForKeyUse( 'react_numeric_key_warning', 'Child objects should have non-numeric keys so ordering is preserved.', component, parentType ); } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} warningID The id used when logging. * @param {string} message The base warning that gets output. * @param {ReactComponent} component Component that requires a key. * @param {*} parentType component's parent's type. */ function warnAndMonitorForKeyUse(warningID, message, component, parentType) { var ownerName = getCurrentOwnerDisplayName(); var parentName = parentType.displayName; var useName = ownerName || parentName; var memoizer = ownerHasKeyUseWarning[warningID]; if (memoizer.hasOwnProperty(useName)) { return; } memoizer[useName] = true; message += ownerName ? (" Check the render method of " + ownerName + ".") : (" Check the renderComponent call using <" + parentName + ">."); // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwnerName = null; if (component._owner && component._owner !== ReactCurrentOwner.current) { // Name of the component that originally created this child. childOwnerName = component._owner.constructor.displayName; message += (" It was passed a child from " + childOwnerName + "."); } message += ' See http://fb.me/react-warning-keys for more information.'; monitorCodeUse(warningID, { component: useName, componentOwner: childOwnerName }); console.warn(message); } /** * Log that we're using an object map. We're considering deprecating this * feature and replace it with proper Map and ImmutableMap data structures. * * @internal */ function monitorUseOfObjectMap() { var currentName = getCurrentOwnerDisplayName() || ''; if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) { return; } ownerHasMonitoredObjectMap[currentName] = true; monitorCodeUse('react_object_map_children'); } /** * Ensure that every component either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {*} component Statically passed child of any type. * @param {*} parentType component's parent's type. * @return {boolean} */ function validateChildKeys(component, parentType) { if (Array.isArray(component)) { for (var i = 0; i < component.length; i++) { var child = component[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(component)) { // This component was passed in a valid location. component._store.validated = true; } else if (component && typeof component === 'object') { monitorUseOfObjectMap(); for (var name in component) { validatePropertyKey(name, component[name], parentType); } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; // This will soon use the warning module monitorCodeUse( 'react_failed_descriptor_type_check', { message: error.message } ); } } } } var ReactElementValidator = { createElement: function(type, props, children) { var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } var name = type.displayName; if (type.propTypes) { checkPropTypes( name, type.propTypes, element.props, ReactPropTypeLocations.prop ); } if (type.contextTypes) { checkPropTypes( name, type.contextTypes, element._context, ReactPropTypeLocations.context ); } return element; }, createFactory: function(type) { var validatedFactory = ReactElementValidator.createElement.bind( null, type ); validatedFactory.type = type; return validatedFactory; } }; module.exports = ReactElementValidator; },{"./ReactCurrentOwner":44,"./ReactElement":60,"./ReactPropTypeLocations":80,"./monitorCodeUse":153}],62:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ "use strict"; var ReactElement = require("./ReactElement"); var invariant = require("./invariant"); var component; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIdsRegistry = {}; var ReactEmptyComponentInjection = { injectEmptyComponent: function(emptyComponent) { component = ReactElement.createFactory(emptyComponent); } }; /** * @return {ReactComponent} component The injected empty component. */ function getEmptyComponent() { ("production" !== process.env.NODE_ENV ? invariant( component, 'Trying to return null from a render, but no null placeholder component ' + 'was injected.' ) : invariant(component)); return component(); } /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIdsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIdsRegistry[id]; } /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return nullComponentIdsRegistry[id]; } var ReactEmptyComponent = { deregisterNullComponentID: deregisterNullComponentID, getEmptyComponent: getEmptyComponent, injection: ReactEmptyComponentInjection, isNullComponentID: isNullComponentID, registerNullComponentID: registerNullComponentID }; module.exports = ReactEmptyComponent; }).call(this,require('_process')) },{"./ReactElement":60,"./invariant":143,"_process":2}],63:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils * @typechecks */ "use strict"; var ReactErrorUtils = { /** * Creates a guarded version of a function. This is supposed to make debugging * of event handlers easier. To aid debugging with the browser's debugger, * this currently simply returns the original function. * * @param {function} func Function to be executed * @param {string} name The name of the guard * @return {function} */ guard: function(func, name) { return func; } }; module.exports = ReactErrorUtils; },{}],64:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ "use strict"; var EventPluginHub = require("./EventPluginHub"); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events = EventPluginHub.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":21}],65:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener * @typechecks static-only */ "use strict"; var EventListener = require("./EventListener"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var PooledClass = require("./PooledClass"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var getEventTarget = require("./getEventTarget"); var getUnboundedScrollPosition = require("./getUnboundedScrollPosition"); /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function() { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo( TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler ); function handleTopLevelImpl(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM( getEventTarget(bookKeeping.nativeEvent) ) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventListener._handleTopLevel( bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent ); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function(handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function(enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function() { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return; } return EventListener.listen( element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType) ); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return; } return EventListener.capture( element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType) ); }, monitorScrollValue: function(refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); EventListener.listen(window, 'resize', callback); }, dispatchEvent: function(topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled( topLevelType, nativeEvent ); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"./EventListener":20,"./ExecutionEnvironment":25,"./Object.assign":31,"./PooledClass":32,"./ReactInstanceHandles":68,"./ReactMount":72,"./ReactUpdates":93,"./getEventTarget":134,"./getUnboundedScrollPosition":139}],66:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ "use strict"; var DOMProperty = require("./DOMProperty"); var EventPluginHub = require("./EventPluginHub"); var ReactComponent = require("./ReactComponent"); var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactNativeComponent = require("./ReactNativeComponent"); var ReactPerf = require("./ReactPerf"); var ReactRootIndex = require("./ReactRootIndex"); var ReactUpdates = require("./ReactUpdates"); var ReactInjection = { Component: ReactComponent.injection, CompositeComponent: ReactCompositeComponent.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"./DOMProperty":14,"./EventPluginHub":21,"./ReactBrowserEventEmitter":35,"./ReactComponent":39,"./ReactCompositeComponent":42,"./ReactEmptyComponent":62,"./ReactNativeComponent":75,"./ReactPerf":77,"./ReactRootIndex":84,"./ReactUpdates":93}],67:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ "use strict"; var ReactDOMSelection = require("./ReactDOMSelection"); var containsNode = require("./containsNode"); var focusNode = require("./focusNode"); var getActiveElement = require("./getActiveElement"); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function(elem) { return elem && ( (elem.nodeName === 'INPUT' && elem.type === 'text') || elem.nodeName === 'TEXTAREA' || elem.contentEditable === 'true' ); }, getSelectionInformation: function() { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function(priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection( priorFocusedElem, priorSelectionRange ); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function(input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName === 'INPUT') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || {start: 0, end: 0}; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function(input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName === 'INPUT') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"./ReactDOMSelection":54,"./containsNode":117,"./focusNode":128,"./getActiveElement":130}],68:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceHandles * @typechecks static-only */ "use strict"; var ReactRootIndex = require("./ReactRootIndex"); var invariant = require("./invariant"); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 100; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { ("production" !== process.env.NODE_ENV ? invariant( isValidID(ancestorID) && isValidID(destinationID), 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID ) : invariant(isValidID(ancestorID) && isValidID(destinationID))); ("production" !== process.env.NODE_ENV ? invariant( isAncestorIDOf(ancestorID, destinationID), 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID ) : invariant(isAncestorIDOf(ancestorID, destinationID))); if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; for (var i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); ("production" !== process.env.NODE_ENV ? invariant( isValidID(longestCommonID), 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID ) : invariant(isValidID(longestCommonID))); return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; ("production" !== process.env.NODE_ENV ? invariant( start !== stop, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start ) : invariant(start !== stop)); var traverseUp = isAncestorIDOf(stop, start); ("production" !== process.env.NODE_ENV ? invariant( traverseUp || isAncestorIDOf(start, stop), 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop ) : invariant(traverseUp || isAncestorIDOf(start, stop))); // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start; /* until break */; id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } ("production" !== process.env.NODE_ENV ? invariant( depth++ < MAX_TREE_DEPTH, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop ) : invariant(depth++ < MAX_TREE_DEPTH)); } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function() { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function(rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function(id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function(targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function(targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, /** * Exposed for unit testing. * @private */ _getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; }).call(this,require('_process')) },{"./ReactRootIndex":84,"./invariant":143,"_process":2}],69:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLegacyElement */ "use strict"; var ReactCurrentOwner = require("./ReactCurrentOwner"); var invariant = require("./invariant"); var monitorCodeUse = require("./monitorCodeUse"); var warning = require("./warning"); var legacyFactoryLogs = {}; function warnForLegacyFactoryCall() { if (!ReactLegacyElementFactory._isLegacyCallWarningEnabled) { return; } var owner = ReactCurrentOwner.current; var name = owner && owner.constructor ? owner.constructor.displayName : ''; if (!name) { name = 'Something'; } if (legacyFactoryLogs.hasOwnProperty(name)) { return; } legacyFactoryLogs[name] = true; ("production" !== process.env.NODE_ENV ? warning( false, name + ' is calling a React component directly. ' + 'Use a factory or JSX instead. See: http://fb.me/react-legacyfactory' ) : null); monitorCodeUse('react_legacy_factory_call', { version: 3, name: name }); } function warnForPlainFunctionType(type) { var isReactClass = type.prototype && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; if (isReactClass) { ("production" !== process.env.NODE_ENV ? warning( false, 'Did not expect to get a React class here. Use `Component` instead ' + 'of `Component.type` or `this.constructor`.' ) : null); } else { if (!type._reactWarnedForThisType) { try { type._reactWarnedForThisType = true; } catch (x) { // just incase this is a frozen object or some special object } monitorCodeUse( 'react_non_component_in_jsx', { version: 3, name: type.name } ); } ("production" !== process.env.NODE_ENV ? warning( false, 'This JSX uses a plain function. Only React components are ' + 'valid in React\'s JSX transform.' ) : null); } } function warnForNonLegacyFactory(type) { ("production" !== process.env.NODE_ENV ? warning( false, 'Do not pass React.DOM.' + type.type + ' to JSX or createFactory. ' + 'Use the string "' + type.type + '" instead.' ) : null); } /** * Transfer static properties from the source to the target. Functions are * rebound to have this reflect the original source. */ function proxyStaticMethods(target, source) { if (typeof source !== 'function') { return; } for (var key in source) { if (source.hasOwnProperty(key)) { var value = source[key]; if (typeof value === 'function') { var bound = value.bind(source); // Copy any properties defined on the function, such as `isRequired` on // a PropTypes validator. for (var k in value) { if (value.hasOwnProperty(k)) { bound[k] = value[k]; } } target[key] = bound; } else { target[key] = value; } } } } // We use an object instead of a boolean because booleans are ignored by our // mocking libraries when these factories gets mocked. var LEGACY_MARKER = {}; var NON_LEGACY_MARKER = {}; var ReactLegacyElementFactory = {}; ReactLegacyElementFactory.wrapCreateFactory = function(createFactory) { var legacyCreateFactory = function(type) { if (typeof type !== 'function') { // Non-function types cannot be legacy factories return createFactory(type); } if (type.isReactNonLegacyFactory) { // This is probably a factory created by ReactDOM we unwrap it to get to // the underlying string type. It shouldn't have been passed here so we // warn. if ("production" !== process.env.NODE_ENV) { warnForNonLegacyFactory(type); } return createFactory(type.type); } if (type.isReactLegacyFactory) { // This is probably a legacy factory created by ReactCompositeComponent. // We unwrap it to get to the underlying class. return createFactory(type.type); } if ("production" !== process.env.NODE_ENV) { warnForPlainFunctionType(type); } // Unless it's a legacy factory, then this is probably a plain function, // that is expecting to be invoked by JSX. We can just return it as is. return type; }; return legacyCreateFactory; }; ReactLegacyElementFactory.wrapCreateElement = function(createElement) { var legacyCreateElement = function(type, props, children) { if (typeof type !== 'function') { // Non-function types cannot be legacy factories return createElement.apply(this, arguments); } var args; if (type.isReactNonLegacyFactory) { // This is probably a factory created by ReactDOM we unwrap it to get to // the underlying string type. It shouldn't have been passed here so we // warn. if ("production" !== process.env.NODE_ENV) { warnForNonLegacyFactory(type); } args = Array.prototype.slice.call(arguments, 0); args[0] = type.type; return createElement.apply(this, args); } if (type.isReactLegacyFactory) { // This is probably a legacy factory created by ReactCompositeComponent. // We unwrap it to get to the underlying class. if (type._isMockFunction) { // If this is a mock function, people will expect it to be called. We // will actually call the original mock factory function instead. This // future proofs unit testing that assume that these are classes. type.type._mockedReactClassConstructor = type; } args = Array.prototype.slice.call(arguments, 0); args[0] = type.type; return createElement.apply(this, args); } if ("production" !== process.env.NODE_ENV) { warnForPlainFunctionType(type); } // This is being called with a plain function we should invoke it // immediately as if this was used with legacy JSX. return type.apply(null, Array.prototype.slice.call(arguments, 1)); }; return legacyCreateElement; }; ReactLegacyElementFactory.wrapFactory = function(factory) { ("production" !== process.env.NODE_ENV ? invariant( typeof factory === 'function', 'This is suppose to accept a element factory' ) : invariant(typeof factory === 'function')); var legacyElementFactory = function(config, children) { // This factory should not be called when JSX is used. Use JSX instead. if ("production" !== process.env.NODE_ENV) { warnForLegacyFactoryCall(); } return factory.apply(this, arguments); }; proxyStaticMethods(legacyElementFactory, factory.type); legacyElementFactory.isReactLegacyFactory = LEGACY_MARKER; legacyElementFactory.type = factory.type; return legacyElementFactory; }; // This is used to mark a factory that will remain. E.g. we're allowed to call // it as a function. However, you're not suppose to pass it to createElement // or createFactory, so it will warn you if you do. ReactLegacyElementFactory.markNonLegacyFactory = function(factory) { factory.isReactNonLegacyFactory = NON_LEGACY_MARKER; return factory; }; // Checks if a factory function is actually a legacy factory pretending to // be a class. ReactLegacyElementFactory.isValidFactory = function(factory) { // TODO: This will be removed and moved into a class validator or something. return typeof factory === 'function' && factory.isReactLegacyFactory === LEGACY_MARKER; }; ReactLegacyElementFactory.isValidClass = function(factory) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( false, 'isValidClass is deprecated and will be removed in a future release. ' + 'Use a more specific validator instead.' ) : null); } return ReactLegacyElementFactory.isValidFactory(factory); }; ReactLegacyElementFactory._isLegacyCallWarningEnabled = true; module.exports = ReactLegacyElementFactory; }).call(this,require('_process')) },{"./ReactCurrentOwner":44,"./invariant":143,"./monitorCodeUse":153,"./warning":163,"_process":2}],70:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLink * @typechecks static-only */ "use strict"; /** * ReactLink encapsulates a common pattern in which a component wants to modify * a prop received from its parent. ReactLink allows the parent to pass down a * value coupled with a callback that, when invoked, expresses an intent to * modify that value. For example: * * React.createClass({ * getInitialState: function() { * return {value: ''}; * }, * render: function() { * var valueLink = new ReactLink(this.state.value, this._handleValueChange); * return <input valueLink={valueLink} />; * }, * this._handleValueChange: function(newValue) { * this.setState({value: newValue}); * } * }); * * We have provided some sugary mixins to make the creation and * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. */ var React = require("./React"); /** * @param {*} value current value of the link * @param {function} requestChange callback to request a change */ function ReactLink(value, requestChange) { this.value = value; this.requestChange = requestChange; } /** * Creates a PropType that enforces the ReactLink API and optionally checks the * type of the value being passed inside the link. Example: * * MyComponent.propTypes = { * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) * } */ function createLinkTypeChecker(linkType) { var shapes = { value: typeof linkType === 'undefined' ? React.PropTypes.any.isRequired : linkType.isRequired, requestChange: React.PropTypes.func.isRequired }; return React.PropTypes.shape(shapes); } ReactLink.PropTypes = { link: createLinkTypeChecker }; module.exports = ReactLink; },{"./React":33}],71:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ "use strict"; var adler32 = require("./adler32"); var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function(markup) { var checksum = adler32(markup); return markup.replace( '>', ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '">' ); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function(markup, element) { var existingChecksum = element.getAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME ); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"./adler32":113}],72:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ "use strict"; var DOMProperty = require("./DOMProperty"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactLegacyElement = require("./ReactLegacyElement"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactPerf = require("./ReactPerf"); var containsNode = require("./containsNode"); var deprecated = require("./deprecated"); var getReactRootElementInContainer = require("./getReactRootElementInContainer"); var instantiateReactComponent = require("./instantiateReactComponent"); var invariant = require("./invariant"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); var warning = require("./warning"); var createElement = ReactLegacyElement.wrapCreateElement( ReactElement.createElement ); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if ("production" !== process.env.NODE_ENV) { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { ("production" !== process.env.NODE_ENV ? invariant( !isValid(cached, id), 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id ) : invariant(!isValid(cached, id))); nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { ("production" !== process.env.NODE_ENV ? invariant( internalGetID(node) === id, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME ) : invariant(internalGetID(node) === id)); var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors( targetID, findDeepestCachedAncestorImpl ); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounting is the process of initializing a React component by creatings its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function(container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function( prevComponent, nextComponent, container, callback) { var nextProps = nextComponent.props; ReactMount.scrollMonitor(container, function() { prevComponent.replaceProps(nextProps, callback); }); if ("production" !== process.env.NODE_ENV) { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function(nextComponent, container) { ("production" !== process.env.NODE_ENV ? invariant( container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ), '_registerComponent(...): Target container is not a DOM element.' ) : invariant(container && ( container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE ))); ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: ReactPerf.measure( 'ReactMount', '_renderNewRootComponent', function( nextComponent, container, shouldReuseMarkup) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. ("production" !== process.env.NODE_ENV ? warning( ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); var componentInstance = instantiateReactComponent(nextComponent, null); var reactRootID = ReactMount._registerComponent( componentInstance, container ); componentInstance.mountComponentIntoNode( reactRootID, container, shouldReuseMarkup ); if ("production" !== process.env.NODE_ENV) { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; } ), /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function(nextElement, container, callback) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(nextElement), 'renderComponent(): Invalid component element.%s', ( typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : ReactLegacyElement.isValidFactory(nextElement) ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like a element typeof nextElement.props !== "undefined" ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '' ) ) : invariant(ReactElement.isValidElement(nextElement))); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevElement = prevComponent._currentElement; if (shouldUpdateReactComponent(prevElement, nextElement)) { return ReactMount._updateRootComponent( prevComponent, nextElement, container, callback ); } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && ReactMount.isRenderedByReact(reactRootElement); var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent( nextElement, container, shouldReuseMarkup ); callback && callback.call(component); return component; }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into the supplied `container`. * * @param {function} constructor React component constructor. * @param {?object} props Initial props of the component instance. * @param {DOMElement} container DOM element to render into. * @return {ReactComponent} Component instance rendered in `container`. */ constructAndRenderComponent: function(constructor, props, container) { var element = createElement(constructor, props); return ReactMount.render(element, container); }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into a container node identified by supplied `id`. * * @param {function} componentConstructor React component constructor * @param {?object} props Initial props of the component instance. * @param {string} id ID of the DOM element to render into. * @return {ReactComponent} Component instance rendered in the container node. */ constructAndRenderComponentByID: function(constructor, props, id) { var domNode = document.getElementById(id); ("production" !== process.env.NODE_ENV ? invariant( domNode, 'Tried to get element with id of "%s" but it is not present on the page.', id ) : invariant(domNode)); return ReactMount.constructAndRenderComponent(constructor, props, domNode); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function(container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function(container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) ("production" !== process.env.NODE_ENV ? warning( ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function of ' + 'props and state; triggering nested component updates from render is ' + 'not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== process.env.NODE_ENV) { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ unmountComponentFromNode: function(instance, container) { instance.unmountComponent(); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function(id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if ("production" !== process.env.NODE_ENV) { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { ("production" !== process.env.NODE_ENV ? invariant( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.' ) : invariant(// Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID)); var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { console.warn( 'ReactMount: Root element has been removed from its original ' + 'container. New container:', rootElement.parentNode ); } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function(id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * True if the supplied `node` is rendered by React. * * @param {*} node DOM Element to check. * @return {boolean} True if the DOM Element appears to be rendered by React. * @internal */ isRenderedByReact: function(node) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component return false; } var id = ReactMount.getID(node); return id ? id.charAt(0) === SEPARATOR : false; }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function(node) { var current = node; while (current && current.parentNode !== current) { if (ReactMount.isRenderedByReact(current)) { return current; } current = current.parentNode; } return null; }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function(ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; ("production" !== process.env.NODE_ENV ? invariant( false, 'findComponentRoot(..., %s): Unable to find 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`.', targetID, ReactMount.getID(ancestorNode) ) : invariant(false)); }, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, purgeID: purgeID }; // Deprecations (remove for 0.13) ReactMount.renderComponent = deprecated( 'ReactMount', 'renderComponent', 'render', this, ReactMount.render ); module.exports = ReactMount; }).call(this,require('_process')) },{"./DOMProperty":14,"./ReactBrowserEventEmitter":35,"./ReactCurrentOwner":44,"./ReactElement":60,"./ReactInstanceHandles":68,"./ReactLegacyElement":69,"./ReactPerf":77,"./containsNode":117,"./deprecated":123,"./getReactRootElementInContainer":137,"./instantiateReactComponent":142,"./invariant":143,"./shouldUpdateReactComponent":159,"./warning":163,"_process":2}],73:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild * @typechecks static-only */ "use strict"; var ReactComponent = require("./ReactComponent"); var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes"); var flattenChildren = require("./flattenChildren"); var instantiateReactComponent = require("./instantiateReactComponent"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, textContent: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, textContent: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates( updateQueue, markupQueue ); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function(nestedChildren, transaction) { var children = flattenChildren(nestedChildren); var mountImages = []; var index = 0; this._renderedChildren = children; for (var name in children) { var child = children[name]; if (children.hasOwnProperty(name)) { // The rendered children must be turned into instances as they're // mounted. var childInstance = instantiateReactComponent(child, null); children[name] = childInstance; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = childInstance.mountComponent( rootID, transaction, this._mountDepth + 1 ); childInstance._mountIndex = index; mountImages.push(mountImage); index++; } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function(nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { errorThrown ? clearQueue() : processQueue(); } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function(nextNestedChildren, transaction) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildren, transaction); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { errorThrown ? clearQueue() : processQueue(); } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function(nextNestedChildren, transaction) { var nextChildren = flattenChildren(nextNestedChildren); var prevChildren = this._renderedChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (shouldUpdateReactComponent(prevElement, nextElement)) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild.receiveComponent(nextElement, transaction); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChildByName(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent( nextElement, null ); this._mountChildByNameAtIndex( nextChildInstance, name, nextIndex, transaction ); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren[name])) { this._unmountChildByName(prevChildren[name], name); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function() { var renderedChildren = this._renderedChildren; for (var name in renderedChildren) { var renderedChild = renderedChildren[name]; // TODO: When is this not true? if (renderedChild.unmountComponent) { renderedChild.unmountComponent(); } } this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function(child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child, mountImage) { enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function(child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function(textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function(child, name, index, transaction) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = child.mountComponent( rootID, transaction, this._mountDepth + 1 ); child._mountIndex = index; this.createChild(child, mountImage); this._renderedChildren = this._renderedChildren || {}; this._renderedChildren[name] = child; }, /** * Unmounts a rendered child by name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @param {string} name Name of the child in `this._renderedChildren`. * @private */ _unmountChildByName: function(child, name) { this.removeChild(child); child._mountIndex = null; child.unmountComponent(); delete this._renderedChildren[name]; } } }; module.exports = ReactMultiChild; },{"./ReactComponent":39,"./ReactMultiChildUpdateTypes":74,"./flattenChildren":127,"./instantiateReactComponent":142,"./shouldUpdateReactComponent":159}],74:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ "use strict"; var keyMirror = require("./keyMirror"); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"./keyMirror":149}],75:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ "use strict"; var assign = require("./Object.assign"); var invariant = require("./invariant"); var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags var tagToComponentClass = {}; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function(componentClass) { genericComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function(componentClasses) { assign(tagToComponentClass, componentClasses); } }; /** * Create an internal class for a specific tag. * * @param {string} tag The tag for which to create an internal instance. * @param {any} props The props passed to the instance constructor. * @return {ReactComponent} component The injected empty component. */ function createInstanceForTag(tag, props, parentType) { var componentClass = tagToComponentClass[tag]; if (componentClass == null) { ("production" !== process.env.NODE_ENV ? invariant( genericComponentClass, 'There is no registered component for the tag %s', tag ) : invariant(genericComponentClass)); return new genericComponentClass(tag, props); } if (parentType === tag) { // Avoid recursion ("production" !== process.env.NODE_ENV ? invariant( genericComponentClass, 'There is no registered component for the tag %s', tag ) : invariant(genericComponentClass)); return new genericComponentClass(tag, props); } // Unwrap legacy factories return new componentClass.type(props); } var ReactNativeComponent = { createInstanceForTag: createInstanceForTag, injection: ReactNativeComponentInjection, }; module.exports = ReactNativeComponent; }).call(this,require('_process')) },{"./Object.assign":31,"./invariant":143,"_process":2}],76:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ "use strict"; var emptyObject = require("./emptyObject"); var invariant = require("./invariant"); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function(object) { return !!( object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function' ); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function(component, ref, owner) { ("production" !== process.env.NODE_ENV ? invariant( ReactOwner.isValidOwner(owner), 'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to add a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function(component, ref, owner) { ("production" !== process.env.NODE_ENV ? invariant( ReactOwner.isValidOwner(owner), 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to remove a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.refs[ref] === component) { owner.detachRef(ref); } }, /** * A ReactComponent must mix this in to have refs. * * @lends {ReactOwner.prototype} */ Mixin: { construct: function() { this.refs = emptyObject; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function(ref, component) { ("production" !== process.env.NODE_ENV ? invariant( component.isOwnedBy(this), 'attachRef(%s, ...): Only a component\'s owner can store a ref to it.', ref ) : invariant(component.isOwnedBy(this))); var refs = this.refs === emptyObject ? (this.refs = {}) : this.refs; refs[ref] = component; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function(ref) { delete this.refs[ref]; } } }; module.exports = ReactOwner; }).call(this,require('_process')) },{"./emptyObject":125,"./invariant":143,"_process":2}],77:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf * @typechecks static-only */ "use strict"; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function(objName, fnName, func) { if ("production" !== process.env.NODE_ENV) { var measuredFunc = null; var wrapper = function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function(measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; }).call(this,require('_process')) },{"_process":2}],78:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ "use strict"; var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); var invariant = require("./invariant"); var joinClasses = require("./joinClasses"); var warning = require("./warning"); var didWarn = false; /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { TransferStrategies: TransferStrategies, /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); }, /** * @lends {ReactPropTransferer.prototype} */ Mixin: { /** * Transfer props from this component to a target component. * * Props that do not have an explicit transfer strategy will be transferred * only if the target component does not already have the prop set. * * This is usually used to pass down props to a returned root component. * * @param {ReactElement} element Component receiving the properties. * @return {ReactElement} The supplied `component`. * @final * @protected */ transferPropsTo: function(element) { ("production" !== process.env.NODE_ENV ? invariant( element._owner === this, '%s: You can\'t call transferPropsTo() on a component that you ' + 'don\'t own, %s. This usually means you are calling ' + 'transferPropsTo() on a component passed in as props or children.', this.constructor.displayName, typeof element.type === 'string' ? element.type : element.type.displayName ) : invariant(element._owner === this)); if ("production" !== process.env.NODE_ENV) { if (!didWarn) { didWarn = true; ("production" !== process.env.NODE_ENV ? warning( false, 'transferPropsTo is deprecated. ' + 'See http://fb.me/react-transferpropsto for more information.' ) : null); } } // Because elements are immutable we have to merge into the existing // props object rather than clone it. transferInto(element.props, this.props); return element; } } }; module.exports = ReactPropTransferer; }).call(this,require('_process')) },{"./Object.assign":31,"./emptyFunction":124,"./invariant":143,"./joinClasses":148,"./warning":163,"_process":2}],79:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ "use strict"; var ReactPropTypeLocationNames = {}; if ("production" !== process.env.NODE_ENV) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; }).call(this,require('_process')) },{"_process":2}],80:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ "use strict"; var keyMirror = require("./keyMirror"); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"./keyMirror":149}],81:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ "use strict"; var ReactElement = require("./ReactElement"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var deprecated = require("./deprecated"); var emptyFunction = require("./emptyFunction"); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var elementTypeChecker = createElementTypeChecker(); var nodeTypeChecker = createNodeChecker(); var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: elementTypeChecker, instanceOf: createInstanceTypeChecker, node: nodeTypeChecker, objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, component: deprecated( 'React.PropTypes', 'component', 'element', this, elementTypeChecker ), renderable: deprecated( 'React.PropTypes', 'renderable', 'node', this, nodeTypeChecker ) }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error( ("Required " + locationName + " `" + propName + "` was not specified in ")+ ("`" + componentName + "`.") ); } } else { return validate(props, propName, componentName, location); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error( ("Invalid " + locationName + " `" + propName + "` of type `" + preciseType + "` ") + ("supplied to `" + componentName + "`, expected `" + expectedType + "`.") ); } } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns()); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error( ("Invalid " + locationName + " `" + propName + "` of type ") + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.") ); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location); if (error instanceof Error) { return error; } } } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactElement.") ); } } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected instance of `" + expectedClassName + "`.") ); } } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { function validate(props, propName, componentName, location) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error( ("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".") ); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` of type ") + ("`" + propType + "` supplied to `" + componentName + "`, expected an object.") ); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location); if (error instanceof Error) { return error; } } } } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { function validate(props, propName, componentName, location) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location) == null) { return; } } var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`.") ); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactNode.") ); } } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` of type `" + propType + "` ") + ("supplied to `" + componentName + "`, expected `object`.") ); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location); if (error) { return error; } } } return createChainableTypeChecker(validate, 'expected `object`'); } function isNode(propValue) { switch(typeof propValue) { case 'number': case 'string': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (ReactElement.isValidElement(propValue)) { return true; } for (var k in propValue) { if (!isNode(propValue[k])) { return false; } } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } module.exports = ReactPropTypes; },{"./ReactElement":60,"./ReactPropTypeLocationNames":79,"./deprecated":123,"./emptyFunction":124}],82:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPutListenerQueue */ "use strict"; var PooledClass = require("./PooledClass"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var assign = require("./Object.assign"); function ReactPutListenerQueue() { this.listenersToPut = []; } assign(ReactPutListenerQueue.prototype, { enqueuePutListener: function(rootNodeID, propKey, propValue) { this.listenersToPut.push({ rootNodeID: rootNodeID, propKey: propKey, propValue: propValue }); }, putListeners: function() { for (var i = 0; i < this.listenersToPut.length; i++) { var listenerToPut = this.listenersToPut[i]; ReactBrowserEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"./Object.assign":31,"./PooledClass":32,"./ReactBrowserEventEmitter":35}],83:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ "use strict"; var CallbackQueue = require("./CallbackQueue"); var PooledClass = require("./PooledClass"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactInputSelection = require("./ReactInputSelection"); var ReactPutListenerQueue = require("./ReactPutListenerQueue"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function() { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occured. `close` * restores the previous value. */ close: function(previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function() { this.reactMountReady.notifyAll(); } }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: function() { this.putListenerQueue.putListeners(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction() { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap proceedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"./CallbackQueue":9,"./Object.assign":31,"./PooledClass":32,"./ReactBrowserEventEmitter":35,"./ReactInputSelection":67,"./ReactPutListenerQueue":82,"./Transaction":110}],84:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRootIndex * @typechecks */ "use strict"; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],85:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactServerRendering */ "use strict"; var ReactElement = require("./ReactElement"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMarkupChecksum = require("./ReactMarkupChecksum"); var ReactServerRenderingTransaction = require("./ReactServerRenderingTransaction"); var instantiateReactComponent = require("./instantiateReactComponent"); var invariant = require("./invariant"); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(element), 'renderToString(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, 0); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(element), 'renderToStaticMarkup(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, 0); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; }).call(this,require('_process')) },{"./ReactElement":60,"./ReactInstanceHandles":68,"./ReactMarkupChecksum":71,"./ReactServerRenderingTransaction":86,"./instantiateReactComponent":142,"./invariant":143,"_process":2}],86:[function(require,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction * @typechecks */ "use strict"; var PooledClass = require("./PooledClass"); var CallbackQueue = require("./CallbackQueue"); var ReactPutListenerQueue = require("./ReactPutListenerQueue"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign( ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin ); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"./CallbackQueue":9,"./Object.assign":31,"./PooledClass":32,"./ReactPutListenerQueue":82,"./Transaction":110,"./emptyFunction":124}],87:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactStateSetters */ "use strict"; var ReactStateSetters = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * @param {ReactCompositeComponent} component * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function(component, funcReturningState) { return function(a, b, c, d, e, f) { var partialState = funcReturningState.call(component, a, b, c, d, e, f); if (partialState) { component.setState(partialState); } }; }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * Note: this is memoized function, which makes it inexpensive to call. * * @param {ReactCompositeComponent} component * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function(component, key) { // Memoize the setters. var cache = component.__keySetters || (component.__keySetters = {}); return cache[key] || (cache[key] = createStateKeySetter(component, key)); } }; function createStateKeySetter(component, key) { // Partial state is allocated outside of the function closure so it can be // reused with every call, avoiding memory allocation when this function // is called. var partialState = {}; return function stateKeySetter(value) { partialState[key] = value; component.setState(partialState); }; } ReactStateSetters.Mixin = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateSetter(function(xValue) { * return {x: xValue}; * })(1); * * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function(funcReturningState) { return ReactStateSetters.createStateSetter(this, funcReturningState); }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateKeySetter('x')(1); * * Note: this is memoized function, which makes it inexpensive to call. * * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function(key) { return ReactStateSetters.createStateKeySetter(this, key); } }; module.exports = ReactStateSetters; },{}],88:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTestUtils */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPropagators = require("./EventPropagators"); var React = require("./React"); var ReactElement = require("./ReactElement"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactMount = require("./ReactMount"); var ReactTextComponent = require("./ReactTextComponent"); var ReactUpdates = require("./ReactUpdates"); var SyntheticEvent = require("./SyntheticEvent"); var assign = require("./Object.assign"); var topLevelTypes = EventConstants.topLevelTypes; function Event(suffix) {} /** * @class ReactTestUtils */ /** * Todo: Support the entire DOM.scry query syntax. For now, these simple * utilities will suffice for testing purposes. * @lends ReactTestUtils */ var ReactTestUtils = { renderIntoDocument: function(instance) { var div = document.createElement('div'); // None of our tests actually require attaching the container to the // DOM, and doing so creates a mess that we rely on test isolation to // clean up, so we're going to stop honoring the name of this method // (and probably rename it eventually) if no problems arise. // document.documentElement.appendChild(div); return React.render(instance, div); }, isElement: function(element) { return ReactElement.isValidElement(element); }, isElementOfType: function(inst, convenienceConstructor) { return ( ReactElement.isValidElement(inst) && inst.type === convenienceConstructor.type ); }, isDOMComponent: function(inst) { return !!(inst && inst.mountComponent && inst.tagName); }, isDOMComponentElement: function(inst) { return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName); }, isCompositeComponent: function(inst) { return typeof inst.render === 'function' && typeof inst.setState === 'function'; }, isCompositeComponentWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponent(inst) && (inst.constructor === type.type)); }, isCompositeComponentElement: function(inst) { if (!ReactElement.isValidElement(inst)) { return false; } // We check the prototype of the type that will get mounted, not the // instance itself. This is a future proof way of duck typing. var prototype = inst.type.prototype; return ( typeof prototype.render === 'function' && typeof prototype.setState === 'function' ); }, isCompositeComponentElementWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponentElement(inst) && (inst.constructor === type)); }, isTextComponent: function(inst) { return inst instanceof ReactTextComponent.type; }, findAllInRenderedTree: function(inst, test) { if (!inst) { return []; } var ret = test(inst) ? [inst] : []; if (ReactTestUtils.isDOMComponent(inst)) { var renderedChildren = inst._renderedChildren; var key; for (key in renderedChildren) { if (!renderedChildren.hasOwnProperty(key)) { continue; } ret = ret.concat( ReactTestUtils.findAllInRenderedTree(renderedChildren[key], test) ); } } else if (ReactTestUtils.isCompositeComponent(inst)) { ret = ret.concat( ReactTestUtils.findAllInRenderedTree(inst._renderedComponent, test) ); } return ret; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the class name matching `className`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithClass: function(root, className) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { var instClassName = inst.props.className; return ReactTestUtils.isDOMComponent(inst) && ( instClassName && (' ' + instClassName + ' ').indexOf(' ' + className + ' ') !== -1 ); }); }, /** * Like scryRenderedDOMComponentsWithClass but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithClass: function(root, className) { var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); if (all.length !== 1) { throw new Error('Did not find exactly one match for class:' + className); } return all[0]; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the tag name matching `tagName`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithTag: function(root, tagName) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isDOMComponent(inst) && inst.tagName === tagName.toUpperCase(); }); }, /** * Like scryRenderedDOMComponentsWithTag but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithTag: function(root, tagName) { var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); if (all.length !== 1) { throw new Error('Did not find exactly one match for tag:' + tagName); } return all[0]; }, /** * Finds all instances of components with type equal to `componentType`. * @return an array of all the matches. */ scryRenderedComponentsWithType: function(root, componentType) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isCompositeComponentWithType( inst, componentType ); }); }, /** * Same as `scryRenderedComponentsWithType` but expects there to be one result * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactComponent} The one match. */ findRenderedComponentWithType: function(root, componentType) { var all = ReactTestUtils.scryRenderedComponentsWithType( root, componentType ); if (all.length !== 1) { throw new Error( 'Did not find exactly one match for componentType:' + componentType ); } return all[0]; }, /** * Pass a mocked component module to this method to augment it with * useful methods that allow it to be used as a dummy React component. * Instead of rendering as usual, the component will become a simple * <div> containing any provided children. * * @param {object} module the mock function object exported from a * module that defines the component to be mocked * @param {?string} mockTagName optional dummy root tag name to return * from render method (overrides * module.mockTagName if provided) * @return {object} the ReactTestUtils object (for chaining) */ mockComponent: function(module, mockTagName) { mockTagName = mockTagName || module.mockTagName || "div"; var ConvenienceConstructor = React.createClass({displayName: 'ConvenienceConstructor', render: function() { return React.createElement( mockTagName, null, this.props.children ); } }); module.mockImplementation(ConvenienceConstructor); module.type = ConvenienceConstructor.type; module.isReactLegacyFactory = true; return this; }, /** * Simulates a top level event being dispatched from a raw event that occured * on an `Element` node. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes` * @param {!Element} node The dom to simulate an event occurring on. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnNode: function(topLevelType, node, fakeNativeEvent) { fakeNativeEvent.target = node; ReactBrowserEventEmitter.ReactEventListener.dispatchEvent( topLevelType, fakeNativeEvent ); }, /** * Simulates a top level event being dispatched from a raw event that occured * on the `ReactDOMComponent` `comp`. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes`. * @param comp {!ReactDOMComponent} * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnDOMComponent: function( topLevelType, comp, fakeNativeEvent) { ReactTestUtils.simulateNativeEventOnNode( topLevelType, comp.getDOMNode(), fakeNativeEvent ); }, nativeTouchData: function(x, y) { return { touches: [ {pageX: x, pageY: y} ] }; }, Simulate: null, SimulateNative: {} }; /** * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)` * - ... (All keys from event plugin `eventTypes` objects) */ function makeSimulator(eventType) { return function(domComponentOrNode, eventData) { var node; if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { node = domComponentOrNode.getDOMNode(); } else if (domComponentOrNode.tagName) { node = domComponentOrNode; } var fakeNativeEvent = new Event(); fakeNativeEvent.target = node; // We don't use SyntheticEvent.getPooled in order to not have to worry about // properly destroying any properties assigned from `eventData` upon release var event = new SyntheticEvent( ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType], ReactMount.getID(node), fakeNativeEvent ); assign(event, eventData); EventPropagators.accumulateTwoPhaseDispatches(event); ReactUpdates.batchedUpdates(function() { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); }); }; } function buildSimulators() { ReactTestUtils.Simulate = {}; var eventType; for (eventType in ReactBrowserEventEmitter.eventNameDispatchConfigs) { /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?object} eventData Fake event data to use in SyntheticEvent. */ ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); } } // Rebuild ReactTestUtils.Simulate whenever event plugins are injected var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder; EventPluginHub.injection.injectEventPluginOrder = function() { oldInjectEventPluginOrder.apply(this, arguments); buildSimulators(); }; var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName; EventPluginHub.injection.injectEventPluginsByName = function() { oldInjectEventPlugins.apply(this, arguments); buildSimulators(); }; buildSimulators(); /** * Exports: * * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` * - ... (All keys from `EventConstants.topLevelTypes`) * * Note: Top level event types are a subset of the entire set of handler types * (which include a broader set of "synthetic" events). For example, onDragDone * is a synthetic event. Except when testing an event plugin or React's event * handling code specifically, you probably want to use ReactTestUtils.Simulate * to dispatch synthetic events. */ function makeNativeSimulator(eventType) { return function(domComponentOrNode, nativeEventData) { var fakeNativeEvent = new Event(eventType); assign(fakeNativeEvent, nativeEventData); if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { ReactTestUtils.simulateNativeEventOnDOMComponent( eventType, domComponentOrNode, fakeNativeEvent ); } else if (!!domComponentOrNode.tagName) { // Will allow on actual dom nodes. ReactTestUtils.simulateNativeEventOnNode( eventType, domComponentOrNode, fakeNativeEvent ); } }; } var eventType; for (eventType in topLevelTypes) { // Event type is stored as 'topClick' - we transform that to 'click' var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. */ ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType); } module.exports = ReactTestUtils; },{"./EventConstants":19,"./EventPluginHub":21,"./EventPropagators":24,"./Object.assign":31,"./React":33,"./ReactBrowserEventEmitter":35,"./ReactElement":60,"./ReactMount":72,"./ReactTextComponent":89,"./ReactUpdates":93,"./SyntheticEvent":102}],89:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTextComponent * @typechecks static-only */ "use strict"; var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactComponent = require("./ReactComponent"); var ReactElement = require("./ReactElement"); var assign = require("./Object.assign"); var escapeTextForBrowser = require("./escapeTextForBrowser"); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactTextComponent * @extends ReactComponent * @internal */ var ReactTextComponent = function(props) { // This constructor and it's argument is currently used by mocks. }; assign(ReactTextComponent.prototype, ReactComponent.Mixin, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {string} Markup for this text node. * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); var escapedText = escapeTextForBrowser(this.props); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return ( '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>' ); }, /** * Updates this component by updating the text content. * * @param {object} nextComponent Contains the next text content. * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextComponent, transaction) { var nextProps = nextComponent.props; if (nextProps !== this.props) { this.props = nextProps; ReactComponent.BackendIDOperations.updateTextContentByID( this._rootNodeID, nextProps ); } } }); var ReactTextComponentFactory = function(text) { // Bypass validation and configuration return new ReactElement(ReactTextComponent, null, null, null, null, text); }; ReactTextComponentFactory.type = ReactTextComponent; module.exports = ReactTextComponentFactory; },{"./DOMPropertyOperations":15,"./Object.assign":31,"./ReactComponent":39,"./ReactElement":60,"./escapeTextForBrowser":126}],90:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactTransitionChildMapping */ "use strict"; var ReactChildren = require("./ReactChildren"); var ReactTransitionChildMapping = { /** * Given `this.props.children`, return an object mapping key to child. Just * simple syntactic sugar around ReactChildren.map(). * * @param {*} children `this.props.children` * @return {object} Mapping of key to child */ getChildMapping: function(children) { return ReactChildren.map(children, function(child) { return child; }); }, /** * When you're adding or removing children some may be added or removed in the * same render pass. We want to show *both* since we want to simultaneously * animate elements in and out. This function takes a previous set of keys * and a new set of keys and merges them with its best guess of the correct * ordering. In the future we may expose some of the utilities in * ReactMultiChild to make this easy, but for now React itself does not * directly have this concept of the union of prevChildren and nextChildren * so we implement it here. * * @param {object} prev prev children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @param {object} next next children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @return {object} a key set that contains all keys in `prev` and all keys * in `next` in a reasonable order. */ mergeChildMappings: function(prev, next) { prev = prev || {}; next = next || {}; function getValueForKey(key) { if (next.hasOwnProperty(key)) { return next[key]; } else { return prev[key]; } } // For each key of `next`, the list of keys to insert before that key in // the combined list var nextKeysPending = {}; var pendingKeys = []; for (var prevKey in prev) { if (next.hasOwnProperty(prevKey)) { if (pendingKeys.length) { nextKeysPending[prevKey] = pendingKeys; pendingKeys = []; } } else { pendingKeys.push(prevKey); } } var i; var childMapping = {}; for (var nextKey in next) { if (nextKeysPending.hasOwnProperty(nextKey)) { for (i = 0; i < nextKeysPending[nextKey].length; i++) { var pendingNextKey = nextKeysPending[nextKey][i]; childMapping[nextKeysPending[nextKey][i]] = getValueForKey( pendingNextKey ); } } childMapping[nextKey] = getValueForKey(nextKey); } // Finally, add the keys which didn't appear before any key in `next` for (i = 0; i < pendingKeys.length; i++) { childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]); } return childMapping; } }; module.exports = ReactTransitionChildMapping; },{"./ReactChildren":38}],91:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function(endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function(endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; },{"./ExecutionEnvironment":25}],92:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionGroup */ "use strict"; var React = require("./React"); var ReactTransitionChildMapping = require("./ReactTransitionChildMapping"); var assign = require("./Object.assign"); var cloneWithProps = require("./cloneWithProps"); var emptyFunction = require("./emptyFunction"); var ReactTransitionGroup = React.createClass({ displayName: 'ReactTransitionGroup', propTypes: { component: React.PropTypes.any, childFactory: React.PropTypes.func }, getDefaultProps: function() { return { component: 'span', childFactory: emptyFunction.thatReturnsArgument }; }, getInitialState: function() { return { children: ReactTransitionChildMapping.getChildMapping(this.props.children) }; }, componentWillReceiveProps: function(nextProps) { var nextChildMapping = ReactTransitionChildMapping.getChildMapping( nextProps.children ); var prevChildMapping = this.state.children; this.setState({ children: ReactTransitionChildMapping.mergeChildMappings( prevChildMapping, nextChildMapping ) }); var key; for (key in nextChildMapping) { var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) { this.keysToEnter.push(key); } } for (key in prevChildMapping) { var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key); if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) { this.keysToLeave.push(key); } } // If we want to someday check for reordering, we could do it here. }, componentWillMount: function() { this.currentlyTransitioningKeys = {}; this.keysToEnter = []; this.keysToLeave = []; }, componentDidUpdate: function() { var keysToEnter = this.keysToEnter; this.keysToEnter = []; keysToEnter.forEach(this.performEnter); var keysToLeave = this.keysToLeave; this.keysToLeave = []; keysToLeave.forEach(this.performLeave); }, performEnter: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillEnter) { component.componentWillEnter( this._handleDoneEntering.bind(this, key) ); } else { this._handleDoneEntering(key); } }, _handleDoneEntering: function(key) { var component = this.refs[key]; if (component.componentDidEnter) { component.componentDidEnter(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { // This was removed before it had fully entered. Remove it. this.performLeave(key); } }, performLeave: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillLeave) { component.componentWillLeave(this._handleDoneLeaving.bind(this, key)); } else { // Note that this is somewhat dangerous b/c it calls setState() // again, effectively mutating the component before all the work // is done. this._handleDoneLeaving(key); } }, _handleDoneLeaving: function(key) { var component = this.refs[key]; if (component.componentDidLeave) { component.componentDidLeave(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) { // This entered again before it fully left. Add it again. this.performEnter(key); } else { var newChildren = assign({}, this.state.children); delete newChildren[key]; this.setState({children: newChildren}); } }, render: function() { // TODO: we could get rid of the need for the wrapper node // by cloning a single child var childrenToRender = {}; for (var key in this.state.children) { var child = this.state.children[key]; if (child) { // You may need to apply reactive updates to a child as it is leaving. // The normal React way to do it won't work since the child will have // already been removed. In case you need this behavior you can provide // a childFactory function to wrap every child, even the ones that are // leaving. childrenToRender[key] = cloneWithProps( this.props.childFactory(child), {ref: key} ); } } return React.createElement( this.props.component, this.props, childrenToRender ); } }); module.exports = ReactTransitionGroup; },{"./Object.assign":31,"./React":33,"./ReactTransitionChildMapping":90,"./cloneWithProps":116,"./emptyFunction":124}],93:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ "use strict"; var CallbackQueue = require("./CallbackQueue"); var PooledClass = require("./PooledClass"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactPerf = require("./ReactPerf"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var warning = require("./warning"); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { ("production" !== process.env.NODE_ENV ? invariant( ReactUpdates.ReactReconcileTransaction && batchingStrategy, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy' ) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy)); } var NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function() { this.callbackQueue.reset(); }, close: function() { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(); } assign( ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a ); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b); } /** * Array comparator for ReactComponents by owner depth * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountDepthComparator(c1, c2) { return c1._mountDepth - c2._mountDepth; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; ("production" !== process.env.NODE_ENV ? invariant( len === dirtyComponents.length, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ) : invariant(len === dirtyComponents.length)); // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountDepthComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, ignore them // TODO: Queue unmounts in the same list to avoid this happening at all var component = dirtyComponents[i]; if (component.isMounted()) { // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; component.performUpdateIfNecessary(transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue( callbacks[j], component ); } } } } } var flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', function() { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } } ); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component, callback) { ("production" !== process.env.NODE_ENV ? invariant( !callback || typeof callback === "function", 'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(!callback || typeof callback === "function")); ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) ("production" !== process.env.NODE_ENV ? warning( ReactCurrentOwner.current == null, 'enqueueUpdate(): Render methods should be a pure function of props ' + 'and state; triggering nested component updates from render is not ' + 'allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component, callback); return; } dirtyComponents.push(component); if (callback) { if (component._pendingCallbacks) { component._pendingCallbacks.push(callback); } else { component._pendingCallbacks = [callback]; } } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { ("production" !== process.env.NODE_ENV ? invariant( batchingStrategy.isBatchingUpdates, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.' ) : invariant(batchingStrategy.isBatchingUpdates)); asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function(ReconcileTransaction) { ("production" !== process.env.NODE_ENV ? invariant( ReconcileTransaction, 'ReactUpdates: must provide a reconcile transaction class' ) : invariant(ReconcileTransaction)); ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function(_batchingStrategy) { ("production" !== process.env.NODE_ENV ? invariant( _batchingStrategy, 'ReactUpdates: must provide a batching strategy' ) : invariant(_batchingStrategy)); ("production" !== process.env.NODE_ENV ? invariant( typeof _batchingStrategy.batchedUpdates === 'function', 'ReactUpdates: must provide a batchedUpdates() function' ) : invariant(typeof _batchingStrategy.batchedUpdates === 'function')); ("production" !== process.env.NODE_ENV ? invariant( typeof _batchingStrategy.isBatchingUpdates === 'boolean', 'ReactUpdates: must provide an isBatchingUpdates boolean attribute' ) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean')); batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; }).call(this,require('_process')) },{"./CallbackQueue":9,"./Object.assign":31,"./PooledClass":32,"./ReactCurrentOwner":44,"./ReactPerf":77,"./Transaction":110,"./invariant":143,"./warning":163,"_process":2}],94:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactWithAddons */ /** * This module exists purely in the open source project, and is meant as a way * to create a separate standalone build of React. This build has "addons", or * functionality we've built and think might be useful but doesn't have a good * place to live inside React core. */ "use strict"; var LinkedStateMixin = require("./LinkedStateMixin"); var React = require("./React"); var ReactComponentWithPureRenderMixin = require("./ReactComponentWithPureRenderMixin"); var ReactCSSTransitionGroup = require("./ReactCSSTransitionGroup"); var ReactTransitionGroup = require("./ReactTransitionGroup"); var ReactUpdates = require("./ReactUpdates"); var cx = require("./cx"); var cloneWithProps = require("./cloneWithProps"); var update = require("./update"); React.addons = { CSSTransitionGroup: ReactCSSTransitionGroup, LinkedStateMixin: LinkedStateMixin, PureRenderMixin: ReactComponentWithPureRenderMixin, TransitionGroup: ReactTransitionGroup, batchedUpdates: ReactUpdates.batchedUpdates, classSet: cx, cloneWithProps: cloneWithProps, update: update }; if ("production" !== process.env.NODE_ENV) { React.addons.Perf = require("./ReactDefaultPerf"); React.addons.TestUtils = require("./ReactTestUtils"); } module.exports = React; }).call(this,require('_process')) },{"./LinkedStateMixin":27,"./React":33,"./ReactCSSTransitionGroup":36,"./ReactComponentWithPureRenderMixin":41,"./ReactDefaultPerf":58,"./ReactTestUtils":88,"./ReactTransitionGroup":92,"./ReactUpdates":93,"./cloneWithProps":116,"./cx":121,"./update":162,"_process":2}],95:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = require("./DOMProperty"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var SVGDOMPropertyConfig = { Properties: { cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox' } }; module.exports = SVGDOMPropertyConfig; },{"./DOMProperty":14}],96:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ "use strict"; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ReactInputSelection = require("./ReactInputSelection"); var SyntheticEvent = require("./SyntheticEvent"); var getActiveElement = require("./getActiveElement"); var isTextInputElement = require("./isTextInputElement"); var keyOf = require("./keyOf"); var shallowEqual = require("./shallowEqual"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({onSelect: null}), captured: keyOf({onSelectCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @param {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement != getActiveElement()) { return; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled( eventTypes.select, activeElementID, nativeEvent ); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. case topLevelTypes.topSelectionChange: case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent); } } }; module.exports = SelectEventPlugin; },{"./EventConstants":19,"./EventPropagators":24,"./ReactInputSelection":67,"./SyntheticEvent":102,"./getActiveElement":130,"./isTextInputElement":146,"./keyOf":150,"./shallowEqual":158}],97:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ServerReactRootIndex * @typechecks */ "use strict"; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function() { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; },{}],98:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginUtils = require("./EventPluginUtils"); var EventPropagators = require("./EventPropagators"); var SyntheticClipboardEvent = require("./SyntheticClipboardEvent"); var SyntheticEvent = require("./SyntheticEvent"); var SyntheticFocusEvent = require("./SyntheticFocusEvent"); var SyntheticKeyboardEvent = require("./SyntheticKeyboardEvent"); var SyntheticMouseEvent = require("./SyntheticMouseEvent"); var SyntheticDragEvent = require("./SyntheticDragEvent"); var SyntheticTouchEvent = require("./SyntheticTouchEvent"); var SyntheticUIEvent = require("./SyntheticUIEvent"); var SyntheticWheelEvent = require("./SyntheticWheelEvent"); var getEventCharCode = require("./getEventCharCode"); var invariant = require("./invariant"); var keyOf = require("./keyOf"); var warning = require("./warning"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { blur: { phasedRegistrationNames: { bubbled: keyOf({onBlur: true}), captured: keyOf({onBlurCapture: true}) } }, click: { phasedRegistrationNames: { bubbled: keyOf({onClick: true}), captured: keyOf({onClickCapture: true}) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({onContextMenu: true}), captured: keyOf({onContextMenuCapture: true}) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({onCopy: true}), captured: keyOf({onCopyCapture: true}) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({onCut: true}), captured: keyOf({onCutCapture: true}) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({onDoubleClick: true}), captured: keyOf({onDoubleClickCapture: true}) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({onDrag: true}), captured: keyOf({onDragCapture: true}) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({onDragEnd: true}), captured: keyOf({onDragEndCapture: true}) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({onDragEnter: true}), captured: keyOf({onDragEnterCapture: true}) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({onDragExit: true}), captured: keyOf({onDragExitCapture: true}) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({onDragLeave: true}), captured: keyOf({onDragLeaveCapture: true}) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({onDragOver: true}), captured: keyOf({onDragOverCapture: true}) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({onDragStart: true}), captured: keyOf({onDragStartCapture: true}) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({onDrop: true}), captured: keyOf({onDropCapture: true}) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({onFocus: true}), captured: keyOf({onFocusCapture: true}) } }, input: { phasedRegistrationNames: { bubbled: keyOf({onInput: true}), captured: keyOf({onInputCapture: true}) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({onKeyDown: true}), captured: keyOf({onKeyDownCapture: true}) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({onKeyPress: true}), captured: keyOf({onKeyPressCapture: true}) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({onKeyUp: true}), captured: keyOf({onKeyUpCapture: true}) } }, load: { phasedRegistrationNames: { bubbled: keyOf({onLoad: true}), captured: keyOf({onLoadCapture: true}) } }, error: { phasedRegistrationNames: { bubbled: keyOf({onError: true}), captured: keyOf({onErrorCapture: true}) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({onMouseDown: true}), captured: keyOf({onMouseDownCapture: true}) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({onMouseMove: true}), captured: keyOf({onMouseMoveCapture: true}) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({onMouseOut: true}), captured: keyOf({onMouseOutCapture: true}) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({onMouseOver: true}), captured: keyOf({onMouseOverCapture: true}) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({onMouseUp: true}), captured: keyOf({onMouseUpCapture: true}) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({onPaste: true}), captured: keyOf({onPasteCapture: true}) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({onReset: true}), captured: keyOf({onResetCapture: true}) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({onScroll: true}), captured: keyOf({onScrollCapture: true}) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({onSubmit: true}), captured: keyOf({onSubmitCapture: true}) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({onTouchCancel: true}), captured: keyOf({onTouchCancelCapture: true}) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({onTouchEnd: true}), captured: keyOf({onTouchEndCapture: true}) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({onTouchMove: true}), captured: keyOf({onTouchMoveCapture: true}) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({onTouchStart: true}), captured: keyOf({onTouchStartCapture: true}) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({onWheel: true}), captured: keyOf({onWheelCapture: true}) } } }; var topLevelEventsToDispatchConfig = { topBlur: eventTypes.blur, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSubmit: eventTypes.submit, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topWheel: eventTypes.wheel }; for (var topLevelType in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType]; } var SimpleEventPlugin = { eventTypes: eventTypes, /** * Same as the default implementation, except cancels the event when return * value is false. This behavior will be disabled in a future release. * * @param {object} Event to be dispatched. * @param {function} Application-level callback. * @param {string} domID DOM ID to pass to the callback. */ executeDispatch: function(event, listener, domID) { var returnValue = EventPluginUtils.executeDispatch(event, listener, domID); ("production" !== process.env.NODE_ENV ? warning( typeof returnValue !== 'boolean', 'Returning `false` from an event handler is deprecated and will be ' + 'ignored in a future release. Instead, manually call ' + 'e.stopPropagation() or e.preventDefault(), as appropriate.' ) : null); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } }, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topError: case topLevelTypes.topReset: case topLevelTypes.topSubmit: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } ("production" !== process.env.NODE_ENV ? invariant( EventConstructor, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType ) : invariant(EventConstructor)); var event = EventConstructor.getPooled( dispatchConfig, topLevelTargetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = SimpleEventPlugin; }).call(this,require('_process')) },{"./EventConstants":19,"./EventPluginUtils":23,"./EventPropagators":24,"./SyntheticClipboardEvent":99,"./SyntheticDragEvent":101,"./SyntheticEvent":102,"./SyntheticFocusEvent":103,"./SyntheticKeyboardEvent":105,"./SyntheticMouseEvent":106,"./SyntheticTouchEvent":107,"./SyntheticUIEvent":108,"./SyntheticWheelEvent":109,"./getEventCharCode":131,"./invariant":143,"./keyOf":150,"./warning":163,"_process":2}],99:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function(event) { return ( 'clipboardData' in event ? event.clipboardData : window.clipboardData ); } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"./SyntheticEvent":102}],100:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent( dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticCompositionEvent, CompositionEventInterface ); module.exports = SyntheticCompositionEvent; },{"./SyntheticEvent":102}],101:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = require("./SyntheticMouseEvent"); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"./SyntheticMouseEvent":106}],102:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent * @typechecks static-only */ "use strict"; var PooledClass = require("./PooledClass"); var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); var getEventTarget = require("./getEventTarget"); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: getEventTarget, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function(event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { this[propName] = nativeEvent[propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; event.preventDefault ? event.preventDefault() : event.returnValue = false; this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function() { var event = this.nativeEvent; event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true; this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function() { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function() { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler); module.exports = SyntheticEvent; },{"./Object.assign":31,"./PooledClass":32,"./emptyFunction":124,"./getEventTarget":134}],103:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"./SyntheticUIEvent":108}],104:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent( dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticInputEvent, InputEventInterface ); module.exports = SyntheticInputEvent; },{"./SyntheticEvent":102}],105:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); var getEventCharCode = require("./getEventCharCode"); var getEventKey = require("./getEventKey"); var getEventModifierState = require("./getEventModifierState"); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function(event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function(event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function(event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"./SyntheticUIEvent":108,"./getEventCharCode":131,"./getEventKey":132,"./getEventModifierState":133}],106:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); var ViewportMetrics = require("./ViewportMetrics"); var getEventModifierState = require("./getEventModifierState"); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function(event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function(event) { return event.relatedTarget || ( event.fromElement === event.srcElement ? event.toElement : event.fromElement ); }, // "Proprietary" Interface. pageX: function(event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function(event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"./SyntheticUIEvent":108,"./ViewportMetrics":111,"./getEventModifierState":133}],107:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ "use strict"; var SyntheticUIEvent = require("./SyntheticUIEvent"); var getEventModifierState = require("./getEventModifierState"); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"./SyntheticUIEvent":108,"./getEventModifierState":133}],108:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent * @typechecks static-only */ "use strict"; var SyntheticEvent = require("./SyntheticEvent"); var getEventTarget = require("./getEventTarget"); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function(event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function(event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"./SyntheticEvent":102,"./getEventTarget":134}],109:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ "use strict"; var SyntheticMouseEvent = require("./SyntheticMouseEvent"); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function(event) { return ( 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0 ); }, deltaY: function(event) { return ( 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0 ); }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"./SyntheticMouseEvent":106}],110:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ "use strict"; var invariant = require("./invariant"); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM upates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function() { this.transactionWrappers = this.getTransactionWrappers(); if (!this.wrapperInitData) { this.wrapperInitData = []; } else { this.wrapperInitData.length = 0; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function() { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { ("production" !== process.env.NODE_ENV ? invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ) : invariant(!this.isInTransaction())); var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) { } } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function(startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) { } } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function(startIndex) { ("production" !== process.env.NODE_ENV ? invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ) : invariant(this.isInTransaction())); var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR) { wrapper.close && wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) { } } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],111:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ "use strict"; var getUnboundedScrollPosition = require("./getUnboundedScrollPosition"); var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function() { var scrollPosition = getUnboundedScrollPosition(window); ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{"./getUnboundedScrollPosition":139}],112:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ "use strict"; var invariant = require("./invariant"); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { ("production" !== process.env.NODE_ENV ? invariant( next != null, 'accumulateInto(...): Accumulated items must not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],113:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ /* jslint bitwise:true */ "use strict"; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonably good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],114:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function(_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],115:[function(require,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelizeStyleName * @typechecks */ "use strict"; var camelize = require("./camelize"); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; },{"./camelize":114}],116:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule cloneWithProps */ "use strict"; var ReactElement = require("./ReactElement"); var ReactPropTransferer = require("./ReactPropTransferer"); var keyOf = require("./keyOf"); var warning = require("./warning"); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {object} child child component you'd like to clone * @param {object} props props you'd like to modify. They will be merged * as if you used `transferPropsTo()`. * @return {object} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; }).call(this,require('_process')) },{"./ReactElement":60,"./ReactPropTransferer":78,"./keyOf":150,"./warning":163,"_process":2}],117:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule containsNode * @typechecks */ var isTextNode = require("./isTextNode"); /*jslint bitwise:true */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"./isTextNode":147}],118:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createArrayFrom * @typechecks */ var toArray = require("./toArray"); /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && // arrays are objects, NodeLists are functions in Safari (typeof obj == 'object' || typeof obj == 'function') && // quacks like an array ('length' in obj) && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 (typeof obj.nodeType != 'number') && ( // a real array (// HTMLCollection/NodeList (Array.isArray(obj) || // arguments ('callee' in obj) || 'item' in obj)) ) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFrom = require('createArrayFrom'); * * function takesOneOrMoreThings(things) { * things = createArrayFrom(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFrom(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFrom; },{"./toArray":160}],119:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createFullPageComponent * @typechecks */ "use strict"; // Defeat circular references by requiring this directly. var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactElement = require("./ReactElement"); var invariant = require("./invariant"); /** * Create a component that will throw an exception when unmounted. * * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. * * @param {string} tag The tag to wrap * @return {function} convenience constructor of new component */ function createFullPageComponent(tag) { var elementFactory = ReactElement.createFactory(tag); var FullPageComponent = ReactCompositeComponent.createClass({ displayName: 'ReactFullPageComponent' + tag, componentWillUnmount: function() { ("production" !== process.env.NODE_ENV ? invariant( false, '%s tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, <head>, ' + 'and <body>) reliably and efficiently. To fix this, have a single ' + 'top-level component that never unmounts render these elements.', this.constructor.displayName ) : invariant(false)); }, render: function() { return elementFactory(this.props); } }); return FullPageComponent; } module.exports = createFullPageComponent; }).call(this,require('_process')) },{"./ReactCompositeComponent":42,"./ReactElement":60,"./invariant":143,"_process":2}],120:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createNodesFromMarkup * @typechecks */ /*jslint evil: true, sub: true */ var ExecutionEnvironment = require("./ExecutionEnvironment"); var createArrayFrom = require("./createArrayFrom"); var getMarkupWrap = require("./getMarkupWrap"); var invariant = require("./invariant"); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; ("production" !== process.env.NODE_ENV ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode)); var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { ("production" !== process.env.NODE_ENV ? invariant( handleScript, 'createNodesFromMarkup(...): Unexpected <script> element rendered.' ) : invariant(handleScript)); createArrayFrom(scripts).forEach(handleScript); } var nodes = createArrayFrom(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; }).call(this,require('_process')) },{"./ExecutionEnvironment":25,"./createArrayFrom":118,"./getMarkupWrap":135,"./invariant":143,"_process":2}],121:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cx */ /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ function cx(classNames) { if (typeof classNames == 'object') { return Object.keys(classNames).filter(function(className) { return classNames[className]; }).join(' '); } else { return Array.prototype.join.call(arguments, ' '); } } module.exports = cx; },{}],122:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue * @typechecks static-only */ "use strict"; var CSSProperty = require("./CSSProperty"); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"./CSSProperty":7}],123:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule deprecated */ var assign = require("./Object.assign"); var warning = require("./warning"); /** * This will log a single deprecation notice per function and forward the call * on to the new API. * * @param {string} namespace The namespace of the call, eg 'React' * @param {string} oldName The old function name, eg 'renderComponent' * @param {string} newName The new function name, eg 'render' * @param {*} ctx The context this forwarded call should run in * @param {function} fn The function to forward on to * @return {*} Will be the value as returned from `fn` */ function deprecated(namespace, oldName, newName, ctx, fn) { var warned = false; if ("production" !== process.env.NODE_ENV) { var newFn = function() { ("production" !== process.env.NODE_ENV ? warning( warned, (namespace + "." + oldName + " will be deprecated in a future version. ") + ("Use " + namespace + "." + newName + " instead.") ) : null); warned = true; return fn.apply(ctx, arguments); }; newFn.displayName = (namespace + "_" + oldName); // We need to make sure all properties of the original fn are copied over. // In particular, this is needed to support PropTypes return assign(newFn, fn); } return fn; } module.exports = deprecated; }).call(this,require('_process')) },{"./Object.assign":31,"./warning":163,"_process":2}],124:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; },{}],125:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== process.env.NODE_ENV) { Object.freeze(emptyObject); } module.exports = emptyObject; }).call(this,require('_process')) },{"_process":2}],126:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextForBrowser * @typechecks static-only */ "use strict"; var ESCAPE_LOOKUP = { "&": "&amp;", ">": "&gt;", "<": "&lt;", "\"": "&quot;", "'": "&#x27;" }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextForBrowser; },{}],127:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ "use strict"; var ReactTextComponent = require("./ReactTextComponent"); var traverseAllChildren = require("./traverseAllChildren"); var warning = require("./warning"); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = !result.hasOwnProperty(name); ("production" !== process.env.NODE_ENV ? warning( keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); if (keyUnique && child != null) { var type = typeof child; var normalizedValue; if (type === 'string') { normalizedValue = ReactTextComponent(child); } else if (type === 'number') { normalizedValue = ReactTextComponent('' + child); } else { normalizedValue = child; } result[name] = normalizedValue; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; }).call(this,require('_process')) },{"./ReactTextComponent":89,"./traverseAllChildren":161,"./warning":163,"_process":2}],128:[function(require,module,exports){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule focusNode */ "use strict"; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch(e) { } } module.exports = focusNode; },{}],129:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ "use strict"; /** * @param {array} an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],130:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getActiveElement * @typechecks */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document body is not yet defined. */ function getActiveElement() /*?DOMElement*/ { try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],131:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode * @typechecks static-only */ "use strict"; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {string} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],132:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey * @typechecks static-only */ "use strict"; var getEventCharCode = require("./getEventCharCode"); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"./getEventCharCode":131}],133:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState * @typechecks static-only */ "use strict"; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { /*jshint validthis:true */ var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],134:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget * @typechecks static-only */ "use strict"; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],135:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getMarkupWrap */ var ExecutionEnvironment = require("./ExecutionEnvironment"); var invariant = require("./invariant"); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = { // Force wrapping for SVG elements because if they get created inside a <div>, // they will be initialized in the wrong namespace (and will not display). 'circle': true, 'defs': true, 'ellipse': true, 'g': true, 'line': true, 'linearGradient': true, 'path': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'text': true }; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg>', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap, 'circle': svgWrap, 'defs': svgWrap, 'ellipse': svgWrap, 'g': svgWrap, 'line': svgWrap, 'linearGradient': svgWrap, 'path': svgWrap, 'polygon': svgWrap, 'polyline': svgWrap, 'radialGradient': svgWrap, 'rect': svgWrap, 'stop': svgWrap, 'text': svgWrap }; /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { ("production" !== process.env.NODE_ENV ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode)); if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; }).call(this,require('_process')) },{"./ExecutionEnvironment":25,"./invariant":143,"_process":2}],136:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ "use strict"; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType == 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],137:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getReactRootElementInContainer */ "use strict"; var DOC_NODE_TYPE = 9; /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } module.exports = getReactRootElementInContainer; },{}],138:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"./ExecutionEnvironment":25}],139:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getUnboundedScrollPosition * @typechecks */ "use strict"; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],140:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenate * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],141:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenateStyleName * @typechecks */ "use strict"; var hyphenate = require("./hyphenate"); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; },{"./hyphenate":140}],142:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent * @typechecks static-only */ "use strict"; var warning = require("./warning"); var ReactElement = require("./ReactElement"); var ReactLegacyElement = require("./ReactLegacyElement"); var ReactNativeComponent = require("./ReactNativeComponent"); var ReactEmptyComponent = require("./ReactEmptyComponent"); /** * Given an `element` create an instance that will actually be mounted. * * @param {object} element * @param {*} parentCompositeType The composite type that resolved this. * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(element, parentCompositeType) { var instance; if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( element && (typeof element.type === 'function' || typeof element.type === 'string'), 'Only functions or strings can be mounted as React components.' ) : null); // Resolve mock instances if (element.type._mockedReactClassConstructor) { // If this is a mocked class, we treat the legacy factory as if it was the // class constructor for future proofing unit tests. Because this might // be mocked as a legacy factory, we ignore any warnings triggerd by // this temporary hack. ReactLegacyElement._isLegacyCallWarningEnabled = false; try { instance = new element.type._mockedReactClassConstructor( element.props ); } finally { ReactLegacyElement._isLegacyCallWarningEnabled = true; } // If the mock implementation was a legacy factory, then it returns a // element. We need to turn this into a real component instance. if (ReactElement.isValidElement(instance)) { instance = new instance.type(instance.props); } var render = instance.render; if (!render) { // For auto-mocked factories, the prototype isn't shimmed and therefore // there is no render function on the instance. We replace the whole // component with an empty component instance instead. element = ReactEmptyComponent.getEmptyComponent(); } else { if (render._isMockFunction && !render._getMockImplementation()) { // Auto-mocked components may have a prototype with a mocked render // function. For those, we'll need to mock the result of the render // since we consider undefined to be invalid results from render. render.mockImplementation( ReactEmptyComponent.getEmptyComponent ); } instance.construct(element); return instance; } } } // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInstanceForTag( element.type, element.props, parentCompositeType ); } else { // Normal case for non-mocks and non-strings instance = new element.type(element.props); } if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function', 'Only React Components can be mounted.' ) : null); } // This actually sets up the internal instance. This will become decoupled // from the public instance in a future diff. instance.construct(element); return instance; } module.exports = instantiateReactComponent; }).call(this,require('_process')) },{"./ReactElement":60,"./ReactEmptyComponent":62,"./ReactLegacyElement":69,"./ReactNativeComponent":75,"./warning":163,"_process":2}],143:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if ("production" !== process.env.NODE_ENV) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; }).call(this,require('_process')) },{"_process":2}],144:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"./ExecutionEnvironment":25}],145:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && ( typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string' )); } module.exports = isNode; },{}],146:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ "use strict"; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { return elem && ( (elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) || elem.nodeName === 'TEXTAREA' ); } module.exports = isTextInputElement; },{}],147:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextNode * @typechecks */ var isNode = require("./isNode"); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"./isNode":145}],148:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ "use strict"; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; },{}],149:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ "use strict"; var invariant = require("./invariant"); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function(obj) { var ret = {}; var key; ("production" !== process.env.NODE_ENV ? invariant( obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.' ) : invariant(obj instanceof Object && !Array.isArray(obj))); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],150:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],151:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mapObject */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; },{}],152:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule memoizeStringOnly * @typechecks static-only */ "use strict"; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function(string) { if (cache.hasOwnProperty(string)) { return cache[string]; } else { return cache[string] = callback.call(this, string); } }; } module.exports = memoizeStringOnly; },{}],153:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule monitorCodeUse */ "use strict"; var invariant = require("./invariant"); /** * Provides open-source compatible instrumentation for monitoring certain API * uses before we're ready to issue a warning or refactor. It accepts an event * name which may only contain the characters [a-z0-9_] and an optional data * object with further information. */ function monitorCodeUse(eventName, data) { ("production" !== process.env.NODE_ENV ? invariant( eventName && !/[^a-z0-9_]/.test(eventName), 'You must provide an eventName using only the characters [a-z0-9_]' ) : invariant(eventName && !/[^a-z0-9_]/.test(eventName))); } module.exports = monitorCodeUse; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],154:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ "use strict"; var ReactElement = require("./ReactElement"); var invariant = require("./invariant"); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(children), 'onlyChild must be passed a children with exactly one child.' ) : invariant(ReactElement.isValidElement(children))); return children; } module.exports = onlyChild; }).call(this,require('_process')) },{"./ReactElement":60,"./invariant":143,"_process":2}],155:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performance * @typechecks */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"./ExecutionEnvironment":25}],156:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performanceNow * @typechecks */ var performance = require("./performance"); /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (!performance || !performance.now) { performance = Date; } var performanceNow = performance.now.bind(performance); module.exports = performanceNow; },{"./performance":155}],157:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = function(node, html) { node.innerHTML = html; }; if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function(node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. node.innerHTML = '\uFEFF' + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; },{"./ExecutionEnvironment":25}],158:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ "use strict"; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; },{}],159:[function(require,module,exports){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ "use strict"; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { if (prevElement && nextElement && prevElement.type === nextElement.type && prevElement.key === nextElement.key && prevElement._owner === nextElement._owner) { return true; } return false; } module.exports = shouldUpdateReactComponent; },{}],160:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule toArray * @typechecks */ var invariant = require("./invariant"); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFrom. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). ("production" !== process.env.NODE_ENV ? invariant( !Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'), 'toArray: Array-like object expected' ) : invariant(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'))); ("production" !== process.env.NODE_ENV ? invariant( typeof length === 'number', 'toArray: Object needs a length property' ) : invariant(typeof length === 'number')); ("production" !== process.env.NODE_ENV ? invariant( length === 0 || (length - 1) in obj, 'toArray: Object should have keys for indices' ) : invariant(length === 0 || (length - 1) in obj)); // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; }).call(this,require('_process')) },{"./invariant":143,"_process":2}],161:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ "use strict"; var ReactElement = require("./ReactElement"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var invariant = require("./invariant"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that: * 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`. * 2. it('should fail when supplied duplicate key', function() { * 3. That a single child and an array with one item have the same key pattern. * }); */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { if (component && component.key != null) { // Explicit key return wrapUserProvidedKey(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} key Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace( userProvidedKeyEscapeRegex, userProvidedKeyEscaper ); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!number} indexSoFar Number of children encountered until this point. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ var traverseAllChildrenImpl = function(children, nameSoFar, indexSoFar, callback, traverseContext) { var nextName, nextIndex; var subtreeCount = 0; // Count of children found in the current subtree. if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; nextName = ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + getComponentKey(child, i) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } else { var type = typeof children; var isOnlyChild = nameSoFar === ''; // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows var storageName = isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar; if (children == null || type === 'boolean') { // All of the above are perceived as null. callback(traverseContext, null, storageName, indexSoFar); subtreeCount = 1; } else if (type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, storageName, indexSoFar); subtreeCount = 1; } else if (type === 'object') { ("production" !== process.env.NODE_ENV ? invariant( !children || children.nodeType !== 1, 'traverseAllChildren(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.' ) : invariant(!children || children.nodeType !== 1)); for (var key in children) { if (children.hasOwnProperty(key)) { nextName = ( nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(key) + SUBSEPARATOR + getComponentKey(children[key], 0) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( children[key], nextName, nextIndex, callback, traverseContext ); } } } } return subtreeCount; }; /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', 0, callback, traverseContext); } module.exports = traverseAllChildren; }).call(this,require('_process')) },{"./ReactElement":60,"./ReactInstanceHandles":68,"./invariant":143,"_process":2}],162:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ "use strict"; var assign = require("./Object.assign"); var keyOf = require("./keyOf"); var invariant = require("./invariant"); function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({$push: null}); var COMMAND_UNSHIFT = keyOf({$unshift: null}); var COMMAND_SPLICE = keyOf({$splice: null}); var COMMAND_SET = keyOf({$set: null}); var COMMAND_MERGE = keyOf({$merge: null}); var COMMAND_APPLY = keyOf({$apply: null}); var ALL_COMMANDS_LIST = [ COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY ]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function(command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { ("production" !== process.env.NODE_ENV ? invariant( Array.isArray(value), 'update(): expected target of %s to be an array; got %s.', command, value ) : invariant(Array.isArray(value))); var specValue = spec[command]; ("production" !== process.env.NODE_ENV ? invariant( Array.isArray(specValue), 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue ) : invariant(Array.isArray(specValue))); } function update(value, spec) { ("production" !== process.env.NODE_ENV ? invariant( typeof spec === 'object', 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET ) : invariant(typeof spec === 'object')); if (spec.hasOwnProperty(COMMAND_SET)) { ("production" !== process.env.NODE_ENV ? invariant( Object.keys(spec).length === 1, 'Cannot have more than one key in an object with %s', COMMAND_SET ) : invariant(Object.keys(spec).length === 1)); return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (spec.hasOwnProperty(COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; ("production" !== process.env.NODE_ENV ? invariant( mergeObj && typeof mergeObj === 'object', 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj ) : invariant(mergeObj && typeof mergeObj === 'object')); ("production" !== process.env.NODE_ENV ? invariant( nextValue && typeof nextValue === 'object', 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue ) : invariant(nextValue && typeof nextValue === 'object')); assign(nextValue, spec[COMMAND_MERGE]); } if (spec.hasOwnProperty(COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function(item) { nextValue.push(item); }); } if (spec.hasOwnProperty(COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function(item) { nextValue.unshift(item); }); } if (spec.hasOwnProperty(COMMAND_SPLICE)) { ("production" !== process.env.NODE_ENV ? invariant( Array.isArray(value), 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value ) : invariant(Array.isArray(value))); ("production" !== process.env.NODE_ENV ? invariant( Array.isArray(spec[COMMAND_SPLICE]), 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE] ) : invariant(Array.isArray(spec[COMMAND_SPLICE]))); spec[COMMAND_SPLICE].forEach(function(args) { ("production" !== process.env.NODE_ENV ? invariant( Array.isArray(args), 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE] ) : invariant(Array.isArray(args))); nextValue.splice.apply(nextValue, args); }); } if (spec.hasOwnProperty(COMMAND_APPLY)) { ("production" !== process.env.NODE_ENV ? invariant( typeof spec[COMMAND_APPLY] === 'function', 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY] ) : invariant(typeof spec[COMMAND_APPLY] === 'function')); nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; }).call(this,require('_process')) },{"./Object.assign":31,"./invariant":143,"./keyOf":150,"_process":2}],163:[function(require,module,exports){ (function (process){ /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = require("./emptyFunction"); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== process.env.NODE_ENV) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (!condition) { var argIndex = 0; console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];})); } }; } module.exports = warning; }).call(this,require('_process')) },{"./emptyFunction":124,"_process":2}],164:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), classSet = React.addons.classSet; module.exports = React.createClass({ displayName: 'Btn', getInitialState: function() { return { children: [], classes: [] }; }, renderChildren: function () { var self = this, childrens = React.Children.count(self.props.children), children = []; if (childrens === 1) { children.push(self.props.children); } else if (childrens > 1) { self.props.children.map(function (item) { children.push(item); }); } return children; }, componentDidMount: function () { var self = this, classes = self.state.classes; if (self.props.classes) { (self.props.classes.split(" ")).map(function (s) { classes[s] = true; }); } self.setState({ classes: classSet(classes) }); }, componentWillReceiveProps: function () { var self = this; self.renderChildren(); }, render: function () { var self = this; return ( React.createElement("div", {className: self.state.classes}, self.renderChildren() ) ); } }); },{"react/addons":3}],165:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), RippleInk = require('./RippleInk'), Icon = require('./Icon'), PubSub = require('../utils/PubSub'), Position = require('../utils/Position'), ClickPosition = require('../utils/ClickPosition'), BackgroundColor = require('../utils/BackgroundColor'); module.exports = React.createClass({ displayName: 'BtnItem', mixins: [PubSub, Position, ClickPosition], getInitialState: function() { return { clicked: false, clickPosition: { x: 0, y: 0 }, showNavBtn: false }; }, renderIcon: function () { if (this.props.icon) { return ( React.createElement(Icon, {name: this.props.icon}) ); } return ( React.createElement("span", null, this.props.label ) ); }, renderChildren: function () { var self = this, childrens = React.Children.count(self.props.children), children = []; if (childrens === 1) { children.push(self.props.children); } else if (childrens > 1) { self.props.children.map(function (item) { children.push(item); }); } return children; }, handleClick: function (event) { var self = this, parentPosition = Position (event.currentTarget), clickPosition = ClickPosition (event, parentPosition), bgColor = BackgroundColor(event), actionClick = self.props.actionClick || false, actionChildren = self.renderChildren(), snackbar = self.props.snackbar || false, toast = self.props.toast || false; /* //eg var clickCases = { "navigation": function() { return self.publish('showNavigation', true); }, "toast": function(click) { return self.publish('toast:' + toast, true); }, "snackbar": function(click) { return self.publish('snackbar:' + snackbar, true); }, "default": function(click, child) { return self.publish('actions:' + click, child); } }; if(o[myCase]) { o[myCase].apply(100, [1, 2, 3]); } else { o["default"](); } //end of eg */ if (actionClick && actionClick === "navigation") { self.publish('showNavigation', true); } if (actionClick && actionClick !== "navigation") { self.publish('actions:'+actionClick, actionChildren); } if (snackbar) { self.publish('snackbar:'+snackbar, true); } if (toast) { self.publish('toast:'+toast, true); } self.setState({ bgColor: bgColor, clickPosition: clickPosition }); if (!self.state.clicked) { self.setState({ clicked: true }); } }, rippleInk: function () { var self = this; if (self.props.rippleEffect) { return ( React.createElement(RippleInk, { bgColor: this.state.bgColor, clickPosition: this.state.clickPosition} ) ); } return false; }, componentDidMount: function () { var self = this; self.subscribe('showNavigationButton', function(data) { self.setState({ showNavigation: data }); }); }, componentWillReceiveProps: function () { this.setState({ clicked: false }); }, renderClass: function () { var self = this, classes = self.props.classes; if (self.props.type) { classes += " e-btn-" + self.props.type; } if (self.props.mini) { classes += "-mini"; } if (self.props.rippleEffect) { classes += " e-ripple"; } return classes; }, renderTooltipText: function () { var self = this, tooltip = (self.props.tooltipText || null); return tooltip; }, renderTooltipPosition: function () { var self = this, position = (self.props.tooltipPosition || null ); return position; }, render: function () { var self = this, classes = self.renderClass(), isDisabled = (self.props.disabled ? 'disabled' : false); return ( React.createElement("button", { className: classes, disabled: isDisabled, onClick: self.handleClick, onTouch: self.handleClick, 'data-tooltip': self.renderTooltipText(), 'data-position': self.renderTooltipPosition() }, self.rippleInk(), self.renderIcon() ) ); } }); },{"../utils/BackgroundColor":174,"../utils/ClickPosition":175,"../utils/Position":178,"../utils/PubSub":179,"./Icon":167,"./RippleInk":172,"react/addons":3}],166:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), Navigation = require('./Navigation'), Btn = require('./Btn'), BtnItem = require('./BtnItem'), List = require('./List'), ListItem = require('./ListItem'); var Component = {}; // Crux - Components var GettingStarted = [ { 'id': 'components-home', 'link': '#', 'text': 'Home', }, { 'id': 'components-download', 'link': '#', 'text': 'Download', } ], Components = [ { 'id': 'components-system', 'link': '#', 'text': 'Build system', }, { 'id': 'components-mongoose', 'link': '#', 'text': 'Mongoose', }, { 'id': 'components-sequelize', 'link': '#', 'text': 'Sequelize (mysql)', }, { 'id': 'components-redis', 'link': '#', 'text': 'Redis store', }, { 'id': 'components-service', 'link': '#', 'text': 'Service integration', }, { 'id': 'components-server', 'link': '#', 'text': 'Express web server', } ]; Component.navigation_menu = ( React.createElement(Navigation, { header: " ", logo: "../assets/img/crux-green.png", footer: "Crux © Privacy & Terms" }, React.createElement(List, { type: "navigation", avatar: false, icon: false }, React.createElement(ListItem, { contentText: "Getting Started", contentLink: "#", more: true, submenu: GettingStarted} ), React.createElement(ListItem, { contentText: "Components", contentLink: "#components", more: true, submenu: Components} ), React.createElement(ListItem, { contentText: "Docs", contentLink: "/docs/"} ) ) ) ); Component.navigation_buttons = ( React.createElement(Btn, null, React.createElement(BtnItem, { type: 'flat', classes: 'simple-button', icon: "navigation-menu", rippleEffect: false, actionClick: "navigation", tooltipText: "Show navigation"} ) ) ); module.exports = function () { return Component; }; },{"./Btn":164,"./BtnItem":165,"./List":168,"./ListItem":169,"./Navigation":171,"react/addons":3}],167:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), classSet = React.addons.classSet; module.exports = React.createClass({ displayName: 'Icon', getInitialState: function() { return { classes: [] }; }, componentDidMount: function () { var self = this, classes = self.state.classes; if (self.props.classes) { (self.props.classes.split(" ")).map(function (s) { classes[s] = true; }); } if (self.props.name) { classes["e-icon-"+self.props.name] = true; } self.setState({ classes: classSet(classes) }); }, render: function () { var self = this; return ( React.createElement("i", {className: self.state.classes}) ); } }); },{"react/addons":3}],168:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), Mobile = require('../utils/Mobile'), PubSub = require('../utils/PubSub'), ListItem = require('./ListItem'), classSet = React.addons.classSet; module.exports = React.createClass({ displayName: 'List', mixins: [PubSub, Mobile], getInitialState: function() { return { classes: { 'e-list': true, 'e-list-navigation': false, 'single-line': true, 'two-line': false, 'multi-line': false, 'has-avatar': true, 'has-icon': true, 'has-checkbox': false, 'has-switches': false, 'right': false, 'left': false, }, isMobile: this.isMobile() }; }, componentDidMount: function () { var self = this, classes = self.state.classes; if (self.props.classes) { (self.props.classes.split(" ")).map(function (s) { classes[s] = true; }); } classes['has-avatar'] = (self.props.avatar) ? true : false; classes['has-icon'] = (self.props.icon) ? true : false; classes['has-right-checkbox'] = (self.props.position === 'right') ? true : false; classes['has-checkbox'] = (self.props.type === 'checkbox' && self.props.position !== 'right' ) ? true : false; classes['two-line'] = (self.props.type === 'two-line') ? true : false; classes['multi-line'] = (self.props.type === 'multi-line') ? true : false; classes['has-switches'] = (self.props.type === 'switch') ? true : false; classes['has-dropdown'] = (self.props.type === 'expand') ? true : false; if (self.props.type === 'navigation' || self.props.type === 'expand') { classes['e-list'] = false; classes['single-line'] = false; classes['e-list-navigation'] = true; } self.setState({ classes: classSet(classes) }); }, componentDidUnmount: function () { // Empty }, renderChildren: function () { var self = this, childrens = React.Children.count(self.props.children), children = []; if (childrens === 1) { var item = self.props.children; item = ( React.addons.cloneWithProps(item, { id: 0, key: 0, dataId: 0, type: self.props.type, position: self.props.position, }) ); children.push(item); } else if (childrens > 1) { self.props.children.map(function (item, key) { item = ( React.addons.cloneWithProps(item, { id: key, key: key, dataId: key, type: self.props.type, position: self.props.position, }) ); children.push(item); }); } return children; }, componentWillReceiveProps: function () { this.renderChildren(); }, render: function () { var self = this; return ( React.createElement("ul", {className: self.state.classes}, self.renderChildren() ) ); } }); },{"../utils/Mobile":177,"../utils/PubSub":179,"./ListItem":169,"react/addons":3}],169:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), Icon = require('./Icon'), RippleInk = require('./RippleInk'), ListItemElement = require('./ListItemElement'), PubSub = require('../utils/PubSub'), Position = require('../utils/Position'), ClickPosition = require('../utils/ClickPosition'), BackgroundColor = require('../utils/BackgroundColor'), classSet = React.addons.classSet; module.exports = React.createClass({ displayName: 'ListItem', mixins: [PubSub], getInitialState: function() { return { classes: { 'e-checkbox': false, }, clickPosition: { x: 0, y: 0 }, dragCSS: {}, isActive: null, expandSubmenu: '', fromElement: 0, toElement: 0 }; }, componentDidMount: function () { var self = this, classes = self.state.classes; if (self.props.classes) { (self.props.classes.split(" ")).map(function (s) { classes[s] = true; }); } classes['has-avatar'] = (self.props.avatar) ? true : false; classes['has-icon'] = (self.props.icon) ? true : false; classes['has-checkbox'] = (self.props.checkbox) ? true : false; classes['has-switches'] = (self.props.type === 'switch') ? true : false; classes['has-right-checkbox'] = (self.props.position === 'right') ? true : false; classes['multi-line'] = (self.props.type === 'lines') ? true : false; self.setState({ classes: classSet(classes) }); }, dragStart: function(ev) { var self = this, element = ev.currentTarget; self.setState({ dragCSS: { // position: 'absolute', // top: element.offsetLeft + "px" }, fromElement: Number(element.id), }); ev.dataTransfer.effectAllowed = 'move'; ev.dataTransfer.setData("text/html", element); }, dragEnd: function(ev) { var self = this, element = ev.target; console.log({ "fromElement" : self.state.fromElement, "toElement" : self.state.toElement }); }, dragOver: function(ev) { var self = this, elementId = ev.currentTarget; self.setState({ dragCSS: { // position: false }, toElement: Number(elementId.id), }); console.log("toElement:" + Number(elementId.id)); }, hideNavigation: function (data) { var parentPosition = Position (data.currentTarget), clickPosition = ClickPosition (data, parentPosition), bgColor = BackgroundColor(data); this.publish('hideNavigation', true); this.publish('showNavigationComponent', data); this.setState({ bgColor: bgColor, clickPosition: clickPosition }); }, renderChildren: function () { var self = this, inputName = (self.props.inputName) ? self.props.inputName : '', contentLink = (self.props.contentLink) ? self.props.contentLink : '', contentText = (self.props.contentText) ? self.props.contentText : '', contentTitle = (self.props.contentTitle) ? self.props.contentTitle : '', contentSubTitle = (self.props.contentSubTitle) ? self.props.contentSubTitle : '', avatarLink = (self.props.avatarLink) ? self.props.avatarLink : '', avatarImg = (self.props.avatarImg) ? self.props.avatarImg : '', avatarAlt = (self.props.avatarAlt) ? self.props.avatarAlt : '', position = (self.props.position) ? self.props.position : false; if (self.props.type === 'checkbox') { if (position === 'right') { return ( React.createElement("li", null, React.createElement("a", {href: avatarLink}, React.createElement("span", {className: "e-list-content"}, React.createElement("img", { className: "e-list-icon", src: avatarImg, alt: avatarAlt} ), React.createElement("span", null, contentText) ) ), React.createElement("div", {className: "e-checkbox"}, React.createElement("label", null, React.createElement("input", { type: "checkbox", name: inputName, className: "toggle", defaultChecked: self.props.isChecked} ), React.createElement("span", {className: "e-wave"}), React.createElement("span", {className: "e-check-valid"}) ) ) ) ); } return ( React.createElement("li", null, React.createElement("div", {className: "e-checkbox"}, React.createElement("label", {className: "e-list-content"}, React.createElement("input", { type: "checkbox", name: inputName, className: "toggle", defaultChecked: self.props.isChecked} ), React.createElement("span", {className: "e-wave"}), React.createElement("span", {className: "e-check-valid"}), React.createElement("span", null, contentText) ) ), React.createElement("a", {href: avatarLink}, React.createElement(Icon, {classes: "e-list-icon", name: self.props.icon}) ) ) ); } if (self.props.type === 'switch') { var showSwitchBox = ''; if (!self.props.isHidden) { showSwitchBox = ( React.createElement("div", {className: "e-switches"}, React.createElement("label", null, React.createElement("input", { type: "checkbox", defaultChecked: self.props.isChecked, name: inputName} ), React.createElement("span", {className: "e-switches-toggle"}) ) ) ); } return ( React.createElement("li", null, React.createElement("a", {href: avatarLink}, React.createElement("span", {className: "e-list-content-fake"}, React.createElement(Icon, {classes: "e-list-icon", name: self.props.icon}), React.createElement("span", null, contentText) ) ), showSwitchBox ) ); } if (self.props.type === 'reorder') { return ( React.createElement("li", { id: self.props.id, draggable: true, onDragEnd: self.dragEnd, onDragStart: self.dragStart, onDragOver: self.dragOver, style: self.state.dragCSS }, React.createElement("a", {href: avatarLink}, React.createElement("span", {className: "e-list-content"}, React.createElement("img", { className: "e-list-avatar", src: avatarImg, alt: avatarAlt} ), React.createElement("span", null, contentText) ) ), React.createElement("a", {href: avatarLink}, React.createElement(Icon, {classes: "e-list-icon", name: self.props.icon}) ) ) ); } if (self.props.type === 'navigation') { var hasMore = null, state_bgColor = this.state.bgColor, state_clickPosition = this.state.clickPosition, hasMenu = null; if (self.props.more) { hasMore = ( React.createElement(Icon, {classes: "e-right", name: "hardware-keyboard-arrow-down"}) ); } if (self.props.submenu) { var submenuItems = []; self.props.submenu.map(function (v, k) { submenuItems.push( React.createElement(ListItemElement, { element: v, key: k, _onClick: self.hideNavigation } ) ); }); hasMenu = ( React.createElement("ul", {className: "e-sublist-navigation"}, submenuItems ) ); } if (contentLink && !self.props.submenu) { return ( React.createElement("li", {className: self.state.isActive}, React.createElement("a", {href: contentLink}, contentText, hasMore ), hasMenu ) ); } return ( React.createElement("li", {className: self.state.isActive}, React.createElement("a", {href: avatarLink, onClick: self.showSubmenu}, contentText, hasMore ), hasMenu ) ); } if (self.props.type === 'expand') { var hasMore = null, hasMenu = null; if (self.props.more) { hasMore = ( React.createElement(Icon, {classes: "e-right", name: "hardware-keyboard-arrow-down"}) ); } if (self.props.submenu) { var submenuItems = []; self.props.submenu.map(function (v, k) { submenuItems.push( React.createElement("li", {key: k}, React.createElement("a", {href: v.link}, v.text ) ) ); }); hasMenu = ( React.createElement("ul", {className: "e-sublist-navigation"}, submenuItems ) ); } // Avatar - testing version /*if (self.props.icon && self.props.avatarImg) { return ( <li className={self.state.isActive}> <a href={avatarLink} onClick={self.showSubmenu}> <span className="e-list-content"> {self.hasAvatar()} {contentText} </span> {hasMore} </a> {hasMenu} </li> ); }*/ return ( React.createElement("li", {className: self.state.isActive}, React.createElement("a", {href: avatarLink, onClick: self.showSubmenu}, contentText, hasMore ), hasMenu ) ); } if (self.props.type === 'single-line') { if (self.props.icon && self.props.avatarImg) { return ( React.createElement("li", null, React.createElement("a", {href: avatarLink}, React.createElement("span", {className: "e-list-content"}, self.hasAvatar(), React.createElement("span", null, contentText) ) ), React.createElement("a", {href: contentLink}, self.hasIcon() ) ) ); } return ( React.createElement("li", null, React.createElement("a", {href: contentLink}, React.createElement("span", {className: "e-list-content"}, self.hasIcon(), self.hasAvatar(), React.createElement("span", null, contentText) ) ) ) ); } if (self.props.type === 'two-line') { if (self.props.icon && self.props.avatarImg) { return ( React.createElement("li", null, React.createElement("a", {href: avatarLink}, React.createElement("span", {className: "e-list-content"}, self.hasAvatar(), React.createElement("span", null, React.createElement("strong", null, contentTitle), React.createElement("br", null), contentText ) ) ), React.createElement("a", {href: contentLink}, self.hasIcon() ) ) ); } return ( React.createElement("li", null, React.createElement("a", {href: contentLink}, React.createElement("span", {className: "e-list-content"}, self.hasIcon(), self.hasAvatar(), React.createElement("span", null, React.createElement("strong", null, contentTitle), React.createElement("br", null), contentText ) ) ) ) ); } if (self.props.type === 'multi-line') { if (self.props.icon && self.props.avatarImg) { return ( React.createElement("li", null, React.createElement("a", {href: avatarLink}, React.createElement("span", {className: "e-list-content"}, self.hasAvatar(), React.createElement("span", null, React.createElement("strong", null, contentTitle), React.createElement("br", null), React.createElement("em", null, contentSubTitle), React.createElement("br", null), contentText ) ) ), React.createElement("a", {href: contentLink}, self.hasIcon() ) ) ); } return ( React.createElement("li", null, React.createElement("a", {href: contentLink}, React.createElement("span", {className: "e-list-content"}, self.hasIcon(), self.hasAvatar(), React.createElement("span", null, React.createElement("strong", null, contentTitle), React.createElement("br", null), React.createElement("em", null, contentSubTitle), React.createElement("br", null), contentText ) ) ) ) ); } return ''; }, hasIcon: function () { var self = this, icon = (self.props.icon) ? self.props.icon : null; if (icon) { return ( React.createElement(Icon, {classes: "e-list-icon", name: self.props.icon}) ); } return null; }, hasAvatar: function () { var self = this, avatarImg = (self.props.avatarImg) ? self.props.avatarImg : null, avatarAlt = (self.props.avatarAlt) ? self.props.avatarAlt : null; if (avatarImg) { return ( React.createElement("img", {className: 'e-list-avatar', src: avatarImg, alt: avatarAlt}) ); } return null; }, showSubmenu: function (ev) { this.setState({ isActive: this.state.isActive !== 'active' ? 'active' : null, }); ev.preventDefault(); }, render: function () { var self = this; return self.renderChildren(); } }); },{"../utils/BackgroundColor":174,"../utils/ClickPosition":175,"../utils/Position":178,"../utils/PubSub":179,"./Icon":167,"./ListItemElement":170,"./RippleInk":172,"react/addons":3}],170:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), PubSub = require('../utils/PubSub'), classSet = React.addons.classSet; module.exports = React.createClass({ displayName: 'ListItemElement', mixins: [PubSub], getInitialState: function() { return { text: false }; }, componentWillReceiveProps: function () { var self = this; self.renderChildren(); }, renderChildren: function () { var self = this, classes = self.state.classes; classes = classSet(classes); return ( React.createElement("li", null, React.createElement("a", { id: self.props.element.id, href: self.props.element.link, onClick: self.props._onClick }, self.props.element.text ) ) ); }, render: function () { var self = this; return self.renderChildren(); } }); },{"../utils/PubSub":179,"react/addons":3}],171:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), Icon = require('./Icon'), Mobile = require('../utils/Mobile'), PubSub = require('../utils/PubSub'), ComponentHTML = require('../utils/ComponentHTML'), classSet = React.addons.classSet; module.exports = React.createClass({ displayName: 'Navigation', mixins: [PubSub, Mobile], getInitialState: function() { return { children: [], isMobile: this.isMobile() ? "e-nav-drawer" : "e-nav-drawer", classes: { 'e-main': false, 'e-navigation-open': false, }, width: window.outerWidth }; }, componentDidMount: function () { var self = this, currentWidth = window.outerWidth; // Load HomePage var init_component = "components-home"; ComponentHTML.set(init_component); /* if (currentWidth <= 1440) { self.publish('showNavigationButton', true); } window.addEventListener("resize", function() { currentWidth = window.outerWidth; if (currentWidth <= 1440) { self.publish('showNavigationButton', true); } }); */ self.subscribe('showNavigation', this.showNavigation); self.subscribe('showNavigationComponent', this.showNavigationComponent); self.subscribe('hideNavigation', this.hideNavigation); }, componentDidUnmount: function () { this.unsubscribe('showNavigation', this.hideNavigation); }, renderChildren: function () { var self = this, childrens = React.Children.count(self.props.children), children = []; // One item if (childrens === 1) { children = self.props.children; } else if (childrens > 1) { // Multiple items self.props.children.map(function (item, key) { item = ( React.addons.cloneWithProps(item, { id: key, key: key }) ); children.push(item); }); } return children; }, renderHeader: function () { var self = this; if (self.props.header) { return ( React.createElement("header", {className: "e-nav-header"}, self.renderLogo(), React.createElement("span", {className: "example-logo"}, self.props.header ) ) ); } return null; }, renderFooter: function () { var self = this; if (self.props.footer) { return ( React.createElement("footer", {className: "e-nav-footer"}, self.props.footer ) ); } return null; }, renderLogo: function () { var self = this, logoAlt = self.props.header ? self.props.header : null; if (self.props.logo) { return ( React.createElement("img", { className: "nav-logo", alt: logoAlt, src: self.props.logo} ) ); } return null; }, showNavigation: function () { var self = this, classes = self.state.classes; classes['e-navigation-open'] = true; self.setState({ classes: classes }); document.querySelector('body').className = 'e-navigation-open'; }, showNavigationComponent: function (data) { if (data.target.id) { ComponentHTML.set(data.target.id); } }, hideNavigation: function () { var self = this, classes = self.state.classes; classes['e-navigation-open'] = false; self.setState({ classes: classes }); document.querySelector('body').className = ''; }, renderContent: function () { var self = this; return ( React.createElement("div", {className: "e-main-content"}, React.createElement("button", { className: "simple-button e-nav-toggle", onClick: self.showNavigation }, React.createElement(Icon, {name: "navigation-menu"}), self.renderChildren() ) ) ); }, renderNavigation: function () { var self = this; return ( React.createElement("aside", {className: self.state.isMobile + " e-shadow-1"}, React.createElement("nav", null, React.createElement("div", {className: "e-navigation-wrapper"}, self.renderHeader(), self.renderChildren() ), self.renderFooter() ) ) ); }, render: function () { var self = this, classes = self.state.classes; classes = classSet(classes); return ( React.createElement("div", {className: classes}, self.renderNavigation(), React.createElement("div", { className: "e-modal-bg", onClick: self.hideNavigation} ) ) ); } }); },{"../utils/ComponentHTML":176,"../utils/Mobile":177,"../utils/PubSub":179,"./Icon":167,"react/addons":3}],172:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; module.exports = React.createClass({ displayName: 'RippleInk', render: function () { var rippleStyle = { left: this.props.clickPosition.x + 'px', top: this.props.clickPosition.y + 'px', backgroundColor: this.props.bgColor }, ripple = ( React.createElement("div", { key: this.props.clickPosition.x, className: 'e-ripple-effect', style: rippleStyle } ) ); return ( React.createElement("div", { ref: "rippleAnimate", className: "e-ripple-container" }, React.createElement(ReactCSSTransitionGroup, { transitionName: "e-ripple-effect" }, ripple ) ) ); } }); },{"react/addons":3}],173:[function(require,module,exports){ 'use strict'; var React = require('react/addons'), ComponentsCrux = require('./components/ComponentsCrux'), ComponentsCrux = ComponentsCrux(); // Navigation Menu + Buttons React.render( ComponentsCrux.navigation_menu, document.getElementById('navigationMenu') ); React.render( ComponentsCrux.navigation_buttons, document.getElementById('navigationBtn') ); var navigationBtn = document.getElementById('navigationBtn'), navigationMenu = document.getElementById('navigationMenu'); },{"./components/ComponentsCrux":166,"react/addons":3}],174:[function(require,module,exports){ 'use strict'; module.exports = function (element) { var color = null; if (element) { color = window.getComputedStyle (element.currentTarget).getPropertyValue('color'). replace("rgb", "rgba").replace(")", ", 0.5)"); } return color; }; },{}],175:[function(require,module,exports){ 'use strict'; module.exports = function (element, parentElement) { var xPosition = 0, yPosition = 0; if (element && parentElement) { xPosition = (element.clientX - parentElement.x); yPosition = (element.clientY - parentElement.y); } console.log("Element + parentElement: "); console.log({ x: xPosition, y: yPosition }); return { x: xPosition, y: yPosition }; }; },{}],176:[function(require,module,exports){ 'use strict'; module.exports = { set: function (id) { var html = '', React = require('react/addons'), ComponentsList = require('../components/ComponentsCrux'), Components = ComponentsList(), ComponentsID = "home", ComponentsDocumentID = "home"; if (id) { var filePath = "./" + id + ".html?fid="+(Math.random()*1000000), xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", filePath, false); xmlhttp.send(); html = xmlhttp.responseText; ComponentsID = id.replace("components-", "").replace("-", "_"); ComponentsDocumentID = id + "-reactjs"; } document.querySelector('.e-main-content').innerHTML = html; if (Components[ComponentsID] && typeof Components[ComponentsID] === 'object') { if (Object.prototype.toString.call((Components[ComponentsID])) === '[object Object]') { React.render( Components[ComponentsID], document.getElementById(ComponentsDocumentID) ); } else if (Object.prototype.toString.call((Components[ComponentsID])) === '[object Array]') { Components[ComponentsID].map(function(reactComponents) { var reactComponentKey = Object.keys(reactComponents).toString(), reactComponentID = (id +"-"+ reactComponentKey).replace("_", "-"); // console.log(reactComponents, reactComponentKey, reactComponentID); if (document.getElementById(reactComponentID)) { React.render( reactComponents[reactComponentKey], document.getElementById(reactComponentID) ); } }); } } } }; },{"../components/ComponentsCrux":166,"react/addons":3}],177:[function(require,module,exports){ 'use strict'; module.exports = { isMobile: function () { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { return false; } } }; },{}],178:[function(require,module,exports){ 'use strict'; module.exports = function (element) { var xPosition = 0; var yPosition = 0; while (element) { xPosition += ( (element.offsetLeft - element.scrollLeft) + element.clientLeft) ; yPosition += ( (element.offsetTop - element.scrollTop) + element.clientTop) ; console.log("Element Position: " + element); element = element.offsetParent; console.log("Element offsetParent Position: " + element); } return { x: xPosition, y: yPosition }; }; },{}],179:[function(require,module,exports){ 'use strict'; var EventEmitter = require('events').EventEmitter, PubSub = new EventEmitter(); PubSub.setMaxListeners(50); module.exports = { publish: function () { PubSub.emit.apply(PubSub, arguments); }, subscribe: function () { PubSub.on.apply(PubSub, arguments); }, unsubscribe: function () { PubSub.removeListener.apply(PubSub, arguments); } }; },{"events":1}]},{},[173]);
// flow-typed signature: a69544fecedd63dad255aca141930d06 // flow-typed version: <<STUB>>/sinon_v^1.17.2/flow_v0.33.0 /** * This is an autogenerated libdef stub for: * * 'sinon' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'sinon' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'sinon/lib/sinon' { declare module.exports: any; } declare module 'sinon/lib/sinon/assert' { declare module.exports: any; } declare module 'sinon/lib/sinon/behavior' { declare module.exports: any; } declare module 'sinon/lib/sinon/call' { declare module.exports: any; } declare module 'sinon/lib/sinon/collection' { declare module.exports: any; } declare module 'sinon/lib/sinon/extend' { declare module.exports: any; } declare module 'sinon/lib/sinon/format' { declare module.exports: any; } declare module 'sinon/lib/sinon/log_error' { declare module.exports: any; } declare module 'sinon/lib/sinon/match' { declare module.exports: any; } declare module 'sinon/lib/sinon/mock' { declare module.exports: any; } declare module 'sinon/lib/sinon/sandbox' { declare module.exports: any; } declare module 'sinon/lib/sinon/spy' { declare module.exports: any; } declare module 'sinon/lib/sinon/stub' { declare module.exports: any; } declare module 'sinon/lib/sinon/test_case' { declare module.exports: any; } declare module 'sinon/lib/sinon/test' { declare module.exports: any; } declare module 'sinon/lib/sinon/times_in_words' { declare module.exports: any; } declare module 'sinon/lib/sinon/typeOf' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/core' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/event' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_server_with_clock' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_server' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_timers' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_xdomain_request' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_xml_http_request' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/timers_ie' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/xdr_ie' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/xhr_ie' { declare module.exports: any; } declare module 'sinon/lib/sinon/walk' { declare module.exports: any; } declare module 'sinon/pkg/sinon-1.17.6' { declare module.exports: any; } declare module 'sinon/pkg/sinon-ie-1.17.6' { declare module.exports: any; } declare module 'sinon/pkg/sinon-ie' { declare module.exports: any; } declare module 'sinon/pkg/sinon-server-1.17.6' { declare module.exports: any; } declare module 'sinon/pkg/sinon-server' { declare module.exports: any; } declare module 'sinon/pkg/sinon' { declare module.exports: any; } // Filename aliases declare module 'sinon/lib/sinon.js' { declare module.exports: $Exports<'sinon/lib/sinon'>; } declare module 'sinon/lib/sinon/assert.js' { declare module.exports: $Exports<'sinon/lib/sinon/assert'>; } declare module 'sinon/lib/sinon/behavior.js' { declare module.exports: $Exports<'sinon/lib/sinon/behavior'>; } declare module 'sinon/lib/sinon/call.js' { declare module.exports: $Exports<'sinon/lib/sinon/call'>; } declare module 'sinon/lib/sinon/collection.js' { declare module.exports: $Exports<'sinon/lib/sinon/collection'>; } declare module 'sinon/lib/sinon/extend.js' { declare module.exports: $Exports<'sinon/lib/sinon/extend'>; } declare module 'sinon/lib/sinon/format.js' { declare module.exports: $Exports<'sinon/lib/sinon/format'>; } declare module 'sinon/lib/sinon/log_error.js' { declare module.exports: $Exports<'sinon/lib/sinon/log_error'>; } declare module 'sinon/lib/sinon/match.js' { declare module.exports: $Exports<'sinon/lib/sinon/match'>; } declare module 'sinon/lib/sinon/mock.js' { declare module.exports: $Exports<'sinon/lib/sinon/mock'>; } declare module 'sinon/lib/sinon/sandbox.js' { declare module.exports: $Exports<'sinon/lib/sinon/sandbox'>; } declare module 'sinon/lib/sinon/spy.js' { declare module.exports: $Exports<'sinon/lib/sinon/spy'>; } declare module 'sinon/lib/sinon/stub.js' { declare module.exports: $Exports<'sinon/lib/sinon/stub'>; } declare module 'sinon/lib/sinon/test_case.js' { declare module.exports: $Exports<'sinon/lib/sinon/test_case'>; } declare module 'sinon/lib/sinon/test.js' { declare module.exports: $Exports<'sinon/lib/sinon/test'>; } declare module 'sinon/lib/sinon/times_in_words.js' { declare module.exports: $Exports<'sinon/lib/sinon/times_in_words'>; } declare module 'sinon/lib/sinon/typeOf.js' { declare module.exports: $Exports<'sinon/lib/sinon/typeOf'>; } declare module 'sinon/lib/sinon/util/core.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/core'>; } declare module 'sinon/lib/sinon/util/event.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/event'>; } declare module 'sinon/lib/sinon/util/fake_server_with_clock.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_server_with_clock'>; } declare module 'sinon/lib/sinon/util/fake_server.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_server'>; } declare module 'sinon/lib/sinon/util/fake_timers.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_timers'>; } declare module 'sinon/lib/sinon/util/fake_xdomain_request.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_xdomain_request'>; } declare module 'sinon/lib/sinon/util/fake_xml_http_request.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_xml_http_request'>; } declare module 'sinon/lib/sinon/util/timers_ie.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/timers_ie'>; } declare module 'sinon/lib/sinon/util/xdr_ie.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/xdr_ie'>; } declare module 'sinon/lib/sinon/util/xhr_ie.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/xhr_ie'>; } declare module 'sinon/lib/sinon/walk.js' { declare module.exports: $Exports<'sinon/lib/sinon/walk'>; } declare module 'sinon/pkg/sinon-1.17.6.js' { declare module.exports: $Exports<'sinon/pkg/sinon-1.17.6'>; } declare module 'sinon/pkg/sinon-ie-1.17.6.js' { declare module.exports: $Exports<'sinon/pkg/sinon-ie-1.17.6'>; } declare module 'sinon/pkg/sinon-ie.js' { declare module.exports: $Exports<'sinon/pkg/sinon-ie'>; } declare module 'sinon/pkg/sinon-server-1.17.6.js' { declare module.exports: $Exports<'sinon/pkg/sinon-server-1.17.6'>; } declare module 'sinon/pkg/sinon-server.js' { declare module.exports: $Exports<'sinon/pkg/sinon-server'>; } declare module 'sinon/pkg/sinon.js' { declare module.exports: $Exports<'sinon/pkg/sinon'>; }
/* * 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'; /** * Class representing a JobStatus. */ class JobStatus { /** * Create a JobStatus. * @member {number} [executionCount] Gets the number of times this job has * executed. * @member {number} [failureCount] Gets the number of times this job has * failed. * @member {number} [faultedCount] Gets the number of faulted occurrences * (occurrences that were retried and failed as many times as the retry * policy states). * @member {date} [lastExecutionTime] Gets the time the last occurrence * executed in ISO-8601 format. Could be empty if job has not run yet. * @member {date} [nextExecutionTime] Gets the time of the next occurrence in * ISO-8601 format. Could be empty if the job is completed. */ constructor() { } /** * Defines the metadata of JobStatus * * @returns {object} metadata of JobStatus * */ mapper() { return { required: false, serializedName: 'JobStatus', type: { name: 'Composite', className: 'JobStatus', modelProperties: { executionCount: { required: false, readOnly: true, serializedName: 'executionCount', type: { name: 'Number' } }, failureCount: { required: false, readOnly: true, serializedName: 'failureCount', type: { name: 'Number' } }, faultedCount: { required: false, readOnly: true, serializedName: 'faultedCount', type: { name: 'Number' } }, lastExecutionTime: { required: false, readOnly: true, serializedName: 'lastExecutionTime', type: { name: 'DateTime' } }, nextExecutionTime: { required: false, readOnly: true, serializedName: 'nextExecutionTime', type: { name: 'DateTime' } } } } }; } } module.exports = JobStatus;
"use strict"; const serializer_1 = require('./serializer'); const schema_tree_1 = require('./schema-tree'); const error_1 = require('./error'); require('./mimetypes'); class InvalidJsonPath extends error_1.JsonSchemaErrorBase { } exports.InvalidJsonPath = InvalidJsonPath; // The schema tree node property of the SchemaClass. const kSchemaNode = Symbol('schema-node'); // The value property of the SchemaClass. const kOriginalRoot = Symbol('schema-value'); /** * Splits a JSON path string into fragments. Fragments can be used to get the value referenced * by the path. For example, a path of "a[3].foo.bar[2]" would give you a fragment array of * ["a", 3, "foo", "bar", 2]. * @param path The JSON string to parse. * @returns {string[]} The fragments for the string. * @private */ function _parseJsonPath(path) { const fragments = (path || '').split(/\./g); const result = []; while (fragments.length > 0) { const fragment = fragments.shift(); const match = fragment.match(/([^\[]+)((\[.*\])*)/); if (!match) { throw new InvalidJsonPath(); } result.push(match[1]); if (match[2]) { const indices = match[2].slice(1, -1).split(']['); result.push(...indices); } } return result.filter(fragment => !!fragment); } /** Get a SchemaTreeNode from the JSON path string. */ function _getSchemaNodeForPath(rootMetaData, path) { let fragments = _parseJsonPath(path); // TODO: make this work with union (oneOf) schemas return fragments.reduce((md, current) => { return md && md.children && md.children[current]; }, rootMetaData); } class SchemaClassBase { constructor(schema, value, ...fallbacks) { this[kOriginalRoot] = value; const forward = fallbacks.length > 0 ? (new SchemaClassBase(schema, fallbacks.pop(), ...fallbacks).$$schema()) : null; this[kSchemaNode] = new schema_tree_1.RootSchemaTreeNode(this, { forward, value, schema }); } $$root() { return this; } $$schema() { return this[kSchemaNode]; } $$originalRoot() { return this[kOriginalRoot]; } /** Sets the value of a destination if the value is currently undefined. */ $$alias(source, destination) { let sourceSchemaTreeNode = _getSchemaNodeForPath(this.$$schema(), source); const fragments = _parseJsonPath(destination); const maybeValue = fragments.reduce((value, current) => { return value && value[current]; }, this.$$originalRoot()); if (maybeValue !== undefined) { sourceSchemaTreeNode.set(maybeValue); return true; } return false; } /** Destroy all links between schemas to allow for GC. */ $$dispose() { this.$$schema().dispose(); } /** Get a value from a JSON path. */ $$get(path) { const node = _getSchemaNodeForPath(this.$$schema(), path); return node ? node.get() : undefined; } /** Set a value from a JSON path. */ $$set(path, value) { const node = _getSchemaNodeForPath(this.$$schema(), path); if (node) { node.set(value); } else { // This might be inside an object that can have additionalProperties, so // a TreeNode would not exist. const splitPath = _parseJsonPath(path); if (!splitPath) { return undefined; } const parent = splitPath .slice(0, -1) .reduce((parent, curr) => parent && parent[curr], this); if (parent) { parent[splitPath[splitPath.length - 1]] = value; } } } /** Get the Schema associated with a path. */ $$typeOf(path) { const node = _getSchemaNodeForPath(this.$$schema(), path); return node ? node.type : null; } $$defined(path) { const node = _getSchemaNodeForPath(this.$$schema(), path); return node ? node.defined : false; } $$delete(path) { const node = _getSchemaNodeForPath(this.$$schema(), path); if (node) { node.destroy(); } } /** Serialize into a string. */ $$serialize(mimetype = 'application/json', ...options) { let str = ''; const serializer = serializer_1.Serializer.fromMimetype(mimetype, (s) => str += s, ...options); serializer.start(); this.$$schema().serialize(serializer); serializer.end(); return str; } } /** * Create a class from a JSON SCHEMA object. Instanciating that class with an object * allows for extended behaviour. * This is the base API to access the Configuration in the CLI. * @param schema * @returns {GeneratedSchemaClass} * @constructor */ function SchemaClassFactory(schema) { class GeneratedSchemaClass extends SchemaClassBase { constructor(value, ...fallbacks) { super(schema, value, ...fallbacks); } } return GeneratedSchemaClass; } exports.SchemaClassFactory = SchemaClassFactory; //# sourceMappingURL=/Users/hansl/Sources/angular-cli/packages/@ngtools/json-schema/src/schema-class-factory.js.map
export default function* () { yield this.clear("dist") yield this.source("src/fly.png").target("dist") }
var suite = require('suite.js'); var f = require('funkit/array'); suite(f.last, [ [[1, 2, 3, 4]], 4, [[]], undefined ]);
'use strict' const chai = require('chai') const dirtyChai = require('dirty-chai') const Persist = require('../../src/server/lobby/persist.js') const expect = chai.expect chai.use(dirtyChai) describe('Persist', () => { const persist = Persist.createPersist() it('lobby ops', async () => { let lobbyId { const lobbyInfo = await persist.createLobby({ userId: '1' }) expect(lobbyInfo.owner.id).to.equal('1') lobbyId = lobbyInfo.id } { const lobbyInfo = await persist.joinLobby({ userId: '2', id: lobbyId }) expect(lobbyInfo.members).to.deep.equal([{ id: '1' }, { id: '2' }]) } { const publicLobbies = await persist.getPublicLobbies() expect(publicLobbies).to.deep.equal([]) } { const lobbyInfo = await persist.setLobbyPublic({ userId: '1', id: lobbyId, public: true }) expect(lobbyInfo.public).to.be.true() } { const publicLobbies = await persist.getPublicLobbies() expect(publicLobbies).to.be.deep.equal([lobbyId]) } let slot1id let slot2id { const lobbyInfo = await persist.setLobbyGame({ userId: '1', id: lobbyId, gameInfo: { json: { playersInfo: { info: 'players', players: { min: 2, max: 2 } } } } }) expect(lobbyInfo.playersInfo.slots.slot.length).to.be.equal(2) slot1id = lobbyInfo.playersInfo.slots.slot[0].id slot2id = lobbyInfo.playersInfo.slots.slot[1].id } { const lobbyInfo = await persist.assignSlot({ lobbyId: lobbyId, userId: '1', senderId: '1', slotId: slot1id }) expect(lobbyInfo.playersInfo.slots.slot[0].user.id).to.be.equal('1') } { const lobbyInfo = await persist.assignSlot({ lobbyId: lobbyId, userId: '2', senderId: '2', slotId: slot2id }) expect(lobbyInfo.playersInfo.slots.slot[1].user.id).to.be.equal('2') } { const lobbyInfo = await persist.assignSlot({ lobbyId: lobbyId, userId: '2', senderId: '2', slotId: slot1id }) expect(lobbyInfo.playersInfo.slots.slot[0].user.id).to.be.equal('1') } { const lobbyInfo = await persist.assignSlot({ lobbyId: lobbyId, userId: '2', senderId: '1', slotId: slot1id }) expect(lobbyInfo.playersInfo.slots.slot[0].user.id).to.be.equal('2') } { const lobbyInfo = await persist.assignSlot({ lobbyId: lobbyId, userId: 'foo', senderId: '1', slotId: slot1id }) expect(lobbyInfo.playersInfo.slots.slot[0].user.id).to.be.equal('2') } { const lobbyInfo = await persist.assignSlot({ lobbyId: lobbyId, senderId: '1', slotId: slot1id }) expect(lobbyInfo.playersInfo.slots.slot[0].user).to.be.undefined() } }) after(() => { persist.close() }) })
angular.module('application', ['ui.scroll']).controller('mainController', [ '$scope', '$log', '$timeout', function($scope, console, $timeout) { var datasource = {}; datasource.cache = { initialize: function() { this.isEnabled = true; this.items = {}; this.getPure = datasource.get; return datasource.get = this.getCached; }, getCached: function(index, count, successCallback) { var self; self = datasource.cache; if (self.isEnabled) { if (self.getItems(index, count, successCallback)) { return; } return self.getPure(index, count, function(result) { self.saveItems(index, count, result); return successCallback(result); }); } return self.getPure(index, count, successCallback); }, toggle: function() { this.isEnabled = !this.isEnabled; return this.items = {}; }, saveItems: function(index, count, resultItems) { var i, item, j, len, results; results = []; for (i = j = 0, len = resultItems.length; j < len; i = ++j) { item = resultItems[i]; if (!this.items.hasOwnProperty(index + i)) { results.push(this.items[index + i] = item); } else { results.push(void 0); } } return results; }, getItems: function(index, count, successCallback) { var i, isCached, j, ref, ref1, result; result = []; isCached = true; for (i = j = ref = index, ref1 = index + count - 1; j <= ref1; i = j += 1) { if (!this.items.hasOwnProperty(i)) { isCached = false; return; } result.push(this.items[i]); } successCallback(result); return true; } }; datasource.get = function(index, count, success) { return $timeout(function() { var i, item, j, ref, ref1, result; result = []; for (i = j = ref = index, ref1 = index + count - 1; ref <= ref1 ? j <= ref1 : j >= ref1; i = ref <= ref1 ? ++j : --j) { item = {}; item.content = "item #" + i; item.data = { some: false }; result.push(item); } return success(result); }, 100); }; $scope.datasource = datasource; datasource.cache.initialize(); } ]);
// This file is part of Indico. // Copyright (C) 2002 - 2021 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import {createSelector} from 'reselect'; import {RequestState} from 'indico/utils/redux'; import {PaperState} from './models'; export const isFetchingInitialPaperDetails = state => state.paper.requests.details.state === RequestState.STARTED && !state.paper.details; export const isPaperStateResetInProgress = state => state.paper.requests.resetState.state === RequestState.STARTED; export const isDeletingComment = state => state.paper.requests.deleteComment.state === RequestState.STARTED; export const isEventLocked = state => state.paper.details.event.isLocked; export const getCurrentUser = state => state.staticData.user; export const getPaperDetails = state => state.paper.details; export const getPaperEvent = state => state.paper.details.event; export const getPaperContribution = state => state.paper.details.contribution; export const getReviewingQuestions = createSelector( getPaperEvent, ({cfp}) => ({ layout: cfp.layoutReviewQuestions, content: cfp.contentReviewQuestions, }) ); export const canJudgePaper = createSelector( getPaperDetails, getPaperEvent, ({isInFinalState, canJudge}, {isLocked}) => !isLocked && !isInFinalState && canJudge ); export const canReviewPaper = createSelector( getPaperDetails, getPaperEvent, ({isInFinalState, canReview}, {isLocked}) => !isLocked && !isInFinalState && canReview ); export const canSubmitNewRevision = createSelector( getPaperDetails, getPaperEvent, ({canSubmitProceedings, canManage, state: {name: stateName}}, {isLocked}) => !isLocked && stateName === PaperState.to_be_corrected && (canManage || canSubmitProceedings) ); export const canCommentPaper = createSelector( getPaperDetails, getPaperEvent, ({isInFinalState, canComment}, {isLocked}) => !isLocked && !isInFinalState && canComment );
$(function() { // Open external links in a new window var hostname = window.location.hostname; $("a[href^=http]") .not("a[href*='" + hostname + "']") .addClass('link external') .attr('target', '_blank'); $('[title!=""]').qtip({ position: { my: 'top center', at: 'bottom center', adjust: { y: 4 } }, style: { classes: 'qtip-tipsy' }, show: { delay: 0 }, hide: { delay: 0 } }); $(window).on('scroll', function() { if (document.body.scrollTop > 0) { $('.navigation').addClass('is-fixed'); } else { $('.navigation').removeClass('is-fixed'); } }); });
/** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ define([ 'jquery', 'uiClass', 'Magento_Paypal/js/rule', 'mageUtils', 'underscore' ], function ($, Class, Rule, utils, _) { 'use strict'; return Class.extend({ defaults: { /** * The event corresponding to the state change */ systemEvent: 'change', /** * The rules applied after the page is loaded */ afterLoadRules: [], /** * An attribute of the element responsible for the activation of the payment method (data attribute) */ enableButton: '[data-enable="payment"]', /** * An attribute of the element responsible for the activation of the Payflow Express (data attribute) */ enableExpress: '[data-enable="express"]', /** * An attribute of the element responsible for the activation of the * PayPal Express In-Context Checkout Experience (data attribute) */ enableInContextPayPal: '[data-enable="in-context-api"]', /** * An attribute of the element responsible for the activation of the Payflow Bml (data attribute) */ enableBml: '[data-enable="bml"]', /** * An attribute of the element responsible for the activation of the PayPal Bml (data attribute) */ enableBmlPayPal: '[data-enable="bml-api"]', /** * An attribute of the element responsible for the visibility of the PayPal Merchant Id (data attribute) */ dependsMerchantId: '[data-enable="merchant-id"]', /** * An attribute of the element responsible for the visibility of the Payflow Bml Sort Order (data attribute) */ dependsBmlSortOrder: '[data-enable="bml-sort-order"]', /** * An attribute of the element responsible for the visibility of the PayPal Bml Sort Order (data attribute) */ dependsBmlApiSortOrder: '[data-enable="bml-api-sort-order"]', /** * Templates element selectors */ templates: { elementSelector: 'div.section-config tr[id$="${ $.identifier }"]:first' } }, /** * Constructor * * @param {Object} config * @param {String} identifier * @returns {exports.initialize} */ initialize: function (config, identifier) { this.initConfig(config); this.$self = this.createElement(identifier); return this; }, /** * Initialization events * * @returns {exports.initEvents} */ initEvents: function () { _.each(this.config.events, function (elementEvents, selector) { var solution = this, selectorButton = solution.$self.find(selector), $self = solution.$self, events = elementEvents; selectorButton.on(solution.systemEvent, function () { _.each(events, function (elementEvent, name) { var predicate = elementEvent.predicate, result = true, /** * @param {Function} functionPredicate */ predicateCallback = function (functionPredicate) { result = functionPredicate(solution, predicate.message, predicate.argument); if (result) { $self.trigger(name); } else { $self.trigger(predicate.event); } }; if (solution.getValue($(this)) === elementEvent.value) { if (predicate.name) { require([ 'Magento_Paypal/js/predicate/' + predicate.name ], predicateCallback); } else { $self.trigger(name); } } }, this); }); }, this); return this; }, /** * @param {Object} $element * @returns {*} */ getValue: function ($element) { if ($element.is(':checkbox')) { return $element.prop('checked') ? '1' : '0'; } return $element.val(); }, /** * Adding event listeners * * @returns {exports.addListeners} */ addListeners: function () { _.each(this.config.relations, function (rules, targetName) { var $target = this.createElement(targetName); _.each(rules, function (instances, instanceName) { _.each(instances, function (instance) { var handler = new Rule({ name: instanceName, $target: $target, $owner: this.$self, data: { buttonConfiguration: this.buttonConfiguration, enableButton: this.enableButton, enableExpress: this.enableExpress, enableInContextPayPal: this.enableInContextPayPal, enableBml: this.enableBml, enableBmlPayPal: this.enableBmlPayPal, dependsMerchantId: this.dependsMerchantId, dependsBmlSortOrder: this.dependsBmlSortOrder, dependsBmlApiSortOrder: this.dependsBmlApiSortOrder, solutionsElements: this.solutionsElements, argument: instance.argument } }); if (instance.event === ':load') { this.afterLoadRules.push(handler); return; } this.$self.on(instance.event, _.bind(handler.apply, handler)); }, this); }, this); }, this); return this; }, /** * Create a jQuery element according to selector * * @param {String} identifier * @returns {*} */ createElement: function (identifier) { if (identifier === ':self') { return this.$self; } return $(utils.template(this.templates.elementSelector, { 'identifier': identifier })); }, /** * Assign solutions elements * * @param {Object} elements * @returns {exports.setSolutionsElements} */ setSolutionsElements: function (elements) { this.solutionsElements = elements; return this; } }); });
var Path = require('path'); var Lab = require('lab'); var Code = require('code'); var Hapi = require('hapi'); var Proxyquire = require('proxyquire'); var Config = require('./config'); var DummyPlugin = require('./fixtures/dummy-plugin'); var lab = exports.lab = Lab.script(); var stub = { BaseModel: {} }; var ModelsPlugin = Proxyquire('..', { './lib/base-model': stub.BaseModel }); lab.experiment('Plugin', function () { lab.test('it returns an error when the db connection fails', function (done) { var realConnect = stub.BaseModel.connect; stub.BaseModel.connect = function (config, callback) { callback(Error('connect failed')); }; var server = new Hapi.Server(); var Plugin = { register: ModelsPlugin, options: Config }; server.connection({ port: 0 }); server.register(Plugin, function (err) { Code.expect(err).to.be.an.object(); stub.BaseModel.connect = realConnect; done(); }); }); lab.test('it successfuly connects to the db and exposes the base model', function (done) { var server = new Hapi.Server(); var Plugin = { register: ModelsPlugin, options: Config }; server.connection({ port: 0 }); server.register(Plugin, function (err) { if (err) { return done(err); } Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object(); Code.expect(server.plugins['hapi-mongo-models'].BaseModel).to.exist(); server.plugins['hapi-mongo-models'].BaseModel.disconnect(); done(); }); }); lab.test('it successfuly connects to the db and exposes defined models', function (done) { var server = new Hapi.Server(); var Plugin = { register: ModelsPlugin, options: { mongodb: Config.mongodb, models: { Dummy: './test/fixtures/dummy-model' } } }; server.connection({ port: 0 }); server.register(Plugin, function (err) { if (err) { return done(err); } Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object(); Code.expect(server.plugins['hapi-mongo-models'].Dummy).to.exist(); server.plugins['hapi-mongo-models'].BaseModel.disconnect(); done(); }); }); lab.test('it successfuly connects to the db and exposes defined models (with absolute paths)', function (done) { var server = new Hapi.Server(); var Plugin = { register: ModelsPlugin, options: { mongodb: Config.mongodb, models: { Dummy: Path.join(__dirname, 'fixtures/dummy-model') } } }; server.connection({ port: 0 }); server.register(Plugin, function (err) { if (err) { return done(err); } Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object(); Code.expect(server.plugins['hapi-mongo-models'].Dummy).to.exist(); server.plugins['hapi-mongo-models'].BaseModel.disconnect(); done(); }); }); lab.test('it successfuly connects to the db and exposes defined models and skips indexing', function (done) { var server = new Hapi.Server(); var Plugin = { register: ModelsPlugin, options: { mongodb: Config.mongodb, models: { Dummy: './test/fixtures/dummy-model' }, autoIndex: false } }; server.connection({ port: 0 }); server.register(Plugin, function (err) { if (err) { return done(err); } server.start(function (err) { if (err) { return done(err); } Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object(); Code.expect(server.plugins['hapi-mongo-models'].Dummy).to.exist(); server.plugins['hapi-mongo-models'].BaseModel.disconnect(); done(); }); }); }); lab.test('it allows models to be added dynamically specifically during another plugin\'s registration', function (done) { var server = new Hapi.Server(); var hapiMongoModelsPlugin = { register: ModelsPlugin, options: { mongodb: Config.mongodb } }; var plugins = [hapiMongoModelsPlugin, DummyPlugin]; server.connection({ port: 0 }); server.register(plugins, function (err) { if (err) { return done(err); } server.start(function (err) { Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object(); Code.expect(server.plugins['hapi-mongo-models'].Dummy).to.exist(); server.plugins['hapi-mongo-models'].BaseModel.disconnect(); done(); }); }); }); });
(function(v){function C(d,a,e,l){if(a.points.errorbars){d=[{x:!0,number:!0,required:!0},{y:!0,number:!0,required:!0}];e=a.points.errorbars;if("x"==e||"xy"==e)a.points.xerr.asymmetric&&d.push({x:!0,number:!0,required:!0}),d.push({x:!0,number:!0,required:!0});if("y"==e||"xy"==e)a.points.yerr.asymmetric&&d.push({y:!0,number:!0,required:!0}),d.push({y:!0,number:!0,required:!0});l.format=d}}function A(d,a,e,l,c,r,B,g,j,h,w){l+=h;c+=h;r+=h;"x"==a.err?(c>e+j?u(d,[[c,l],[Math.max(e+j,w[0]),l]]):B=!1,r<e- j?u(d,[[Math.min(e-j,w[1]),l],[r,l]]):g=!1):(c<l-j?u(d,[[e,c],[e,Math.min(l-j,w[0])]]):B=!1,r>l+j?u(d,[[e,Math.max(l+j,w[1])],[e,r]]):g=!1);j=null!=a.radius?a.radius:j;B&&("-"==a.upperCap?"x"==a.err?u(d,[[c,l-j],[c,l+j]]):u(d,[[e-j,c],[e+j,c]]):v.isFunction(a.upperCap)&&("x"==a.err?a.upperCap(d,c,l,j):a.upperCap(d,e,c,j)));g&&("-"==a.lowerCap?"x"==a.err?u(d,[[r,l-j],[r,l+j]]):u(d,[[e-j,r],[e+j,r]]):v.isFunction(a.lowerCap)&&("x"==a.err?a.lowerCap(d,r,l,j):a.lowerCap(d,e,r,j)))}function u(d,a){d.beginPath(); d.moveTo(a[0][0],a[0][1]);for(var e=1;e<a.length;e++)d.lineTo(a[e][0],a[e][1]);d.stroke()}function D(d,a){var e=d.getPlotOffset();a.save();a.translate(e.left,e.top);v.each(d.getData(),function(d,c){if(c.points.errorbars&&(c.points.xerr.show||c.points.yerr.show)){var e=c.datapoints.points,u=c.datapoints.pointsize,g=[c.xaxis,c.yaxis],j=c.points.radius,h=[c.points.xerr,c.points.yerr],w=!1;if(g[0].p2c(g[0].max)<g[0].p2c(g[0].min)){var w=!0,s=h[0].lowerCap;h[0].lowerCap=h[0].upperCap;h[0].upperCap=s}var v= !1;g[1].p2c(g[1].min)<g[1].p2c(g[1].max)&&(v=!0,s=h[1].lowerCap,h[1].lowerCap=h[1].upperCap,h[1].upperCap=s);for(var n=0;n<c.datapoints.points.length;n+=u){var x,b=c.datapoints.points,p=null,q=null,k=null,m=null;x=c.points.xerr;var f=c.points.yerr,t=c.points.errorbars;"x"==t||"xy"==t?x.asymmetric?(p=b[n+2],q=b[n+3],"xy"==t&&(f.asymmetric?(k=b[n+4],m=b[n+5]):k=b[n+4])):(p=b[n+2],"xy"==t&&(f.asymmetric?(k=b[n+3],m=b[n+4]):k=b[n+3])):"y"==t&&(f.asymmetric?(k=b[n+2],m=b[n+3]):k=b[n+2]);null==q&&(q=p); null==m&&(m=k);b=[p,q,k,m];x.show||(b[0]=null,b[1]=null);f.show||(b[2]=null,b[3]=null);x=b;for(f=0;f<h.length;f++)if(b=[g[f].min,g[f].max],x[f*h.length]&&(p=e[n],q=e[n+1],k=[p,q][f]+x[f*h.length+1],m=[p,q][f]-x[f*h.length],!("x"==h[f].err&&(q>g[1].max||q<g[1].min||k<g[0].min||m>g[0].max))))if(!("y"==h[f].err&&(p>g[0].max||p<g[0].min||k<g[1].min||m>g[1].max))){var z=t=!0;k>b[1]&&(t=!1,k=b[1]);m<b[0]&&(z=!1,m=b[0]);if("x"==h[f].err&&w||"y"==h[f].err&&v)s=m,m=k,k=s,s=z,z=t,t=s,s=b[0],b[0]=b[1],b[1]= s;p=g[0].p2c(p);q=g[1].p2c(q);k=g[f].p2c(k);m=g[f].p2c(m);b[0]=g[f].p2c(b[0]);b[1]=g[f].p2c(b[1]);var s=h[f].lineWidth?h[f].lineWidth:c.points.lineWidth,y=null!=c.points.shadowSize?c.points.shadowSize:c.shadowSize;0<s&&0<y&&(y/=2,a.lineWidth=y,a.strokeStyle="rgba(0,0,0,0.1)",A(a,h[f],p,q,k,m,t,z,j,y+y/2,b),a.strokeStyle="rgba(0,0,0,0.2)",A(a,h[f],p,q,k,m,t,z,j,y/2,b));a.strokeStyle=h[f].color?h[f].color:c.color;a.lineWidth=s;A(a,h[f],p,q,k,m,t,z,j,0,b)}}}});a.restore()}v.plot.plugins.push({init:function(d){d.hooks.processRawData.push(C); d.hooks.draw.push(D)},options:{series:{points:{errorbars:null,xerr:{err:"x",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null},yerr:{err:"y",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null}}}},name:"errorbars",version:"1.0"})})(jQuery);
"use strict"; const actionUtil = require('sails/lib/hooks/blueprints/actionUtil'); /** * Destroy One Record * DELETE /:model/:id * * Destroys the single model instance with the specified `id` from the data adapter for the given model if it exists. */ module.exports = (req, res) => { const Model = actionUtil.parseModel(req); const pk = actionUtil.requirePk(req); Model .destroy(pk) .then(records => records[0] ? res.ok(records[0]) : res.notFound()) .catch(res.negotiate); };
function p2kwiet428023489469_btnSubmitProfile_onClick_seq0(eventobject) { return triggerEvent.call(this); }
Package.describe({ summary: "Expressive, dynamic, robust CSS", name: "mquandalle:stylus", version: "1.1.1", git: "https://github.com/mquandalle/meteor-stylus.git" }); Package._transitional_registerBuildPlugin({ name: "compileStylus", use: [], sources: [ 'plugin/compile-stylus.js' ], npmDependencies: { stylus: "0.51.1", nib: "1.1.0", jeet: "6.1.2", rupture: "0.6.1", axis: "0.3.2", typographic: "2.9.3", "autoprefixer-stylus": "0.6.0" } }); Package.on_test(function (api) { api.use(['tinytest', 'mquandalle:stylus', 'test-helpers']); api.add_files([ 'tests/presence.styl', 'tests/importer.styl', 'tests/relative.import.styl', 'tests/absolute.import.styl', 'tests/nib_.styl', 'tests/jeet_.styl', 'tests/rupture_.styl', 'tests/axis_.styl', 'tests/typographic_.styl', 'tests/autoprefixer_.styl', 'tests/tinytest.js' ],'client'); });
import SharedFactoryGuyBehavior from './shared-factory-guy-tests'; import SharedFactoryGuyTestHelperBehavior from './shared-factory-guy-test-helper-tests'; import { title, inlineSetup } from '../helpers/utility-methods'; var SharedAdapterBehavior = {}; SharedAdapterBehavior.all = function (adapter, adapterType) { var App = null; module(title(adapter, 'FactoryGuy#make'), inlineSetup(App, adapterType)); SharedFactoryGuyBehavior.makeTests(); module(title(adapter, 'FactoryGuy#makeList'), inlineSetup(App, adapterType)); SharedFactoryGuyBehavior.makeListTests(); module(title(adapter, 'FactoryGuyTestHelper#buildUrl'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.buildUrl(); module(title(adapter, 'FactoryGuyTestHelper#handleFind'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleFindTests(); module(title(adapter, 'FactoryGuyTestHelper#handleReload'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleReloadTests(); module(title(adapter, 'FactoryGuyTestHelper#handleFindAll'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleFindAllTests(); module(title(adapter, 'FactoryGuyTestHelper#handleQuery'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleQueryTests(); module(title(adapter, 'FactoryGuyTestHelper#handleCreate'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleCreateTests(); module(title(adapter, 'FactoryGuyTestHelper#handleUpdate'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleUpdateTests(); module(title(adapter, 'FactoryGuyTestHelper#handleDelete'), inlineSetup(App, adapterType)); SharedFactoryGuyTestHelperBehavior.handleDeleteTests(); }; export default SharedAdapterBehavior;
module.exports = { description: 'large variable count deduping' };
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'justify', 'no', { block: 'Blokkjuster', center: 'Midtstill', left: 'Venstrejuster', right: 'Høyrejuster' });
// Copyright 2021 Mathias Bynens. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- author: Mathias Bynens description: > Unicode property escapes for `Script_Extensions=Saurashtra` info: | Generated by https://github.com/mathiasbynens/unicode-property-escapes-tests Unicode v14.0.0 esid: sec-static-semantics-unicodematchproperty-p features: [regexp-unicode-property-escapes] includes: [regExpUtils.js] ---*/ const matchSymbols = buildString({ loneCodePoints: [], ranges: [ [0x00A880, 0x00A8C5], [0x00A8CE, 0x00A8D9] ] }); testPropertyEscapes( /^\p{Script_Extensions=Saurashtra}+$/u, matchSymbols, "\\p{Script_Extensions=Saurashtra}" ); testPropertyEscapes( /^\p{Script_Extensions=Saur}+$/u, matchSymbols, "\\p{Script_Extensions=Saur}" ); testPropertyEscapes( /^\p{scx=Saurashtra}+$/u, matchSymbols, "\\p{scx=Saurashtra}" ); testPropertyEscapes( /^\p{scx=Saur}+$/u, matchSymbols, "\\p{scx=Saur}" ); const nonMatchSymbols = buildString({ loneCodePoints: [], ranges: [ [0x00DC00, 0x00DFFF], [0x000000, 0x00A87F], [0x00A8C6, 0x00A8CD], [0x00A8DA, 0x00DBFF], [0x00E000, 0x10FFFF] ] }); testPropertyEscapes( /^\P{Script_Extensions=Saurashtra}+$/u, nonMatchSymbols, "\\P{Script_Extensions=Saurashtra}" ); testPropertyEscapes( /^\P{Script_Extensions=Saur}+$/u, nonMatchSymbols, "\\P{Script_Extensions=Saur}" ); testPropertyEscapes( /^\P{scx=Saurashtra}+$/u, nonMatchSymbols, "\\P{scx=Saurashtra}" ); testPropertyEscapes( /^\P{scx=Saur}+$/u, nonMatchSymbols, "\\P{scx=Saur}" );
/* eslint no-console: 0 */ const consoleWarn = console.warn; const consoleError = console.error; const errorWhitelist = [ ]; function throwError(msg) { if (errorWhitelist.every(regex => !regex.test(msg))) throw new Error(msg); } console.warn = throwError; console.error = throwError; before(() => { console.error = throwError; console.warn = throwError; }); beforeEach(() => { console.error = throwError; console.warn = throwError; }); after(() => { console.warn = consoleWarn; console.error = consoleError; }); afterEach(() => { console.warn = consoleWarn; console.error = consoleError; });
define([ 'jquery', '../utils', '../keys' ], function ($, Utils, KEYS) { function Search (decorated, $element, options) { decorated.call(this, $element, options); } Search.prototype.render = function (decorated) { var $search = $( '<li class="select2-search select2-search--inline">' + '<input class="select2-search__field" type="search" tabindex="-1"' + ' role="textbox" />' + '</li>' ); this.$searchContainer = $search; this.$search = $search.find('input'); var $rendered = decorated.call(this); return $rendered; }; Search.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); container.on('open', function () { self.$search.attr('tabindex', 0); self.$search.focus(); }); container.on('close', function () { self.$search.attr('tabindex', -1); self.$search.val(''); }); container.on('enable', function () { self.$search.prop('disabled', false); }); container.on('disable', function () { self.$search.prop('disabled', true); }); this.$selection.on('keydown', '.select2-search--inline', function (evt) { evt.stopPropagation(); self.trigger('keypress', evt); self._keyUpPrevented = evt.isDefaultPrevented(); var key = evt.which; if (key === KEYS.BACKSPACE && self.$search.val() === '') { var $previousChoice = self.$searchContainer .prev('.select2-selection__choice'); if ($previousChoice.length > 0) { var item = $previousChoice.data('data'); self.searchRemoveChoice(item); } } }); this.$selection.on('keyup', '.select2-search--inline', function (evt) { self.handleSearch(evt); }); }; Search.prototype.createPlaceholder = function (decorated, placeholder) { this.$search.attr('placeholder', placeholder.text); }; Search.prototype.update = function (decorated, data) { this.$search.attr('placeholder', ''); decorated.call(this, data); this.$selection.find('.select2-selection__rendered') .append(this.$searchContainer); this.resizeSearch(); }; Search.prototype.handleSearch = function () { this.resizeSearch(); if (!this._keyUpPrevented) { var input = this.$search.val(); this.trigger('query', { term: input }); } this._keyUpPrevented = false; }; Search.prototype.searchRemoveChoice = function (decorated, item) { this.trigger('unselect', { data: item }); this.trigger('open'); this.$search.val(item.text + ' '); }; Search.prototype.resizeSearch = function () { this.$search.css('width', '25px'); var width = ''; if (this.$search.attr('placeholder') !== '') { width = this.$selection.find('.select2-selection__rendered').innerWidth(); } else { var minimumWidth = this.$search.val().length + 1; width = (minimumWidth * 0.75) + 'em'; } this.$search.css('width', width); }; return Search; });
define({ "page1": { "selectToolHeader": "选择一种方法,以选择要进行批量更新的记录。", "selectToolDesc": "该微件提供了 3 种不同的方法来生成一组要更新的选定记录。只能从中选择一种方法。如果您需要使用其中的多种方法,请创建微件的新实例。", "selectByShape": "根据区域选择", "shapeTypeSelector": "单击您想要允许的工具", "shapeType": { "point": "点", "line": "线", "polyline": "折线", "freehandPolyline": "手绘折线", "extent": "范围", "polygon": "面", "freehandPolygon": "手绘面" }, "freehandPolygon": "手绘面", "selectBySpatQuery": "根据要素选择", "selectByAttQuery": "根据要素和相关要素选择", "selectByQuery": "根据查询选择", "toolNotSelected": "请选择一种选择方法", "noDrawToolSelected": "请至少选择一个绘图工具" }, "page2": { "layersToolHeader": "选择要更新的图层和选择工具选项(如果存在)。", "layersToolDesc": "您在第一页所选的选择方法将被用于选择和更新下列图层集。如果您选中了多个图层,则仅可更新通用可编辑字段。依据您对选择工具所做的具体选择,将需要不同的其他选项。", "layerTable": { "colUpdate": "更新", "colLabel": "图层", "colSelectByLayer": "根据图层选择", "colSelectByField": "查询字段", "colhighlightSymbol": "高亮显示符号" }, "toggleLayers": "在打开与关闭之间切换图层的可见性", "noEditableLayers": "无可编辑图层", "noLayersSelected": "在继续处理前请选择一个或多个图层。" }, "page3": { "commonFieldsHeader": "选择要批量更新的字段。", "commonFieldsDesc": "只有通用可编辑字段会显示在下方。请选择您希望更新的字段。如果不同图层的同一字段具有不同的域,则只会显示并使用一个域。", "noCommonFields": "无通用字段", "fieldTable": { "colEdit": "可编辑", "colName": "名称", "colAlias": "别名", "colAction": "操作" } }, "tabs": { "selection": "定义选择类型", "layers": "定义要更新的图层", "fields": "定义要更新的字段" }, "errorOnOk": "请在保存配置前填写所有参数", "next": "前进", "back": "后退", "save": "保存符号", "cancel": "取消", "ok": "确定", "symbolPopup": "符号选择器", "editHeaderText": "要在微件顶部显示的文本", "widgetIntroSelectByArea": "请使用以下工具之一以创建要更新的所选要素集。 如果行<font class='maxRecordInIntro'>突出显示</font>,则已超出最大记录数。", "widgetIntroSelectByFeature": "使用以下工具从 <font class='layerInIntro'>${0}</font> 图层中选择要素。 将使用此要素来选择并更新所有相交要素。 如果行<font class='maxRecordInIntro'>突出显示</font>,则已超出最大记录数。", "widgetIntroSelectByFeatureQuery": "使用以下工具从 <font class='layerInIntro'>${0}</font> 中选择要素。 将使用此要素的 <font class='layerInIntro'>${1}</font> 属性来查询以下图层并更新生成的要素。 如果行<font class='maxRecordInIntro'>突出显示</font>,则已超出最大记录数。", "widgetIntroSelectByQuery": "输入用于创建选择集的值。 如果行<font class='maxRecordInIntro'>突出显示</font>,则已超出最大记录数。" });
/** * Created by weagl on 9/4/2015. */ var gulp = require('gulp'); var paths = require('../paths'); var eslint = require('gulp-eslint'); gulp.task('lint', function(){ return gulp.src(paths.source) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); });
// webpack2 vue 异步引用组件 export default function(Vue){ // Vue.component('search', () => import('@/components/search.vue')) }
export{default as adaptV4Theme}from"./adaptV4Theme";export*from"./colorManipulator";export{default as createTheme,createMuiTheme}from"./createTheme";export{default as unstable_createMuiStrictModeTheme}from"./createMuiStrictModeTheme";export{default as createStyles}from"./createStyles";export{getUnit as unstable_getUnit,toUnitless as unstable_toUnitless}from"./cssUtils";export{default as responsiveFontSizes}from"./responsiveFontSizes";export{duration,easing}from"./createTransitions";export{default as useTheme}from"./useTheme";export{default as unstable_useThemeProps}from"./useThemeProps";export{default as styled}from"./styled";export{default as experimentalStyled}from"./styled";export{default as ThemeProvider}from"./ThemeProvider";export{default as StyledEngineProvider}from"@material-ui/styled-engine/StyledEngineProvider";
import {apiFetch} from './util' import {getChannelId, getUserId} from './cache' export default function inviteToChannel(channelName, userHandles) { const promises = userHandles.map(userHandle => _inviteUserToChannel(channelName, userHandle)) return Promise.all(promises) } async function _inviteUserToChannel(channelName, userHandle) { const channelId = await getChannelId(channelName) const userId = await getUserId(userHandle) const body = { channel: channelId, user: userId, } const result = await apiFetch('/api/channels.invite', { method: 'POST', body, }).catch(err => { // ignore errors if user is already in channel if (!err.message.includes('already_in_channel')) { throw err } return {ok: true, channel: {id: channelId, name: channelName}} }) return result.channel }
'use strict'; var React = require('react'); var PureRenderMixin = require('react-addons-pure-render-mixin'); var SvgIcon = require('../../svg-icon'); var DeviceGpsFixed = React.createClass({ displayName: 'DeviceGpsFixed', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z' }) ); } }); module.exports = DeviceGpsFixed;
var searchData= [ ['squarednorm_40',['squaredNorm',['../namespacesml.html#a805dd265cb260d6066d83553503340df',1,'sml']]] ];
import * as components from './components'; export { components, };
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: ['bower_components/foundation/scss'] }, dist: { options: { outputStyle: 'compressed' }, files: { 'css/app.css': 'scss/app.scss' } } }, watch: { grunt: {files: ['Gruntfile.js']}, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('build', ['sass']); grunt.registerTask('default', ['build', 'watch']); }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.ef = {})); }(this, function (exports) { 'use strict'; // Set the escape character var char = '&'; var doubleChar = char + char; // Initlize RegExp var oct = new RegExp(("\\" + char + "[0-7]{1,3}"), 'g'); var ucp = new RegExp(("\\" + char + "u\\[.*?\\]"), 'g'); var uni = new RegExp(("\\" + char + "u.{0,4}"), 'g'); var hex = new RegExp(("\\" + char + "x.{0,2}"), 'g'); var esc = new RegExp(("\\" + char), 'g'); var b = new RegExp(("\\" + char + "b"), 'g'); var t = new RegExp(("\\" + char + "t"), 'g'); var n = new RegExp(("\\" + char + "n"), 'g'); var v = new RegExp(("\\" + char + "v"), 'g'); var f = new RegExp(("\\" + char + "f"), 'g'); var r = new RegExp(("\\" + char + "r"), 'g'); // Escape octonary sequence var O2C = function () { throw new SyntaxError('Octal escape sequences are not allowed in EFML.') }; // Escape unicode code point sequence var UC2C = function (val) { val = val.substr(3, val.length - 4); val = parseInt(val, 16); if (!val) { throw new SyntaxError('Invalid Unicode escape sequence') } try { return String.fromCodePoint(val) } catch (err) { throw new SyntaxError('Undefined Unicode code-point') } }; // Escape unicode sequence var U2C = function (val) { val = val.substring(2); val = parseInt(val, 16); if (!val) { throw new SyntaxError('Invalid Unicode escape sequence') } return String.fromCharCode(val) }; // Escape hexadecimal sequence var X2C = function (val) { val = "00" + (val.substring(2)); val = parseInt(val, 16); if (!val) { throw new SyntaxError('Invalid hexadecimal escape sequence') } return String.fromCharCode(val) }; var efEscape = function (string) { // Split strings var splitArr = string.split(doubleChar); var escaped = []; // Escape all known escape characters for (var i$1 = 0, list = splitArr; i$1 < list.length; i$1 += 1) { var i = list[i$1]; var escapedStr = i .replace(oct, O2C) .replace(ucp, UC2C) .replace(uni, U2C) .replace(hex, X2C) .replace(b, '\b') .replace(t, '\t') .replace(n, '\n') .replace(v, '\v') .replace(f, '\f') .replace(r, '\r') // Remove all useless escape characters .replace(esc, ''); escaped.push(escapedStr); } // Return escaped string return escaped.join(char) }; var checkEscape = function (string) { return string[string.length - 1] === char; }; var splitWith = function (string, char) { var splitArr = string.split(char); var escapedSplit = []; var escaped = false; for (var i$1 = 0, list = splitArr; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (escaped) { escapedSplit[escapedSplit.length - 1] += "" + char + i; } else { escapedSplit.push(i); } escaped = checkEscape(i); } return escapedSplit }; var splitBy = function (string, char) { var splitArr = string.split(doubleChar); var escaped = splitWith(splitArr.shift(), char); for (var i$1 = 0, list = splitArr; i$1 < list.length; i$1 += 1) { var i = list[i$1]; var escapedSplit = splitWith(i, char); escaped[escaped.length - 1] += "" + doubleChar + (escapedSplit.shift()); escaped.push.apply(escaped, escapedSplit); } return escaped }; var typeSymbols = '>#%@.-+'; var reserved = [ '$ctx', '$data', '$refs', '$methods', '$mount', '$umount', '$subscribe', '$unsubscribe', '$update', '$destroy', '__DIRECTMOUNT__' ]; var mustache = /\{\{.+?\}\}/g; var spaceIndent = /^(\t*)( *).*/; var hashref = /#([^}]|}[^}])*$/; var getErrorMsg = function (msg, line) { if ( line === void 0 ) line = -2; return ("Failed to parse eft template: " + msg + ". at line " + (line + 1)); }; var isEmpty = function (string) { return !string.replace(/\s/, ''); }; var checkValidType = function (obj) { return ['number', 'boolean', 'string'].indexOf(typeof obj) > -1; }; var ESCAPE = function (string) { if (!string) { return [string, false] } try { var parsed = JSON.parse(string); if (['number', 'boolean'].indexOf(typeof parsed) === -1) { return [efEscape(string), true] } return [parsed, false] } catch (e) { return [efEscape(string), true] } }; var getOffset = function (string, parsingInfo) { if (parsingInfo.offset !== null) { return } parsingInfo.offset = string.match(/\s*/)[0]; if (parsingInfo.offset) { parsingInfo.offsetReg = parsingInfo.offset; } }; var removeOffset = function (string, parsingInfo, i) { if (parsingInfo.offsetReg) { var removed = false; string = string.replace(parsingInfo.offsetReg, function () { removed = true; return '' }); if (!removed) { throw new SyntaxError(getErrorMsg(("Expected indent to be grater than 0 and less than " + (parsingInfo.prevDepth + 1) + ", but got -1"), i)) } } return string }; var getIndent = function (string, parsingInfo) { if (parsingInfo.indentReg) { return } var spaces = string.match(spaceIndent)[2]; if (spaces) { parsingInfo.indentReg = new RegExp(spaces, 'g'); } }; var getDepth = function (string, parsingInfo, i) { var depth = 0; if (parsingInfo.indentReg) { string = string.replace(/^\s*/, function (str) { return str.replace(parsingInfo.indentReg, '\t'); }); } var content = string.replace(/^\t*/, function (str) { depth = str.length; return '' }); if ((/^\s/).test(content)) { throw new SyntaxError(getErrorMsg('Bad indent', i)) } return { depth: depth, content: content } }; var resolveDepth = function (ast, depth) { var currentNode = ast; for (var i = 0; i < depth; i++) { currentNode = currentNode[currentNode.length - 1]; } return currentNode }; var splitDefault = function (string) { string = string.slice(2, string.length - 2); var ref = splitBy(string, '='); var _path = ref[0]; var _default = ref.slice(1); var pathArr = splitBy(_path.trim(), '.').map(efEscape); var ref$1 = ESCAPE(_default.join('=').trim()); var defaultVal = ref$1[0]; var escaped = ref$1[1]; if (checkValidType(defaultVal) && (escaped || (!escaped && defaultVal !== ''))) { return [pathArr, defaultVal] } return [pathArr] }; var splitLiterals = function (string) { var strs = string.split(mustache); if (strs.length === 1) { return ESCAPE(string)[0] } var tmpl = []; if (strs.length === 2 && !strs[0] && !strs[1]) { tmpl.push(0); } else { tmpl.push(strs.map(efEscape)); } var mustaches = string.match(mustache); if (mustaches) { tmpl.push.apply(tmpl, mustaches.map(splitDefault)); } return tmpl }; var pushStr = function (textArr, str) { if (str) { textArr.push(str); } }; var parseText = function (string) { var result = splitLiterals(string); if (checkValidType(result)) { return [("" + result)] } var strs = result[0]; var exprs = result.slice(1); var textArr = []; for (var i = 0; i < exprs.length; i++) { pushStr(textArr, strs[i]); textArr.push(exprs[i]); } pushStr(textArr, strs[strs.length - 1]); return textArr }; var dotToSpace = function (val) { return val.replace(/\./g, ' '); }; var parseTag = function (string) { var tagInfo = {}; var ref = splitBy(string.replace(hashref, function (val) { tagInfo.ref = val.slice(1); return '' }), '.'); var tag = ref[0]; var content = ref.slice(1); tagInfo.tag = efEscape(tag); tagInfo.class = splitLiterals(content.join('.')); if (typeof tagInfo.class === 'string') { tagInfo.class = dotToSpace(tagInfo.class).trim(); } else if (tagInfo.class[0]) { tagInfo.class[0] = tagInfo.class[0].map(dotToSpace); } return tagInfo }; var parseNodeProps = function (string) { var splited = splitBy(string, '='); return { name: efEscape(splited.shift().trim()), value: splitLiterals(splited.join('=').trim()) } }; var parseEvent = function (string) { var splited = splitBy(string, '='); return { name: splited.shift().trim(), value: splited.join('=').trim() } }; var setOption = function (options, option) { switch (option) { case 'stop': { options.s = 1; break } case 'stopImmediate': { options.i = 1; break } case 'prevent': { options.p = 1; break } case 'shift': { options.h = 1; break } case 'alt': { options.a = 1; break } case 'ctrl': { options.c = 1; break } case 'meta': { options.t = 1; break } case 'capture': { options.u = 1; break } default: { console.warn(("Abandoned unsupported eft event option '" + option + "'.")); } } }; var getOption = function (options, keys, option) { var keyCode = parseInt(option, 10); if (isNaN(keyCode)) { return setOption(options, efEscape(option)) } keys.push(keyCode); }; var getEventOptions = function (name) { var options = {}; var keys = []; var ref = splitBy(name, '.'); var listener = ref[0]; var ops = ref.slice(1); options.l = efEscape(listener); for (var i$1 = 0, list = ops; i$1 < list.length; i$1 += 1) { var i = list[i$1]; getOption(options, keys, i); } if (keys.length > 0) { options.k = keys; } return options }; var splitEvents = function (string) { var ref = splitBy(string, ':'); var name = ref[0]; var value = ref.slice(1); var content = value.join(':'); var escapedName = efEscape(name.trim()); if (content) { return [escapedName, splitLiterals(content)] } return [escapedName] }; var parseLine = function (ref) { var ref$6, ref$7; var line = ref.line; var ast = ref.ast; var parsingInfo = ref.parsingInfo; var i = ref.i; if (isEmpty(line)) { return } getOffset(line, parsingInfo); var trimmedLine = removeOffset(line, parsingInfo, i); getIndent(trimmedLine, parsingInfo); var ref$1 = getDepth(trimmedLine, parsingInfo, i); var depth = ref$1.depth; var content = ref$1.content; if (content) { if (depth < 0 || depth - parsingInfo.prevDepth > 1 || (depth - parsingInfo.prevDepth === 1 && ['comment', 'tag'].indexOf(parsingInfo.prevType) === -1) || (parsingInfo.prevType !== 'comment' && depth === 0 && parsingInfo.topExists)) { throw new SyntaxError(getErrorMsg(("Expected indent to be grater than 0 and less than " + (parsingInfo.prevDepth + 1) + ", but got " + depth), i)) } var type = content[0]; content = content.slice(1); if (!content && typeSymbols.indexOf(type) >= 0) { throw new SyntaxError(getErrorMsg('Empty content', i)) } // Jump back to upper level if (depth < parsingInfo.prevDepth || (depth === parsingInfo.prevDepth && parsingInfo.prevType === 'tag')) { parsingInfo.currentNode = resolveDepth(ast, depth); } parsingInfo.prevDepth = depth; switch (type) { case '>': { var info = parseTag(content); var newNode = [{ t: info.tag }]; if (info.class) { newNode[0].a = {}; newNode[0].a.class = info.class; } if (info.ref) { newNode[0].r = info.ref; } parsingInfo.currentNode.push(newNode); parsingInfo.currentNode = newNode; parsingInfo.prevType = 'tag'; break } case '#': { var ref$2 = parseNodeProps(content); var name = ref$2.name; var value = ref$2.value; if (!parsingInfo.currentNode[0].a) { parsingInfo.currentNode[0].a = {}; } parsingInfo.currentNode[0].a[name] = value; parsingInfo.prevType = 'attr'; break } case '%': { var ref$3 = parseNodeProps(content); var name$1 = ref$3.name; var value$1 = ref$3.value; if (!parsingInfo.currentNode[0].p) { parsingInfo.currentNode[0].p = {}; } parsingInfo.currentNode[0].p[name$1] = value$1; parsingInfo.prevType = 'prop'; break } case '@': { var ref$4 = parseEvent(content); var name$2 = ref$4.name; var value$2 = ref$4.value; if (!parsingInfo.currentNode[0].e) { parsingInfo.currentNode[0].e = []; } var options = getEventOptions(name$2); var ref$5 = splitEvents(value$2); var method = ref$5[0]; var _value = ref$5[1]; options.m = method; if (_value) { options.v = _value; } parsingInfo.currentNode[0].e.push(options); parsingInfo.prevType = 'event'; break } case '.': { (ref$6 = parsingInfo.currentNode).push.apply(ref$6, parseText(content)); parsingInfo.prevType = 'text'; break } case '|': { if (parsingInfo.currentNode.length > 1) { content = "\n" + content; } (ref$7 = parsingInfo.currentNode).push.apply(ref$7, parseText(content)); parsingInfo.prevType = 'multiline-text'; break } case '-': { if (reserved.indexOf(content) !== -1) { throw new SyntaxError(getErrorMsg(("Reserved name '" + content + "' should not be used"), i)) } parsingInfo.currentNode.push({ n: content, t: 0 }); parsingInfo.prevType = 'node'; break } case '+': { parsingInfo.currentNode.push({ n: content, t: 1 }); parsingInfo.prevType = 'list'; break } default: { parsingInfo.prevType = 'comment'; } } } }; var parseEft = function (template) { if (!template) { throw new TypeError(getErrorMsg('Template required, but nothing given')) } var tplType = typeof template; if (tplType !== 'string') { throw new TypeError(getErrorMsg(("Expected a string, but got a(n) " + tplType))) } var lines = template.split(/\r?\n/); var ast = [{t: 0}]; var parsingInfo = { indentReg: null, prevDepth: 0, offset: null, offsetReg: null, prevType: 'comment', currentNode: ast, topExists: false, }; for (var i = 0; i < lines.length; i++) { parseLine({line: lines[i], ast: ast, parsingInfo: parsingInfo, i: i}); } if (ast.length <= 1) { throw new SyntaxError(getErrorMsg('Nothing to be parsed', lines.length - 1)) } if (ast.length === 2 && Array.isArray(ast[1]) && Object.hasOwnProperty.call(ast[1][0], 't')) { return ast[1] } return ast }; var parse = function (template, parser) { if (!parser) { parser = parseEft; } return parser(template) }; var typeOf = function (obj) { if (Array.isArray(obj)) { return 'array' } return typeof obj }; var mixStr = function (strs) { var exprs = [], len = arguments.length - 1; while ( len-- > 0 ) exprs[ len ] = arguments[ len + 1 ]; var string = ''; for (var i = 0; i < exprs.length; i++) { if (typeof exprs[i] === 'undefined') { string += strs[i]; } else { string += (strs[i] + exprs[i]); } } return string + strs[strs.length - 1] }; var getVal = function (ref) { var dataNode = ref.dataNode; var _key = ref._key; var data = dataNode[_key]; if (typeof data === 'undefined') { return '' } return data }; var mixVal = function (strs) { var exprs = [], len = arguments.length - 1; while ( len-- > 0 ) exprs[ len ] = arguments[ len + 1 ]; if (!strs) { return getVal(exprs[0]) } var template = [strs]; template.push.apply(template, exprs.map(getVal)); return mixStr.apply(void 0, template) }; var version = "0.9.6"; var proto = Array.prototype; var ARR = { copy: function copy(arr) { return proto.slice.call(arr, 0) }, empty: function empty(arr) { arr.length = 0; return arr }, equals: function equals(left, right) { if (!Array.isArray(right)) { return false } if (left === right) { return true } if (left.length !== right.length) { return false } for (var i = 0, l = left.length; i < l; i++) { if (left[i] !== right[i]) { return false } } return true }, pop: function pop(arr) { return proto.pop.call(arr) }, push: function push(arr) { var items = [], len = arguments.length - 1; while ( len-- > 0 ) items[ len ] = arguments[ len + 1 ]; return proto.push.apply(arr, items) }, remove: function remove(arr, item) { var index = proto.indexOf.call(arr, item); if (index > -1) { proto.splice.call(arr, index, 1); return item } }, reverse: function reverse(arr) { return proto.reverse.call(arr) }, rightUnique: function rightUnique(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { for (var j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) { j = i += 1; } } newArr.push(arr[i]); } return newArr }, shift: function shift(arr) { return proto.shift.call(arr) }, slice: function slice(arr, index, length) { return proto.slice.call(arr, index, length) }, sort: function sort(arr, fn) { return proto.sort.call(arr, fn) }, splice: function splice(arr) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return proto.splice.apply(arr, args) }, unshift: function unshift(arr) { var items = [], len = arguments.length - 1; while ( len-- > 0 ) items[ len ] = arguments[ len + 1 ]; return proto.unshift.apply(arr, items) } }; if (window.Set && Array.from) { ARR.unique = function (arr) { return Array.from(new Set(arr)); }; } else { ARR.unique = ARR.rightUnique; } // Wrap console functions for `[EF]` perfix var strTpl = '[EF] %s'; var dbg = { log: console.log.bind(console, strTpl), info: console.info.bind(console, strTpl), warn: console.warn.bind(console, strTpl), error: console.error.bind(console, strTpl) }; var modificationQueue = []; var domQueue = []; var userQueue = []; var count = 0; var queue = function (handlers) { return modificationQueue.push.apply(modificationQueue, handlers); }; var queueDom = function (handler) { return domQueue.push(handler); }; var onNextRender = function (handler) { return userQueue.push(handler); }; var isPaused = function () { return count > 0; }; var inform = function () { count += 1; return count }; var execModifications = function () { if (modificationQueue.length === 0) { return } var renderQueue = ARR.unique(modificationQueue); ARR.empty(modificationQueue); for (var i$1 = 0, list = renderQueue; i$1 < list.length; i$1 += 1) { var i = list[i$1]; i(); } }; var execDomModifications = function () { if (domQueue.length === 0) { return } var domRenderQueue = ARR.rightUnique(domQueue); ARR.empty(domQueue); for (var i$1 = 0, list = domRenderQueue; i$1 < list.length; i$1 += 1) { var i = list[i$1]; i(); } }; var execUserQueue = function () { if (userQueue.length === 0) { return } var userFnQueue = ARR.unique(userQueue); ARR.empty(userQueue); for (var i$1 = 0, list = userFnQueue; i$1 < list.length; i$1 += 1) { var i = list[i$1]; i(); } }; var exec = function (immediate) { if (!immediate && (count -= 1) > 0) { return count } count = 0; if (modificationQueue.length > 0) { execModifications(); } if (domQueue.length > 0) { execDomModifications(); } // Execute user queue after DOM update if (userQueue.length > 0) { setTimeout(execUserQueue, 0); } return count }; var bundle = function (cb) { inform(); try { return exec(cb(inform, exec)) } catch (e) { dbg.error('Error caught when executing bundle:\n', e); return exec() } }; // Enough for ef's usage, so no need for a full polyfill var legacyAssign = function (ee, er) { for (var i in er) { ee[i] = er[i]; } return ee }; var assign = Object.assign || legacyAssign; var resolveAllPath = function (ref) { var _path = ref._path; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; for (var i$1 = 0, list = _path; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (!handlers[i]) { handlers[i] = {}; } if (!subscribers[i]) { subscribers[i] = {}; } if (!innerData[i]) { innerData[i] = {}; } handlers = handlers[i]; subscribers = subscribers[i]; innerData = innerData[i]; } return { handlerNode: handlers, subscriberNode: subscribers, dataNode: innerData } }; // Workaround for the third bug of buble: // https://github.com/bublejs/buble/issues/106 var defineNode = function (key, obj) { var node = {}; Object.defineProperty(obj, key, { get: function get() { return node }, set: function set(data) { inform(); assign(node, data); exec(); }, configurable: false, enumerable: true }); return node }; var resolveReactivePath = function (_path, obj) { for (var i$1 = 0, list = _path; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (obj[i]) { obj = obj[i]; } else { obj = defineNode(i, obj); } } return obj }; var resolve = function (ref) { var _path = ref._path; var _key = ref._key; var data = ref.data; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; var parentNode = resolveReactivePath(_path, data); var ref$1 = resolveAllPath({_path: _path, handlers: handlers, subscribers: subscribers, innerData: innerData}); var handlerNode = ref$1.handlerNode; var subscriberNode = ref$1.subscriberNode; var dataNode = ref$1.dataNode; if (!handlerNode[_key]) { handlerNode[_key] = []; } if (!subscriberNode[_key]) { subscriberNode[_key] = []; } /* eslint no-undefined: "off" */ if (!Object.prototype.hasOwnProperty.call(dataNode, _key)) { dataNode[_key] = undefined; } return { parentNode: parentNode, handlerNode: handlerNode[_key], subscriberNode: subscriberNode[_key], dataNode: dataNode } }; var resolveSubscriber = function (_path, subscribers) { var pathArr = _path.split('.'); var key = pathArr.pop(); for (var i$1 = 0, list = pathArr; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (!subscribers[i]) { subscribers[i] = {}; } subscribers = subscribers[i]; } return subscribers[key] }; var subscriberCallStack = []; var pushStack = function (subscriberNode) { return subscriberCallStack.push(subscriberNode); }; var popStack = function (subscriberNode) { return ARR.remove(subscriberCallStack, subscriberNode); }; var execSubscribers = function (subscriberNode, data) { // Stop chain reaction when being called again in the context // There is no way for the caller to know it shouldn't update the node again // So this is the only method to avoid recursion // Push the current subscriberNode to stack as an identifier pushStack(subscriberNode); // Execute the subscriber function inform(); try { for (var i = 0, list = subscriberNode; i < list.length; i += 1) { var subscriber = list[i]; subscriber(data); } } catch (e) { dbg.error('Error caught when executing subscribers:\n', e); } exec(); // Remove the subscriberNode from the stack so it could be called again popStack(subscriberNode); }; /* eslint-disable no-self-compare */ var isnan = function (obj) { return obj !== obj; }; var initDataNode = function (ref) { var parentNode = ref.parentNode; var dataNode = ref.dataNode; var handlerNode = ref.handlerNode; var subscriberNode = ref.subscriberNode; var ctx = ref.ctx; var _key = ref._key; Object.defineProperty(parentNode, _key, { get: function get() { return dataNode[_key] }, set: function set(value) { // Comparing NaN is like eating a cake and suddenly encounter a grain of sand if (dataNode[_key] === value || (isnan(dataNode[_key]) && isnan(value))) { return } dataNode[_key] = value; inform(); queue(handlerNode); exec(); if (subscriberNode.length > 0) { execSubscribers(subscriberNode, {state: ctx.state, value: value}); } }, enumerable: true }); }; var initBinding = function (ref) { var bind = ref.bind; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; var _path = ARR.copy(bind[0]); var _key = _path.pop(); var ref$1 = resolve({ _path: _path, _key: _key, data: ctx.data, handlers: handlers, subscribers: subscribers, innerData: innerData }); var parentNode = ref$1.parentNode; var handlerNode = ref$1.handlerNode; var subscriberNode = ref$1.subscriberNode; var dataNode = ref$1.dataNode; // Initlize data binding node if not exist if (!Object.prototype.hasOwnProperty.call(parentNode, _key)) { initDataNode({parentNode: parentNode, dataNode: dataNode, handlerNode: handlerNode, subscriberNode: subscriberNode, ctx: ctx, _key: _key}); } // Update default value // bind[1] is the default value for this node if (bind.length > 1) { parentNode[_key] = bind[1]; } return {dataNode: dataNode, parentNode: parentNode, handlerNode: handlerNode, subscriberNode: subscriberNode, _key: _key} }; var isInstance = function (er, ee) { return er.constructor === ee; }; // https://github.com/bublejs/buble/issues/197 var enumerableFalse = function (classObj, keys) { for (var i$1 = 0, list = keys; i$1 < list.length; i$1 += 1) { var i = list[i$1]; Object.defineProperty(classObj.prototype, i, {enumerable: false}); } return classObj }; // https://github.com/bublejs/buble/issues/131 var prepareArgs = function (self, node) { var args = ARR.copy(self); ARR.unshift(args, node); return args }; var proto$1 = Node.prototype; // Will require a weakmap polyfill for IE10 and below var mountingPointStore = new WeakMap(); var DOM = {}; var EFFragment = /*@__PURE__*/(function (Array) { function EFFragment () { Array.apply(this, arguments); } if ( Array ) EFFragment.__proto__ = Array; EFFragment.prototype = Object.create( Array && Array.prototype ); EFFragment.prototype.constructor = EFFragment; EFFragment.prototype.appendTo = function appendTo (node) { DOM.append.apply(null, prepareArgs(this, node)); }; EFFragment.prototype.insertBeforeTo = function insertBeforeTo (node) { var args = ARR.copy(this); ARR.unshift(args, node); DOM.before.apply(null, prepareArgs(this, node)); }; EFFragment.prototype.insertAfterTo = function insertAfterTo (node) { var args = ARR.copy(this); ARR.unshift(args, node); DOM.after.apply(null, prepareArgs(this, node)); }; EFFragment.prototype.remove = function remove () { for (var i$1 = 0, list = this; i$1 < list.length; i$1 += 1) { var i = list[i$1]; DOM.remove(i); } }; return EFFragment; }(Array)); var MountingList = /*@__PURE__*/(function (Array) { function MountingList(info) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; Array.apply(this, args); Object.defineProperty(this, '__info__', {value: info}); } if ( Array ) MountingList.__proto__ = Array; MountingList.prototype = Object.create( Array && Array.prototype ); MountingList.prototype.constructor = MountingList; MountingList.prototype.empty = function empty () { inform(); for (var i$1 = 0, list = ARR.copy(this); i$1 < list.length; i$1 += 1) { var i = list[i$1]; i.$destroy(); } exec(); ARR.empty(this); }; MountingList.prototype.clear = function clear () { inform(); for (var i$1 = 0, list = ARR.copy(this); i$1 < list.length; i$1 += 1) { var i = list[i$1]; i.$umount(); } exec(); ARR.empty(this); }; MountingList.prototype.pop = function pop () { if (this.length === 0) { return } var poped = Array.prototype.pop.call(this); poped.$umount(); return poped }; MountingList.prototype.push = function push () { var items = [], len = arguments.length; while ( len-- ) items[ len ] = arguments[ len ]; var ref = this.__info__; var ctx = ref.ctx; var key = ref.key; var anchor = ref.anchor; var elements = []; inform(); for (var i$1 = 0, list = items; i$1 < list.length; i$1 += 1) { var i = list[i$1]; ARR.push(elements, i.$mount({parent: ctx.state, key: key})); } if (this.length === 0) { DOM.after.apply(DOM, [ anchor ].concat( elements )); } else { DOM.after.apply(DOM, [ this[this.length - 1].$ctx.nodeInfo.placeholder ].concat( elements )); } exec(); return Array.prototype.push.apply(this, items) }; MountingList.prototype.remove = function remove (item) { if (this.indexOf(item) === -1) { return } item.$umount(); return item }; MountingList.prototype.reverse = function reverse () { var ref = this.__info__; var ctx = ref.ctx; var key = ref.key; var anchor = ref.anchor; if (this.length === 0) { return this } var tempArr = ARR.copy(this); var elements = []; inform(); for (var i = tempArr.length - 1; i >= 0; i--) { tempArr[i].$umount(); ARR.push(elements, tempArr[i].$mount({parent: ctx.state, key: key})); } Array.prototype.push.apply(this, ARR.reverse(tempArr)); DOM.after.apply(DOM, [ anchor ].concat( elements )); exec(); return this }; MountingList.prototype.shift = function shift () { if (this.length === 0) { return } var shifted = Array.prototype.shift.call(this); shifted.$umount(); return shifted }; MountingList.prototype.sort = function sort (fn) { var ref = this.__info__; var ctx = ref.ctx; var key = ref.key; var anchor = ref.anchor; if (this.length === 0) { return this } var sorted = ARR.copy(Array.prototype.sort.call(this, fn)); var elements = []; inform(); for (var i$1 = 0, list = sorted; i$1 < list.length; i$1 += 1) { var i = list[i$1]; i.$umount(); ARR.push(elements, i.$mount({parent: ctx.state, key: key})); } Array.prototype.push.apply(this, sorted); DOM.after.apply(DOM, [ anchor ].concat( elements )); exec(); return this }; MountingList.prototype.splice = function splice () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; if (this.length === 0) { return this } var spliced = ARR.splice.apply(ARR, [ ARR.copy(this) ].concat( args )); inform(); for (var i$1 = 0, list = spliced; i$1 < list.length; i$1 += 1) { var i = list[i$1]; i.$umount(); } exec(); return spliced }; MountingList.prototype.unshift = function unshift () { var ref$1; var items = [], len = arguments.length; while ( len-- ) items[ len ] = arguments[ len ]; var ref = this.__info__; var ctx = ref.ctx; var key = ref.key; var anchor = ref.anchor; if (this.length === 0) { return (ref$1 = this).push.apply(ref$1, items).length } var elements = []; inform(); for (var i$1 = 0, list = items; i$1 < list.length; i$1 += 1) { var i = list[i$1]; ARR.push(elements, i.$mount({parent: ctx.state, key: key})); } DOM.after.apply(DOM, [ anchor ].concat( elements )); exec(); return Array.prototype.unshift.apply(this, items) }; return MountingList; }(Array)); DOM.before = function (node) { var nodes = [], len = arguments.length - 1; while ( len-- > 0 ) nodes[ len ] = arguments[ len + 1 ]; var tempFragment = document.createDocumentFragment(); for (var i$1 = 0, list = nodes; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (isInstance(i, EFFragment)) { i.appendTo(tempFragment); } else { proto$1.appendChild.call(tempFragment, i); } } proto$1.insertBefore.call(node.parentNode, tempFragment, node); }; DOM.after = function (node) { var nodes = [], len = arguments.length - 1; while ( len-- > 0 ) nodes[ len ] = arguments[ len + 1 ]; var tempFragment = document.createDocumentFragment(); for (var i$1 = 0, list = nodes; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (isInstance(i, EFFragment)) { i.appendTo(tempFragment); } else { proto$1.appendChild.call(tempFragment, i); } } if (node.nextSibling) { proto$1.insertBefore.call(node.parentNode, tempFragment, node.nextSibling); } else { proto$1.appendChild.call(node.parentNode, tempFragment); } }; var handleMountingPoint = function (mountingPoint, tempFragment) { var node = mountingPoint.node; if (!node) { return } if (isInstance(node, MountingList)) { for (var i = 0, list = node; i < list.length; i += 1) { var j = list[i]; var ref = j.$ctx.nodeInfo; var element = ref.element; var placeholder = ref.placeholder; DOM.append(tempFragment, element, placeholder); } } else { var ref$1 = node.$ctx.nodeInfo; var element$1 = ref$1.element; var placeholder$1 = ref$1.placeholder; DOM.append(tempFragment, element$1, placeholder$1); } }; DOM.append = function (node) { var nodes = [], len = arguments.length - 1; while ( len-- > 0 ) nodes[ len ] = arguments[ len + 1 ]; if (isInstance(node, EFFragment)) { return node.push.apply(node, nodes) } if ([1,9,11].indexOf(node.nodeType) === -1) { return } var tempFragment = document.createDocumentFragment(); for (var i$1 = 0, list = nodes; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (isInstance(i, EFFragment)) { i.appendTo(tempFragment); } else { proto$1.appendChild.call(tempFragment, i); var mountingPoint = mountingPointStore.get(i); if (mountingPoint) { handleMountingPoint(mountingPoint, tempFragment); } } } proto$1.appendChild.call(node, tempFragment); }; DOM.remove = function (node) { if (isInstance(node, EFFragment)) { node.remove(); } else { proto$1.removeChild.call(node.parentNode, node); } }; // addClass(node, className) { // const classes = className.split(' ') // node.classList.add(...classes) // }, // removeClass(node, className) { // const classes = className.split(' ') // node.classList.remove(...classes) // }, // toggleClass(node, className) { // const classes = className.split(' ') // const classArr = node.className.split(' ') // for (let i of classes) { // const classIndex = classArr.indexOf(i) // if (classIndex > -1) { // classArr.splice(classIndex, 1) // } else { // classArr.push(i) // } // } // node.className = classArr.join(' ').trim() // }, // replaceWith(node, newNode) { // const parent = node.parentNode // if (parent) proto.replaceChild.call(parent, newNode, node) // }, // swap(node, newNode) { // const nodeParent = node.parentNode // const newNodeParent = newNode.parentNode // const nodeSibling = node.nextSibling // const newNodeSibling = newNode.nextSibling // if (nodeParent && newNodeParent) { // proto.insertBefore.call(nodeParent, newNode, nodeSibling) // proto.insertBefore.call(newNodeParent, node, newNodeSibling) // } // }, // prepend(node, ...nodes) { // if ([1,9,11].indexOf(node.nodeType) === -1) { // return // } // const tempFragment = document.createDocumentFragment() // nodes.reverse() // for (let i of nodes) { // proto.appendChild.call(tempFragment, i) // } // if (node.firstChild) { // proto.insertBefore.call(node, tempFragment, node.firstChild) // } else { // proto.appendChild.call(node, tempFragment) // } // }, // appendTo(node, newNode) { // proto.appendChild.call(newNode, node) // }, // prependTo(node, newNode) { // if (newNode.firstChild) { // proto.insertBefore.call(newNode, node, node.firstChild) // } else { // proto.appendChild.call(newNode, node) // } // }, // empty(node) { // node.innerHTML = '' // }, enumerableFalse(MountingList, ['constructor', 'empty', 'clear', 'pop', 'push', 'remove', 'reverse', 'shift', 'sort', 'splice', 'unshift']); /* Get new events that works in all target browsers * though a little bit old-fashioned */ var getEvent = function (name, props) { if ( props === void 0 ) props = { bubbles: false, cancelable: false }; var event = document.createEvent('Event'); event.initEvent(name, props.bubbles, props.cancelable); return event }; var checkValidType$1 = function (obj) { return ['number', 'boolean', 'string'].indexOf(typeof obj) > -1; }; // SVG/MathML tags w/ xlink attributes require specific namespace to work properly var svgNS = 'http://www.w3.org/2000/svg'; var mathNS = 'http://www.w3.org/1998/Math/MathML'; var xlinkNS = 'http://www.w3.org/1999/xlink'; var createByTag = function (tag, svg) { // SVG is always the most prioritized if (svg) { return document.createElementNS(svgNS, tag) } // Then MathML if (tag.toLowerCase() === 'math') { return document.createElementNS(mathNS, tag) } // Then HTML return document.createElement(tag) }; var getElement = function (ref$1) { var tag = ref$1.tag; var ref = ref$1.ref; var refs = ref$1.refs; var svg = ref$1.svg; var element = createByTag(tag, svg); if (ref) { Object.defineProperty(refs, ref, { value: element, enumerable: true }); } return element }; var regTmpl = function (ref) { var val = ref.val; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; var handler = ref.handler; if (Array.isArray(val)) { var strs = val[0]; var exprs = val.slice(1); var tmpl = [strs]; var _handler = function () { return handler(mixVal.apply(void 0, tmpl)); }; tmpl.push.apply(tmpl, exprs.map(function (item) { var ref = initBinding({bind: item, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); var dataNode = ref.dataNode; var handlerNode = ref.handlerNode; var _key = ref._key; handlerNode.push(_handler); return {dataNode: dataNode, _key: _key} })); return _handler } return function () { return val; } }; var updateOthers = function (ref) { var parentNode = ref.parentNode; var handlerNode = ref.handlerNode; var _handler = ref._handler; var _key = ref._key; var value = ref.value; // Remove handler for this element temporarily ARR.remove(handlerNode, _handler); inform(); parentNode[_key] = value; exec(); // Add back the handler ARR.push(handlerNode, _handler); }; var addValListener = function (ref) { var _handler = ref._handler; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; var element = ref.element; var key = ref.key; var expr = ref.expr; var ref$1 = initBinding({bind: expr, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); var parentNode = ref$1.parentNode; var handlerNode = ref$1.handlerNode; var _key = ref$1._key; var _update = function () { return updateOthers({parentNode: parentNode, handlerNode: handlerNode, _handler: _handler, _key: _key, value: element.value}); }; if (key === 'value') { // Listen to input, keyup and change events in order to work in most browsers. element.addEventListener('input', _update, true); element.addEventListener('keyup', _update, true); element.addEventListener('change', _update, true); // // Remove keyup and change listener if browser supports input event correctly // const removeListener = () => { // element.removeEventListener('input', removeListener, true) // element.removeEventListener('keyup', _update, true) // element.removeEventListener('change', _update, true) // } // element.addEventListener('input', removeListener, true) } else { element.addEventListener('change', function () { // Trigger change to the element it-self element.dispatchEvent(getEvent('ef-change-event')); if (element.tagName === 'INPUT' && element.type === 'radio' && element.name !== '') { // Trigger change to the the same named radios var radios = document.querySelectorAll(("input[name=" + (element.name) + "]")); if (radios) { var selected = ARR.copy(radios); ARR.remove(selected, element); /* Event triggering could cause unwanted render triggers * no better ways came up at the moment */ for (var i$1 = 0, list = selected; i$1 < list.length; i$1 += 1) { var i = list[i$1]; i.dispatchEvent(getEvent('ef-change-event')); } } } }, true); // Use custom event to avoid loops and conflicts element.addEventListener('ef-change-event', function () { return updateOthers({parentNode: parentNode, handlerNode: handlerNode, _handler: _handler, _key: _key, value: element.checked}); }); } }; var getAttrHandler = function (element, key) { if (key === 'class') { return function (val) { val = ("" + val).replace(/\s+/g, ' ').trim(); // Remove attribute when value is empty if (!val) { return element.removeAttribute(key) } element.setAttribute(key, val); } } // Handle xlink namespace if (key.indexOf('xlink:') === 0) { return function (val) { // Remove attribute when value is empty if (val === '') { return element.removeAttributeNS(xlinkNS, key) } element.setAttributeNS(xlinkNS, key, val); } } return function (val) { // Remove attribute when value is empty if (val === '') { return element.removeAttribute(key) } element.setAttribute(key, val); } }; var addAttr = function (ref) { var element = ref.element; var attr = ref.attr; var key = ref.key; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; if (checkValidType$1(attr)) { // Handle xlink namespace if (key.indexOf('xlink:') === 0) { return element.setAttributeNS(xlinkNS, key, attr) } return element.setAttribute(key, attr) } var handler = getAttrHandler(element, key); queue([regTmpl({val: attr, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData, handler: handler})]); }; var addProp = function (ref) { var element = ref.element; var prop = ref.prop; var key = ref.key; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; if (checkValidType$1(prop)) { element[key] = prop; } else { var handler = function (val) { element[key] = val; }; var _handler = regTmpl({val: prop, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData, handler: handler}); if ((key === 'value' || key === 'checked') && !prop[0]) { addValListener({_handler: _handler, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData, element: element, key: key, expr: prop[1]}); } queue([_handler]); } }; var rawHandler = function (val) { return val; }; var addEvent = function (ref) { var element = ref.element; var event = ref.event; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; /** * l: listener : string * m: method : string * s: stopPropagation : number/undefined * i: stopImmediatePropagation : number/undefined * p: preventDefault : number/undefined * h: shiftKey : number/undefined * a: altKey : number/undefined * c: ctrlKey : number/undefined * t: metaKey : number/undefined * u: capture : number/undefined * k: keyCodes : array/undefined * v: value : string/array/undefined */ var l = event.l; var m = event.m; var s = event.s; var i = event.i; var p = event.p; var h = event.h; var a = event.a; var c = event.c; var t = event.t; var u = event.u; var k = event.k; var v = event.v; var _handler = regTmpl({val: v, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData, handler: rawHandler}); element.addEventListener(l, function (e) { if (!!h !== !!e.shiftKey || !!a !== !!e.altKey || !!c !== !!e.ctrlKey || !!t !== !!e.metaKey || (k && k.indexOf(e.which) === -1)) { return } if (s) { e.stopPropagation(); } if (i) { e.stopImmediatePropagation(); } if (p) { e.preventDefault(); } if (ctx.methods[m]) { ctx.methods[m]({e: e, value: _handler(), state: ctx.state}); } else { dbg.warn(("Method named '" + m + "' not found! Value been passed is:"), _handler()); } }, !!u); }; var createElement = function (ref) { var info = ref.info; var ctx = ref.ctx; var innerData = ref.innerData; var refs = ref.refs; var handlers = ref.handlers; var subscribers = ref.subscribers; var svg = ref.svg; /** * t: tag : string | int, 0 means fragment * a: attr : object * p: prop : object * e: event : array * r: reference : string */ var t = info.t; var a = info.a; var p = info.p; var e = info.e; var r = info.r; if (t === 0) { return new EFFragment() } var element = getElement({tag: t, ref: r, refs: refs, svg: svg}); for (var i in a) { addAttr({element: element, attr: a[i], key: i, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); } for (var i$1 in p) { addProp({element: element, prop: p[i$1], key: i$1, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); } for (var i$2 in e) { addEvent({element: element, event: e[i$2], ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); } return element }; var mountOptions = { BEFORE: 'before', AFTER: 'after', APPEND: 'append', REPLACE: 'replace' }; var nullComponent = Object.create(null); var checkDestroyed = function (state) { if (!state.$ctx) { throw new Error('[EF] This component has been destroyed!') } }; var bindTextNode = function (ref) { var node = ref.node; var ctx = ref.ctx; var handlers = ref.handlers; var subscribers = ref.subscribers; var innerData = ref.innerData; var element = ref.element; // Data binding text node var textNode = document.createTextNode(''); var ref$1 = initBinding({bind: node, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); var dataNode = ref$1.dataNode; var handlerNode = ref$1.handlerNode; var _key = ref$1._key; var handler = function () { var value = dataNode[_key]; if (typeof value === 'undefined') { textNode.textContent = ''; return } textNode.textContent = dataNode[_key]; }; handlerNode.push(handler); queue([handler]); // Append element to the component DOM.append(element, textNode); }; var updateMountingNode = function (ref) { var ctx = ref.ctx; var key = ref.key; var value = ref.value; var children = ctx.children; var child = children[key]; var anchor = child.anchor; var node = child.node; if (node === value) { return } inform(); // Update component if (node) { if (value === nullComponent) { value = null; } else { node.$umount(); } } // Update stored value child.node = value; if (value) { value.$mount({target: anchor, parent: ctx.state, option: mountOptions.BEFORE, key: key}); } exec(); }; var updateMountingList = function (ref) { var ctx = ref.ctx; var key = ref.key; var value = ref.value; var children = ctx.children; var ref$1 = children[key]; var anchor = ref$1.anchor; var node = ref$1.node; if (ARR.equals(node, value)) { return } if (value) { value = ARR.copy(value); } else { value = []; } var fragment = document.createDocumentFragment(); // Update components inform(); if (node) { node.clear(); for (var i = 0, list = value; i < list.length; i += 1) { var item = list[i]; if (item.$ctx.nodeInfo.parent) { item.$umount(); } DOM.append(fragment, item.$mount({parent: ctx.state, key: key})); } } else { for (var i$1 = 0, list$1 = value; i$1 < list$1.length; i$1 += 1) { var item$1 = list$1[i$1]; DOM.append(fragment, item$1.$mount({parent: ctx.state, key: key})); } } // Update stored value node.length = 0; ARR.push.apply(ARR, [ node ].concat( value )); // Append to current component DOM.after(anchor, fragment); exec(); }; var mountingPointUpdaters = [ updateMountingNode, updateMountingList ]; var applyMountingPoint = function (type, key, tpl) { Object.defineProperty(tpl.prototype, key, { get: function get() { { checkDestroyed(this); } return this.$ctx.children[key].node }, set: function set(value) { { checkDestroyed(this); } var ctx = this.$ctx; mountingPointUpdaters[type]({ctx: ctx, key: key, value: value}); }, enumerable: true }); }; var bindMountingNode = function (ref) { var ctx = ref.ctx; var key = ref.key; var anchor = ref.anchor; var children = ctx.children; var isFragment = ctx.isFragment; children[key] = {anchor: anchor}; if (isFragment) { DOM.append(ctx.safeZone, anchor); mountingPointStore.set(anchor, children[key]); } }; var bindMountingList = function (ref) { var ctx = ref.ctx; var key = ref.key; var anchor = ref.anchor; var children = ctx.children; var isFragment = ctx.isFragment; children[key] = { node: new MountingList({ctx: ctx, key: key, anchor: anchor}), anchor: anchor }; if (isFragment) { DOM.append(ctx.safeZone, anchor); mountingPointStore.set(anchor, children[key]); } }; // Walk through the AST to perform proper actions var resolveAST = function (ref) { var node = ref.node; var nodeType = ref.nodeType; var element = ref.element; var ctx = ref.ctx; var innerData = ref.innerData; var refs = ref.refs; var handlers = ref.handlers; var subscribers = ref.subscribers; var svg = ref.svg; var create = ref.create; var EFBaseComponent = ref.EFBaseComponent; switch (nodeType) { // Static text node case 'string': { DOM.append(element, document.createTextNode(node)); break } // Child element or a dynamic text node case 'array': { // Recursive call for child element if (typeOf(node[0]) === 'object') { DOM.append(element, create({node: node, ctx: ctx, innerData: innerData, refs: refs, handlers: handlers, subscribers: subscribers, svg: svg, create: create, EFBaseComponent: EFBaseComponent})); } // Dynamic text node else { bindTextNode({node: node, ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData, element: element}); } break } // Mounting points case 'object': { var anchor = document.createTextNode(''); // Single node mounting point if (node.t === 0) { bindMountingNode({ctx: ctx, key: node.n, anchor: anchor}); } // Multi node mounting point else { bindMountingList({ctx: ctx, key: node.n, anchor: anchor}); } // Append anchor { DOM.append(element, document.createComment(("EF MOUNTING POINT '" + (node.n) + "' START"))); } DOM.append(element, anchor); { DOM.append(element, document.createComment(("EF MOUNTING POINT '" + (node.n) + "' END"))); } break } default: } }; // Create elements based on description from AST var create = function (ref) { var node = ref.node; var ctx = ref.ctx; var innerData = ref.innerData; var refs = ref.refs; var handlers = ref.handlers; var subscribers = ref.subscribers; var svg = ref.svg; var create = ref.create; var EFBaseComponent = ref.EFBaseComponent; var info = node[0]; var childNodes = node.slice(1); var fragment = info.t === 0; // Enter SVG mode if (!fragment && !svg && info.t.toLowerCase() === 'svg') { svg = true; } // First create an element according to the description var element = createElement({info: info, ctx: ctx, innerData: innerData, refs: refs, handlers: handlers, subscribers: subscribers, svg: svg}); if (fragment && 'development' !== 'production') { element.push(document.createComment('EF FRAGMENT START')); } // Leave SVG mode if tag is `foreignObject` if (svg && info.t.toLowerCase() === 'foreignobject') { svg = false; } // Append child nodes for (var i$1 = 0, list = childNodes; i$1 < list.length; i$1 += 1) { var i = list[i$1]; if (i instanceof EFBaseComponent) { i.$mount({target: element}); } else { resolveAST({node: i, nodeType: typeOf(i), element: element, ctx: ctx, innerData: innerData, refs: refs, handlers: handlers, subscribers: subscribers, svg: svg, create: create, EFBaseComponent: EFBaseComponent}); } } if (fragment && 'development' !== 'production') { element.push(document.createComment('EF FRAGMENT END')); } return element }; var unsubscribe = function (pathStr, fn, subscribers) { var subscriberNode = resolveSubscriber(pathStr, subscribers); ARR.remove(subscriberNode, fn); }; var EFBaseComponent = /*@__PURE__*/(function () { function EFBaseComponent(ast) { var children = {}; var refs = {}; var data = {}; var innerData = {}; var methods = {}; var handlers = {}; var subscribers = {}; var nodeInfo = { placeholder: null, replace: [], parent: null, key: null }; /* Detatched components will be put in the safe zone. * Split safe zone to each component in order to make * the component memory recycleable when lost reference */ var safeZone = document.createDocumentFragment(); { nodeInfo.placeholder = document.createComment('EF COMPONENT PLACEHOLDER'); } var mount = function () { if (nodeInfo.replace.length > 0) { for (var i$1 = 0, list = nodeInfo.replace; i$1 < list.length; i$1 += 1) { var i = list[i$1]; DOM.remove(i); } ARR.empty(nodeInfo.replace); } DOM.before(nodeInfo.placeholder, nodeInfo.element); }; var ctx = { mount: mount, refs: refs, data: data, innerData: innerData, methods: methods, handlers: handlers, subscribers: subscribers, nodeInfo: nodeInfo, safeZone: safeZone, children: children, state: this, isFragment: ast[0].t === 0 }; Object.defineProperty(this, '$ctx', { value: ctx, enumerable: false, configurable: true }); inform(); nodeInfo.element = create({node: ast, ctx: ctx, innerData: innerData, refs: refs, handlers: handlers, subscribers: subscribers, svg: false, create: create, EFBaseComponent: EFBaseComponent}); DOM.append(safeZone, nodeInfo.placeholder); queueDom(mount); exec(); } var prototypeAccessors = { $data: { configurable: true },$methods: { configurable: true },$refs: { configurable: true } }; prototypeAccessors.$data.get = function () { { checkDestroyed(this); } return this.$ctx.data }; prototypeAccessors.$data.set = function (newData) { { checkDestroyed(this); } inform(); assign(this.$ctx.data, newData); exec(); }; prototypeAccessors.$methods.get = function () { { checkDestroyed(this); } return this.$ctx.methods }; prototypeAccessors.$methods.set = function (newMethods) { { checkDestroyed(this); } this.$ctx.methods = newMethods; }; prototypeAccessors.$refs.get = function () { { checkDestroyed(this); } return this.$ctx.refs }; EFBaseComponent.prototype.$mount = function $mount (ref) { var target = ref.target; var option = ref.option; var parent = ref.parent; var key = ref.key; { checkDestroyed(this); } var ref$1 = this.$ctx; var nodeInfo = ref$1.nodeInfo; var mount = ref$1.mount; if (typeof target === 'string') { target = document.querySelector(target); } inform(); if (nodeInfo.parent) { this.$umount(); { dbg.warn('Component detached from previous mounting point.'); } } if (!parent) { parent = target; } if (!key) { key = '__DIRECTMOUNT__'; } nodeInfo.parent = parent; nodeInfo.key = key; queueDom(mount); if (!target) { exec(); return nodeInfo.placeholder } switch (option) { case mountOptions.BEFORE: { DOM.before(target, nodeInfo.placeholder); break } case mountOptions.AFTER: { DOM.after(target, nodeInfo.placeholder); break } case mountOptions.REPLACE: { DOM.before(target, nodeInfo.placeholder); nodeInfo.replace.push(target); break } case mountOptions.APPEND: default: { // Parent is EFFragment should only happen when using jsx if (isInstance(parent, EFFragment)) { DOM.append(target, nodeInfo.element); } else { DOM.append(target, nodeInfo.placeholder); } } } return exec() }; EFBaseComponent.prototype.$umount = function $umount () { { checkDestroyed(this); } var ref = this.$ctx; var nodeInfo = ref.nodeInfo; var safeZone = ref.safeZone; var mount = ref.mount; var parent = nodeInfo.parent; var key = nodeInfo.key; nodeInfo.parent = null; nodeInfo.key = null; inform(); if (parent) { if (key !== '__DIRECTMOUNT__') { if (parent[key]) { if (Array.isArray(parent[key])) { // Remove self from parent list mounting point ARR.remove(parent[key], this); } else { parent[key] = nullComponent; } } // Else Remove elements from fragment parent } else if (isInstance(parent, EFFragment)) { ARR.remove(parent.$ctx.nodeInfo.element, nodeInfo.element); } } DOM.append(safeZone, nodeInfo.placeholder); queueDom(mount); return exec() }; EFBaseComponent.prototype.$subscribe = function $subscribe (pathStr, subscriber) { { checkDestroyed(this); } var ctx = this.$ctx; var handlers = ctx.handlers; var subscribers = ctx.subscribers; var innerData = ctx.innerData; var _path = pathStr.split('.'); var ref = initBinding({bind: [_path], ctx: ctx, handlers: handlers, subscribers: subscribers, innerData: innerData}); var dataNode = ref.dataNode; var subscriberNode = ref.subscriberNode; var _key = ref._key; inform(); // Execute the subscriber function immediately try { subscriber({state: this, value: dataNode[_key]}); // Put the subscriber inside the subscriberNode subscriberNode.push(subscriber); } catch (e) { dbg.error('Error caught when registering subscriber:\n', e); } exec(); }; EFBaseComponent.prototype.$unsubscribe = function $unsubscribe (pathStr, fn) { { checkDestroyed(this); } var ref = this.$ctx; var subscribers = ref.subscribers; unsubscribe(pathStr, fn, subscribers); }; EFBaseComponent.prototype.$update = function $update (newState) { { checkDestroyed(this); } inform(); legacyAssign(this, newState); exec(); }; EFBaseComponent.prototype.$destroy = function $destroy () { { checkDestroyed(this); } var ref = this.$ctx; var nodeInfo = ref.nodeInfo; var isFragment = ref.isFragment; var children = ref.children; inform(); this.$umount(); if (isFragment) { for (var i in children) { mountingPointStore.delete(children[i].anchor); } } // Detatch all mounted components for (var i$1 in this) { if (typeOf(this[i$1]) === 'array') { this[i$1].clear(); } else { this[i$1] = null; } } // Remove context delete this.$ctx; // Push DOM removement operation to query queueDom(function () { DOM.remove(nodeInfo.element); DOM.remove(nodeInfo.placeholder); }); // Render return exec() }; Object.defineProperties( EFBaseComponent.prototype, prototypeAccessors ); return EFBaseComponent; }()); enumerableFalse(EFBaseComponent, ['$mount', '$umount', '$subscribe', '$unsubscribe', '$update', '$destroy']); var getGetter = function (ref, ref$1) { var base = ref.base; var key = ref.key; var checkTrue = ref$1.checkTrue; var get = ref$1.get; var set = ref$1.set; if (get) { if (!set) { throw new Error('Setter must be defined when getter exists') } return get } if (checkTrue) { return function() { return checkTrue(base(this)[key], this) } } return function() { return base(this)[key] } }; var getSetter = function (ref, ref$1) { var base = ref.base; var key = ref.key; var checkTrue = ref$1.checkTrue; var trueVal = ref$1.trueVal; var falseVal = ref$1.falseVal; var get = ref$1.get; var set = ref$1.set; if (set) { if (!get) { throw new Error('Getter must be defined when setter exists') } return set } if (checkTrue) { return function(val) { var baseNode = base(this); var _trueVal = trueVal; var _falseVal = falseVal; if (typeof trueVal !== 'function') { trueVal = function () { return _trueVal; }; } if (typeof falseVal !== 'function') { falseVal = function () { return _falseVal; }; } if (val) { baseNode[key] = trueVal(this); } else { baseNode[key] = falseVal(this); } } } return function(val) { base(this)[key] = val; } }; var defaultRoot = function (state) { return state.$data; }; var getBase = function (root) { if (!root) { return defaultRoot } if (typeof root === 'function') { return root } if (typeof root === 'string') { root = root.split('.'); } return function (base) { for (var i = 0, list = root; i < list.length; i += 1) { var key = list[i]; base = base[key]; } return base } }; var registerProps = function (tpl, propMap) { for (var prop in propMap) { /* Options: * key: key on root, default to prop * base: a function that returns the base of the key, default returns $data * trueVal: value when true, only used when checkTrue is set * falseVal: value when false, only used when checkTrue is set * checkTrue: a function returns true or false based on input value * get: getter, will ignore all other settings except set * set: setter, will ignore all other settings except get */ var options = propMap[prop]; var base = getBase(options.base); var key = options.key || prop; var basicProperty = {base: base, key: key}; var get = getGetter(basicProperty, options); var set = getSetter(basicProperty, options); Object.defineProperty(tpl.prototype, prop, { get: get, set: set, enumerable: true, configurable: false }); } return tpl }; var Fragment = /*@__PURE__*/(function (EFBaseComponent) { function Fragment() { var children = [], len = arguments.length; while ( len-- ) children[ len ] = arguments[ len ]; EFBaseComponent.call(this, [{t: 0} ].concat( children)); } if ( EFBaseComponent ) Fragment.__proto__ = EFBaseComponent; Fragment.prototype = Object.create( EFBaseComponent && EFBaseComponent.prototype ); Fragment.prototype.constructor = Fragment; return Fragment; }(EFBaseComponent)); // Make a helper component for text fragments var textFragmentAst = [{t: 0},[['text']]]; var TextFragment = /*@__PURE__*/(function (EFBaseComponent) { function TextFragment(text) { inform(); EFBaseComponent.call(this, textFragmentAst); this.text = text; exec(); } if ( EFBaseComponent ) TextFragment.__proto__ = EFBaseComponent; TextFragment.prototype = Object.create( EFBaseComponent && EFBaseComponent.prototype ); TextFragment.prototype.constructor = TextFragment; return TextFragment; }(EFBaseComponent)); registerProps(TextFragment, {text: {}}); var textToFragment = function (value) { if (typeof value === 'string') { return new TextFragment(value) } return value }; var createElement$1 = function (tag, attrs) { var children = [], len = arguments.length - 2; while ( len-- > 0 ) children[ len ] = arguments[ len + 2 ]; // Create special component for fragment if (tag === Fragment) { return new (Function.prototype.bind.apply( Fragment, [ null ].concat( children) )) } // Create an instance if tag is an ef class if (Object.isPrototypeOf.call(EFBaseComponent, tag)) { if (children.length <= 0) { return new tag(attrs) } return new tag(assign({children: children.map(textToFragment)}, attrs || {})) } // Else return the generated basic component // Transform all label only attributes to ef-supported style var transformedAttrs = assign({}, attrs); for (var i in transformedAttrs) { if (transformedAttrs[i] === true) { transformedAttrs[i] = ''; } } return new EFBaseComponent([ { t: tag, a: transformedAttrs } ].concat( children )) }; var version$1 = "0.9.6"; // Import everything // Apply mounting point properties for classes var applyMountingPoints = function (node, tpl) { var nodeType = typeOf(node); switch (nodeType) { case 'array': { var info = node[0]; var childNodes = node.slice(1); if (typeOf(info) === 'object') { for (var i$1 = 0, list = childNodes; i$1 < list.length; i$1 += 1) { var i = list[i$1]; applyMountingPoints(i, tpl); } } break } case 'object': { if (node.t > 1) { throw new TypeError(("[EF] Not a standard ef.js AST: Unknown mounting point type '" + (node.t) + "'")) } applyMountingPoint(node.t, node.n, tpl); break } case 'string': { break } default: { throw new TypeError(("[EF] Not a standard ef.js AST: Unknown node type '" + nodeType + "'")) } } }; // Return a brand new class for the new component var create$1 = function (value) { var ast = value; var EFComponent = /*@__PURE__*/(function (EFBaseComponent) { function EFComponent(newState) { inform(); EFBaseComponent.call(this, ast); if (newState) { this.$update(newState); } exec(); } if ( EFBaseComponent ) EFComponent.__proto__ = EFBaseComponent; EFComponent.prototype = Object.create( EFBaseComponent && EFBaseComponent.prototype ); EFComponent.prototype.constructor = EFComponent; return EFComponent; }(EFBaseComponent)); applyMountingPoints(ast, EFComponent); // Workaround for a bug of buble // https://github.com/bublejs/buble/issues/197 Object.defineProperty(EFComponent.prototype, 'constructor', {enumerable: false}); return EFComponent }; { dbg.info(("ef-core v" + version$1 + " initialized!")); } // Import everything // Set parser var parser = parseEft; var create$2 = function (value) { var valType = typeOf(value); if (valType === 'string') { value = parse(value, parser); } else if (valType !== 'array') { throw new TypeError('Cannot create new component without proper template or AST!') } return create$1(value) }; // Change parser var setParser = function (newParser) { parser = newParser; }; var t$1 = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return create$2(mixStr.apply(void 0, args)); }; { console.info(("[EF] ef.js v" + version + " initialized!")); } exports.Fragment = Fragment; exports.TextFragment = TextFragment; exports.bundle = bundle; exports.create = create$2; exports.createElement = createElement$1; exports.exec = exec; exports.inform = inform; exports.isPaused = isPaused; exports.mountOptions = mountOptions; exports.onNextRender = onNextRender; exports.parseEft = parseEft; exports.registerProps = registerProps; exports.setParser = setParser; exports.t = t$1; exports.version = version; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=ef.dev.js.map
var exceptions = require("../lib/exceptions"); var should = require("should"); exports.testIllegalArgumentException = function (test) { try { exceptions.ILLEGAL_ARGUMENT.thro("NOOOO"); } catch (error) { error.name.should.equal("IllegalArgumentException"); error.stack.should.not.include("exceptions.js"); error.stack.should.include("NOOOO"); test.done(); } }; exports.testIllegalStateException = function (test) { try { exceptions.ILLEGAL_STATE.thro("Bad state"); } catch (error) { error.name.should.equal("IllegalStateException"); error.stack.should.not.include("exceptions.js"); error.stack.should.include("Bad state"); test.done(); } }; exports.testIOException = function (test) { try { exceptions.IO.thro("Bad IO"); } catch (error) { error.name.should.equal("IOException"); error.stack.should.not.include("exceptions.js"); error.stack.should.include("Bad IO"); test.done(); } }; exports.testCustomException = function (test) { var NOT_ENCAPSULATED_EXCEPTION = new exceptions.Exception("NotEncapsulatedException"); try { NOT_ENCAPSULATED_EXCEPTION.thro("Exception does not protect name and thro members"); } catch (error) { error.name.should.equal("NotEncapsulatedException"); error.stack.should.not.include("exceptions.js"); error.stack.should.include("Exception does not protect name and thro members"); test.done(); } }; exports.testExceptionWithErrorCause = function (test) { var cause = new Error("I caused it. I'm sorry. It was an accident"); try { exceptions.ILLEGAL_STATE.thro("Bad state with cause", cause); } catch (error) { error.stack.should.include("IllegalStateException"); error.stack.should.include("I caused it."); test.done(); } };
/* Utility functions */ var hasOwnProp = Object.prototype.hasOwnProperty /** * Returns an new object with all of the properties from each received object. * When there are identical properties, the right-most property takes precedence. * * @returns {object} A new object containing all the properties. */ function _mixobj () { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] if (source) { for (var key in source) { // istanbul ignore else if (hasOwnProp.call(source, key)) { target[key] = source[key] } } } } return target } /** * Loads and returns a module instance without generating error. * * @param {string} name - The name of the module to require * @returns {Function} Module instance, or null if error. */ function _tryreq (name) { var mod = null try { mod = require(name) } catch (e) {/**/} return mod } module.exports = { mixobj: _mixobj, tryreq: _tryreq }
/*! * jQuery JavaScript Library v2.0.3 -wrap,-css,-event-alias,-effects,-offset,-dimensions,-deprecated * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:16Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3 -wrap,-css,-event-alias,-effects,-offset,-dimensions,-deprecated", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
({ baseUrl: "js/lib", map: { '*': { 'jquery': 'zepto' } }, dir: "../www-built", appDir: "../www", removeCombined: true, modules: [ { name: "../app" } ] })
'use strict'; /* Directives */ angular.module('myApp.directives', []). directive('appVersion', ['version', function (version) { return function (scope, elm, attrs) { elm.text(version); }; }]);
define( ({ loading: 'Chargement en cours...', loadMore: 'Autres chargements' }) );
/** * Dependencies */ var Server = require('ws').Server; var protocol = require('../protocol/index'); var mixin = require('utils-merge'); /** * Private variables and functions */ var devices = {}; // { deviceid: [ws, ws, ws] } var apps = {}; // { deviceid: [ws, ws, ws] } var clean = function (ws) { ws.devices.forEach(function (deviceid) { if (Array.isArray(devices[deviceid]) && devices[deviceid][0] === ws) { delete devices[deviceid]; protocol.postMessage({ type: 'device.online', deviceid: deviceid, online: false }); } var pos, wsList = apps[deviceid]; if (wsList && (pos = wsList.indexOf(ws)) !== -1) { wsList.splice(pos, 1); if (wsList.length === 0) delete apps[deviceid]; } }); }; var Types = { 'REQUEST': 1, 'RESPONSE': 2, 'UNKNOWN': 0 }; var getType = function (msg) { if (msg.action && msg.deviceid && msg.apikey) return Types.REQUEST; if (typeof msg.error === 'number') return Types.RESPONSE; return Types.UNKNOWN; }; var postRequest = function (ws, req) { if (req.ws && req.ws === ws) { return; } ws.send(JSON.stringify(req, function (key, value) { if (key === 'ws') { // exclude property ws from resulting JSON string return undefined; } return value; })); }; var postRequestToApps = function (req) { apps[req.deviceid] && apps[req.deviceid].forEach(function (ws) { postRequest(ws, req); }); }; protocol.on('device.update', function (req) { postRequestToApps(req); }); protocol.on('device.online', function (req) { postRequestToApps(req); }); protocol.on('app.update', function (req) { devices[req.deviceid] && devices[req.deviceid].forEach(function (ws) { // Transform timers for ITEAD indie device postRequest(ws, protocol.utils.transformRequest(req)); }); }); /** * Exports */ module.exports = function (httpServer) { var server = new Server({ server: httpServer, path: '/api/ws' }); server.on('connection', function (ws) { ws.devices = []; ws.on('message', function (msg) { try { msg = JSON.parse(msg); } catch (err) { // Ignore non-JSON message return; } switch (getType(msg)) { case Types.UNKNOWN: return; case Types.RESPONSE: protocol.postResponse(msg); return; case Types.REQUEST: msg.ws = ws; protocol.postRequest(msg, function (res) { // Transform timers for ITEAD indie device if (protocol.utils.fromDevice(msg) && protocol.utils.isFactoryDeviceid(msg.deviceid)) { res = protocol.utils.transformResponse(res); } ws.send(JSON.stringify(res)); if (res.error) return; // Message sent from device if (protocol.utils.fromDevice(msg)) { devices[msg.deviceid] = devices[msg.deviceid] || []; if (devices[msg.deviceid][0] === ws) return; devices[msg.deviceid] = [ws]; ws.devices.push(msg.deviceid); protocol.postMessage({ type: 'device.online', deviceid: msg.deviceid, online: true }); return; } // Message sent from apps apps[msg.deviceid] = apps[msg.deviceid] || []; if (apps[msg.deviceid].indexOf(ws) !== -1) return; apps[msg.deviceid].push(ws); ws.devices.push(msg.deviceid); }); } }); ws.on('close', function () { clean(ws); }); ws.on('error', function () { clean(ws); }); }); };
(function ($) { $(function () {}); $(window).load(function () {}); })(jQuery);
{ "translatorID": "a5998785-222b-4459-9ce8-9c081d599af7", "label": "Milli Kütüphane", "creator": "Philipp Zumstein", "target": "^https?://(www\\.)?kasif\\.mkutup\\.gov\\.tr/", "minVersion": "4.0", "maxVersion": "", "priority": 100, "inRepository": true, "translatorType": 4, "browserSupport": "gcsibv", "lastUpdated": "2017-10-01 17:23:23" } /* ***** BEGIN LICENSE BLOCK ***** Copyright © 2017 Philipp Zumstein This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ // attr()/text() v2 function attr(docOrElem,selector,attr,index){var elem=index?docOrElem.querySelectorAll(selector).item(index):docOrElem.querySelector(selector);return elem?elem.getAttribute(attr):null}function text(docOrElem,selector,index){var elem=index?docOrElem.querySelectorAll(selector).item(index):docOrElem.querySelector(selector);return elem?elem.textContent:null} function detectWeb(doc, url) { if (url.indexOf('/SonucDetay.aspx?MakId=')>-1) { return "book"; } else if (url.indexOf('/OpacArama.aspx?')>-1 && getSearchResults(doc, true)) { return "multiple"; } Z.monitorDOMChanges(doc.getElementById('dvKapsam'), {childList: true}); } function getSearchResults(doc, checkOnly) { var items = {}; var found = false; var rows = doc.querySelectorAll('.SonucDiv1'); for (var i=0; i<rows.length; i++) { var onclick = rows[i].onclick; var href; if (onclick) { var param = onclick.toString().match(/Goster\((\d+),(\d+)\)/); if (param) { //we don't handle articles which don't have MARC data if (param[2] !== "1700") { href = 'SonucDetay.aspx?MakId=' + param[1]; } } } var title = ZU.trimInternal(rows[i].textContent); if (!href || !title) continue; if (checkOnly) return true; found = true; items[href] = title; } return found ? items : false; } function doWeb(doc, url) { if (detectWeb(doc, url) == "multiple") { Zotero.selectItems(getSearchResults(doc, false), function (items) { if (!items) { return true; } var articles = []; for (var i in items) { articles.push(i); } ZU.processDocuments(articles, scrape); }); } else { scrape(doc, url); } } function scrape(doc, url) { var lines = doc.querySelectorAll('#cntPlcPortal_grdMrc tr'); //call MARC translator var translator = Zotero.loadTranslator("import"); translator.setTranslator("a6ee60df-1ddc-4aae-bb25-45e0537be973"); translator.getTranslatorObject(function (marc) { var record = new marc.record(); var newItem = new Zotero.Item(); //ignore the table headings in lines[0] record.leader = text(lines[1], 'td', 4); var fieldTag, indicators, fieldContent; for (var j=2; j<lines.length; j++) { //multiple lines with same fieldTag do not repeat it //i.e. in these cases we will just take same value as before if (text(lines[j], 'td', 0).trim().length>0) { fieldTag = text(lines[j], 'td', 0); } indicators = text(lines[j], 'td', 1) + text(lines[j], 'td', 2); fieldContent = ''; if (text(lines[j], 'td', 3).trim().length>0) { fieldContent = marc.subfieldDelimiter + text(lines[j], 'td', 3); } fieldContent += text(lines[j], 'td', 4); record.addField(fieldTag, indicators, fieldContent); } record.translate(newItem); //don't save value "no publisher" = "yayl.y." if (newItem.publisher == 'yayl.y.') { delete newItem.publisher; } newItem.complete(); }); } /** BEGIN TEST CASES **/ var testCases = [ { "type": "web", "url": "https://kasif.mkutup.gov.tr/SonucDetay.aspx?MakId=954757", "items": [ { "itemType": "book", "title": "Protestanlıkta sakramentler", "creators": [ { "firstName": "Muhammet", "lastName": "Tarakçı", "creatorType": "author" } ], "date": "2012", "ISBN": "9786054487059", "callNumber": "2014 AD 15480", "language": "TUR", "libraryCatalog": "Milli Kütüphane", "numPages": "296", "place": "Bursa", "publisher": "Emin Yayınları", "series": "Emin Yayınları", "seriesNumber": "122", "attachments": [], "tags": [ "Protestanlık (Hıristiyanlık)" ], "notes": [ { "note": "Dizin vardır" } ], "seeAlso": [] } ] }, { "type": "web", "url": "https://kasif.mkutup.gov.tr/SonucDetay.aspx?MakId=423635", "items": [ { "itemType": "book", "title": "Peygamberlik makamı ve sevgili peygamberimiz", "creators": [ { "firstName": "Nihat (F)", "lastName": "Dalgın", "creatorType": "editor" }, { "firstName": "Yunus (F)", "lastName": "Macit", "creatorType": "editor" } ], "date": "1992", "callNumber": "1993 AD 4043", "language": "TUR", "libraryCatalog": "Milli Kütüphane", "numPages": "126", "place": "Samsun", "attachments": [], "tags": [], "notes": [], "seeAlso": [] } ] } ] /** END TEST CASES **/
/** * @fileoverview restrict values that can be used as Promise rejection reasons * @author Teddy Katz */ "use strict"; const astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "require using Error objects as Promise rejection reasons", category: "Best Practices", recommended: false }, fixable: null, schema: [ { type: "object", properties: { allowEmptyReject: { type: "boolean" } }, additionalProperties: false } ] }, create(context) { const ALLOW_EMPTY_REJECT = context.options.length && context.options[0].allowEmptyReject; //---------------------------------------------------------------------- // Helpers //---------------------------------------------------------------------- /** * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise * @returns {void} */ function checkRejectCall(callExpression) { if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) { return; } if ( !callExpression.arguments.length || !astUtils.couldBeError(callExpression.arguments[0]) || callExpression.arguments[0].type === "Identifier" && callExpression.arguments[0].name === "undefined" ) { context.report({ node: callExpression, message: "Expected the Promise rejection reason to be an Error." }); } } /** * Determines whether a function call is a Promise.reject() call * @param {ASTNode} node A CallExpression node * @returns {boolean} `true` if the call is a Promise.reject() call */ function isPromiseRejectCall(node) { return node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "Promise" && node.callee.property.type === "Identifier" && node.callee.property.name === "reject"; } //---------------------------------------------------------------------- // Public //---------------------------------------------------------------------- return { // Check `Promise.reject(value)` calls. CallExpression(node) { if (isPromiseRejectCall(node)) { checkRejectCall(node); } }, /* * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls. * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that * the nodes in the expression already have the `parent` property. */ "NewExpression:exit"(node) { if ( node.callee.type === "Identifier" && node.callee.name === "Promise" && node.arguments.length && astUtils.isFunction(node.arguments[0]) && node.arguments[0].params.length > 1 && node.arguments[0].params[1].type === "Identifier" ) { context.getDeclaredVariables(node.arguments[0]) /* * Find the first variable that matches the second parameter's name. * If the first parameter has the same name as the second parameter, then the variable will actually * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten * by the second parameter. It's not possible for an expression with the variable to be evaluated before * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for * this case. */ .find(variable => variable.name === node.arguments[0].params[1].name) // Get the references to that variable. .references // Only check the references that read the parameter's value. .filter(ref => ref.isRead()) // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`. .filter(ref => ref.identifier.parent.type === "CallExpression" && ref.identifier === ref.identifier.parent.callee) // Check the argument of the function call to determine whether it's an Error. .forEach(ref => checkRejectCall(ref.identifier.parent)); } } }; } };
"use strict"; const emojiRegExp = require("emoji-regex")(); function findEmoji(text) { const result = []; let match; while ((match = emojiRegExp.exec(text))) { result.push({ start: match.index, end: match.index + match[0].length, emoji: match[0], }); } return result; } export default findEmoji;
;(function (window) { var angular = window.angular; /** TEMPLATE /template/treasure-overlay-spinner/treasure-overlay-spinner.html * <div class="treasure-overlay-spinner-content"> * <div class="treasure-overlay-spinner-container"> * <div class="treasure-overlay-spinner"></div> * </div> * <ng-transclude></ng-transclude> * </div> */ // constants var TEMPLATE_PATH = '/template/treasure-overlay-spinner/treasure-overlay-spinner.html'; var TEMPLATE = ''; TEMPLATE += '<div class="treasure-overlay-spinner-content">'; TEMPLATE += '<div class="treasure-overlay-spinner-container">'; TEMPLATE += '<div class="treasure-overlay-spinner"></div>'; TEMPLATE += '</div>'; TEMPLATE += '<ng-transclude></ng-transclude>'; TEMPLATE += '</div>'; // module angular.module('treasure-overlay-spinner', ['ngAnimate']); // directive angular.module('treasure-overlay-spinner').directive('treasureOverlaySpinner', overlaySpinner); overlaySpinner.$inject = ['$animate']; function overlaySpinner ($animate) { return { templateUrl: TEMPLATE_PATH, scope: {active: '='}, transclude: true, restrict: 'E', link: link }; function link (scope, iElement) { scope.$watch('active', statusWatcher); function statusWatcher (active) { $animate[active ? 'addClass' : 'removeClass'](iElement, 'treasure-overlay-spinner-active'); } } } // template angular.module('treasure-overlay-spinner').run(overlaySpinnerTemplate); overlaySpinnerTemplate.$inject = ['$templateCache']; function overlaySpinnerTemplate ($templateCache) { $templateCache.put(TEMPLATE_PATH, TEMPLATE); } }.call(this, window));
'use strict'; define([ 'underscore', 'backbone' ], function(_, Backbone) { var ResumeModel = Backbone.Model.extend({ defaults: {} }); return ResumeModel; });
/** * Module dependencies. */ var express = require('express'), app = module.exports = express(); /** * App configuration. */ app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.favicon()); app.use(app.router); //app.use('/assets', express.static(__dirname + '/src/shared/assets')); app.use('/vendor', express.static(__dirname + '/vendor')); app.use('/assets/demo', express.static(__dirname + '/views/assets')); app.use('/static', express.static(__dirname + '/views/static')); app.use('/test', express.static(__dirname + '/tests')); app.use('/libs', express.static(__dirname + '/libs')); /** * Render HTML files */ app.set('views', __dirname + '/views'); app.set('view options', {'layout': false}); app.engine('html', require('ejs').renderFile); /** * Routes */ require('./routes'); /** * Listen */ app.listen(3040); console.log('Express app started on port 3040');
const blockedResources = [ "google-analytics.com", "api.mixpanel.com", "fonts.googleapis.com", "stats.g.doubleclick.net", "mc.yandex.ru", "use.typekit.net", "beacon.tapfiliate.com", "js-agent.newrelic.com", "api.segment.io", "woopra.com", "static.olark.com", "static.getclicky.com", "fast.fonts.com", "youtube.com/embed", "cdn.heapanalytics.com", "googleads.g.doubleclick.net", "pagead2.googlesyndication.com", "fullstory.com/rec", "navilytics.com/nls_ajax.php", "log.optimizely.com/event", "hn.inspectlet.com", "tpc.googlesyndication.com", "partner.googleadservices.com", ".ttf", ".eot", ".otf", ".woff", ".png", ".gif", ".tiff", ".pdf", ".jpg", ".jpeg", ".ico", ".svg" ]; module.exports = { tabCreated: (req, res, next) => { req.prerender.tab.Network.setRequestInterception({ patterns: [{urlPattern: '*'}] }).then(() => { next(); }); req.prerender.tab.Network.requestIntercepted(({interceptionId, request}) => { let shouldBlock = false; blockedResources.forEach((substring) => { if (request.url.indexOf(substring) >= 0) { shouldBlock = true; } }); let interceptOptions = {interceptionId}; if (shouldBlock) { interceptOptions.errorReason = 'Aborted'; } req.prerender.tab.Network.continueInterceptedRequest(interceptOptions); }); } };
/** * @fileoverview Test file for default-param-last * @author Chiawen Chen */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/default-param-last"); const { RuleTester } = require("../../../lib/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const SHOULD_BE_LAST = "shouldBeLast"; const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 8 } }); const cannedError = { messageId: SHOULD_BE_LAST, type: "AssignmentPattern" }; ruleTester.run("default-param-last", rule, { valid: [ "function f() {}", "function f(a) {}", "function f(a = 5) {}", "function f(a, b) {}", "function f(a, b = 5) {}", "function f(a, b = 5, c = 5) {}", "function f(a, b = 5, ...c) {}", "const f = () => {}", "const f = (a) => {}", "const f = (a = 5) => {}", "const f = function f() {}", "const f = function f(a) {}", "const f = function f(a = 5) {}" ], invalid: [ { code: "function f(a = 5, b) {}", errors: [ { messageId: SHOULD_BE_LAST, column: 12, endColumn: 17 } ] }, { code: "function f(a = 5, b = 6, c) {}", errors: [ { messageId: SHOULD_BE_LAST, column: 12, endColumn: 17 }, { messageId: SHOULD_BE_LAST, column: 19, endColumn: 24 } ] }, { code: "function f (a = 5, b, c = 6, d) {}", errors: [cannedError, cannedError] }, { code: "function f(a = 5, b, c = 5) {}", errors: [ { messageId: SHOULD_BE_LAST, column: 12, endColumn: 17 } ] }, { code: "const f = (a = 5, b, ...c) => {}", errors: [cannedError] }, { code: "const f = function f (a, b = 5, c) {}", errors: [cannedError] }, { code: "const f = (a = 5, { b }) => {}", errors: [cannedError] }, { code: "const f = ({ a } = {}, b) => {}", errors: [cannedError] }, { code: "const f = ({ a, b } = { a: 1, b: 2 }, c) => {}", errors: [cannedError] }, { code: "const f = ([a] = [], b) => {}", errors: [cannedError] }, { code: "const f = ([a, b] = [1, 2], c) => {}", errors: [cannedError] } ] });
let flexSpec = require('./flex-spec') let Declaration = require('../declaration') class FlexDirection extends Declaration { /** * Return property name by final spec */ normalize () { return 'flex-direction' } /** * Use two properties for 2009 spec */ insert (decl, prefix, prefixes) { let spec ;[spec, prefix] = flexSpec(prefix) if (spec !== 2009) { return super.insert(decl, prefix, prefixes) } let already = decl.parent.some( i => i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction' ) if (already) { return undefined } let v = decl.value let orient, dir if (v === 'inherit' || v === 'initial' || v === 'unset') { orient = v dir = v } else { orient = v.includes('row') ? 'horizontal' : 'vertical' dir = v.includes('reverse') ? 'reverse' : 'normal' } let cloned = this.clone(decl) cloned.prop = prefix + 'box-orient' cloned.value = orient if (this.needCascade(decl)) { cloned.raws.before = this.calcBefore(prefixes, decl, prefix) } decl.parent.insertBefore(decl, cloned) cloned = this.clone(decl) cloned.prop = prefix + 'box-direction' cloned.value = dir if (this.needCascade(decl)) { cloned.raws.before = this.calcBefore(prefixes, decl, prefix) } return decl.parent.insertBefore(decl, cloned) } /** * Clean two properties for 2009 spec */ old (prop, prefix) { let spec ;[spec, prefix] = flexSpec(prefix) if (spec === 2009) { return [prefix + 'box-orient', prefix + 'box-direction'] } else { return super.old(prop, prefix) } } } FlexDirection.names = ['flex-direction', 'box-direction', 'box-orient'] module.exports = FlexDirection
/** * Copyright (c) 2013 Petka Antonov * * 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:</p> * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ "use strict"; module.exports = function(Promise) { var THIS = {}; var util = require("./util.js"); var es5 = require("./es5.js"); var errors = require("./errors.js"); var nodebackForResolver = require("./promise_resolver.js") ._nodebackForResolver; var RejectionError = errors.RejectionError; var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var notEnumerableProp = util.notEnumerableProp; var deprecated = util.deprecated; var ASSERT = require("./assert.js"); var roriginal = new RegExp("__beforePromisified__" + "$"); var hasProp = {}.hasOwnProperty; function isPromisified(fn) { return fn.__isPromisified__ === true; } var inheritedMethods = (function() { if (es5.isES5) { var create = Object.create; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; return function(cur) { var original = cur; var ret = []; var visitedKeys = create(null); while (cur !== null) { var keys = es5.keys(cur); for (var i = 0, len = keys.length; i < len; ++i) { var key = keys[i]; if (visitedKeys[key] || roriginal.test(key) || hasProp.call(original, key + "__beforePromisified__") ) { continue; } visitedKeys[key] = true; var desc = getOwnPropertyDescriptor(cur, key); if (desc != null && typeof desc.value === "function" && !isPromisified(desc.value)) { ret.push(key, desc.value); } } cur = es5.getPrototypeOf(cur); } return ret; }; } else { return function(obj) { var ret = []; /*jshint forin:false */ for (var key in obj) { if (roriginal.test(key) || hasProp.call(obj, key + "__beforePromisified__")) { continue; } var fn = obj[key]; if (typeof fn === "function" && !isPromisified(fn)) { ret.push(key, fn); } } return ret; }; } })(); Promise.prototype.error = function Promise$_error(fn) { return this.caught(RejectionError, fn); }; function makeNodePromisifiedEval(callback, receiver, originalName) { function getCall(count) { var args = new Array(count); for (var i = 0, len = args.length; i < len; ++i) { args[i] = "a" + (i+1); } var comma = count > 0 ? "," : ""; if (typeof callback === "string" && receiver === THIS) { return "this['" + callback + "']("+args.join(",") + comma +" fn);"+ "break;"; } return (receiver === void 0 ? "callback("+args.join(",")+ comma +" fn);" : "callback.call("+(receiver === THIS ? "this" : "receiver")+", "+args.join(",") + comma + " fn);") + "break;"; } function getArgs() { return "var args = new Array(len + 1);" + "var i = 0;" + "for (var i = 0; i < len; ++i) { " + " args[i] = arguments[i];" + "}" + "args[i] = fn;"; } var callbackName = (typeof originalName === "string" ? originalName + "Async" : "promisified"); return new Function("Promise", "callback", "receiver", "withAppended", "maybeWrapAsError", "nodebackForResolver", "var ret = function " + callbackName + "(a1, a2, a3, a4, a5) {\"use strict\";" + "var len = arguments.length;" + "var resolver = Promise.pending(" + callbackName + ");" + "var fn = nodebackForResolver(resolver);"+ "try{" + "switch(len) {" + "case 1:" + getCall(1) + "case 2:" + getCall(2) + "case 3:" + getCall(3) + "case 0:" + getCall(0) + "case 4:" + getCall(4) + "case 5:" + getCall(5) + "default: " + getArgs() + (typeof callback === "string" ? "this['" + callback + "'].apply(" : "callback.apply(" ) + (receiver === THIS ? "this" : "receiver") + ", args); break;" + "}" + "}" + "catch(e){ " + "" + "resolver.reject(maybeWrapAsError(e));" + "}" + "return resolver.promise;" + "" + "}; ret.__isPromisified__ = true; return ret;" )(Promise, callback, receiver, withAppended, maybeWrapAsError, nodebackForResolver); } function makeNodePromisifiedClosure(callback, receiver) { function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; if (typeof callback === "string") { callback = _receiver[callback]; } var resolver = Promise.pending(promisified); var fn = nodebackForResolver(resolver); try { callback.apply(_receiver, withAppended(arguments, fn)); } catch(e) { resolver.reject(maybeWrapAsError(e)); } return resolver.promise; } promisified.__isPromisified__ = true; return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function f(){} function _promisify(callback, receiver, isAll) { if (isAll) { var methods = inheritedMethods(callback); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var originalKey = key + "__beforePromisified__"; var promisifiedKey = key + "Async"; notEnumerableProp(callback, originalKey, fn); callback[promisifiedKey] = makeNodePromisified(originalKey, THIS, key); } if (methods.length > 16) f.prototype = callback; return callback; } else { return makeNodePromisified(callback, receiver, void 0); } } Promise.promisify = function Promise$Promisify(callback, receiver) { if (typeof callback === "object" && callback !== null) { deprecated("Promise.promisify for promisifying entire objects " + "is deprecated. Use Promise.promisifyAll instead."); return _promisify(callback, receiver, true); } if (typeof callback !== "function") { throw new TypeError("callback must be a function"); } if (isPromisified(callback)) { return callback; } return _promisify( callback, arguments.length < 2 ? THIS : receiver, false); }; Promise.promisifyAll = function Promise$PromisifyAll(target) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("Cannot promisify " + typeof target); } return _promisify(target, void 0, true); }; };
/* * 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'; /** * @class * Initializes a new instance of the JobProperties class. * @constructor * The common Data Lake Analytics job properties. * * @member {string} [runtimeVersion] the runtime version of the Data Lake * Analytics engine to use for the specific type of job being run. * * @member {string} script the script to run * * @member {string} type Polymorhpic Discriminator * */ function JobProperties() { } /** * Defines the metadata of JobProperties * * @returns {object} metadata of JobProperties * */ JobProperties.prototype.mapper = function () { return { required: false, serializedName: 'JobProperties', type: { name: 'Composite', polymorphicDiscriminator: 'type', uberParent: 'JobProperties', className: 'JobProperties', modelProperties: { runtimeVersion: { required: false, serializedName: 'runtimeVersion', type: { name: 'String' } }, script: { required: true, serializedName: 'script', type: { name: 'String' } }, type: { required: true, serializedName: 'type', type: { name: 'String' } } } } }; }; module.exports = JobProperties;
/* */ "format global"; //! moment.js locale configuration //! locale : hungarian (hu) //! author : Adam Brunner : https://github.com/adambrunner (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(["../moment"], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } var hu = moment.defineLocale('hu', { months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), weekdays : 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), weekdaysShort : 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), weekdaysMin : 'v_h_k_sze_cs_p_szo'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'LT:ss', L : 'YYYY.MM.DD.', LL : 'YYYY. MMMM D.', LLL : 'YYYY. MMMM D., LT', LLLL : 'YYYY. MMMM D., dddd LT' }, meridiemParse: /de|du/i, isPM: function (input) { return input.charAt(1).toLowerCase() === 'u'; }, meridiem : function (hours, minutes, isLower) { if (hours < 12) { return isLower === true ? 'de' : 'DE'; } else { return isLower === true ? 'du' : 'DU'; } }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : '%s múlva', past : '%s', s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); return hu; }));
MaxMover = Mover.clone().newSlots({ protoType: "MaxMover", rd: null, zd: null, speed: 2 }).setSlots({ init: function() { Mover.init.apply(this) /* var dt = .002 this._rd = new THREE.Vector3(0, dt*this._speed, dt*this._speed) this._zd = 1 this._nextShift = 3*60 */ this.setRate(1) }, setRate: function(r) { this._rate = r var dt = .002 this._rd = new THREE.Vector3(0, dt*r*this._speed, dt*r*this._speed) this._zd = 1*r this._nextShift = 3*60/r }, object: function() { return this._thing._object }, update: function(dt) { //this.setRate(dt) Mover.update.apply(this) var obj = this.object() obj.rotation.add(this._rd) obj.position.z += this._zd if (this._t > this._nextShift || Math.abs(obj.rotation.y) > .45) { if (1 < .5) { this._rd.z = - this._rd.z } { this._rd.y = - this._rd.y } this._zd = - this._zd //this._nextShift = this._t + (3 + Math.random()*3)*60 //*100000 this._nextShift = this._t + (3 +10*3)*60 //*100000 } var zmax = 600 if (obj.position.z > zmax/2) { obj.position.z = zmax/2 } if (obj.position.z < -zmax) { obj.position.z = -zmax } //this._t ++ } })
describe('Preprocessor', function () { var H = envision, Preprocessor = H.Preprocessor; it('defines preprocessor', function () { expect(H.Preprocessor).toBeDefined(); }); it('creates a preprocessor', function () { expect(new H.Preprocessor()).toBeDefined(); }); it('gets private data from options', function () { var data = [[],[]], options = { data : data }, preprocessor = new H.Preprocessor(options); expect(preprocessor.getData()).toBe(data); }); it('sets new private data', function () { var data = [[],[]], options = { data : [[], []] }, preprocessor = new H.Preprocessor(options); expect(preprocessor.getData()).not.toBe(data); preprocessor.setData(data); expect(preprocessor.getData()).toBe(data); }); it('calculates length', function () { var preprocessor = new Preprocessor({data : [[], []]}); expect(preprocessor.length()).toBe(0); preprocessor.setData([[0], [1]]); expect(preprocessor.length()).toBe(1); }); describe('Validation', function () { var preprocessor; beforeEach(function () { preprocessor = new H.Preprocessor(); }); afterEach(function () { preprocessor = null; }); it('expects array data', function () { expect(function () { preprocessor.setData({}); }) .toThrow(new Error("Array expected.")); }); it('expects at least two dimensions', function () { var e = new Error('Data must contain at least two dimensions.'); expect(function () { preprocessor.setData([]); }).toThrow(e); expect(function () { preprocessor.setData([[]]); }).toThrow(e); }); it('expects each dimension to be an array', function () { expect(function () { preprocessor.setData([[], {}]); }) .toThrow(new Error('Data dimensions must be arrays.')); }); it('expects each dimension to have the same number of points', function () { expect(function () { preprocessor.setData([[], [1]]); }) .toThrow(new Error('Data dimensions must contain the same number of points.')); }); it('validates options data', function () { var options = { data : {} }; expect(function () { new H.Preprocessor(options); }) .toThrow(new Error("Array expected.")); }); }); describe('Bounds', function () { var preprocessor; beforeEach(function () { var x = [], y = [], data = [x, y], i; for (i = 0; i < 10; i++) { x.push(i); y.push(10 - 1 - i); } this.data = data; preprocessor = new Preprocessor({ data : data }); }); afterEach(function () { preprocessor = null; }); it('bounds data', function () { preprocessor.bound(4, 6); expect(preprocessor.length()).toBe(3); expect(preprocessor.getData()).toEqual([ [4, 5, 6], [5, 4, 3] ]); }); it('resets data', function () { var data = preprocessor.getData(), bounded = preprocessor.bound(4, 6).getData(); preprocessor.reset(); expect(bounded).not.toBe(data); expect(preprocessor.getData()).toBe(data); }); it('makes empty data for bounds out of range', function () { preprocessor.bound(10, 12); expect(preprocessor.length()).toBe(0); expect(preprocessor.getData()).toEqual([[],[]]); }); it('bounds from the beginning', function () { preprocessor.bound(0, 2); expect(preprocessor.length()).toBe(3); expect(preprocessor.getData()).toEqual([ [0, 1, 2], [9, 8, 7] ]); }); it('includes points outside the range if match not exact', function () { preprocessor.bound(3.5, 6.5); expect(preprocessor.length()).toBe(5); expect(preprocessor.getData()).toEqual([ [3, 4, 5, 6, 7], [6, 5, 4, 3, 2] ]); }); it('skips bounding when boundary null / undefined', function () { preprocessor.bound(null, undefined); expect(preprocessor.length()).toBe(10); expect(preprocessor.getData()).toBe(this.data); }); }); describe('Subsample', function () { var length = 10, data, preprocessor; beforeEach(function () { var x = [], y = [], i; for (i = 0; i < length; i++) { x.push(i); y.push(10 - 1 - i); } data = [x, y]; preprocessor = new Preprocessor({ data : data }); }); afterEach(function () { preprocessor = null; }); it('subsamples data', function () { preprocessor.subsample(5); expect(preprocessor.length()).toBe(5); expect(preprocessor.getData()).toEqual([ [0, 2, 4, 6, 9], [9, 7, 5, 3, 0] ]); }); it('always includes endpoints', function () { var i, newData, newLength; for (i = 0; i < 10; i++) { preprocessor.setData(data); preprocessor.subsample(i); newData = preprocessor.getData(); newLength = preprocessor.length(); expect(newLength).toBeGreaterThan(1); expect(newData[0][0]).toBe(data[0][0]); expect(newData[1][0]).toBe(data[1][0]); expect(newData[0][newLength - 1]).toBe(data[0][length - 1]); expect(newData[1][newLength - 1]).toBe(data[1][length - 1]); } }); it('length equals resolution when resolution 2 or greather', function () { var i; for (i = 2; i < length ; i++) { preprocessor.setData(data); preprocessor.subsample(i); expect(preprocessor.length()).toBe(i); } }); it('does not subsample data not longer than resolution', function () { preprocessor.subsample(length); expect(preprocessor.length()).toBe(length); expect(preprocessor.getData()).toBe(data); }); }); describe('MinMaxSubsample', function () { var length = 100, data, preprocessor; beforeEach(function () { var x = [], y = [], i; for (i = 0; i < length; i++) { x.push(i); y.push(Math.sin(i/10)); } data = [x, y]; preprocessor = new Preprocessor({ data : data }); }); afterEach(function () { preprocessor = null; }); it('subsamples data', function () { preprocessor.subsampleMinMax(10); var data = preprocessor.getData(), x = data[0], y = data[1]; expect(Math.min.apply(Math, data[1])).toEqual(Math.min.apply(Math, y)); expect(Math.max.apply(Math, data[1])).toEqual(Math.max.apply(Math, y)); }); }); describe('Subsample Bounding', function () { var length = 10, strategies = ['subsample', 'subsampleMinMax']; beforeEach(function () { var x = [], y = [], data = [x, y], i; for (i = 0; i < length; i++) { x.push(i); y.push(10 - 1 - i); } this.data = data; this.preprocessor = new Preprocessor({ data : data }); }); it('subsamples and bounds', function () { // TODO implement strategies var preprocessor = this.preprocessor; preprocessor .bound(0, 7) .subsample(4); expect(preprocessor.length()).toBe(4); expect(preprocessor.getData()).toEqual([ [0, 2, 4, 7], [9, 7, 5, 2] ]); }); _.each(strategies, function (strategy) { it('skips ' + strategy + ' but bounds when res > bounded count', function () { var preprocessor = this.preprocessor; preprocessor .bound(0, 7) [strategy](9); // > 8 (bound length), < length expect(preprocessor.length()).toBe(8); expect(preprocessor.getData()).toEqual([ [0, 1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3, 2] ]); }); it('skips bounding ' + strategy + ' when subsampling but not bounding', function () { var preprocessor = this.preprocessor; preprocessor[strategy](10); expect(preprocessor.length()).toBe(10); expect(preprocessor.getData()).toBe(this.data); }); }, this); }); describe('Chaining', function () { var preprocessor; beforeEach(function () { preprocessor = new Preprocessor({ data : [[],[]] }); }); it('chains setData', function () { expect(preprocessor.setData([[],[]])).toBe(preprocessor); }); it('chains reset', function () { expect(preprocessor.reset()).toBe(preprocessor); }); it('chains bound', function () { expect(preprocessor.bound(0, 1)).toBe(preprocessor); }); it('chains subsample', function () { expect(preprocessor.subsample(10)).toBe(preprocessor); }); it('chains subsampleMinMax', function () { expect(preprocessor.subsampleMinMax(0, 1)).toBe(preprocessor); }); }); });
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* Tabulator v4.2.6 (c) Oliver Folkerd */ var Clipboard = function Clipboard(table) { this.table = table; this.mode = true; this.copySelector = false; this.copySelectorParams = {}; this.copyFormatter = false; this.copyFormatterParams = {}; this.pasteParser = function () {}; this.pasteAction = function () {}; this.htmlElement = false; this.config = {}; this.blocked = true; //block copy actions not originating from this command }; Clipboard.prototype.initialize = function () { var self = this; this.mode = this.table.options.clipboard; if (this.mode === true || this.mode === "copy") { this.table.element.addEventListener("copy", function (e) { var data; self.processConfig(); if (!self.blocked) { e.preventDefault(); data = self.generateContent(); if (window.clipboardData && window.clipboardData.setData) { window.clipboardData.setData('Text', data); } else if (e.clipboardData && e.clipboardData.setData) { e.clipboardData.setData('text/plain', data); if (self.htmlElement) { e.clipboardData.setData('text/html', self.htmlElement.outerHTML); } } else if (e.originalEvent && e.originalEvent.clipboardData.setData) { e.originalEvent.clipboardData.setData('text/plain', data); if (self.htmlElement) { e.originalEvent.clipboardData.setData('text/html', self.htmlElement.outerHTML); } } self.table.options.clipboardCopied.call(this.table, data); self.reset(); } }); } if (this.mode === true || this.mode === "paste") { this.table.element.addEventListener("paste", function (e) { self.paste(e); }); } this.setPasteParser(this.table.options.clipboardPasteParser); this.setPasteAction(this.table.options.clipboardPasteAction); }; Clipboard.prototype.processConfig = function () { var config = { columnHeaders: "groups", rowGroups: true, columnCalcs: true }; if (typeof this.table.options.clipboardCopyHeader !== "undefined") { config.columnHeaders = this.table.options.clipboardCopyHeader; console.warn("DEPRECATION WANRING - clipboardCopyHeader option has been depricated, please use the columnHeaders property on the clipboardCopyConfig option"); } if (this.table.options.clipboardCopyConfig) { for (var key in this.table.options.clipboardCopyConfig) { config[key] = this.table.options.clipboardCopyConfig[key]; } } if (config.rowGroups && this.table.options.groupBy && this.table.modExists("groupRows")) { this.config.rowGroups = true; } if (config.columnHeaders) { if ((config.columnHeaders === "groups" || config === true) && this.table.columnManager.columns.length != this.table.columnManager.columnsByIndex.length) { this.config.columnHeaders = "groups"; } else { this.config.columnHeaders = "columns"; } } else { this.config.columnHeaders = false; } if (config.columnCalcs && this.table.modExists("columnCalcs")) { this.config.columnCalcs = true; } }; Clipboard.prototype.reset = function () { this.blocked = false; this.originalSelectionText = ""; }; Clipboard.prototype.setPasteAction = function (action) { switch (typeof action === "undefined" ? "undefined" : _typeof(action)) { case "string": this.pasteAction = this.pasteActions[action]; if (!this.pasteAction) { console.warn("Clipboard Error - No such paste action found:", action); } break; case "function": this.pasteAction = action; break; } }; Clipboard.prototype.setPasteParser = function (parser) { switch (typeof parser === "undefined" ? "undefined" : _typeof(parser)) { case "string": this.pasteParser = this.pasteParsers[parser]; if (!this.pasteParser) { console.warn("Clipboard Error - No such paste parser found:", parser); } break; case "function": this.pasteParser = parser; break; } }; Clipboard.prototype.paste = function (e) { var data, rowData, rows; if (this.checkPaseOrigin(e)) { data = this.getPasteData(e); rowData = this.pasteParser.call(this, data); if (rowData) { e.preventDefault(); if (this.table.modExists("mutator")) { rowData = this.mutateData(rowData); } rows = this.pasteAction.call(this, rowData); this.table.options.clipboardPasted.call(this.table, data, rowData, rows); } else { this.table.options.clipboardPasteError.call(this.table, data); } } }; Clipboard.prototype.mutateData = function (data) { var self = this, output = []; if (Array.isArray(data)) { data.forEach(function (row) { output.push(self.table.modules.mutator.transformRow(row, "clipboard")); }); } else { output = data; } return output; }; Clipboard.prototype.checkPaseOrigin = function (e) { var valid = true; if (e.target.tagName != "DIV" || this.table.modules.edit.currentCell) { valid = false; } return valid; }; Clipboard.prototype.getPasteData = function (e) { var data; if (window.clipboardData && window.clipboardData.getData) { data = window.clipboardData.getData('Text'); } else if (e.clipboardData && e.clipboardData.getData) { data = e.clipboardData.getData('text/plain'); } else if (e.originalEvent && e.originalEvent.clipboardData.getData) { data = e.originalEvent.clipboardData.getData('text/plain'); } return data; }; Clipboard.prototype.copy = function (selector, selectorParams, formatter, formatterParams, internal) { var range, sel; this.blocked = false; if (this.mode === true || this.mode === "copy") { if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { range = document.createRange(); range.selectNodeContents(this.table.element); sel = window.getSelection(); if (sel.toString() && internal) { selector = "userSelection"; formatter = "raw"; selectorParams = sel.toString(); } sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") { textRange = document.body.createTextRange(); textRange.moveToElementText(this.table.element); textRange.select(); } this.setSelector(selector); this.copySelectorParams = typeof selectorParams != "undefined" && selectorParams != null ? selectorParams : this.config.columnHeaders; this.setFormatter(formatter); this.copyFormatterParams = typeof formatterParams != "undefined" && formatterParams != null ? formatterParams : {}; document.execCommand('copy'); if (sel) { sel.removeAllRanges(); } } }; Clipboard.prototype.setSelector = function (selector) { selector = selector || this.table.options.clipboardCopySelector; switch (typeof selector === "undefined" ? "undefined" : _typeof(selector)) { case "string": if (this.copySelectors[selector]) { this.copySelector = this.copySelectors[selector]; } else { console.warn("Clipboard Error - No such selector found:", selector); } break; case "function": this.copySelector = selector; break; } }; Clipboard.prototype.setFormatter = function (formatter) { formatter = formatter || this.table.options.clipboardCopyFormatter; switch (typeof formatter === "undefined" ? "undefined" : _typeof(formatter)) { case "string": if (this.copyFormatters[formatter]) { this.copyFormatter = this.copyFormatters[formatter]; } else { console.warn("Clipboard Error - No such formatter found:", formatter); } break; case "function": this.copyFormatter = formatter; break; } }; Clipboard.prototype.generateContent = function () { var data; this.htmlElement = false; data = this.copySelector.call(this, this.config, this.copySelectorParams); return this.copyFormatter.call(this, data, this.config, this.copyFormatterParams); }; Clipboard.prototype.generateSimpleHeaders = function (columns) { var headers = []; columns.forEach(function (column) { headers.push(column.definition.title); }); return headers; }; Clipboard.prototype.generateColumnGroupHeaders = function (columns) { var _this = this; var output = []; this.table.columnManager.columns.forEach(function (column) { var colData = _this.processColumnGroup(column); if (colData) { output.push(colData); } }); return output; }; Clipboard.prototype.processColumnGroup = function (column) { var _this2 = this; var subGroups = column.columns; var groupData = { type: "group", title: column.definition.title, column: column }; if (subGroups.length) { groupData.subGroups = []; groupData.width = 0; subGroups.forEach(function (subGroup) { var subGroupData = _this2.processColumnGroup(subGroup); if (subGroupData) { groupData.width += subGroupData.width; groupData.subGroups.push(subGroupData); } }); if (!groupData.width) { return false; } } else { if (column.field && column.visible) { groupData.width = 1; } else { return false; } } return groupData; }; Clipboard.prototype.groupHeadersToRows = function (columns) { var headers = []; function parseColumnGroup(column, level) { if (typeof headers[level] === "undefined") { headers[level] = []; } headers[level].push(column.title); if (column.subGroups) { column.subGroups.forEach(function (subGroup) { parseColumnGroup(subGroup, level + 1); }); } else { padColumnheaders(); } } function padColumnheaders() { var max = 0; headers.forEach(function (title) { var len = title.length; if (len > max) { max = len; } }); headers.forEach(function (title) { var len = title.length; if (len < max) { for (var i = len; i < max; i++) { title.push(""); } } }); } columns.forEach(function (column) { parseColumnGroup(column, 0); }); return headers; }; Clipboard.prototype.rowsToData = function (rows, config, params) { var columns = this.table.columnManager.columnsByIndex, data = []; rows.forEach(function (row) { var rowArray = [], rowData = row instanceof RowComponent ? row.getData("clipboard") : row; columns.forEach(function (column) { var value = column.getFieldValue(rowData); switch (typeof value === "undefined" ? "undefined" : _typeof(value)) { case "object": value = JSON.stringify(value); break; case "undefined": case "null": value = ""; break; default: value = value; } rowArray.push(value); }); data.push(rowArray); }); return data; }; Clipboard.prototype.buildComplexRows = function (config) { var _this3 = this; var output = [], groups = this.table.modules.groupRows.getGroups(); groups.forEach(function (group) { output.push(_this3.processGroupData(group)); }); return output; }; Clipboard.prototype.processGroupData = function (group) { var _this4 = this; var subGroups = group.getSubGroups(); var groupData = { type: "group", key: group.key }; if (subGroups.length) { groupData.subGroups = []; subGroups.forEach(function (subGroup) { groupData.subGroups.push(_this4.processGroupData(subGroup)); }); } else { groupData.rows = group.getRows(true); } return groupData; }; Clipboard.prototype.getCalcRow = function (calcs, selector, pos) { var calcData = calcs[selector]; if (calcData) { if (pos) { calcData = calcData[pos]; } if (Object.keys(calcData).length) { return this.rowsToData([calcData]); } } return []; }; Clipboard.prototype.buildOutput = function (rows, config, params) { var _this5 = this; var output = [], calcs, columns = this.table.columnManager.columnsByIndex; if (config.columnHeaders) { if (config.columnHeaders == "groups") { columns = this.generateColumnGroupHeaders(this.table.columnManager.columns); output = output.concat(this.groupHeadersToRows(columns)); } else { output.push(this.generateSimpleHeaders(columns)); } } if (this.config.columnCalcs) { calcs = this.table.getCalcResults(); } //generate styled content if (this.table.options.clipboardCopyStyled) { this.generateHTML(rows, columns, calcs, config, params); } //generate unstyled content if (config.rowGroups) { rows.forEach(function (row) { output = output.concat(_this5.parseRowGroupData(row, config, params, calcs || {})); }); } else { if (config.columnCalcs) { output = output.concat(this.getCalcRow(calcs, "top")); } output = output.concat(this.rowsToData(rows, config, params)); if (config.columnCalcs) { output = output.concat(this.getCalcRow(calcs, "bottom")); } } return output; }; Clipboard.prototype.parseRowGroupData = function (group, config, params, calcObj) { var _this6 = this; var groupData = []; groupData.push([group.key]); if (group.subGroups) { group.subGroups.forEach(function (subGroup) { groupData = groupData.concat(_this6.parseRowGroupData(subGroup, config, params, calcObj[group.key] ? calcObj[group.key].groups || {} : {})); }); } else { if (config.columnCalcs) { groupData = groupData.concat(this.getCalcRow(calcObj, group.key, "top")); } groupData = groupData.concat(this.rowsToData(group.rows, config, params)); if (config.columnCalcs) { groupData = groupData.concat(this.getCalcRow(calcObj, group.key, "bottom")); } } return groupData; }; Clipboard.prototype.generateHTML = function (rows, columns, calcs, config, params) { var self = this, data = [], headers = [], body, oddRow, evenRow, calcRow, firstRow, firstCell, firstGroup, lastCell, styleCells; //create table element this.htmlElement = document.createElement("table"); self.mapElementStyles(this.table.element, this.htmlElement, ["border-top", "border-left", "border-right", "border-bottom"]); function generateSimpleHeaders() { var headerEl = document.createElement("tr"); columns.forEach(function (column) { var columnEl = document.createElement("th"); columnEl.innerHTML = column.definition.title; self.mapElementStyles(column.getElement(), columnEl, ["border-top", "border-left", "border-right", "border-bottom", "background-color", "color", "font-weight", "font-family", "font-size"]); headerEl.appendChild(columnEl); }); self.mapElementStyles(self.table.columnManager.getHeadersElement(), headerEl, ["border-top", "border-left", "border-right", "border-bottom", "background-color", "color", "font-weight", "font-family", "font-size"]); self.htmlElement.appendChild(document.createElement("thead").appendChild(headerEl)); } function generateHeaders(headers) { var headerHolderEl = document.createElement("thead"); headers.forEach(function (columns) { var headerEl = document.createElement("tr"); columns.forEach(function (column) { var columnEl = document.createElement("th"); if (column.width > 1) { columnEl.colSpan = column.width; } if (column.height > 1) { columnEl.rowSpan = column.height; } columnEl.innerHTML = column.title; self.mapElementStyles(column.element, columnEl, ["border-top", "border-left", "border-right", "border-bottom", "background-color", "color", "font-weight", "font-family", "font-size"]); headerEl.appendChild(columnEl); }); self.mapElementStyles(self.table.columnManager.getHeadersElement(), headerEl, ["border-top", "border-left", "border-right", "border-bottom", "background-color", "color", "font-weight", "font-family", "font-size"]); headerHolderEl.appendChild(headerEl); }); self.htmlElement.appendChild(headerHolderEl); } function parseColumnGroup(column, level) { if (typeof headers[level] === "undefined") { headers[level] = []; } headers[level].push({ title: column.title, width: column.width, height: 1, children: !!column.subGroups, element: column.column.getElement() }); if (column.subGroups) { column.subGroups.forEach(function (subGroup) { parseColumnGroup(subGroup, level + 1); }); } } function padVerticalColumnheaders() { headers.forEach(function (row, index) { row.forEach(function (header) { if (!header.children) { header.height = headers.length - index; } }); }); } function addCalcRow(calcs, selector, pos) { var calcData = calcs[selector]; if (calcData) { if (pos) { calcData = calcData[pos]; } if (Object.keys(calcData).length) { // calcRowIndexs.push(body.length); processRows([calcData]); } } } //create headers if needed if (config.columnHeaders) { if (config.columnHeaders == "groups") { columns.forEach(function (column) { parseColumnGroup(column, 0); }); padVerticalColumnheaders(); generateHeaders(headers); } else { generateSimpleHeaders(); } } columns = this.table.columnManager.columnsByIndex; //create table body body = document.createElement("tbody"); //lookup row styles if (window.getComputedStyle) { oddRow = this.table.element.querySelector(".tabulator-row-odd:not(.tabulator-group):not(.tabulator-calcs)"); evenRow = this.table.element.querySelector(".tabulator-row-even:not(.tabulator-group):not(.tabulator-calcs)"); calcRow = this.table.element.querySelector(".tabulator-row.tabulator-calcs"); firstRow = this.table.element.querySelector(".tabulator-row:not(.tabulator-group):not(.tabulator-calcs)"); firstGroup = this.table.element.getElementsByClassName("tabulator-group")[0]; if (firstRow) { styleCells = firstRow.getElementsByClassName("tabulator-cell"); firstCell = styleCells[0]; lastCell = styleCells[styleCells.length - 1]; } } function processRows(rowArray) { //add rows to table rowArray.forEach(function (row, i) { var rowEl = document.createElement("tr"), styleRow = firstRow, isCalc = false, rowData; if (row instanceof RowComponent) { rowData = row.getData("clipboard"); } else { rowData = row; isCalc = true; } columns.forEach(function (column, j) { var cellEl = document.createElement("td"), value = column.getFieldValue(rowData); switch (typeof value === "undefined" ? "undefined" : _typeof(value)) { case "object": value = JSON.stringify(value); break; case "undefined": case "null": value = ""; break; default: value = value; } cellEl.innerHTML = value; if (column.definition.align) { cellEl.style.textAlign = column.definition.align; } if (j < columns.length - 1) { if (firstCell) { self.mapElementStyles(firstCell, cellEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size"]); } } else { if (firstCell) { self.mapElementStyles(firstCell, cellEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size"]); } } rowEl.appendChild(cellEl); }); if (isCalc) { styleRow = calcRow; } else { if (!(i % 2) && oddRow) { styleRow = oddRow; } if (i % 2 && evenRow) { styleRow = evenRow; } } if (styleRow) { self.mapElementStyles(styleRow, rowEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]); } body.appendChild(rowEl); }); } function processGroup(group, calcObj) { var groupEl = document.createElement("tr"), groupCellEl = document.createElement("td"); groupCellEl.colSpan = columns.length; groupCellEl.innerHTML = group.key; groupEl.appendChild(groupCellEl); body.appendChild(groupEl); self.mapElementStyles(firstGroup, groupEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]); if (group.subGroups) { group.subGroups.forEach(function (subGroup) { processGroup(subGroup, calcObj[group.key] ? calcObj[group.key].groups || {} : {}); }); } else { if (config.columnCalcs) { addCalcRow(calcObj, group.key, "top"); } processRows(group.rows); if (config.columnCalcs) { addCalcRow(calcObj, group.key, "bottom"); } } } if (config.rowGroups) { rows.forEach(function (group) { processGroup(group, calcs || {}); }); } else { if (config.columnCalcs) { addCalcRow(calcs, "top"); } processRows(rows); if (config.columnCalcs) { addCalcRow(calcs, "bottom"); } } this.htmlElement.appendChild(body); }; Clipboard.prototype.mapElementStyles = function (from, to, props) { var lookup = { "background-color": "backgroundColor", "color": "fontColor", "font-weight": "fontWeight", "font-family": "fontFamily", "font-size": "fontSize", "border-top": "borderTop", "border-left": "borderLeft", "border-right": "borderRight", "border-bottom": "borderBottom" }; if (window.getComputedStyle) { var fromStyle = window.getComputedStyle(from); props.forEach(function (prop) { to.style[lookup[prop]] = fromStyle.getPropertyValue(prop); }); } // return window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(property) : element.style[property.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })]; }; Clipboard.prototype.copySelectors = { userSelection: function userSelection(config, params) { return params; }, selected: function selected(config, params) { var rows = []; if (this.table.modExists("selectRow", true)) { rows = this.table.modules.selectRow.getSelectedRows(); } if (config.rowGroups) { console.warn("Clipboard Warning - select coptSelector does not support row groups"); } return this.buildOutput(rows, config, params); }, table: function table(config, params) { if (config.rowGroups) { console.warn("Clipboard Warning - table coptSelector does not support row groups"); } return this.buildOutput(this.table.rowManager.getComponents(), config, params); }, active: function active(config, params) { var rows; if (config.rowGroups) { rows = this.buildComplexRows(config); } else { rows = this.table.rowManager.getComponents(true); } return this.buildOutput(rows, config, params); } }; Clipboard.prototype.copyFormatters = { raw: function raw(data, params) { return data; }, table: function table(data, params) { var output = []; data.forEach(function (row) { row.forEach(function (value) { if (typeof value == "undefined") { value = ""; } value = typeof value == "undefined" || value === null ? "" : value.toString(); if (value.match(/\r|\n/)) { value = value.split('"').join('""'); value = '"' + value + '"'; } }); output.push(row.join("\t")); }); return output.join("\n"); } }; Clipboard.prototype.pasteParsers = { table: function table(clipboard) { var data = [], success = false, headerFindSuccess = true, columns = this.table.columnManager.columns, columnMap = [], rows = []; //get data from clipboard into array of columns and rows. clipboard = clipboard.split("\n"); clipboard.forEach(function (row) { data.push(row.split("\t")); }); if (data.length && !(data.length === 1 && data[0].length < 2)) { success = true; //check if headers are present by title data[0].forEach(function (value) { var column = columns.find(function (column) { return value && column.definition.title && value.trim() && column.definition.title.trim() === value.trim(); }); if (column) { columnMap.push(column); } else { headerFindSuccess = false; } }); //check if column headers are present by field if (!headerFindSuccess) { headerFindSuccess = true; columnMap = []; data[0].forEach(function (value) { var column = columns.find(function (column) { return value && column.field && value.trim() && column.field.trim() === value.trim(); }); if (column) { columnMap.push(column); } else { headerFindSuccess = false; } }); if (!headerFindSuccess) { columnMap = this.table.columnManager.columnsByIndex; } } //remove header row if found if (headerFindSuccess) { data.shift(); } data.forEach(function (item) { var row = {}; item.forEach(function (value, i) { if (columnMap[i]) { row[columnMap[i].field] = value; } }); rows.push(row); }); return rows; } else { return false; } } }; Clipboard.prototype.pasteActions = { replace: function replace(rows) { return this.table.setData(rows); }, update: function update(rows) { return this.table.updateOrAddData(rows); }, insert: function insert(rows) { return this.table.addData(rows); } }; Tabulator.prototype.registerModule("clipboard", Clipboard);
require('ember-views'); require('ember-routing/location/api'); require('ember-routing/location/none_location'); require('ember-routing/location/hash_location'); require('ember-routing/location/history_location'); require('ember-routing/location/auto_location');
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createMount; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _react = _interopRequireDefault(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); var PropTypes = _interopRequireWildcard(require("prop-types")); var _enzyme = require("enzyme"); /** * Can't just mount <React.Fragment>{node}</React.Fragment> * because that swallows wrapper.setProps * * why class component: * https://github.com/airbnb/enzyme/issues/2043 */ // eslint-disable-next-line react/prefer-stateless-function var Mode = /*#__PURE__*/ function (_React$Component) { (0, _inherits2.default)(Mode, _React$Component); function Mode() { (0, _classCallCheck2.default)(this, Mode); return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Mode).apply(this, arguments)); } (0, _createClass2.default)(Mode, [{ key: "render", value: function render() { // Excess props will come from e.g. enzyme setProps var _this$props = this.props, __element = _this$props.__element, __strict = _this$props.__strict, other = (0, _objectWithoutProperties2.default)(_this$props, ["__element", "__strict"]); var Component = __strict ? _react.default.StrictMode : _react.default.Fragment; return _react.default.createElement(Component, null, _react.default.cloneElement(__element, other)); } }]); return Mode; }(_react.default.Component); // Generate an enhanced mount function. process.env.NODE_ENV !== "production" ? Mode.propTypes = { /** * this is essentially children. However we can't use children because then * using `wrapper.setProps({ children })` would work differently if this component * would be the root. */ __element: PropTypes.element.isRequired, __strict: PropTypes.bool.isRequired } : void 0; function createMount() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$mount = options.mount, mount = _options$mount === void 0 ? _enzyme.mount : _options$mount, globalStrict = options.strict, globalEnzymeOptions = (0, _objectWithoutProperties2.default)(options, ["mount", "strict"]); var attachTo = document.createElement('div'); attachTo.className = 'app'; attachTo.setAttribute('id', 'app'); document.body.insertBefore(attachTo, document.body.firstChild); var mountWithContext = function mountWithContext(node) { var localOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _localOptions$disable = localOptions.disableUnnmount, disableUnnmount = _localOptions$disable === void 0 ? false : _localOptions$disable, _localOptions$strict = localOptions.strict, strict = _localOptions$strict === void 0 ? globalStrict : _localOptions$strict, localEnzymeOptions = (0, _objectWithoutProperties2.default)(localOptions, ["disableUnnmount", "strict"]); if (!disableUnnmount) { _reactDom.default.unmountComponentAtNode(attachTo); } // some tests require that no other components are in the tree // e.g. when doing .instance(), .state() etc. return mount(strict == null ? node : _react.default.createElement(Mode, { __element: node, __strict: Boolean(strict) }), (0, _extends2.default)({ attachTo: attachTo }, globalEnzymeOptions, {}, localEnzymeOptions)); }; mountWithContext.attachTo = attachTo; mountWithContext.cleanUp = function () { _reactDom.default.unmountComponentAtNode(attachTo); attachTo.parentElement.removeChild(attachTo); }; return mountWithContext; }
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import { isFragment } from 'react-is'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { display: 'flex', justifyContent: 'center', height: 56, backgroundColor: theme.palette.background.paper } }); const BottomNavigation = /*#__PURE__*/React.forwardRef(function BottomNavigation(props, ref) { const { children, classes, className, component: Component = 'div', onChange, showLabels = false, value } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "component", "onChange", "showLabels", "value"]); return /*#__PURE__*/React.createElement(Component, _extends({ className: clsx(classes.root, className), ref: ref }, other), React.Children.map(children, (child, childIndex) => { if (! /*#__PURE__*/React.isValidElement(child)) { return null; } if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: The BottomNavigation component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } const childValue = child.props.value === undefined ? childIndex : child.props.value; return /*#__PURE__*/React.cloneElement(child, { selected: childValue === value, showLabel: child.props.showLabel !== undefined ? child.props.showLabel : showLabels, value: childValue, onChange }); })); }); process.env.NODE_ENV !== "production" ? BottomNavigation.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes /* @typescript-to-proptypes-ignore */ .elementType, /** * Callback fired when the value changes. * * @param {object} event The event source of the callback. **Warning**: This is a generic event not a change event. * @param {any} value We default to the index of the child. */ onChange: PropTypes.func, /** * If `true`, all `BottomNavigationAction`s will show their labels. * By default, only the selected `BottomNavigationAction` will show its label. */ showLabels: PropTypes.bool, /** * The value of the currently selected `BottomNavigationAction`. */ value: PropTypes.any } : void 0; export default withStyles(styles, { name: 'MuiBottomNavigation' })(BottomNavigation);
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import { isFragment } from 'react-is'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import experimentalStyled from '../styles/experimentalStyled'; import useThemeProps from '../styles/useThemeProps'; import { duration } from '../styles/createTransitions'; import Zoom from '../Zoom'; import Fab from '../Fab'; import capitalize from '../utils/capitalize'; import isMuiElement from '../utils/isMuiElement'; import useForkRef from '../utils/useForkRef'; import useControlled from '../utils/useControlled'; import speedDialClasses, { getSpeedDialUtilityClass } from './speedDialClasses'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; const useUtilityClasses = styleProps => { const { classes, open, direction } = styleProps; const slots = { root: ['root', `direction${capitalize(direction)}`], fab: ['fab'], actions: ['actions', !open && 'actionsClosed'] }; return composeClasses(slots, getSpeedDialUtilityClass, classes); }; function getOrientation(direction) { if (direction === 'up' || direction === 'down') { return 'vertical'; } if (direction === 'right' || direction === 'left') { return 'horizontal'; } return undefined; } function clamp(value, min, max) { if (value < min) { return min; } if (value > max) { return max; } return value; } const dialRadius = 32; const spacingActions = 16; const SpeedDialRoot = experimentalStyled('div', {}, { name: 'MuiSpeedDial', slot: 'Root', overridesResolver: (props, styles) => { const { styleProps } = props; return _extends({}, styles.root, styles[`direction${capitalize(styleProps.direction)}`]); } })(({ theme, styleProps }) => _extends({ zIndex: theme.zIndex.speedDial, display: 'flex', alignItems: 'center', pointerEvents: 'none' }, styleProps.direction === 'up' && { flexDirection: 'column-reverse', [`& .${speedDialClasses.actions}`]: { flexDirection: 'column-reverse', marginBottom: -dialRadius, paddingBottom: spacingActions + dialRadius } }, styleProps.direction === 'down' && { flexDirection: 'column', [`& .${speedDialClasses.actions}`]: { flexDirection: 'column', marginTop: -dialRadius, paddingTop: spacingActions + dialRadius } }, styleProps.direction === 'left' && { flexDirection: 'row-reverse', [`& .${speedDialClasses.actions}`]: { flexDirection: 'row-reverse', marginRight: -dialRadius, paddingRight: spacingActions + dialRadius } }, styleProps.direction === 'right' && { flexDirection: 'row', [`& .${speedDialClasses.actions}`]: { flexDirection: 'row', marginLeft: -dialRadius, paddingLeft: spacingActions + dialRadius } })); const SpeedDialFab = experimentalStyled(Fab, {}, { name: 'MuiSpeedDial', slot: 'Fab', overridesResolver: (props, styles) => styles.fab })(() => ({ pointerEvents: 'auto' })); const SpeedDialActions = experimentalStyled('div', {}, { name: 'MuiSpeedDial', slot: 'Actions', overridesResolver: (props, styles) => { const { styleProps } = props; return _extends({}, styles.actions, !styleProps.open && styles.actionsClosed); } })(({ styleProps }) => _extends({ display: 'flex', pointerEvents: 'auto' }, !styleProps.open && { transition: 'top 0s linear 0.2s', pointerEvents: 'none' })); const SpeedDial = /*#__PURE__*/React.forwardRef(function SpeedDial(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiSpeedDial' }); const { ariaLabel, FabProps: { ref: origDialButtonRef } = {}, children: childrenProp, className, direction = 'up', hidden = false, icon, onBlur, onClose, onFocus, onKeyDown, onMouseEnter, onMouseLeave, onOpen, open: openProp, TransitionComponent = Zoom, transitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen }, TransitionProps } = props, FabProps = _objectWithoutPropertiesLoose(props.FabProps, ["ref"]), other = _objectWithoutPropertiesLoose(props, ["ariaLabel", "FabProps", "children", "className", "direction", "hidden", "icon", "onBlur", "onClose", "onFocus", "onKeyDown", "onMouseEnter", "onMouseLeave", "onOpen", "open", "openIcon", "TransitionComponent", "transitionDuration", "TransitionProps"]); const [open, setOpenState] = useControlled({ controlled: openProp, default: false, name: 'SpeedDial', state: 'open' }); const styleProps = _extends({}, props, { open, direction }); const classes = useUtilityClasses(styleProps); const eventTimer = React.useRef(); React.useEffect(() => { return () => { clearTimeout(eventTimer.current); }; }, []); /** * an index in actions.current */ const focusedAction = React.useRef(0); /** * pressing this key while the focus is on a child SpeedDialAction focuses * the next SpeedDialAction. * It is equal to the first arrow key pressed while focus is on the SpeedDial * that is not orthogonal to the direction. * @type {utils.ArrowKey?} */ const nextItemArrowKey = React.useRef(); /** * refs to the Button that have an action associated to them in this SpeedDial * [Fab, ...(SpeedDialActions > Button)] * @type {HTMLButtonElement[]} */ const actions = React.useRef([]); actions.current = [actions.current[0]]; const handleOwnFabRef = React.useCallback(fabFef => { actions.current[0] = fabFef; }, []); const handleFabRef = useForkRef(origDialButtonRef, handleOwnFabRef); /** * creates a ref callback for the Button in a SpeedDialAction * Is called before the original ref callback for Button that was set in buttonProps * * @param dialActionIndex {number} * @param origButtonRef {React.RefObject?} */ const createHandleSpeedDialActionButtonRef = (dialActionIndex, origButtonRef) => { return buttonRef => { actions.current[dialActionIndex + 1] = buttonRef; if (origButtonRef) { origButtonRef(buttonRef); } }; }; const handleKeyDown = event => { if (onKeyDown) { onKeyDown(event); } const key = event.key.replace('Arrow', '').toLowerCase(); const { current: nextItemArrowKeyCurrent = key } = nextItemArrowKey; if (event.key === 'Escape') { setOpenState(false); actions.current[0].focus(); if (onClose) { onClose(event, 'escapeKeyDown'); } return; } if (getOrientation(key) === getOrientation(nextItemArrowKeyCurrent) && getOrientation(key) !== undefined) { event.preventDefault(); const actionStep = key === nextItemArrowKeyCurrent ? 1 : -1; // stay within array indices const nextAction = clamp(focusedAction.current + actionStep, 0, actions.current.length - 1); actions.current[nextAction].focus(); focusedAction.current = nextAction; nextItemArrowKey.current = nextItemArrowKeyCurrent; } }; React.useEffect(() => { // actions were closed while navigation state was not reset if (!open) { focusedAction.current = 0; nextItemArrowKey.current = undefined; } }, [open]); const handleClose = event => { if (event.type === 'mouseleave' && onMouseLeave) { onMouseLeave(event); } if (event.type === 'blur' && onBlur) { onBlur(event); } clearTimeout(eventTimer.current); if (event.type === 'blur') { eventTimer.current = setTimeout(() => { setOpenState(false); if (onClose) { onClose(event, 'blur'); } }); } else { setOpenState(false); if (onClose) { onClose(event, 'mouseLeave'); } } }; const handleClick = event => { if (FabProps.onClick) { FabProps.onClick(event); } clearTimeout(eventTimer.current); if (open) { setOpenState(false); if (onClose) { onClose(event, 'toggle'); } } else { setOpenState(true); if (onOpen) { onOpen(event, 'toggle'); } } }; const handleOpen = event => { if (event.type === 'mouseenter' && onMouseEnter) { onMouseEnter(event); } if (event.type === 'focus' && onFocus) { onFocus(event); } // When moving the focus between two items, // a chain if blur and focus event is triggered. // We only handle the last event. clearTimeout(eventTimer.current); if (!open) { // Wait for a future focus or click event eventTimer.current = setTimeout(() => { setOpenState(true); if (onOpen) { const eventMap = { focus: 'focus', mouseenter: 'mouseEnter' }; onOpen(event, eventMap[event.type]); } }); } }; // Filter the label for valid id characters. const id = ariaLabel.replace(/^[^a-z]+|[^\w:.-]+/gi, ''); const allItems = React.Children.toArray(childrenProp).filter(child => { if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: The SpeedDial component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } return /*#__PURE__*/React.isValidElement(child); }); const children = allItems.map((child, index) => { const _child$props = child.props, { FabProps: { ref: origButtonRef } = {}, tooltipPlacement: tooltipPlacementProp } = _child$props, ChildFabProps = _objectWithoutPropertiesLoose(_child$props.FabProps, ["ref"]); const tooltipPlacement = tooltipPlacementProp || (getOrientation(direction) === 'vertical' ? 'left' : 'top'); return /*#__PURE__*/React.cloneElement(child, { FabProps: _extends({}, ChildFabProps, { ref: createHandleSpeedDialActionButtonRef(index, origButtonRef) }), delay: 30 * (open ? index : allItems.length - index), open, tooltipPlacement, id: `${id}-action-${index}` }); }); return /*#__PURE__*/_jsxs(SpeedDialRoot, _extends({ className: clsx(classes.root, className), ref: ref, role: "presentation", onKeyDown: handleKeyDown, onBlur: handleClose, onFocus: handleOpen, onMouseEnter: handleOpen, onMouseLeave: handleClose, styleProps: styleProps }, other, { children: [/*#__PURE__*/_jsx(TransitionComponent, _extends({ in: !hidden, timeout: transitionDuration, unmountOnExit: true }, TransitionProps, { children: /*#__PURE__*/_jsx(SpeedDialFab, _extends({ color: "primary", "aria-label": ariaLabel, "aria-haspopup": "true", "aria-expanded": open, "aria-controls": `${id}-actions` }, FabProps, { onClick: handleClick, className: clsx(classes.fab, FabProps.className), ref: handleFabRef, styleProps: styleProps, children: /*#__PURE__*/React.isValidElement(icon) && isMuiElement(icon, ['SpeedDialIcon']) ? /*#__PURE__*/React.cloneElement(icon, { open }) : icon })) })), /*#__PURE__*/_jsx(SpeedDialActions, { id: `${id}-actions`, role: "menu", "aria-orientation": getOrientation(direction), className: clsx(classes.actions, !open && classes.actionsClosed), styleProps: styleProps, children: children })] })); }); process.env.NODE_ENV !== "production" ? SpeedDial.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The aria-label of the button element. * Also used to provide the `id` for the `SpeedDial` element and its children. */ ariaLabel: PropTypes.string.isRequired, /** * SpeedDialActions to display when the SpeedDial is `open`. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The direction the actions open relative to the floating action button. * @default 'up' */ direction: PropTypes.oneOf(['down', 'left', 'right', 'up']), /** * Props applied to the [`Fab`](/api/fab/) element. * @default {} */ FabProps: PropTypes.object, /** * If `true`, the SpeedDial is hidden. * @default false */ hidden: PropTypes.bool, /** * The icon to display in the SpeedDial Fab. The `SpeedDialIcon` component * provides a default Icon with animation. */ icon: PropTypes.node, /** * @ignore */ onBlur: PropTypes.func, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. * @param {string} reason Can be: `"toggle"`, `"blur"`, `"mouseLeave"`, `"escapeKeyDown"`. */ onClose: PropTypes.func, /** * @ignore */ onFocus: PropTypes.func, /** * @ignore */ onKeyDown: PropTypes.func, /** * @ignore */ onMouseEnter: PropTypes.func, /** * @ignore */ onMouseLeave: PropTypes.func, /** * Callback fired when the component requests to be open. * * @param {object} event The event source of the callback. * @param {string} reason Can be: `"toggle"`, `"focus"`, `"mouseEnter"`. */ onOpen: PropTypes.func, /** * If `true`, the component is shown. */ open: PropTypes.bool, /** * The icon to display in the SpeedDial Fab when the SpeedDial is open. */ openIcon: PropTypes.node, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The component used for the transition. * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component. * @default Zoom */ TransitionComponent: PropTypes.elementType, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * @default { * enter: duration.enteringScreen, * exit: duration.leavingScreen, * } */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]), /** * Props applied to the transition element. * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component. */ TransitionProps: PropTypes.object } : void 0; export default SpeedDial;
var BASE_PATH = process.env.NIGHTWATCH_COV ? 'lib-cov' : 'lib'; var path = require('path'); module.exports = { setUp : function(cb) { this.Runner = require('../../../'+ BASE_PATH +'/runner/run.js'); process.removeAllListeners('exit'); process.removeAllListeners('uncaughtException'); cb(); }, tearDown : function(callback) { delete require.cache[require.resolve('../../../'+ BASE_PATH +'/runner/run.js')]; callback(); }, testRunEmptyFolder : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/empty'); this.Runner.run([testsPath], {}, { output_folder : false }, function(err) { test.ok(err.message.indexOf('No tests defined!') === 0); test.done(); }); }, testRunSimple : function(test) { test.expect(5); var testsPath = path.join(process.cwd(), '/sampletests/simple'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.ok('sample' in results.modules); test.ok('demoTest' in results.modules.sample.completed); test.done(); }); }, testRunNoSkipTestcasesOnFail : function(test) { test.expect(11); var testsPath = path.join(process.cwd(), '/sampletests/withfailures'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, skip_testcases_on_fail: false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(results.passed, 2); test.equals(results.failed, 2); test.equals(results.errors, 0); test.equals(results.skipped, 0); test.equals(err, null); test.done(); }); }, testRunSkipTestcasesOnFail : function(test) { test.expect(9); var testsPath = path.join(process.cwd(), '/sampletests/withfailures'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(results.passed, 1); test.equals(results.failed, 1); test.equals(results.errors, 0); test.equals(results.modules.sample.skipped[0], 'demoTest2'); test.equals(err, null); test.done(); }); }, testRunRetries : function(test) { test.expect(11); var testsPath = path.join(process.cwd(), '/sampletests/withfailures'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, retries: 1 }, function(err, results) { test.equals(results.passed, 1); test.equals(results.failed, 1); test.equals(results.errors, 0); test.equals(results.skipped, 0); test.equals(err, null); test.done(); }); }, testRunRetriesNoSkipTestcasesOnFail : function(test) { test.expect(15); var testsPath = path.join(process.cwd(), '/sampletests/withfailures'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, skip_testcases_on_fail: false, globals : { test : test } }, { output_folder : false, start_session : true, retries: 1 }, function(err, results) { test.equals(results.passed, 2); test.equals(results.failed, 2); test.equals(results.errors, 0); test.equals(results.skipped, 0); test.equals(err, null); test.done(); }); }, testRunSuiteRetries : function(test) { test.expect(13); var testsPath = path.join(process.cwd(), '/sampletests/withfailures'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, suite_retries: 1 }, function(err, results) { test.equals(results.passed, 1); test.equals(results.failed, 1); test.equals(results.errors, 0); test.equals(results.skipped, 0); test.equals(err, null); test.done(); }); }, testRunSuiteRetriesNoSkipTestcasesOnFail : function(test) { test.expect(13); var testsPath = path.join(process.cwd(), '/sampletests/withfailures'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, skip_testcases_on_fail: false, globals : { test : test } }, { output_folder : false, start_session : true, suite_retries: 1 }, function(err, results) { test.equals(results.errors, 0); test.equals(results.skipped, 0); test.equals(err, null); test.done(); }); }, 'test run multiple sources and same module name' : function(test) { var srcFolders = [ path.join(process.cwd(), '/sampletests/simple'), path.join(process.cwd(), '/sampletests/mixed') ]; this.Runner.run(srcFolders, { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, src_folders : srcFolders }, function(err, results) { test.equals(err, null); test.ok('simple/sample' in results.modules); test.ok('mixed/sample' in results.modules); test.ok('demoTest' in results.modules['simple/sample'].completed); test.ok('demoTestMixed' in results.modules['mixed/sample'].completed); test.done(); }); }, testRunMultipleSrcFolders : function(test) { test.expect(8); var testsPath = path.join(process.cwd(), '/sampletests/simple'); var testsPath2 = path.join(process.cwd(), '/sampletests/srcfolders'); var srcFolders = [testsPath2, testsPath]; this.Runner.run(srcFolders, { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, src_folders : srcFolders }, function(err, results) { test.equals(err, null); test.ok('simple/sample' in results.modules); test.ok('demoTest' in results.modules['simple/sample'].completed); test.ok('srcfolders/other_sample' in results.modules); test.ok('srcFoldersTest' in results.modules['srcfolders/other_sample'].completed); test.done(); }); }, testRunWithExcludeFolder : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/withexclude'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test }, exclude : ['excluded'] }, { output_folder : false, start_session : true }, function(err, results) { test.ok(!('excluded-module' in results.modules)); test.ok(!('not-excluded' in results.modules)); test.done(); }); }, testRunWithExcludePattern : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/withexclude'); var testPattern = path.join('excluded', 'excluded-*'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test }, exclude : [testPattern] }, { output_folder : false, start_session : true }, function(err, results) { test.ok(!('excluded-module' in results.modules)); test.done(); }); }, testRunWithExcludeFile : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/withexclude'); var testPattern = path.join('excluded', 'excluded-module.js'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test }, exclude : [testPattern] }, { output_folder : false, start_session : true }, function(err, results) { test.ok(!('excluded-module' in results.modules)); test.ok('not-excluded' in results.modules); test.done(); }); }, testRunAsync : function(test) { test.expect(5); var testsPath = path.join(process.cwd(), '/sampletests/async'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.ok('sample' in results.modules); test.ok('demoTestAsync' in results.modules.sample.completed); test.done(); }); }, testRunAsyncWithBeforeAndAfter : function(test) { test.expect(34); var testsPath = path.join(process.cwd(), '/sampletests/before-after'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.ok('sampleWithBeforeAndAfter' in results.modules); var result = results.modules.sampleWithBeforeAndAfter.completed; test.ok('demoTestAsyncOne' in result); test.ok('demoTestAsyncTwo' in result); test.ok(!('beforeEach' in result)); test.ok(!('before' in result)); test.ok(!('afterEach' in result)); test.ok(!('after' in result)); test.ok('syncBeforeAndAfter' in results.modules); test.ok('demoTestAsyncOne' in result); test.ok('demoTestAsyncTwo' in result); test.ok(!('beforeEach' in result)); test.ok(!('before' in result)); test.ok(!('afterEach' in result)); test.ok(!('after' in result)); test.done(); }); }, testRunWithGlobalBeforeAndAfter : function(test) { test.expect(22); var testsPath = path.join(process.cwd(), '/sampletests/before-after'); var beforeEachCount = 0; var afterEachCount = 0; this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test, beforeEach: function() { beforeEachCount++; }, afterEach: function() { afterEachCount++; } } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.equals(beforeEachCount, 3); test.equals(afterEachCount, 3); test.done(); }); }, testRunWithGlobalAsyncBeforeEachAndAfterEach : function(test) { test.expect(22); var testsPath = path.join(process.cwd(), '/sampletests/before-after'); var beforeEachCount = 0; var afterEachCount = 0; this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test, beforeEach: function(done) { setTimeout(function() { beforeEachCount++; done(); }, 100); }, afterEach: function(done) { setTimeout(function() { afterEachCount++; done(); }, 100); } } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.equals(beforeEachCount, 3); test.equals(afterEachCount, 3); test.done(); }); }, testRunWithGlobalAsyncBeforeEachAndAfterEachWithBrowser : function(test) { test.expect(25); var testsPath = path.join(process.cwd(), '/sampletests/before-after'); var beforeEachCount = 0; var afterEachCount = 0; this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test, beforeEach: function(client, done) { test.deepEqual(client.globals, this); setTimeout(function() { beforeEachCount++; done(); }, 100); }, afterEach: function(client, done) { setTimeout(function() { afterEachCount++; done(); }, 100); } } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.equals(beforeEachCount, 3); test.equals(afterEachCount, 3); test.done(); }); }, testRunWithGlobalReporter : function(test) { test.expect(22); var testsPath = path.join(process.cwd(), '/sampletests/before-after'); var reporterCount = 0; this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test, reporter: function(results) { test.ok('modules' in results); reporterCount++; } } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.equals(reporterCount, 1); test.done(); }); }, testRunWithGlobalAsyncReporter : function(test) { test.expect(22); var testsPath = path.join(process.cwd(), '/sampletests/before-after'); var reporterCount = 0; this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test, reporter: function(results, done) { test.ok('modules' in results); reporterCount++; done(); } } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.equals(reporterCount, 1); test.done(); }); }, testRunMixed : function(test) { test.expect(6); var testsPath = path.join(process.cwd(), '/sampletests/mixed'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.ok('sample' in results.modules); test.ok('demoTestMixed' in results.modules.sample.completed); test.done(); }); }, testRunWithTags : function(test) { var testsPath = path.join(process.cwd(), 'sampletests'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test }, tag_filter : ['login'] }, { output_folder : false, start_session : true }, function(err, results) { test.ok(('demoTagTest' in results.modules.sample.completed), 'demoTagTest was ran'); test.ok(Object.keys(results.modules).length === 1, 'There was only 1 test running.'); test.done(); }); }, testRunWithTagsAndFilterEmpty : function(test) { var testsPath = path.join(process.cwd(), 'sampletests'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test }, filter : 'syncnames/*', tag_filter : ['login'] }, { output_folder : false, start_session : true }, function(err, results) { test.ok(err); test.equal(results, false); test.done(); }); }, testRunWithTagsAndFilterNotEmpty : function(test) { var testsPath = path.join(process.cwd(), 'sampletests'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test }, filter : 'tags/*', tag_filter : ['login'] }, { output_folder : false, start_session : true }, function(err, results) { test.equal(err, null); test.ok(('demoTagTest' in results.modules.sample.completed), 'demoTagTest was ran'); test.done(); }); }, testRunWithOutput : function(test) { var src_folders = [ path.join(process.cwd(), 'sampletests/withsubfolders') ]; var currentTestArray = []; this.Runner.run(src_folders, { seleniumPort : 10195, silent : true, output : false, globals : { test : test, beforeEach : function(client, done) { currentTestArray.push({ name : client.currentTest.name, module : client.currentTest.module }); done(); } } }, { output_folder : 'output', start_session : true, src_folders : src_folders, reporter : 'junit' }, function(err, results) { test.equals(err, null); test.deepEqual(currentTestArray, [ { name: '', module: 'simple/sample' }, { name: '', module: 'tags/sample' } ]); var fs = require('fs'); fs.readdir(src_folders[0], function(err, list) { test.deepEqual(list, ['simple', 'tags'], 'The subfolders have been created.'); var simpleReportFile = 'output/simple/FIREFOX_TEST_TEST_sample.xml'; var tagsReportFile = 'output/tags/FIREFOX_TEST_TEST_sample.xml'; test.ok(fs.existsSync(simpleReportFile), 'The simple report file was not created.'); test.ok(fs.existsSync(tagsReportFile), 'The tags report file was not created.'); test.done(); }); }); }, testRunModuleSyncName : function(test) { test.expect(3); var testsPath = path.join(process.cwd(), '/sampletests/syncnames'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, sync_test_names : true, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.ok('sampleTest' in results.modules); test.done(); }); }, testRunUnitTests : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/unittests'); test.expect(3); this.Runner.run([testsPath], { silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : false }, function(err, results) { test.equals(err, null); test.done(); }); }, testRunTestcase : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/before-after/syncBeforeAndAfter.js'); this.Runner.run(testsPath, { silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, testcase : 'demoTestSyncOne' }, function(err, results) { test.equals(err, null); test.ok('demoTestSyncOne' in results.modules.syncBeforeAndAfter.completed); test.ok(!('demoTestSyncTwo' in results.modules.syncBeforeAndAfter.completed)); test.done(); }); }, testRunTestCaseWithBeforeAndAfter : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/before-after/syncBeforeAndAfter.js'); test.expect(11); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, testcase : 'demoTestSyncOne' }, function(err, results) { test.equals(err, null); var result = results.modules.syncBeforeAndAfter.completed; test.ok('demoTestSyncOne' in result); test.ok(!('beforeEach' in result)); test.ok(!('before' in result)); test.ok(!('afterEach' in result)); test.ok(!('after' in result)); test.done(); }); }, testRunTestcaseInvalid : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/before-after/syncBeforeAndAfter.js'); this.Runner.run(testsPath, { silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true, testcase : 'Unknown' }, function(err, results) { test.equals(err.message, 'Error: "Unknown" is not a valid testcase in the current test suite.'); test.done(); }); }, testRunCurrentTestName : function(test) { test.expect(10); var testsPath = path.join(process.cwd(), '/sampletests/before-after/sampleSingleTest.js'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test, beforeEach: function(client, done) { test.equal(client.currentTest.name, ''); test.equal(client.currentTest.module, 'sampleSingleTest'); done(); }, afterEach: function(client, done) { test.equal(client.currentTest.name, null); test.equal(client.currentTest.module, 'sampleSingleTest'); done(); } } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.done(); }); }, testRunCurrentTestInAfterEach : function(test) { var testsPath = path.join(process.cwd(), '/sampletests/withaftereach/sampleSingleTest.js'); this.Runner.run([testsPath], { seleniumPort : 10195, silent : true, output : false, globals : { test : test } }, { output_folder : false, start_session : true }, function(err, results) { test.equals(err, null); test.done(); }); } };
'use strict'; // ------------------------------------------------------------------------------ // Requirements // ------------------------------------------------------------------------------ var rule = require('../rules/interval-service'); var RuleTester = require('eslint').RuleTester; var commonFalsePositives = require('./utils/commonFalsePositives'); // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ var eslintTester = new RuleTester(); eslintTester.run('interval-service', rule, { valid: [ '$interval(function() {})', '$interval(function() {}, 1000)', '$interval(function() {}, 1000, 2)', '$interval(function() {}, 1000, true)' ].concat(commonFalsePositives), invalid: [ {code: 'window.setInterval(function() {}, 1000)', errors: [{message: 'You should use the $interval service instead of the default window.setInterval method'}]}, {code: 'window.setInterval(function() {}, 1000, param1)', errors: [{message: 'You should use the $interval service instead of the default window.setInterval method'}]}, {code: 'setInterval(function() {}, 1000)', errors: [{message: 'You should use the $interval service instead of the default window.setInterval method'}]}, {code: 'setInterval(function() {}, 1000, param1)', errors: [{message: 'You should use the $interval service instead of the default window.setInterval method'}]} ] });
var Look = (function () { var that = this; this.Router = {}; this.Router.init = function () { Backbone.history.start({ pushState: true, root: '/' }); }; this.Router.route = ''; var LookRouter = Backbone.Router.extend({ routes: { '' : 'transactionsPage', transactions : 'transactionsPage', metrics : 'metricsPage', cpu : 'cpuPage', memory : 'memoryPage' }, transactionsPage : function () { that.Router.go('transactions', true) }, metricsPage : function () { that.Router.go('metrics', true) }, cpuPage : function () { that.Router.go('cpu', true) }, memoryPage : function () { that.Router.go('memory', true) } }); this.Router.router = new LookRouter(); this.Router.go = function (page, notNavigate) { if (!notNavigate) { that.Router.router.navigate(page); } if (page !== that.Router.route) { if (that.Router.route) { $('#' + that.Router.route + '-link').removeClass('active'); $('#' + that.Router.route + '-page').hide(); } $('#' + page + '-link').addClass('active'); $('#' + page + '-page').show(); that.Router.route = page; } if (that.Router.route === 'metrics') { that.Metrics.refreshPlots(); } return false; }; return this; }.call(Look || {}));
/* global QUnit */ // import { BooleanKeyframeTrack } from '../../../../../src/animation/tracks/BooleanKeyframeTrack.js'; export default QUnit.module( 'Animation', () => { QUnit.module( 'Tracks', () => { QUnit.module( 'BooleanKeyframeTrack', () => { QUnit.todo( 'write me !', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); } ); } ); } );
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); var _ru_RU = require('rc-pagination/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); var _ru_RU3 = require('../date-picker/locale/ru_RU'); var _ru_RU4 = _interopRequireDefault(_ru_RU3); var _ru_RU5 = require('../time-picker/locale/ru_RU'); var _ru_RU6 = _interopRequireDefault(_ru_RU5); var _ru_RU7 = require('../calendar/locale/ru_RU'); var _ru_RU8 = _interopRequireDefault(_ru_RU7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } _moment2['default'].locale('ru'); /** * Created by Andrey Gayvoronsky on 13/04/16. */ exports['default'] = { locale: 'ru', Pagination: _ru_RU2['default'], DatePicker: _ru_RU4['default'], TimePicker: _ru_RU6['default'], Calendar: _ru_RU8['default'], Table: { filterTitle: 'Фильтр', filterConfirm: 'OK', filterReset: 'Сбросить', emptyText: 'Нет данных', selectAll: 'Выбрать всё', selectInvert: 'Инвертировать выбор' }, Modal: { okText: 'OK', cancelText: 'Отмена', justOkText: 'OK' }, Popconfirm: { okText: 'OK', cancelText: 'Отмена' }, Transfer: { notFoundContent: 'Ничего не найдено', searchPlaceholder: 'Введите название для поиска', itemUnit: 'item', itemsUnit: 'items' }, Select: { notFoundContent: 'Ничего не найдено' }, Upload: { uploading: 'Закачиваю...', removeFile: 'Удалить файл', uploadError: 'Ошибка при закачке', previewFile: 'Предпросмотр файла' } }; module.exports = exports['default'];
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey * http://scratchdisk.com/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name Project * * @class A Project object in Paper.js is what usually is referred to as the * document: The top level object that holds all the items contained in the * scene graph. As the term document is already taken in the browser context, * it is called Project. * * Projects allow the manipulation of the styles that are applied to all newly * created items, give access to the selected items, and will in future versions * offer ways to query for items in the scene graph defining specific * requirements, and means to persist and load from different formats, such as * SVG and PDF. * * The currently active project can be accessed through the * {@link PaperScope#project} variable. * * An array of all open projects is accessible through the * {@link PaperScope#projects} variable. */ var Project = PaperScopeItem.extend(/** @lends Project# */{ _class: 'Project', _list: 'projects', _reference: 'project', // TODO: Add arguments to define pages /** * Creates a Paper.js project containing one empty {@link Layer}, referenced * by {@link Project#activeLayer}. * * Note that when working with PaperScript, a project is automatically * created for us and the {@link PaperScope#project} variable points to it. * * @param {HTMLCanvasElement|String} element the HTML canvas element that * should be used as the element for the view, or an ID string by which to * find the element. */ initialize: function Project(element) { // Activate straight away by passing true to PaperScopeItem constructor, // so paper.project is set, as required by Layer and DoumentView // constructors. PaperScopeItem.call(this, true); this.layers = []; this._activeLayer = null; this.symbols = []; this._currentStyle = new Style(null, null, this); // If no view is provided, we create a 1x1 px canvas view just so we // have something to do size calculations with. // (e.g. PointText#_getBounds) this._view = View.create(this, element || CanvasProvider.getCanvas(1, 1)); this._selectedItems = {}; this._selectedItemCount = 0; // See Item#draw() for an explanation of _updateVersion this._updateVersion = 0; // Change tracking, not in use for now. Activate once required: // this._changes = []; // this._changesById = {}; }, _serialize: function(options, dictionary) { // Just serialize layers to an array for now, they will be unserialized // into the active project automatically. We might want to add proper // project serialization later, but deserialization of a layers array // will always work. // Pass true for compact, so 'Project' does not get added as the class return Base.serialize(this.layers, options, true, dictionary); }, /** * Activates this project, so all newly created items will be placed * in it. * * @name Project#activate * @function */ /** * Clears the project by removing all {@link Project#layers} and * {@link Project#symbols}. */ clear: function() { for (var i = this.layers.length - 1; i >= 0; i--) this.layers[i].remove(); this.symbols = []; }, /** * Checks whether the project has any content or not. * * @return Boolean */ isEmpty: function() { return this.layers.length === 0; }, /** * Removes this project from the {@link PaperScope#projects} list, and also * removes its view, if one was defined. */ remove: function remove() { if (!remove.base.call(this)) return false; if (this._view) this._view.remove(); return true; }, /** * The reference to the project's view. * @type View * @bean */ getView: function() { return this._view; }, /** * The currently active path style. All selected items and newly * created items will be styled with this style. * * @type Style * @bean * * @example {@paperscript} * project.currentStyle = { * fillColor: 'red', * strokeColor: 'black', * strokeWidth: 5 * } * * // The following paths will take over all style properties of * // the current style: * var path = new Path.Circle(new Point(75, 50), 30); * var path2 = new Path.Circle(new Point(175, 50), 20); * * @example {@paperscript} * project.currentStyle.fillColor = 'red'; * * // The following path will take over the fill color we just set: * var path = new Path.Circle(new Point(75, 50), 30); * var path2 = new Path.Circle(new Point(175, 50), 20); */ getCurrentStyle: function() { return this._currentStyle; }, setCurrentStyle: function(style) { // TODO: Style selected items with the style: this._currentStyle.initialize(style); }, /** * The index of the project in the {@link PaperScope#projects} list. * * @type Number * @bean */ getIndex: function() { return this._index; }, /** * Gives access to the project's configurable options. * * @type Object * @bean * @deprecated use {@link PaperScope#settings} instead. */ getOptions: function() { return this._scope.settings; }, /** * {@grouptitle Project Content} * * The layers contained within the project. * * @name Project#layers * @type Layer[] */ /** * The layer which is currently active. New items will be created on this * layer by default. * * @type Layer * @bean */ getActiveLayer: function() { return this._activeLayer || new Layer({ project: this }); }, /** * The symbols contained within the project. * * @name Project#symbols * @type Symbol[] */ /** * The selected items contained within the project. * * @type Item[] * @bean */ getSelectedItems: function() { // TODO: Return groups if their children are all selected, // and filter out their children from the list. // TODO: The order of these items should be that of their // drawing order. var items = []; for (var id in this._selectedItems) { var item = this._selectedItems[id]; if (item.isInserted()) items.push(item); } return items; }, // Project#insertChild() and #addChild() are helper functions called in // Item#copyTo(), Layer#initialize(), Layer#_insertSibling() // They are called the same as the functions on Item so duck-typing works. insertChild: function(index, item, _preserve) { if (item instanceof Layer) { item._remove(false, true); Base.splice(this.layers, [item], index, 0); item._setProject(this, true); // See Item#_remove() for an explanation of this: if (this._changes) item._changed(/*#=*/Change.INSERTION); // TODO: this._changed(/*#=*/Change.LAYERS); // Also activate this layer if there was none before if (!this._activeLayer) this._activeLayer = item; } else if (item instanceof Item) { // Anything else than layers needs to be added to a layer first (this._activeLayer // NOTE: If there is no layer and this project is not the active // one, passing insert: false and calling addChild on the // project will handle it correctly. || this.insertChild(index, new Layer(Item.NO_INSERT))) .insertChild(index, item, _preserve); } else { item = null; } return item; }, addChild: function(item, _preserve) { return this.insertChild(undefined, item, _preserve); }, // TODO: Implement setSelectedItems? _updateSelection: function(item) { var id = item._id, selectedItems = this._selectedItems; if (item._selected) { if (selectedItems[id] !== item) { this._selectedItemCount++; selectedItems[id] = item; } } else if (selectedItems[id] === item) { this._selectedItemCount--; delete selectedItems[id]; } }, /** * Selects all items in the project. */ selectAll: function() { var layers = this.layers; for (var i = 0, l = layers.length; i < l; i++) layers[i].setFullySelected(true); }, /** * Deselects all selected items in the project. */ deselectAll: function() { var selectedItems = this._selectedItems; for (var i in selectedItems) selectedItems[i].setFullySelected(false); }, /** * Perform a hit-test on the items contained within the project at the * location of the specified point. * * The options object allows you to control the specifics of the hit-test * and may contain a combination of the following values: * * @option [options.tolerance={@link PaperScope#settings}.hitTolerance] * {Number} the tolerance of the hit-test in points * @option options.class {Function} only hit-test again a certain item class * and its sub-classes: {@code Group, Layer, Path, CompoundPath, * Shape, Raster, PlacedSymbol, PointText}, etc * @option options.fill {Boolean} hit-test the fill of items * @option options.stroke {Boolean} hit-test the stroke of path items, * taking into account the setting of stroke color and width * @option options.segments {Boolean} hit-test for {@link Segment#point} of * {@link Path} items * @option options.curves {Boolean} hit-test the curves of path items, * without taking the stroke color or width into account * @option options.handles {Boolean} hit-test for the handles * ({@link Segment#handleIn} / {@link Segment#handleOut}) of path segments. * @option options.ends {Boolean} only hit-test for the first or last * segment points of open path items * @option options.bounds {Boolean} hit-test the corners and side-centers of * the bounding rectangle of items ({@link Item#bounds}) * @option options.center {Boolean} hit-test the {@link Rectangle#center} of * the bounding rectangle of items ({@link Item#bounds}) * @option options.guides {Boolean} hit-test items that have * {@link Item#guide} set to {@code true} * @option options.selected {Boolean} only hit selected items * * @param {Point} point the point where the hit-test should be performed * @param {Object} [options={ fill: true, stroke: true, segments: true, * tolerance: true }] * @return {HitResult} a hit result object that contains more * information about what exactly was hit or {@code null} if nothing was * hit */ hitTest: function(/* point, options */) { // We don't need to do this here, but it speeds up things since we won't // repeatedly convert in Item#hitTest() then. var point = Point.read(arguments), options = HitResult.getOptions(Base.read(arguments)); // Loop backwards, so layers that get drawn last are tested first for (var i = this.layers.length - 1; i >= 0; i--) { var res = this.layers[i]._hitTest(point, options); if (res) return res; } return null; }, /** * {@grouptitle Fetching and matching items} * * Fetch items contained within the project whose properties match the * criteria in the specified object. * Extended matching is possible by providing a compare function or * regular expression. Matching points, colors only work as a comparison * of the full object, not partial matching (e.g. only providing the x- * coordinate to match all points with that x-value). Partial matching * does work for {@link Item#data}. * Matching items against a rectangular area is also possible, by setting * either {@code match.inside} or {@code match.overlapping} to a rectangle * describing the area in which the items either have to be fully or partly * contained. * * @option match.inside {Rectangle} the rectangle in which the items need to * be fully contained * @option match.overlapping {Rectangle} the rectangle with which the items * need to at least partly overlap * * @example {@paperscript} // Fetch all selected path items: * var path1 = new Path.Circle({ * center: [50, 50], * radius: 25, * fillColor: 'black' * }); * * var path2 = new Path.Circle({ * center: [150, 50], * radius: 25, * fillColor: 'black' * }); * * // Select path2: * path2.selected = true; * * // Fetch all selected path items: * var items = project.getItems({ * selected: true, * class: Path * }); * * // Change the fill color of the selected path to red: * items[0].fillColor = 'red'; * * @example {@paperscript} // Fetch all items with a specific fill color: * var path1 = new Path.Circle({ * center: [50, 50], * radius: 25, * fillColor: 'black' * }); * * var path2 = new Path.Circle({ * center: [150, 50], * radius: 25, * fillColor: 'purple' * }); * * // Fetch all items with a purple fill color: * var items = project.getItems({ * fillColor: 'purple' * }); * * // Select the fetched item: * items[0].selected = true; * * @example {@paperscript} // Fetch items at a specific position: * var path1 = new Path.Circle({ * center: [50, 50], * radius: 25, * fillColor: 'black' * }); * * var path2 = new Path.Circle({ * center: [150, 50], * radius: 25, * fillColor: 'black' * }); * * // Fetch all path items positioned at {x: 150, y: 150}: * var items = project.getItems({ * position: [150, 50] * }); * * // Select the fetched path: * items[0].selected = true; * * @example {@paperscript} // Fetch items using a comparing function: * * // Create a circle shaped path: * var path1 = new Path.Circle({ * center: [50, 50], * radius: 25, * fillColor: 'black' * }); * * // Create a circle shaped path with 50% opacity: * var path2 = new Path.Circle({ * center: [150, 50], * radius: 25, * fillColor: 'black', * opacity: 0.5 * }); * * // Fetch all items whose opacity is smaller than 1 * var items = paper.project.getItems({ * opacity: function(value) { * return value < 1; * } * }); * * // Select the fetched item: * items[0].selected = true; * * @example {@paperscript} // Fetch items using a comparing function (2): * * // Create a rectangle shaped path (4 segments): * var path1 = new Path.Rectangle({ * from: [25, 25], * to: [75, 75], * strokeColor: 'black', * strokeWidth: 10 * }); * * // Create a line shaped path (2 segments): * var path2 = new Path.Line({ * from: [125, 50], * to: [175, 50], * strokeColor: 'black', * strokeWidth: 10 * }); * * // Fetch all paths with 2 segments: * var items = project.getItems({ * class: Path, * segments: function(segments) { * return segments.length == 2; * } * }); * * // Select the fetched path: * items[0].selected = true; * * @example {@paperscript} // Match (nested) properties of the data property: * * // Create a black circle shaped path: * var path1 = new Path.Circle({ * center: [50, 50], * radius: 25, * fillColor: 'black', * data: { * person: { * name: 'john', * length: 200, * hair: true * } * } * }); * * // Create a red circle shaped path: * var path2 = new Path.Circle({ * center: [150, 50], * radius: 25, * fillColor: 'red', * data: { * person: { * name: 'john', * length: 180, * hair: false * } * } * }); * * // Fetch all items whose data object contains a person * // object whose name is john and length is 180: * var items = paper.project.getItems({ * data: { * person: { * name: 'john', * length: 180 * } * } * }); * * // Select the fetched item: * items[0].selected = true; * * @example {@paperscript} // Match strings using regular expressions: * * // Create a path named 'aardvark': * var path1 = new Path.Circle({ * center: [50, 50], * radius: 25, * fillColor: 'black', * name: 'aardvark' * }); * * // Create a path named 'apple': * var path2 = new Path.Circle({ * center: [150, 50], * radius: 25, * fillColor: 'black', * name: 'apple' * }); * * // Create a path named 'banana': * var path2 = new Path.Circle({ * center: [250, 50], * radius: 25, * fillColor: 'black', * name: 'banana' * }); * * // Fetch all items that have a name starting with 'a': * var items = project.getItems({ * name: /^a/ * }); * * // Change the fill color of the matched items: * for (var i = 0; i < items.length; i++) { * items[i].fillColor = 'red'; * } * * @see Item#matches(match) * @see Item#getItems(match) * @param {Object} match the criteria to match against * @return {Item[]} the list of matching items contained in the project */ getItems: function(match) { return Item._getItems(this.layers, match); }, /** * Fetch the first item contained within the project whose properties * match the criteria in the specified object. * Extended matching is possible by providing a compare function or * regular expression. Matching points, colors only work as a comparison * of the full object, not partial matching (e.g. only providing the x- * coordinate to match all points with that x-value). Partial matching * does work for {@link Item#data}. * See {@link #getItems(match)} for a selection of illustrated examples. * * @param {Object} match the criteria to match against * @return {Item} the first item in the project matching the given criteria */ getItem: function(match) { return Item._getItems(this.layers, match, null, null, true)[0] || null; }, /** * {@grouptitle Importing / Exporting JSON and SVG} * * Exports (serializes) the project with all its layers and child items to * a JSON data object or string. * * @name Project#exportJSON * @function * * @option [options.asString=true] {Boolean} whether the JSON is returned as * a {@code Object} or a {@code String} * @option [options.precision=5] {Number} the amount of fractional digits in * numbers used in JSON data * * @param {Object} [options] the serialization options * @return {String} the exported JSON data */ /** * Imports (deserializes) the stored JSON data into the project. * Note that the project is not cleared first. You can call * {@link Project#clear()} to do so. * * @param {String} json the JSON data to import from */ importJSON: function(json) { this.activate(); // Provide the activeLayer as a possible target for layers, but only if // it's empty. var layer = this._activeLayer; return Base.importJSON(json, layer && layer.isEmpty() && layer); }, /** * Exports the project with all its layers and child items as an SVG DOM, * all contained in one top level SVG group node. * * @name Project#exportSVG * @function * * @option [options.asString=false] {Boolean} whether a SVG node or a * {@code String} is to be returned * @option [options.precision=5] {Number} the amount of fractional digits in * numbers used in SVG data * @option [options.matchShapes=false] {Boolean} whether path items should * tried to be converted to shape items, if their geometries can be made to * match * * @param {Object} [options] the export options * @return {SVGElement} the project converted to an SVG node */ /** * Converts the provided SVG content into Paper.js items and adds them to * the active layer of this project. * Note that the project is not cleared first. You can call * {@link Project#clear()} to do so. * * @name Project#importSVG * @function * * @option [options.expandShapes=false] {Boolean} whether imported shape * items should be expanded to path items * @option [options.onLoad] {Function} the callback function to call once * the SVG content is loaded from the given URL. Only required when loading * from external files. * @option [options.applyMatrix={@link PaperScope#settings}.applyMatrix] * {Boolean} whether imported items should have their transformation * matrices applied to their contents or not * * @param {SVGElement|String} svg the SVG content to import, either as a SVG * DOM node, a string containing SVG content, or a string describing the URL * of the SVG file to fetch. * @param {Object} [options] the import options * @return {Item} the newly created Paper.js item containing the converted * SVG content */ /** * Imports the provided external SVG file, converts it into Paper.js items * and adds them to the active layer of this project. * Note that the project is not cleared first. You can call * {@link Project#clear()} to do so. * * @name Project#importSVG * @function * * @param {SVGElement|String} svg the URL of the SVG file to fetch. * @param {Function} onLoad the callback function to call once the SVG * content is loaded from the given URL. * @return {Item} the newly created Paper.js item containing the converted * SVG content */ draw: function(ctx, matrix, pixelRatio) { // Increase the _updateVersion before the draw-loop. After that, items // that are visible will have their _updateVersion set to the new value. this._updateVersion++; ctx.save(); matrix.applyToContext(ctx); // Use new Base() so we can use param.extend() to easily override values var param = new Base({ offset: new Point(0, 0), pixelRatio: pixelRatio, viewMatrix: matrix.isIdentity() ? null : matrix, matrices: [new Matrix()], // Start with the identity matrix. // Tell the drawing routine that we want to keep _globalMatrix up to // date. Item#rasterize() and Raster#getAverageColor() should not // set this. updateMatrix: true }); for (var i = 0, layers = this.layers, l = layers.length; i < l; i++) layers[i].draw(ctx, param); ctx.restore(); // Draw the selection of the selected items in the project: if (this._selectedItemCount > 0) { ctx.save(); ctx.strokeWidth = 1; var items = this._selectedItems, size = this._scope.settings.handleSize, version = this._updateVersion; for (var id in items) items[id]._drawSelection(ctx, matrix, size, items, version); ctx.restore(); } } });
/* * Copyright (c) 2012 - present 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, regexp: true */ /*global define, $, brackets, jasmine, expect, beforeEach, waitsFor, waitsForDone, runs, spyOn */ define(function (require, exports, module) { 'use strict'; var Commands = require("command/Commands"), FileUtils = require("file/FileUtils"), Async = require("utils/Async"), DocumentManager = require("document/DocumentManager"), Editor = require("editor/Editor").Editor, EditorManager = require("editor/EditorManager"), MainViewManager = require("view/MainViewManager"), FileSystemError = require("filesystem/FileSystemError"), FileSystem = require("filesystem/FileSystem"), WorkspaceManager = require("view/WorkspaceManager"), ExtensionLoader = require("utils/ExtensionLoader"), UrlParams = require("utils/UrlParams").UrlParams, LanguageManager = require("language/LanguageManager"); var TEST_PREFERENCES_KEY = "com.adobe.brackets.test.preferences", EDITOR_USE_TABS = false, EDITOR_SPACE_UNITS = 4, OPEN_TAG = "{{", RE_MARKER = /\{\{(\d+)\}\}/g, absPathPrefix = (brackets.platform === "win" ? "c:/" : "/"), _testSuites = {}, _testWindow, _doLoadExtensions, _rootSuite = { id: "__brackets__" }, _unitTestReporter; MainViewManager._initialize($("#mock-main-view")); function _getFileSystem() { return _testWindow ? _testWindow.brackets.test.FileSystem : FileSystem; } /** * Delete a path * @param {string} fullPath * @param {boolean=} silent Defaults to false. When true, ignores ERR_NOT_FOUND when deleting path. * @return {$.Promise} Resolved when deletion complete, or rejected if an error occurs */ function deletePath(fullPath, silent) { var result = new $.Deferred(); _getFileSystem().resolve(fullPath, function (err, item) { if (!err) { item.unlink(function (err) { if (!err) { result.resolve(); } else { if (err === FileSystemError.NOT_FOUND && silent) { result.resolve(); } else { console.error("Unable to remove " + fullPath, err); result.reject(err); } } }); } else { if (err === FileSystemError.NOT_FOUND && silent) { result.resolve(); } else { console.error("Unable to remove " + fullPath, err); result.reject(err); } } }); return result.promise(); } /** * Set permissions on a path * @param {!string} path Path to change permissions on * @param {!string} mode New mode as an octal string * @return {$.Promise} Resolved when permissions are set or rejected if an error occurs */ function chmod(path, mode) { var deferred = new $.Deferred(); brackets.fs.chmod(path, parseInt(mode, 8), function (err) { if (err) { deferred.reject(err); } else { deferred.resolve(); } }); return deferred.promise(); } function testDomain() { return brackets.testing.nodeConnection.domains.testing; } /** * Remove a directory (recursively) or file * * @param {!string} path Path to remove * @return {$.Promise} Resolved when the path is removed, rejected if there was a problem */ function remove(path) { return testDomain().remove(path); } /** * Copy a directory (recursively) or file * * @param {!string} src Path to copy * @param {!string} dest Destination directory * @return {$.Promise} Resolved when the path is copied, rejected if there was a problem */ function copy(src, dest) { return testDomain().copy(src, dest); } /** * Rename a directory or file. * @return {$.Promise} Resolved when the path is rename, rejected if there was a problem */ function rename(src, dest) { return testDomain().rename(src, dest); } /** * Resolves a path string to a File or Directory * @param {!string} path Path to a file or directory * @return {$.Promise} A promise resolved when the file/directory is found or * rejected when any error occurs. */ function resolveNativeFileSystemPath(path) { var result = new $.Deferred(); _getFileSystem().resolve(path, function (err, item) { if (!err) { result.resolve(item); } else { result.reject(err); } }); return result.promise(); } /** * Utility for tests that wait on a Promise to complete. Placed in the global namespace so it can be used * similarly to the standard Jasmine waitsFor(). Unlike waitsFor(), must be called from INSIDE * the runs() that generates the promise. * @param {$.Promise} promise * @param {string} operationName Name used for timeout error message */ window.waitsForDone = function (promise, operationName, timeout) { timeout = timeout || 1000; expect(promise).toBeTruthy(); promise.fail(function (err) { expect("[" + operationName + "] promise rejected with: " + err).toBe("(expected resolved instead)"); }); waitsFor(function () { return promise.state() === "resolved"; }, "success [" + operationName + "]", timeout); }; /** * Utility for tests that waits on a Promise to fail. Placed in the global namespace so it can be used * similarly to the standards Jasmine waitsFor(). Unlike waitsFor(), must be called from INSIDE * the runs() that generates the promise. * @param {$.Promise} promise * @param {string} operationName Name used for timeout error message */ window.waitsForFail = function (promise, operationName, timeout) { timeout = timeout || 1000; expect(promise).toBeTruthy(); promise.done(function (result) { expect("[" + operationName + "] promise resolved with: " + result).toBe("(expected rejected instead)"); }); waitsFor(function () { return promise.state() === "rejected"; }, "failure " + operationName, timeout); }; /** * Get or create a NativeFileSystem rooted at the system root. * @return {$.Promise} A promise resolved when the native file system is found or rejected when an error occurs. */ function getRoot() { var deferred = new $.Deferred(); resolveNativeFileSystemPath("/").then(deferred.resolve, deferred.reject); return deferred.promise(); } function getTestRoot() { // /path/to/brackets/test/SpecRunner.html var path = window.location.pathname; path = path.substr(0, path.lastIndexOf("/")); path = FileUtils.convertToNativePath(path); return path; } function getTestPath(path) { return getTestRoot() + path; } /** * Get the temporary unit test project path. Use this path for unit tests that need to modify files on disk. * @return {$.string} Path to the temporary unit test project */ function getTempDirectory() { return getTestPath("/temp"); } /** * Create the temporary unit test project directory. */ function createTempDirectory() { var deferred = new $.Deferred(); runs(function () { _getFileSystem().getDirectoryForPath(getTempDirectory()).create(function (err) { if (err && err !== FileSystemError.ALREADY_EXISTS) { deferred.reject(err); } else { deferred.resolve(); } }); }); waitsForDone(deferred, "Create temp directory", 500); } function _resetPermissionsOnSpecialTempFolders() { var folders = [], baseDir = getTempDirectory(), promise; folders.push(baseDir + "/cant_read_here"); folders.push(baseDir + "/cant_write_here"); promise = Async.doSequentially(folders, function (folder) { var deferred = new $.Deferred(); _getFileSystem().resolve(folder, function (err, entry) { if (!err) { // Change permissions if the directory exists chmod(folder, "777").then(deferred.resolve, deferred.reject); } else { if (err === FileSystemError.NOT_FOUND) { // Resolve the promise since the folder to reset doesn't exist deferred.resolve(); } else { deferred.reject(); } } }); return deferred.promise(); }, true); return promise; } /** * Remove temp folder used for temporary unit tests files */ function removeTempDirectory() { var deferred = new $.Deferred(), baseDir = getTempDirectory(); runs(function () { _resetPermissionsOnSpecialTempFolders().done(function () { deletePath(baseDir, true).then(deferred.resolve, deferred.reject); }).fail(function () { deferred.reject(); }); deferred.fail(function (err) { console.log("boo"); }); waitsForDone(deferred.promise(), "removeTempDirectory", 2000); }); } function getBracketsSourceRoot() { var path = window.location.pathname; path = path.split("/"); path = path.slice(0, path.length - 2); path.push("src"); return path.join("/"); } /** * Returns a Document suitable for use with an Editor in isolation, but that can be registered with * DocumentManager via addRef() so it is maintained for global updates like name and language changes. * * Like a normal Document, if you cause an addRef() on this you MUST call releaseRef() later. * * @param {!{language:?string, filename:?string, content:?string }} options * Language defaults to JavaScript, filename defaults to a placeholder name, and * content defaults to "". */ function createMockActiveDocument(options) { var language = options.language || LanguageManager.getLanguage("javascript"), filename = options.filename || (absPathPrefix + "_unitTestDummyPath_/_dummyFile_" + Date.now() + "." + language._fileExtensions[0]), content = options.content || ""; // Use unique filename to avoid collissions in open documents list var dummyFile = _getFileSystem().getFileForPath(filename); var docToShim = new DocumentManager.Document(dummyFile, new Date(), content); // Prevent adding doc to working set by not dispatching "dirtyFlagChange". // TODO: Other functionality here needs to be kept in sync with Document._handleEditorChange(). In the // future, we should fix things so that we either don't need mock documents or that this // is factored so it will just run in both. docToShim._handleEditorChange = function (event, editor, changeList) { this.isDirty = !editor._codeMirror.isClean(); this._notifyDocumentChange(changeList); }; docToShim.notifySaved = function () { throw new Error("Cannot notifySaved() a unit-test dummy Document"); }; return docToShim; } /** * Returns a Document suitable for use with an Editor in isolation: i.e., a Document that will * never be set as the currentDocument or added to the working set. * * Unlike a real Document, does NOT need to be explicitly cleaned up. * * @param {?string} initialContent Defaults to "" * @param {?string} languageId Defaults to JavaScript * @param {?string} filename Defaults to an auto-generated filename with the language's extension */ function createMockDocument(initialContent, languageId, filename) { var language = LanguageManager.getLanguage(languageId) || LanguageManager.getLanguage("javascript"), options = { language: language, content: initialContent, filename: filename }, docToShim = createMockActiveDocument(options); // Prevent adding doc to global 'open docs' list; prevents leaks or collisions if a test // fails to clean up properly (if test fails, or due to an apparent bug with afterEach()) docToShim.addRef = function () {}; docToShim.releaseRef = function () {}; docToShim._ensureMasterEditor = function () { if (!this._masterEditor) { // Don't let Document create an Editor itself via EditorManager; the unit test can't clean that up throw new Error("Use create/destroyMockEditor() to test edit operations"); } }; return docToShim; } /** * Returns a mock element (in the test runner window) that's offscreen, for * parenting UI you want to unit-test. When done, make sure to delete it with * remove(). * @return {jQueryObject} a jQuery object for an offscreen div */ function createMockElement() { return $("<div/>") .css({ position: "absolute", left: "-10000px", top: "-10000px" }) .appendTo($("body")); } function createEditorInstance(doc, pane, visibleRange) { var $editorHolder = pane.$el || pane; // To handle actual pane mock or a fake container var editor = new Editor(doc, true, $editorHolder.get(0), visibleRange); Editor.setUseTabChar(EDITOR_USE_TABS); Editor.setSpaceUnits(EDITOR_SPACE_UNITS); if (pane.addView) { pane.addView(editor); editor._paneId = pane.id; } EditorManager._notifyActiveEditorChanged(editor); return editor; } /** * Returns an Editor tied to the given Document, but suitable for use in isolation * (without being placed inside the surrounding Brackets UI). The Editor *will* be * reported as the "active editor" by EditorManager. * * Must be cleaned up by calling destroyMockEditor(document) later. * * @param {!Document} doc * @param {{startLine: number, endLine: number}=} visibleRange * @return {!Editor} */ function createMockEditorForDocument(doc, visibleRange) { // Initialize EditorManager/WorkspaceManager and position the editor-holder offscreen // (".content" may not exist, but that's ok for headless tests where editor height doesn't matter) var $editorHolder = createMockElement().css("width", "1000px").attr("id", "hidden-editors"); WorkspaceManager._setMockDOM($(".content"), $editorHolder); // create Editor instance return createEditorInstance(doc, $editorHolder, visibleRange); } /** * Returns a Document and Editor suitable for use in isolation: the Document * will never be set as the currentDocument or added to the working set and the * Editor does not live inside a full-blown Brackets UI layout. The Editor *will* be * reported as the "active editor" by EditorManager, however. * * Must be cleaned up by calling destroyMockEditor(document) later. * * @param {string=} initialContent * @param {string=} languageId * @param {{startLine: number, endLine: number}=} visibleRange * @return {!{doc:!Document, editor:!Editor}} */ function createMockEditor(initialContent, languageId, visibleRange) { // create dummy Document, then Editor tied to it var doc = createMockDocument(initialContent, languageId); return { doc: doc, editor: createMockEditorForDocument(doc, visibleRange) }; } function createMockPane($el, paneId) { createMockElement() .attr("class", "pane-header") .appendTo($el); var $fakeContent = createMockElement() .attr("class", "pane-content") .appendTo($el); return { $el: $el, id: paneId || 'first-pane', $content: $fakeContent, addView: function (editor) { this.$content.append(editor.$el); }, showView: function (editor) { } }; } /** * Destroy the Editor instance for a given mock Document. * @param {!Document} doc Document whose master editor to destroy */ function destroyMockEditor(doc) { EditorManager._notifyActiveEditorChanged(null); MainViewManager._destroyEditorIfNotNeeded(doc); // Clear editor holder so EditorManager doesn't try to resize destroyed object $("#hidden-editors").remove(); } /** * Dismiss the currently open dialog as if the user had chosen the given button. Dialogs close * asynchronously; after calling this, you need to start a new runs() block before testing the * outcome. Also, in cases where asynchronous tasks are performed after the dialog closes, * clients must also wait for any additional promises. * @param {string} buttonId One of the Dialogs.DIALOG_BTN_* symbolic constants. * @param {boolean=} enableFirst If true, then enable the button before clicking. */ function clickDialogButton(buttonId, enableFirst) { // Make sure there's one and only one dialog open var $dlg = _testWindow.$(".modal.instance"), promise = $dlg.data("promise"); expect($dlg.length).toBe(1); // Make sure desired button exists var $dismissButton = $dlg.find(".dialog-button[data-button-id='" + buttonId + "']"); expect($dismissButton.length).toBe(1); if (enableFirst) { // Remove the disabled prop. $dismissButton.prop("disabled", false); } // Click the button $dismissButton.click(); // Dialog should resolve/reject the promise waitsForDone(promise, "dismiss dialog"); } function createTestWindowAndRun(spec, callback, options) { runs(function () { // Position popup windows in the lower right so they're out of the way var testWindowWid = 1000, testWindowHt = 700, testWindowX = window.screen.availWidth - testWindowWid, testWindowY = window.screen.availHeight - testWindowHt, optionsStr = "left=" + testWindowX + ",top=" + testWindowY + ",width=" + testWindowWid + ",height=" + testWindowHt; var params = new UrlParams(); // setup extension loading in the test window params.put("extensions", _doLoadExtensions ? "default,dev," + ExtensionLoader.getUserExtensionPath() : "default"); // disable update check in test windows params.put("skipUpdateCheck", true); // disable loading of sample project params.put("skipSampleProjectLoad", true); // disable initial dialog for live development params.put("skipLiveDevelopmentInfo", true); // signals that main.js should configure RequireJS for tests params.put("testEnvironment", true); if (options) { // option to set the params if (options.hasOwnProperty("params")) { var paramObject = options.params || {}; var obj; for (obj in paramObject) { if (paramObject.hasOwnProperty(obj)) { params.put(obj, paramObject[obj]); } } } // option to launch test window with either native or HTML menus if (options.hasOwnProperty("hasNativeMenus")) { params.put("hasNativeMenus", (options.hasNativeMenus ? "true" : "false")); } } _testWindow = window.open(getBracketsSourceRoot() + "/index.html?" + params.toString(), "_blank", optionsStr); // Displays the primary console messages from the test window in the the // test runner's console as well. ["debug", "log", "info", "warn", "error"].forEach(function (method) { var originalMethod = _testWindow.console[method]; _testWindow.console[method] = function () { var log = ["[testWindow] "].concat(Array.prototype.slice.call(arguments, 0)); console[method].apply(console, log); originalMethod.apply(_testWindow.console, arguments); }; }); _testWindow.isBracketsTestWindow = true; _testWindow.executeCommand = function executeCommand(cmd, args) { return _testWindow.brackets.test.CommandManager.execute(cmd, args); }; _testWindow.closeAllFiles = function closeAllFiles() { runs(function () { var promise = _testWindow.executeCommand(_testWindow.brackets.test.Commands.FILE_CLOSE_ALL); _testWindow.brackets.test.Dialogs.cancelModalDialogIfOpen( _testWindow.brackets.test.DefaultDialogs.DIALOG_ID_SAVE_CLOSE, _testWindow.brackets.test.DefaultDialogs.DIALOG_BTN_DONTSAVE ); waitsForDone(promise, "Close all open files in working set"); }); }; }); // FIXME (issue #249): Need an event or something a little more reliable... waitsFor( function isBracketsDoneLoading() { return _testWindow.brackets && _testWindow.brackets.test && _testWindow.brackets.test.doneLoading; }, "brackets.test.doneLoading", 10000 ); runs(function () { // callback allows specs to query the testWindow before they run callback.call(spec, _testWindow); }); } function closeTestWindow() { // debug-only to see testWindow state before closing // waits(500); runs(function () { //we need to mark the documents as not dirty before we close //or the window will stay open prompting to save var openDocs = _testWindow.brackets.test.DocumentManager.getAllOpenDocuments(); openDocs.forEach(function resetDoc(doc) { if (doc.isDirty) { //just refresh it back to it's current text. This will mark it //clean to save doc.refreshText(doc.getText(), doc.diskTimestamp); } }); _testWindow.close(); _testWindow.executeCommand = null; _testWindow = null; }); } function loadProjectInTestWindow(path) { runs(function () { // begin loading project path var result = _testWindow.brackets.test.ProjectManager.openProject(path); // wait for file system to finish loading waitsForDone(result, "ProjectManager.openProject()", 10000); }); } /** * Parses offsets from text offset markup (e.g. "{{1}}" for offset 1). * @param {!string} text Text to parse * @return {!{offsets:!Array.<{line:number, ch:number}>, text:!string, original:!string}} */ function parseOffsetsFromText(text) { var offsets = [], output = [], i = 0, line = 0, charAt = 0, ch = 0, length = text.length, exec = null, found = false; while (i < length) { found = false; if (text.slice(i, i + OPEN_TAG.length) === OPEN_TAG) { // find "{{[0-9]+}}" RE_MARKER.lastIndex = i; exec = RE_MARKER.exec(text); found = (exec !== null && exec.index === i); if (found) { // record offset info offsets[exec[1]] = {line: line, ch: ch}; // advance i += exec[0].length; } } if (!found) { charAt = text.substr(i, 1); output.push(charAt); if (charAt === '\n') { line++; ch = 0; } else { ch++; } i++; } } return {offsets: offsets, text: output.join(""), original: text}; } /** * Creates absolute paths based on the test window's current project * @param {!Array.<string>|string} paths Project relative file path(s) to convert. May pass a single string path or array. * @return {!Array.<string>|string} Absolute file path(s) */ function makeAbsolute(paths) { var fullPath = _testWindow.brackets.test.ProjectManager.getProjectRoot().fullPath; function prefixProjectPath(path) { if (path.indexOf(fullPath) === 0) { return path; } return fullPath + path; } if (Array.isArray(paths)) { return paths.map(prefixProjectPath); } else { return prefixProjectPath(paths); } } /** * Creates relative paths based on the test window's current project. Any paths, * outside the project are included in the result, but left as absolute paths. * @param {!Array.<string>|string} paths Absolute file path(s) to convert. May pass a single string path or array. * @return {!Array.<string>|string} Relative file path(s) */ function makeRelative(paths) { var fullPath = _testWindow.brackets.test.ProjectManager.getProjectRoot().fullPath, fullPathLength = fullPath.length; function removeProjectPath(path) { if (path.indexOf(fullPath) === 0) { return path.substring(fullPathLength); } return path; } if (Array.isArray(paths)) { return paths.map(removeProjectPath); } else { return removeProjectPath(paths); } } function makeArray(arg) { if (!Array.isArray(arg)) { return [arg]; } return arg; } /** * Opens project relative file paths in the test window * @param {!(Array.<string>|string)} paths Project relative file path(s) to open * @return {!$.Promise} A promise resolved with a mapping of project-relative path * keys to a corresponding Document */ function openProjectFiles(paths) { var result = new $.Deferred(), fullpaths = makeArray(makeAbsolute(paths)), keys = makeArray(makeRelative(paths)), docs = {}, FileViewController = _testWindow.brackets.test.FileViewController, DocumentManager = _testWindow.brackets.test.DocumentManager; Async.doSequentially(fullpaths, function (path, i) { var one = new $.Deferred(); FileViewController.openFileAndAddToWorkingSet(path).done(function (file) { docs[keys[i]] = DocumentManager.getOpenDocumentForPath(file.fullPath); one.resolve(); }).fail(function (err) { one.reject(err); }); return one.promise(); }, false).done(function () { result.resolve(docs); }).fail(function (err) { result.reject(err); }).always(function () { docs = null; FileViewController = null; }); return result.promise(); } /** * Create or overwrite a text file * @param {!string} path Path for a file to be created/overwritten * @param {!string} text Text content for the new file * @param {!FileSystem} fileSystem FileSystem instance to use. Normally, use the instance from * testWindow so the test copy of Brackets is aware of the newly-created file. * @return {$.Promise} A promise resolved when the file is written or rejected when an error occurs. */ function createTextFile(path, text, fileSystem) { var deferred = new $.Deferred(), file = fileSystem.getFileForPath(path), options = { blind: true // overwriting previous files is OK }; file.write(text, options, function (err) { if (!err) { deferred.resolve(file); } else { deferred.reject(err); } }); return deferred.promise(); } /** * Copy a file source path to a destination * @param {!File} source Entry for the source file to copy * @param {!string} destination Destination path to copy the source file * @param {?{parseOffsets:boolean}} options parseOffsets allows optional * offset markup parsing. File is written to the destination path * without offsets. Offset data is passed to the doneCallbacks of the * promise. * @return {$.Promise} A promise resolved when the file is copied to the * destination. */ function copyFileEntry(source, destination, options) { options = options || {}; var deferred = new $.Deferred(); // read the source file FileUtils.readAsText(source).done(function (text, modificationTime) { getRoot().done(function (nfs) { var offsets; // optionally parse offsets if (options.parseOffsets) { var parseInfo = parseOffsetsFromText(text); text = parseInfo.text; offsets = parseInfo.offsets; } // create the new File createTextFile(destination, text, _getFileSystem()).done(function (entry) { deferred.resolve(entry, offsets, text); }).fail(function (err) { deferred.reject(err); }); }); }).fail(function (err) { deferred.reject(err); }); return deferred.promise(); } /** * Copy a directory source to a destination * @param {!Directory} source Directory to copy * @param {!string} destination Destination path to copy the source directory to * @param {?{parseOffsets:boolean, infos:Object, removePrefix:boolean}}} options * parseOffsets - allows optional offset markup parsing. File is written to the * destination path without offsets. Offset data is passed to the * doneCallbacks of the promise. * infos - an optional Object used when parseOffsets is true. Offset * information is attached here, indexed by the file destination path. * removePrefix - When parseOffsets is true, set removePrefix true * to add a new key to the infos array that drops the destination * path root. * @return {$.Promise} A promise resolved when the directory and all it's * contents are copied to the destination or rejected immediately * upon the first error. */ function copyDirectoryEntry(source, destination, options) { options = options || {}; options.infos = options.infos || {}; var parseOffsets = options.parseOffsets || false, removePrefix = options.removePrefix || true, deferred = new $.Deferred(), destDir = _getFileSystem().getDirectoryForPath(destination); // create the destination folder destDir.create(function (err) { if (err && err !== FileSystemError.ALREADY_EXISTS) { deferred.reject(); return; } source.getContents(function (err, contents) { if (!err) { // copy all children of this directory var copyChildrenPromise = Async.doInParallel( contents, function copyChild(child) { var childDestination = destination + "/" + child.name, promise; if (child.isDirectory) { promise = copyDirectoryEntry(child, childDestination, options); } else { promise = copyFileEntry(child, childDestination, options); if (parseOffsets) { // save offset data for each file path promise.done(function (destinationEntry, offsets, text) { options.infos[childDestination] = { offsets : offsets, fileEntry : destinationEntry, text : text }; }); } } return promise; } ); copyChildrenPromise.then(deferred.resolve, deferred.reject); } else { deferred.reject(err); } }); }); deferred.always(function () { // remove destination path prefix if (removePrefix && options.infos) { var shortKey; Object.keys(options.infos).forEach(function (key) { shortKey = key.substr(destination.length + 1); options.infos[shortKey] = options.infos[key]; }); } }); return deferred.promise(); } /** * Copy a file or directory source path to a destination * @param {!string} source Path for the source file or directory to copy * @param {!string} destination Destination path to copy the source file or directory * @param {?{parseOffsets:boolean, infos:Object, removePrefix:boolean}}} options * parseOffsets - allows optional offset markup parsing. File is written to the * destination path without offsets. Offset data is passed to the * doneCallbacks of the promise. * infos - an optional Object used when parseOffsets is true. Offset * information is attached here, indexed by the file destination path. * removePrefix - When parseOffsets is true, set removePrefix true * to add a new key to the infos array that drops the destination * path root. * @return {$.Promise} A promise resolved when the directory and all it's * contents are copied to the destination or rejected immediately * upon the first error. */ function copyPath(source, destination, options) { var deferred = new $.Deferred(); resolveNativeFileSystemPath(source).done(function (entry) { var promise; if (entry.isDirectory) { promise = copyDirectoryEntry(entry, destination, options); } else { promise = copyFileEntry(entry, destination, options); } promise.then(deferred.resolve, function (err) { console.error(destination); deferred.reject(); }); }).fail(function () { deferred.reject(); }); return deferred.promise(); } /** * Set editor cursor position to the given offset then activate an inline editor. * @param {!Editor} editor * @param {!{line:number, ch:number}} offset * @return {$.Promise} a promise that will be resolved when an inline * editor is created or rejected when no inline editors are available. */ function toggleQuickEditAtOffset(editor, offset) { editor.setCursorPos(offset.line, offset.ch); return _testWindow.executeCommand(Commands.TOGGLE_QUICK_EDIT); } /** * Simulate key event. Found this code here: * http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key * * TODO: need parameter(s) for modifier keys * * @param {Number} key Key code * @param (String) event Key event to simulate * @param {HTMLElement} element Element to receive event */ function simulateKeyEvent(key, event, element) { var doc = element.ownerDocument, oEvent = doc.createEvent('KeyboardEvent'); if (event !== "keydown" && event !== "keyup" && event !== "keypress") { console.log("SpecRunnerUtils.simulateKeyEvent() - unsupported keyevent: " + event); return; } // Chromium Hack: need to override the 'which' property. // Note: this code is not designed to work in IE, Safari, // or other browsers. Well, maybe with Firefox. YMMV. Object.defineProperty(oEvent, 'keyCode', { get: function () { return this.keyCodeVal; } }); Object.defineProperty(oEvent, 'which', { get: function () { return this.keyCodeVal; } }); Object.defineProperty(oEvent, 'charCode', { get: function () { return this.keyCodeVal; } }); if (oEvent.initKeyboardEvent) { oEvent.initKeyboardEvent(event, true, true, doc.defaultView, key, 0, false, false, false, false); } else { oEvent.initKeyEvent(event, true, true, doc.defaultView, false, false, false, false, key, 0); } oEvent.keyCodeVal = key; if (oEvent.keyCode !== key) { console.log("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")"); } element.dispatchEvent(oEvent); } function getTestWindow() { return _testWindow; } function setLoadExtensionsInTestWindow(doLoadExtensions) { _doLoadExtensions = doLoadExtensions; } /** * Change the size of an editor. The window size is not affected by this function. * CodeMirror will change it's size withing Brackets. * * @param {!Editor} editor - instance of Editor * @param {?number} width - the new width of the editor in pixel * @param {?number} height - the new height of the editor in pixel */ function resizeEditor(editor, width, height) { var oldSize = {}; if (editor) { var jquery = editor.getRootElement().ownerDocument.defaultView.$, $editorHolder = jquery('#editor-holder'), $content = jquery('.content'); // preserve old size oldSize.width = $editorHolder.width(); oldSize.height = $editorHolder.height(); if (width) { $content.width(width); $editorHolder.width(width); editor.setSize(width, null); // Update CM size } if (height) { $content.height(height); $editorHolder.height(height); editor.setSize(null, height); // Update CM size } editor.refreshAll(true); // update CM } return oldSize; } /** * Extracts the jasmine.log() and/or jasmine.expect() messages from the given result, * including stack traces if available. * @param {Object} result A jasmine result item (from results.getItems()). * @return {string} the error message from that item. */ function getResultMessage(result) { var message; if (result.type === 'log') { message = result.toString(); } else if (result.type === 'expect' && result.passed && !result.passed()) { message = result.message; if (result.trace.stack) { message = result.trace.stack; } } return message; } /** * Searches the DOM tree for text containing the given content. Useful for verifying * that data you expect to show up in the UI somewhere is actually there. * * @param {jQueryObject|Node} root The root element to search from. Can be either a jQuery object * or a raw DOM node. * @param {string} content The content to find. * @param {boolean} asLink If true, find the content in the href of an <a> tag, otherwise find it in text nodes. * @return true if content was found */ function findDOMText(root, content, asLink) { // Unfortunately, we can't just use jQuery's :contains() selector, because it appears that // you can't escape quotes in it. var i; if (root.jquery) { root = root.get(0); } if (!root) { return false; } else if (!asLink && root.nodeType === 3) { // text node return root.textContent.indexOf(content) !== -1; } else { if (asLink && root.nodeType === 1 && root.tagName.toLowerCase() === "a" && root.getAttribute("href") === content) { return true; } var children = root.childNodes; for (i = 0; i < children.length; i++) { if (findDOMText(children[i], content, asLink)) { return true; } } return false; } } /** * Patches ProjectManager.getAllFiles() in the given test window (for just the current it() block) so that it * includes one extra file in its results. The file need not actually exist on disk. * @param {!Window} testWindow Brackets popup window * @param {string} extraFilePath Absolute path for the extra result file */ function injectIntoGetAllFiles(testWindow, extraFilePath) { var ProjectManager = testWindow.brackets.test.ProjectManager, FileSystem = testWindow.brackets.test.FileSystem, origGetAllFiles = ProjectManager.getAllFiles; spyOn(ProjectManager, "getAllFiles").andCallFake(function () { var testResult = new testWindow.$.Deferred(); origGetAllFiles.apply(ProjectManager, arguments).done(function (result) { var dummyFile = FileSystem.getFileForPath(extraFilePath); var newResult = result.concat([dummyFile]); testResult.resolve(newResult); }).fail(function (error) { testResult.reject(error); }); return testResult; }); } /** * Counts the number of active specs in the current suite. Includes all * descendants. * @param {(jasmine.Suite|jasmine.Spec)} suiteOrSpec * @return {number} */ function countSpecs(suiteOrSpec) { var children = suiteOrSpec.children && typeof suiteOrSpec.children === "function" && suiteOrSpec.children(); if (Array.isArray(children)) { var childCount = 0; children.forEach(function (child) { childCount += countSpecs(child); }); return childCount; } if (jasmine.getEnv().specFilter(suiteOrSpec)) { return 1; } return 0; } /** * @private * Adds a new before all or after all function to the current suite. If requires it creates a new * object to store the before all and after all functions and a spec counter for the current suite. * @param {string} type "beforeFirst" or "afterLast" * @param {function} func The function to store */ function _addSuiteFunction(type, func) { var suiteId = (jasmine.getEnv().currentSuite || _rootSuite).id; if (!_testSuites[suiteId]) { _testSuites[suiteId] = { beforeFirst : [], afterLast : [], specCounter : null }; } _testSuites[suiteId][type].push(func); } /** * Utility for tests that need to open a window or do something before every test in a suite * @param {function} func */ window.beforeFirst = function (func) { _addSuiteFunction("beforeFirst", func); }; /** * Utility for tests that need to close a window or do something after every test in a suite * @param {function} func */ window.afterLast = function (func) { _addSuiteFunction("afterLast", func); }; /** * @private * Returns an array with the parent suites of the current spec with the top most suite last * @return {Array.<jasmine.Suite>} */ function _getParentSuites() { var suite = jasmine.getEnv().currentSpec.suite, suites = []; while (suite) { suites.push(suite); suite = suite.parentSuite; } return suites; } /** * @private * Calls each function in the given array of functions * @param {Array.<function>} functions */ function _callFunctions(functions) { var spec = jasmine.getEnv().currentSpec; functions.forEach(function (func) { func.apply(spec); }); } /** * Calls the before first functions for the parent suites of the current spec when is the first spec of the suite. */ function runBeforeFirst() { var suites = _getParentSuites().reverse(); // SpecRunner-scoped beforeFirst if (_testSuites[_rootSuite.id].beforeFirst) { _callFunctions(_testSuites[_rootSuite.id].beforeFirst); _testSuites[_rootSuite.id].beforeFirst = null; } // Iterate through all the parent suites of the current spec suites.forEach(function (suite) { // If we have functions for this suite and it was never called, initialize the spec counter if (_testSuites[suite.id] && _testSuites[suite.id].specCounter === null) { _callFunctions(_testSuites[suite.id].beforeFirst); _testSuites[suite.id].specCounter = countSpecs(suite); } }); } /** * @private * @return {boolean} True if the current spect is the last spec to be run */ function _isLastSpec() { return _unitTestReporter.activeSpecCompleteCount === _unitTestReporter.activeSpecCount - 1; } /** * Calls the after last functions for the parent suites of the current spec when is the last spec of the suite. */ function runAfterLast() { var suites = _getParentSuites(); // Iterate throught all the parent suites of the current spec suites.forEach(function (suite) { // If we have functions for this suite, reduce the spec counter if (_testSuites[suite.id] && _testSuites[suite.id].specCounter > 0) { _testSuites[suite.id].specCounter--; // If this was the last spec of the suite run the after last functions and remove it if (_testSuites[suite.id].specCounter === 0) { _callFunctions(_testSuites[suite.id].afterLast); delete _testSuites[suite.id]; } } }); // SpecRunner-scoped afterLast if (_testSuites[_rootSuite.id].afterLast && _isLastSpec()) { _callFunctions(_testSuites[_rootSuite.id].afterLast); _testSuites[_rootSuite.id].afterLast = null; } } // "global" custom matchers beforeEach(function () { this.addMatchers({ /** * Expects the given editor's selection to be a cursor at the given position (no range selected) */ toHaveCursorPosition: function (line, ch) { var editor = this.actual; var selection = editor.getSelection(); var notString = this.isNot ? "not " : ""; var start = selection.start; var end = selection.end; var selectionMoreThanOneCharacter = start.line !== end.line || start.ch !== end.ch; this.message = function () { var message = "Expected the cursor to " + notString + "be at (" + line + ", " + ch + ") but it was actually at (" + start.line + ", " + start.ch + ")"; if (!this.isNot && selectionMoreThanOneCharacter) { message += " and more than one character was selected."; } return message; }; var positionsMatch = start.line === line && start.ch === ch; // when adding the not operator, it's confusing to check both the size of the // selection and the position. We just check the position in that case. if (this.isNot) { return positionsMatch; } else { return !selectionMoreThanOneCharacter && positionsMatch; } } }); }); function setUnitTestReporter(reporter) { _unitTestReporter = reporter; } exports.TEST_PREFERENCES_KEY = TEST_PREFERENCES_KEY; exports.EDITOR_USE_TABS = EDITOR_USE_TABS; exports.EDITOR_SPACE_UNITS = EDITOR_SPACE_UNITS; exports.chmod = chmod; exports.remove = remove; exports.copy = copy; exports.rename = rename; exports.getTestRoot = getTestRoot; exports.getTestPath = getTestPath; exports.getTempDirectory = getTempDirectory; exports.createTempDirectory = createTempDirectory; exports.getBracketsSourceRoot = getBracketsSourceRoot; exports.makeAbsolute = makeAbsolute; exports.resolveNativeFileSystemPath = resolveNativeFileSystemPath; exports.createEditorInstance = createEditorInstance; exports.createMockDocument = createMockDocument; exports.createMockActiveDocument = createMockActiveDocument; exports.createMockElement = createMockElement; exports.createMockEditorForDocument = createMockEditorForDocument; exports.createMockEditor = createMockEditor; exports.createMockPane = createMockPane; exports.createTestWindowAndRun = createTestWindowAndRun; exports.closeTestWindow = closeTestWindow; exports.clickDialogButton = clickDialogButton; exports.destroyMockEditor = destroyMockEditor; exports.loadProjectInTestWindow = loadProjectInTestWindow; exports.openProjectFiles = openProjectFiles; exports.toggleQuickEditAtOffset = toggleQuickEditAtOffset; exports.createTextFile = createTextFile; exports.copyDirectoryEntry = copyDirectoryEntry; exports.copyFileEntry = copyFileEntry; exports.copyPath = copyPath; exports.deletePath = deletePath; exports.getTestWindow = getTestWindow; exports.simulateKeyEvent = simulateKeyEvent; exports.setLoadExtensionsInTestWindow = setLoadExtensionsInTestWindow; exports.getResultMessage = getResultMessage; exports.parseOffsetsFromText = parseOffsetsFromText; exports.findDOMText = findDOMText; exports.injectIntoGetAllFiles = injectIntoGetAllFiles; exports.countSpecs = countSpecs; exports.runBeforeFirst = runBeforeFirst; exports.runAfterLast = runAfterLast; exports.removeTempDirectory = removeTempDirectory; exports.setUnitTestReporter = setUnitTestReporter; exports.resizeEditor = resizeEditor; });
'use strict'; const common = require('../common'); const stream = require('stream'); const assert = require('assert'); // A consumer stream with a very low highWaterMark, which starts in a state // where it buffers the chunk it receives rather than indicating that they // have been consumed. const writable = new stream.Writable({ highWaterMark: 5 }); let isCurrentlyBufferingWrites = true; const queue = []; writable._write = (chunk, encoding, cb) => { if (isCurrentlyBufferingWrites) queue.push({ chunk, cb }); else cb(); }; const readable = new stream.Readable({ read() {} }); readable.pipe(writable); readable.once('pause', common.mustCall(() => { assert.strictEqual( readable._readableState.awaitDrainWriters, writable, 'Expected awaitDrainWriters to be a Writable but instead got ' + `${readable._readableState.awaitDrainWriters}` ); // First pause, resume manually. The next write() to writable will still // return false, because chunks are still being buffered, so it will increase // the awaitDrain counter again. process.nextTick(common.mustCall(() => { readable.resume(); })); readable.once('pause', common.mustCall(() => { assert.strictEqual( readable._readableState.awaitDrainWriters, writable, '.resume() should not reset the awaitDrainWriters, but instead got ' + `${readable._readableState.awaitDrainWriters}` ); // Second pause, handle all chunks from now on. Once all callbacks that // are currently queued up are handled, the awaitDrain drain counter should // fall back to 0 and all chunks that are pending on the readable side // should be flushed. isCurrentlyBufferingWrites = false; for (const queued of queue) queued.cb(); })); })); readable.push(Buffer.alloc(100)); // Fill the writable HWM, first 'pause'. readable.push(Buffer.alloc(100)); // Second 'pause'. readable.push(Buffer.alloc(100)); // Should get through to the writable. readable.push(null); writable.on('finish', common.mustCall(() => { assert.strictEqual( readable._readableState.awaitDrainWriters, null, `awaitDrainWriters should be reset to null after all chunks are written but instead got ${readable._readableState.awaitDrainWriters}` ); // Everything okay, all chunks were written. }));
/* eslint no-unused-vars: 0 */ "use strict"; exports.__esModule = true; // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _types = require("../../../types"); var t = _interopRequireWildcard(_types); var metadata = { group: "builtin-pre" }; exports.metadata = metadata; /** * [Please add a description.] */ function isString(node) { return t.isLiteral(node) && typeof node.value === "string"; } /** * [Please add a description.] */ function buildBinaryExpression(left, right) { var node = t.binaryExpression("+", left, right); node._templateLiteralProduced = true; return node; } /** * [Please add a description.] */ function crawl(path) { if (path.is("_templateLiteralProduced")) { crawl(path.get("left")); crawl(path.get("right")); } else if (!path.isBaseType("string") && !path.isBaseType("number")) { path.replaceWith(t.callExpression(t.identifier("String"), [path.node])); } } /** * [Please add a description.] */ var visitor = { /** * [Please add a description.] */ TaggedTemplateExpression: function TaggedTemplateExpression(node, parent, scope, file) { var quasi = node.quasi; var args = []; var strings = []; var raw = []; var _arr = quasi.quasis; for (var _i = 0; _i < _arr.length; _i++) { var elem = _arr[_i]; strings.push(t.literal(elem.value.cooked)); raw.push(t.literal(elem.value.raw)); } strings = t.arrayExpression(strings); raw = t.arrayExpression(raw); var templateName = "tagged-template-literal"; if (file.isLoose("es6.templateLiterals")) templateName += "-loose"; args.push(t.callExpression(file.addHelper(templateName), [strings, raw])); args = args.concat(quasi.expressions); return t.callExpression(node.tag, args); }, /** * [Please add a description.] */ TemplateLiteral: function TemplateLiteral(node, parent, scope, file) { var nodes = []; var _arr2 = node.quasis; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var elem = _arr2[_i2]; nodes.push(t.literal(elem.value.cooked)); var expr = node.expressions.shift(); if (expr) nodes.push(expr); } // filter out empty string literals nodes = nodes.filter(function (n) { return !t.isLiteral(n, { value: "" }); }); // since `+` is left-to-right associative // ensure the first node is a string if first/second isn't if (!isString(nodes[0]) && !isString(nodes[1])) { nodes.unshift(t.literal("")); } if (nodes.length > 1) { var root = buildBinaryExpression(nodes.shift(), nodes.shift()); var _arr3 = nodes; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var _node = _arr3[_i3]; root = buildBinaryExpression(root, _node); } this.replaceWith(root); //crawl(this); } else { return nodes[0]; } } }; exports.visitor = visitor;
/** * @license Angular v2.4.4 * (c) 2010-2016 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/http'), require('rxjs/ReplaySubject'), require('rxjs/Subject'), require('rxjs/operator/take')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/http', 'rxjs/ReplaySubject', 'rxjs/Subject', 'rxjs/operator/take'], factory) : (factory((global.ng = global.ng || {}, global.ng.http = global.ng.http || {}, global.ng.http.testing = global.ng.http.testing || {}),global.ng.core,global.ng.http,global.Rx,global.Rx,global.Rx.Observable.prototype)); }(this, function (exports,_angular_core,_angular_http,rxjs_ReplaySubject,rxjs_Subject,rxjs_operator_take) { 'use strict'; /** * * Mock Connection to represent a {@link Connection} for tests. * * @experimental */ var MockConnection = (function () { function MockConnection(req) { this.response = rxjs_operator_take.take.call(new rxjs_ReplaySubject.ReplaySubject(1), 1); this.readyState = _angular_http.ReadyState.Open; this.request = req; } /** * Sends a mock response to the connection. This response is the value that is emitted to the * {@link EventEmitter} returned by {@link Http}. * * ### Example * * ``` * var connection; * backend.connections.subscribe(c => connection = c); * http.request('data.json').subscribe(res => console.log(res.text())); * connection.mockRespond(new Response(new ResponseOptions({ body: 'fake response' }))); //logs * 'fake response' * ``` * */ MockConnection.prototype.mockRespond = function (res) { if (this.readyState === _angular_http.ReadyState.Done || this.readyState === _angular_http.ReadyState.Cancelled) { throw new Error('Connection has already been resolved'); } this.readyState = _angular_http.ReadyState.Done; this.response.next(res); this.response.complete(); }; /** * Not yet implemented! * * Sends the provided {@link Response} to the `downloadObserver` of the `Request` * associated with this connection. */ MockConnection.prototype.mockDownload = function (res) { // this.request.downloadObserver.onNext(res); // if (res.bytesLoaded === res.totalBytes) { // this.request.downloadObserver.onCompleted(); // } }; // TODO(jeffbcross): consider using Response type /** * Emits the provided error object as an error to the {@link Response} {@link EventEmitter} * returned * from {@link Http}. * * ### Example * * ``` * var connection; * backend.connections.subscribe(c => connection = c); * http.request('data.json').subscribe(res => res, err => console.log(err))); * connection.mockError(new Error('error')); * ``` * */ MockConnection.prototype.mockError = function (err) { // Matches ResourceLoader semantics this.readyState = _angular_http.ReadyState.Done; this.response.error(err); }; return MockConnection; }()); /** * A mock backend for testing the {@link Http} service. * * This class can be injected in tests, and should be used to override providers * to other backends, such as {@link XHRBackend}. * * ### Example * * ``` * import {Injectable, ReflectiveInjector} from '@angular/core'; * import {async, fakeAsync, tick} from '@angular/core/testing'; * import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http'; * import {Response, ResponseOptions} from '@angular/http'; * import {MockBackend, MockConnection} from '@angular/http/testing'; * * const HERO_ONE = 'HeroNrOne'; * const HERO_TWO = 'WillBeAlwaysTheSecond'; * * @Injectable() * class HeroService { * constructor(private http: Http) {} * * getHeroes(): Promise<String[]> { * return this.http.get('myservices.de/api/heroes') * .toPromise() * .then(response => response.json().data) * .catch(e => this.handleError(e)); * } * * private handleError(error: any): Promise<any> { * console.error('An error occurred', error); * return Promise.reject(error.message || error); * } * } * * describe('MockBackend HeroService Example', () => { * beforeEach(() => { * this.injector = ReflectiveInjector.resolveAndCreate([ * {provide: ConnectionBackend, useClass: MockBackend}, * {provide: RequestOptions, useClass: BaseRequestOptions}, * Http, * HeroService, * ]); * this.heroService = this.injector.get(HeroService); * this.backend = this.injector.get(ConnectionBackend) as MockBackend; * this.backend.connections.subscribe((connection: any) => this.lastConnection = connection); * }); * * it('getHeroes() should query current service url', () => { * this.heroService.getHeroes(); * expect(this.lastConnection).toBeDefined('no http service connection at all?'); * expect(this.lastConnection.request.url).toMatch(/api\/heroes$/, 'url invalid'); * }); * * it('getHeroes() should return some heroes', fakeAsync(() => { * let result: String[]; * this.heroService.getHeroes().then((heroes: String[]) => result = heroes); * this.lastConnection.mockRespond(new Response(new ResponseOptions({ * body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}), * }))); * tick(); * expect(result.length).toEqual(2, 'should contain given amount of heroes'); * expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero'); * expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero'); * })); * * it('getHeroes() while server is down', fakeAsync(() => { * let result: String[]; * let catchedError: any; * this.heroService.getHeroes() * .then((heroes: String[]) => result = heroes) * .catch((error: any) => catchedError = error); * this.lastConnection.mockRespond(new Response(new ResponseOptions({ * status: 404, * statusText: 'URL not Found', * }))); * tick(); * expect(result).toBeUndefined(); * expect(catchedError).toBeDefined(); * })); * }); * ``` * * This method only exists in the mock implementation, not in real Backends. * * @experimental */ var MockBackend = (function () { function MockBackend() { var _this = this; this.connectionsArray = []; this.connections = new rxjs_Subject.Subject(); this.connections.subscribe(function (connection) { return _this.connectionsArray.push(connection); }); this.pendingConnections = new rxjs_Subject.Subject(); } /** * Checks all connections, and raises an exception if any connection has not received a response. * * This method only exists in the mock implementation, not in real Backends. */ MockBackend.prototype.verifyNoPendingRequests = function () { var pending = 0; this.pendingConnections.subscribe(function (c) { return pending++; }); if (pending > 0) throw new Error(pending + " pending connections to be resolved"); }; /** * Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve * connections, if it's expected that there are connections that have not yet received a response. * * This method only exists in the mock implementation, not in real Backends. */ MockBackend.prototype.resolveAllConnections = function () { this.connections.subscribe(function (c) { return c.readyState = 4; }); }; /** * Creates a new {@link MockConnection}. This is equivalent to calling `new * MockConnection()`, except that it also will emit the new `Connection` to the `connections` * emitter of this `MockBackend` instance. This method will usually only be used by tests * against the framework itself, not by end-users. */ MockBackend.prototype.createConnection = function (req) { if (!req || !(req instanceof _angular_http.Request)) { throw new Error("createConnection requires an instance of Request, got " + req); } var connection = new MockConnection(req); this.connections.next(connection); return connection; }; MockBackend.decorators = [ { type: _angular_core.Injectable }, ]; /** @nocollapse */ MockBackend.ctorParameters = function () { return []; }; return MockBackend; }()); exports.MockConnection = MockConnection; exports.MockBackend = MockBackend; }));
define("aaa", function(){ return "<p>aaa模块已加载</p>" })
/** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ var fs = require( 'fs' ); THREE = require( '../build/three.js' ); var srcFolder = __dirname + '/../examples/js/'; var dstFolder = __dirname + '/../examples/jsm/'; var files = [ { path: 'animation/AnimationClipCreator.js', dependencies: [], ignoreList: [] }, { path: 'animation/CCDIKSolver.js', dependencies: [], ignoreList: [ 'SkinnedMesh' ] }, { path: 'animation/MMDAnimationHelper.js', dependencies: [ { name: 'CCDIKSolver', path: 'animation/CCDIKSolver.js' }, { name: 'MMDPhysics', path: 'animation/MMDPhysics.js' } ], ignoreList: [ 'AnimationClip', 'Audio', 'Camera', 'SkinnedMesh' ] }, { path: 'animation/MMDPhysics.js', dependencies: [], ignoreList: [ 'SkinnedMesh' ] }, { path: 'animation/TimelinerController.js', dependencies: [], ignoreList: [] }, { path: 'cameras/CinematicCamera.js', dependencies: [ { name: 'BokehShader', path: 'shaders/BokehShader2.js' }, { name: 'BokehDepthShader', path: 'shaders/BokehShader2.js' } ], ignoreList: [] }, { path: 'controls/DragControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/DeviceOrientationControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/FirstPersonControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/FlyControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/OrbitControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/PointerLockControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/TrackballControls.js', dependencies: [], ignoreList: [] }, { path: 'controls/TransformControls.js', dependencies: [], ignoreList: [] }, { path: 'curves/CurveExtras.js', dependencies: [], ignoreList: [] }, { path: 'curves/NURBSCurve.js', dependencies: [ { name: 'NURBSUtils', path: 'curves/NURBSUtils.js' } ], ignoreList: [] }, { path: 'curves/NURBSSurface.js', dependencies: [ { name: 'NURBSUtils', path: 'curves/NURBSUtils.js' } ], ignoreList: [] }, { path: 'curves/NURBSUtils.js', dependencies: [], ignoreList: [] }, { path: 'effects/AnaglyphEffect.js', dependencies: [], ignoreList: [] }, { path: 'effects/AsciiEffect.js', dependencies: [], ignoreList: [] }, { path: 'effects/OutlineEffect.js', dependencies: [], ignoreList: [] }, { path: 'effects/ParallaxBarrierEffect.js', dependencies: [], ignoreList: [] }, { path: 'effects/PeppersGhostEffect.js', dependencies: [], ignoreList: [] }, { path: 'effects/StereoEffect.js', dependencies: [], ignoreList: [] }, { path: 'exporters/ColladaExporter.js', dependencies: [], ignoreList: [] }, { path: 'exporters/DRACOExporter.js', dependencies: [], ignoreList: [ 'Geometry' ] }, { path: 'exporters/GLTFExporter.js', dependencies: [], ignoreList: [ 'AnimationClip', 'Camera', 'Geometry', 'Material', 'Mesh', 'Object3D', 'RGBFormat', 'Scenes', 'ShaderMaterial' ] }, { path: 'exporters/MMDExporter.js', dependencies: [ { name: 'MMDParser', path: 'libs/mmdparser.module.js' } ], ignoreList: [] }, { path: 'exporters/OBJExporter.js', dependencies: [], ignoreList: [] }, { path: 'exporters/PLYExporter.js', dependencies: [], ignoreList: [] }, { path: 'exporters/STLExporter.js', dependencies: [], ignoreList: [] }, { path: 'exporters/TypedGeometryExporter.js', dependencies: [], ignoreList: [] }, { path: 'geometries/BoxLineGeometry.js', dependencies: [], ignoreList: [] }, { path: 'geometries/ConvexGeometry.js', dependencies: [ { name: 'ConvexHull', path: 'math/ConvexHull.js' } ], ignoreList: [] }, { path: 'geometries/DecalGeometry.js', dependencies: [], ignoreList: [] }, { path: 'geometries/LightningStrike.js', dependencies: [ { name: 'SimplexNoise', path: 'math/SimplexNoise.js' } ], ignoreList: [ 'Mesh' ] }, { path: 'geometries/ParametricGeometries.js', dependencies: [], ignoreList: [] }, { path: 'geometries/TeapotBufferGeometry.js', dependencies: [], ignoreList: [] }, { path: 'interactive/SelectionBox.js', dependencies: [], ignoreList: [] }, { path: 'interactive/SelectionHelper.js', dependencies: [], ignoreList: [] }, { path: 'lights/LightProbeGenerator.js', dependencies: [], ignoreList: [] }, { path: 'lights/RectAreaLightUniformsLib.js', dependencies: [], ignoreList: [] }, { path: 'lines/Line2.js', dependencies: [ { name: 'LineSegments2', path: 'lines/LineSegments2.js' }, { name: 'LineGeometry', path: 'lines/LineGeometry.js' }, { name: 'LineMaterial', path: 'lines/LineMaterial.js' } ], ignoreList: [] }, { path: 'lines/LineGeometry.js', dependencies: [ { name: 'LineSegmentsGeometry', path: 'lines/LineSegmentsGeometry.js' } ], ignoreList: [] }, { path: 'lines/LineMaterial.js', dependencies: [], ignoreList: [] }, { path: 'lines/LineSegments2.js', dependencies: [ { name: 'LineSegmentsGeometry', path: 'lines/LineSegmentsGeometry.js' }, { name: 'LineMaterial', path: 'lines/LineMaterial.js' } ], ignoreList: [] }, { path: 'lines/LineSegmentsGeometry.js', dependencies: [], ignoreList: [] }, { path: 'lines/Wireframe.js', dependencies: [ { name: 'LineSegmentsGeometry', path: 'lines/LineSegmentsGeometry.js' }, { name: 'LineMaterial', path: 'lines/LineMaterial.js' } ], ignoreList: [] }, { path: 'lines/WireframeGeometry2.js', dependencies: [ { name: 'LineSegmentsGeometry', path: 'lines/LineSegmentsGeometry.js' } ], ignoreList: [] }, { path: 'loaders/3MFLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/AMFLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/AssimpLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/BasisTextureLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/BVHLoader.js', dependencies: [], ignoreList: [ 'Bones' ] }, { path: 'loaders/ColladaLoader.js', dependencies: [ { name: 'TGALoader', path: 'loaders/TGALoader.js' } ], ignoreList: [] }, { path: 'loaders/DDSLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/DRACOLoader.js', dependencies: [], ignoreList: [ 'LoadingManager' ] }, { path: 'loaders/EXRLoader.js', dependencies: [ { name: 'Zlib', path: 'libs/inflate.module.min.js' } ], ignoreList: [] }, { path: 'loaders/FBXLoader.js', dependencies: [ { name: 'Zlib', path: 'libs/inflate.module.min.js' }, { name: 'NURBSCurve', path: 'curves/NURBSCurve.js' } ], ignoreList: [] }, { path: 'loaders/GCodeLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/GLTFLoader.js', dependencies: [], ignoreList: [ 'NoSide', 'Matrix2', 'Camera', 'Texture' ] }, { path: 'loaders/HDRCubeTextureLoader.js', dependencies: [ { name: 'RGBELoader', path: 'loaders/RGBELoader.js' } ], ignoreList: [] }, { path: 'loaders/KMZLoader.js', dependencies: [ { name: 'ColladaLoader', path: 'loaders/ColladaLoader.js' } ], ignoreList: [] }, { path: 'loaders/LDrawLoader.js', dependencies: [], ignoreList: [ 'Cache', 'Material', 'Object3D' ] }, { path: 'loaders/LWOLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/KTXLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/MD2Loader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/MMDLoader.js', dependencies: [ { name: 'TGALoader', path: 'loaders/TGALoader.js' }, { name: 'MMDParser', path: 'libs/mmdparser.module.js' } ], ignoreList: [ 'Camera', 'LoadingManager' ] }, { path: 'loaders/MTLLoader.js', dependencies: [], ignoreList: [ 'BackSide', 'DoubleSide', 'ClampToEdgeWrapping', 'MirroredRepeatWrapping' ] }, { path: 'loaders/NRRDLoader.js', dependencies: [ { name: 'Zlib', path: 'libs/gunzip.module.min.js' }, { name: 'Volume', path: 'misc/Volume.js' } ], ignoreList: [] }, { path: 'loaders/OBJLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/PCDLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/PDBLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/PLYLoader.js', dependencies: [], ignoreList: [ 'Mesh' ] }, { path: 'loaders/PRWMLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/PVRLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/RGBELoader.js', dependencies: [], ignoreList: [ 'RGBAFormat' ] }, { path: 'loaders/STLLoader.js', dependencies: [], ignoreList: [ 'Mesh', 'MeshPhongMaterial' ] }, { path: 'loaders/SVGLoader.js', dependencies: [], ignoreList: [ 'Color' ] }, { path: 'loaders/TDSLoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/TGALoader.js', dependencies: [], ignoreList: [] }, { path: 'loaders/TTFLoader.js', dependencies: [], ignoreList: [ 'Font' ] }, { path: 'loaders/VRMLLoader.js', dependencies: [ { name: 'chevrotain', path: 'libs/chevrotain.module.min.js' } ], ignoreList: [] }, { path: 'loaders/VRMLoader.js', dependencies: [ { name: 'GLTFLoader', path: 'loaders/GLTFLoader.js' } ], ignoreList: [] }, { path: 'loaders/VTKLoader.js', dependencies: [ { name: 'Zlib', path: 'libs/inflate.module.min.js' } ], ignoreList: [] }, { path: 'loaders/XLoader.js', dependencies: [], ignoreList: [] }, { path: 'math/ColorConverter.js', dependencies: [], ignoreList: [] }, { path: 'math/ConvexHull.js', dependencies: [], ignoreList: [] }, { path: 'math/ImprovedNoise.js', dependencies: [], ignoreList: [] }, { path: 'math/Lut.js', dependencies: [], ignoreList: [] }, { path: 'math/SimplexNoise.js', dependencies: [], ignoreList: [] }, { path: 'misc/ConvexObjectBreaker.js', dependencies: [ { name: 'ConvexBufferGeometry', path: 'geometries/ConvexGeometry.js' } ], ignoreList: [ 'Matrix4' ] }, { path: 'misc/GPUComputationRenderer.js', dependencies: [], ignoreList: [] }, { path: 'misc/Gyroscope.js', dependencies: [], ignoreList: [] }, { path: 'misc/MD2Character.js', dependencies: [ { name: 'MD2Loader', path: 'loaders/MD2Loader.js' } ], ignoreList: [] }, { path: 'misc/MD2CharacterComplex.js', dependencies: [ { name: 'MD2Loader', path: 'loaders/MD2Loader.js' }, { name: 'MorphBlendMesh', path: 'misc/MorphBlendMesh.js' } ], ignoreList: [] }, { path: 'misc/MorphAnimMesh.js', dependencies: [], ignoreList: [] }, { path: 'misc/MorphBlendMesh.js', dependencies: [], ignoreList: [] }, { path: 'misc/Ocean.js', dependencies: [ { name: 'OceanShaders', path: 'shaders/OceanShaders.js' } ], ignoreList: [] }, { path: 'misc/RollerCoaster.js', dependencies: [], ignoreList: [] }, { path: 'misc/Volume.js', dependencies: [ { name: 'VolumeSlice', path: 'misc/VolumeSlice.js' } ], ignoreList: [] }, { path: 'misc/VolumeSlice.js', dependencies: [], ignoreList: [] }, { path: 'modifiers/ExplodeModifier.js', dependencies: [], ignoreList: [] }, { path: 'modifiers/SimplifyModifier.js', dependencies: [], ignoreList: [] }, { path: 'modifiers/SubdivisionModifier.js', dependencies: [], ignoreList: [] }, { path: 'modifiers/TessellateModifier.js', dependencies: [], ignoreList: [] }, { path: 'objects/Fire.js', dependencies: [], ignoreList: [] }, { path: 'objects/Lensflare.js', dependencies: [], ignoreList: [] }, { path: 'objects/LightningStorm.js', dependencies: [ { name: 'LightningStrike', path: 'geometries/LightningStrike.js' } ], ignoreList: [ 'Material' ] }, { path: 'objects/MarchingCubes.js', dependencies: [], ignoreList: [] }, { path: 'objects/Reflector.js', dependencies: [], ignoreList: [] }, { path: 'objects/Refractor.js', dependencies: [], ignoreList: [] }, { path: 'objects/ReflectorRTT.js', dependencies: [ { name: 'Reflector', path: 'objects/Reflector.js' } ], ignoreList: [] }, { path: 'objects/ShadowMesh.js', dependencies: [], ignoreList: [] }, { path: 'objects/Sky.js', dependencies: [], ignoreList: [] }, { path: 'objects/Water.js', dependencies: [], ignoreList: [] }, { path: 'objects/Water2.js', dependencies: [ { name: 'Reflector', path: 'objects/Reflector.js' }, { name: 'Refractor', path: 'objects/Refractor.js' } ], ignoreList: [] }, { path: 'postprocessing/AdaptiveToneMappingPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' }, { name: 'LuminosityShader', path: 'shaders/LuminosityShader.js' }, { name: 'ToneMapShader', path: 'shaders/ToneMapShader.js' } ], ignoreList: [] }, { path: 'postprocessing/AfterimagePass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'AfterimageShader', path: 'shaders/AfterimageShader.js' } ], ignoreList: [] }, { path: 'postprocessing/BloomPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' }, { name: 'ConvolutionShader', path: 'shaders/ConvolutionShader.js' } ], ignoreList: [] }, { path: 'postprocessing/BokehPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'BokehShader', path: 'shaders/BokehShader.js' } ], ignoreList: [] }, { path: 'postprocessing/ClearPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' } ], ignoreList: [] }, { path: 'postprocessing/CubeTexturePass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' } ], ignoreList: [] }, { path: 'postprocessing/DotScreenPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'DotScreenShader', path: 'shaders/DotScreenShader.js' } ], ignoreList: [] }, { path: 'postprocessing/EffectComposer.js', dependencies: [ { name: 'CopyShader', path: 'shaders/CopyShader.js' }, { name: 'ShaderPass', path: 'postprocessing/ShaderPass.js' }, { name: 'MaskPass', path: 'postprocessing/MaskPass.js' }, { name: 'ClearMaskPass', path: 'postprocessing/MaskPass.js' } ], ignoreList: [] }, { path: 'postprocessing/FilmPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'FilmShader', path: 'shaders/FilmShader.js' } ], ignoreList: [] }, { path: 'postprocessing/GlitchPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'DigitalGlitch', path: 'shaders/DigitalGlitch.js' } ], ignoreList: [] }, { path: 'postprocessing/HalftonePass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'HalftoneShader', path: 'shaders/HalftoneShader.js' } ], ignoreList: [] }, { path: 'postprocessing/MaskPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' } ], ignoreList: [] }, { path: 'postprocessing/OutlinePass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' } ], ignoreList: [] }, { path: 'postprocessing/RenderPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' } ], ignoreList: [] }, { path: 'postprocessing/SAOPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'SAOShader', path: 'shaders/SAOShader.js' }, { name: 'DepthLimitedBlurShader', path: 'shaders/DepthLimitedBlurShader.js' }, { name: 'BlurShaderUtils', path: 'shaders/DepthLimitedBlurShader.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' }, { name: 'UnpackDepthRGBAShader', path: 'shaders/UnpackDepthRGBAShader.js' } ], ignoreList: [] }, { path: 'postprocessing/SavePass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' } ], ignoreList: [] }, { path: 'postprocessing/ShaderPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' } ], ignoreList: [] }, { path: 'postprocessing/SMAAPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'SMAAEdgesShader', path: 'shaders/SMAAShader.js' }, { name: 'SMAAWeightsShader', path: 'shaders/SMAAShader.js' }, { name: 'SMAABlendShader', path: 'shaders/SMAAShader.js' } ], ignoreList: [] }, { path: 'postprocessing/SSAARenderPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' } ], ignoreList: [] }, { path: 'postprocessing/SSAOPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'SimplexNoise', path: 'math/SimplexNoise.js' }, { name: 'SSAOShader', path: 'shaders/SSAOShader.js' }, { name: 'SSAOBlurShader', path: 'shaders/SSAOShader.js' }, { name: 'SSAODepthShader', path: 'shaders/SSAOShader.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' } ], ignoreList: [] }, { path: 'postprocessing/TAARenderPass.js', dependencies: [ { name: 'SSAARenderPass', path: 'postprocessing/SSAARenderPass.js' } ], ignoreList: [] }, { path: 'postprocessing/TexturePass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' } ], ignoreList: [] }, { path: 'postprocessing/UnrealBloomPass.js', dependencies: [ { name: 'Pass', path: 'postprocessing/Pass.js' }, { name: 'CopyShader', path: 'shaders/CopyShader.js' }, { name: 'LuminosityHighPassShader', path: 'shaders/LuminosityHighPassShader.js' } ], ignoreList: [] }, { path: 'renderers/CSS2DRenderer.js', dependencies: [], ignoreList: [] }, { path: 'renderers/CSS3DRenderer.js', dependencies: [], ignoreList: [] }, { path: 'renderers/Projector.js', dependencies: [], ignoreList: [] }, { path: 'renderers/SVGRenderer.js', dependencies: [ { name: 'Projector', path: 'renderers/Projector.js' }, { name: 'RenderableFace', path: 'renderers/Projector.js' }, { name: 'RenderableLine', path: 'renderers/Projector.js' }, { name: 'RenderableSprite', path: 'renderers/Projector.js' } ], ignoreList: [] }, { path: 'shaders/AfterimageShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/BasicShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/BleachBypassShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/BlendShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/BokehShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/BokehShader2.js', dependencies: [], ignoreList: [] }, { path: 'shaders/BrightnessContrastShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/ColorCorrectionShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/ColorifyShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/ConvolutionShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/CopyShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/DepthLimitedBlurShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/DigitalGlitch.js', dependencies: [], ignoreList: [] }, { path: 'shaders/DOFMipMapShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/DotScreenShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/FilmShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/FocusShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/FreiChenShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/FresnelShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/FXAAShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/GammaCorrectionShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/GodRaysShader.js', dependencies: [], ignoreList: [ 'MeshDepthMaterial' ] }, { path: 'shaders/HalftoneShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/HorizontalBlurShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/HorizontalTiltShiftShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/HueSaturationShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/KaleidoShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/LuminosityHighPassShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/LuminosityShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/MirrorShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/NormalMapShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/OceanShaders.js', dependencies: [], ignoreList: [] }, { path: 'shaders/ParallaxShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/PixelShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/RGBShiftShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/SAOShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/SepiaShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/SMAAShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/SobelOperatorShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/SSAOShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/TechnicolorShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/ToneMapShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/ToonShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/TranslucentShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/TriangleBlurShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/UnpackDepthRGBAShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/VerticalBlurShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/VerticalTiltShiftShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/VignetteShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/VolumeShader.js', dependencies: [], ignoreList: [] }, { path: 'shaders/WaterRefractionShader.js', dependencies: [], ignoreList: [] }, { path: 'utils/BufferGeometryUtils.js', dependencies: [], ignoreList: [] }, { path: 'utils/GeometryUtils.js', dependencies: [], ignoreList: [] }, { path: 'utils/SceneUtils.js', dependencies: [], ignoreList: [] }, { path: 'utils/ShadowMapViewer.js', dependencies: [ { name: 'UnpackDepthRGBAShader', path: 'shaders/UnpackDepthRGBAShader.js' } ], ignoreList: [] }, { path: 'utils/SkeletonUtils.js', dependencies: [], ignoreList: [] }, { path: 'utils/TypedArrayUtils.js', dependencies: [], ignoreList: [] }, { path: 'utils/UVsDebug.js', dependencies: [], ignoreList: [ 'SphereBufferGeometry' ] }, { path: 'WebGL.js', dependencies: [], ignoreList: [] }, ]; for ( var i = 0; i < files.length; i ++ ) { var file = files[ i ]; convert( file.path, file.dependencies, file.ignoreList ); } // function convert( path, exampleDependencies, ignoreList ) { var contents = fs.readFileSync( srcFolder + path, 'utf8' ); var classNames = []; var coreDependencies = {}; // imports contents = contents.replace( /^\/\*+[^*]*\*+(?:[^/*][^*]*\*+)*\//, function ( match ) { return `${match}\n\n_IMPORTS_`; } ); // class name contents = contents.replace( /THREE\.([a-zA-Z0-9]+) = /g, function ( match, p1 ) { classNames.push( p1 ); console.log( p1 ); return `var ${p1} = `; } ); contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9]+)(\.{0,1})/g, function ( match, p1, p2, p3 ) { if ( p1 === '\'' ) return match; // Inside a string if ( classNames.includes( p2 ) ) return `${p2}${p3}`; return match; } ); // methods contents = contents.replace( /new THREE\.([a-zA-Z0-9]+)\(/g, function ( match, p1 ) { if ( ignoreList.includes( p1 ) ) return match; if ( p1 in THREE ) coreDependencies[ p1 ] = true; return `new ${p1}(`; } ); // constants contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9_]+)/g, function ( match, p1, p2 ) { if ( ignoreList.includes( p2 ) ) return match; if ( p1 === '\'' ) return match; // Inside a string if ( classNames.includes( p2 ) ) return p2; if ( p2 in THREE ) coreDependencies[ p2 ] = true; // console.log( match, p2 ); return `${p2}`; } ); // var keys = Object.keys( coreDependencies ) .filter( value => ! classNames.includes( value ) ) .map( value => '\n\t' + value ) .sort() .toString(); var imports = ''; // compute path prefix for imports/exports var level = path.split( '/' ).length - 1; var pathPrefix = '../'.repeat( level ); // core imports if ( keys ) imports += `import {${keys}\n} from "${pathPrefix}../../build/three.module.js";`; // example imports for ( var dependency of exampleDependencies ) { imports += `\nimport { ${dependency.name} } from "${pathPrefix}${dependency.path}";`; } // exports var exports = `export { ${classNames.join( ", " )} };\n`; var output = contents.replace( '_IMPORTS_', imports ) + '\n' + exports; // console.log( output ); fs.writeFileSync( dstFolder + path, output, 'utf-8' ); }
/* eslint-env mocha, browser*/ /* global proclaim, it */ it('should have min safe integer defined', function() { proclaim.isDefined(Number.MIN_SAFE_INTEGER); }); it('should be correct value', function() { proclaim.equal(Number.MIN_SAFE_INTEGER, -Math.pow(2, 53) + 1); }); xit('should not be enumerable', function() { if (Number.propertyIsEnumerable) { proclaim.equal(Number.propertyIsEnumerable('MIN_SAFE_INTEGER'), false); } else { this.skip(); } });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.5.4.13_A3_T2; * @section: 15.5.4.13; * @assertion: String.prototype.slice (start, end) can be applied to object instances; * @description: Apply String.prototype.slice to Object instance, use other value for start and end values; */ __instance = new Object(); __instance.slice = String.prototype.slice; ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (__instance.slice(8,__instance.toString().length) !== "Object]") { $ERROR('#1: __instance = new Object(); __instance.slice = String.prototype.slice; __instance.slice(8,__instance.toString().length) === "Object]". Actual: '+__instance.slice(8,__instance.toString().length) ); } // //////////////////////////////////////////////////////////////////////////////
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dijit/layout/BorderContainer' ], function ( declare, lang, on, Topic, BorderContainer ) { return declare([BorderContainer], { baseClass: 'ViewerApp', state: null, apiServiceUrl: window.App.dataAPI, refresh: function () { }, postCreate: function () { this.inherited(arguments); on(this.domNode, 'UpdateHash', lang.hitch(this, 'onUpdateHash')); on(this.domNode, 'SetAnchor', lang.hitch(this, 'onSetAnchor')); // start watching for changes of state, and signal for the first time. this.watch('state', lang.hitch(this, 'onSetState')); }, onSetState: function (attr, oldVal, newVal) { }, onSetAnchor: function (evt) { }, _setStateAttr: function (state) { // console.log("Base _setStateAttr: ", state); this._set('state', state); }, onUpdateHash: function (evt) { // console.log("OnUpdateHash: ", evt); // console.log("Current State: ", this.state, " hash params: ", this.state.hashParams); if (!this.state) { this.state = {}; } if (!this.state.hashParams) { this.state.hashParams = {}; } if (evt.hashParams) { // console.log("EVT.hashParams: ", evt.hashParams); this.state.hashParams = evt.hashParams; } else if (evt.hashProperty == 'view_tab') { this.state.hashParams = { view_tab: evt.value }; } if (evt.hashProperty) { this.state.hashParams[evt.hashProperty] = evt.value; } var l = window.location.pathname + window.location.search + '#' + Object.keys(this.state.hashParams).map(function (key) { if (key && this.state.hashParams[key]) { return key + '=' + this.state.hashParams[key]; } return ''; }, this).filter(function (x) { return !!x; }).join('&'); // console.log("onUpdateHash. nav to: ", l); Topic.publish('/navigate', { href: l }); }, startup: function () { if (this._started) { return; } this.inherited(arguments); this.onSetState('state', '', this.state); } }); });
$.fn.DataTable.ext.pager.full_numbers_no_ellipses=function(e,r){function a(e,r){var a;void 0===r?(r=0,a=e):(a=r,r=e);for(var n=[],t=r;t<a;t++)n.push(t);return n}var n=[],t=$.fn.DataTable.ext.pager.numbers_length,l=Math.floor(t/2);return(n=r<=t?a(0,r):e<=l?a(0,t):r-1-l<=e?a(r-t,r):a(e-l,e+l+1)).DT_el="span",["first","previous",n,"next","last"]};
/*! * jQuery Transit - CSS3 transitions and transformations * Copyright(c) 2011 Rico Sta. Cruz <rico@ricostacruz.com> * MIT Licensed. * * http://ricostacruz.com/jquery.transit * http://github.com/rstacruz/jquery.transit */ (function($) { "use strict"; $.transit = { version: "0.1.2", // Map of $.css() keys to values for 'transitionProperty'. // See https://developer.mozilla.org/en/CSS/CSS_transitions#Properties_that_can_be_animated propertyMap: { marginLeft : 'margin', marginRight : 'margin', marginBottom : 'margin', marginTop : 'margin', paddingLeft : 'padding', paddingRight : 'padding', paddingBottom : 'padding', paddingTop : 'padding' }, // Will simply transition "instantly" if false enabled: true }; var div = document.createElement('div'); // Helper function to get the proper vendor property name. // (`transition` => `WebkitTransition`) function getVendorPropertyName(prop) { var prefixes = ['Moz', 'Webkit', 'O', 'ms']; var prop_ = prop.charAt(0).toUpperCase() + prop.substr(1); if (prop in div.style) { return prop; } for (var i=0; i<prefixes.length; ++i) { var vendorProp = prefixes[i] + prop_; if (vendorProp in div.style) { return vendorProp; } } } var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; // Check for the browser's transitions support. // You can access this in jQuery's `$.support.transition`. // As per [jQuery's cssHooks documentation](http://api.jquery.com/jQuery.cssHooks/), // we set $.support.transition to a string of the actual property name used. var support = { transition : getVendorPropertyName('transition'), transitionDelay : getVendorPropertyName('transitionDelay'), transform : getVendorPropertyName('transform'), transformOrigin : getVendorPropertyName('transformOrigin') }; $.extend($.support, support); var eventNames = { 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'WebkitTransition': 'webkitTransitionEnd', 'msTransition': 'MSTransitionEnd' }; // Detect the 'transitionend' event needed. var transitionEnd = eventNames[support.transition] || null; // Avoid memory leak in IE. div = null; // ## $.cssEase // List of easing aliases that you can use with `$.fn.transition`. $.cssEase = { '_default': 'ease', 'in': 'ease-in', 'out': 'ease-out', 'in-out': 'ease-in-out', 'snap': 'cubic-bezier(0,1,.5,1)' }; // ## 'transform' CSS hook // Allows you to use the `transform` property in CSS. // // $("#hello").css({ transform: "rotate(90deg)" }); // // $("#hello").css('transform'); // //=> { rotate: '90deg' } // $.cssHooks.transform = { // The getter returns a `Transform` object. get: function(elem) { return $(elem).data('transform'); }, // The setter accepts a `Transform` object or a string. set: function(elem, v) { var value = v; if (!(value instanceof Transform)) { value = new Transform(value); } // We've seen the 3D version of Scale() not work in Chrome when the // element being scaled extends outside of the viewport. Thus, we're // forcing Chrome to not use the 3d transforms as well. Not sure if // translate is affectede, but not risking it. Detection code from // http://davidwalsh.name/detecting-google-chrome-javascript if (support.transform === 'WebkitTransform' && !isChrome) { elem.style[support.transform] = value.toString(true); } else { elem.style[support.transform] = value.toString(); } $(elem).data('transform', value); } }; // ## 'transformOrigin' CSS hook // Allows the use for `transformOrigin` to define where scaling and rotation // is pivoted. // // $("#hello").css({ transformOrigin: '0 0' }); // $.cssHooks.transformOrigin = { get: function(elem) { return elem.style[support.transformOrigin]; }, set: function(elem, value) { elem.style[support.transformOrigin] = value; } }; // ## Other CSS hooks // Allows you to rotate, scale and translate. registerCssHook('scale'); registerCssHook('translate'); registerCssHook('rotate'); registerCssHook('rotateX'); registerCssHook('rotateY'); registerCssHook('rotate3d'); registerCssHook('perspective'); registerCssHook('skewX'); registerCssHook('skewY'); registerCssHook('x', true); registerCssHook('y', true); // ## Transform class // This is the main class of a transformation property that powers // `$.fn.css({ transform: '...' })`. // // This is, in essence, a dictionary object with key/values as `-transform` // properties. // // var t = new Transform("rotate(90) scale(4)"); // // t.rotate //=> "90deg" // t.scale //=> "4,4" // // Setters are accounted for. // // t.set('rotate', 4) // t.rotate //=> "4deg" // // Convert it to a CSS string using the `toString()` and `toString(true)` (for WebKit) // functions. // // t.toString() //=> "rotate(90deg) scale(4,4)" // t.toString(true) //=> "rotate(90deg) scale3d(4,4,0)" (WebKit version) // function Transform(str) { if (typeof str === 'string') { this.parse(str); } return this; } Transform.prototype = { // ### setFromString() // Sets a property from a string. // // t.setFromString('scale', '2,4'); // // Same as set('scale', '2', '4'); // setFromString: function(prop, val) { var args = (typeof val === 'string') ? val.split(',') : (val.constructor === Array) ? val : [ val ]; args.unshift(prop); Transform.prototype.set.apply(this, args); }, // ### set() // Sets a property. // // t.set('scale', 2, 4); // set: function(prop) { var args = Array.prototype.slice.apply(arguments, [1]); if (this.setter[prop]) { this.setter[prop].apply(this, args); } else { this[prop] = args.join(','); } }, get: function(prop) { if (this.getter[prop]) { return this.getter[prop].apply(this); } else { return this[prop] || 0; } }, setter: { // ### rotate // // .css({ rotate: 30 }) // .css({ rotate: "30" }) // .css({ rotate: "30deg" }) // .css({ rotate: "30deg" }) // rotate: function(theta) { this.rotate = unit(theta, 'deg'); }, rotateX: function(theta) { this.rotateX = unit(theta, 'deg'); }, rotateY: function(theta) { this.rotateY = unit(theta, 'deg'); }, // ### scale // // .css({ scale: 9 }) //=> "scale(9,9)" // .css({ scale: '3,2' }) //=> "scale(3,2)" // scale: function(x, y) { if (y === undefined) { y = x; } this.scale = x + "," + y; }, // ### skewX + skewY skewX: function(x) { this.skewX = unit(x, 'deg'); }, skewY: function(y) { this.skewY = unit(y, 'deg'); }, // ### perspectvie perspective: function(dist) { this.perspective = unit(dist, 'px'); }, // ### x / y // Translations. Notice how this keeps the other value. // // .css({ x: 4 }) //=> "translate(4px, 0)" // .css({ y: 10 }) //=> "translate(4px, 10px)" // x: function(x) { this.set('translate', x, null); }, y: function(y) { this.set('translate', null, y); }, // ### translate // Notice how this keeps the other value. // // .css({ translate: '2, 5' }) //=> "translate(2px, 5px)" // translate: function(x, y) { if (this._translateX === undefined) { this._translateX = 0; } if (this._translateY === undefined) { this._translateY = 0; } if (x !== null) { this._translateX = unit(x, 'px'); } if (y !== null) { this._translateY = unit(y, 'px'); } this.translate = this._translateX + "," + this._translateY; } }, getter: { x: function() { return this._translateX || 0; }, y: function() { return this._translateY || 0; }, scale: function() { var s = (this.scale || "1,1").split(','); if (s[0]) { s[0] = parseFloat(s[0]); } if (s[1]) { s[1] = parseFloat(s[1]); } // "2.5,2.5" => 2.5 // "2.5,1" => [2.5,1] return (s[0] === s[1]) ? s[0] : s; }, rotate3d: function() { var s = (this.rotate3d || "0,0,0,0deg").split(','); for (var i=0; i<=3; ++i) { if (s[i]) { s[i] = parseFloat(s[i]); } } if (s[3]) { s[3] = unit(s[3], 'deg'); } return s; } }, // ### parse() // Parses from a string. Called on constructor. parse: function(str) { var self = this; str.replace(/([a-zA-Z0-9]+)\((.*?)\)/g, function(x, prop, val) { self.setFromString(prop, val); }); }, // ### toString() // Converts to a `transition` CSS property string. If `use3d` is given, // it converts to a `-webkit-transition` CSS property string instead. toString: function(use3d) { var re = []; for (var i in this) { if ((this.hasOwnProperty(i)) && (i[0] !== '_')) { if (use3d && (i === 'scale')) { re.push(i + "3d(" + this[i] + ",1)"); } else if (use3d && (i === 'translate')) { re.push(i + "3d(" + this[i] + ",0)"); } else { re.push(i + "(" + this[i] + ")"); } } } return re.join(" "); } }; function callOrQueue(self, queue, fn) { if (queue === true) { self.queue(fn); } else if (queue) { self.queue(queue, fn); } else { fn(); } } // ### getProperties(dict) // Returns properties (for `transition-property`) for dictionary `props`. The // value of `props` is what you would expect in `$.css(...)`. function getProperties(props) { var re = []; $.each(props, function(key) { key = $.camelCase(key); // Convert "text-align" => "textAlign" key = $.transit.propertyMap[key] || key; key = uncamel(key); // Convert back to dasherized if ($.inArray(key, re) === -1) { re.push(key); } }); return re; } // ### getTransition() // Returns the transition string to be used for the `transition` CSS property. // // Example: // // getTransition({ opacity: 1, rotate: 30 }, 500, 'ease'); // //=> 'opacity 500ms ease, -webkit-transform 500ms ease' // function getTransition(properties, duration, easing, delay) { // Get the CSS properties needed. var props = getProperties(properties); // Account for aliases (`in` => `ease-in`). if ($.cssEase[easing]) { easing = $.cssEase[easing]; } // Build the duration/easing/delay attributes for it. var attribs = '' + toMS(duration) + ' ' + easing; if (parseInt(delay, 10) > 0) { attribs += ' ' + toMS(delay); } // For more properties, add them this way: // "margin 200ms ease, padding 200ms ease, ..." var transitions = []; $.each(props, function(i, name) { transitions.push(name + ' ' + attribs); }); return transitions.join(', '); } // ## $.fn.transition // Works like $.fn.animate(), but uses CSS transitions. // // $("...").transition({ opacity: 0.1, scale: 0.3 }); // // // Specific duration // $("...").transition({ opacity: 0.1, scale: 0.3 }, 500); // // // With duration and easing // $("...").transition({ opacity: 0.1, scale: 0.3 }, 500, 'in'); // // // With callback // $("...").transition({ opacity: 0.1, scale: 0.3 }, function() { ... }); // // // With everything // $("...").transition({ opacity: 0.1, scale: 0.3 }, 500, 'in', function() { ... }); // // // Alternate syntax // $("...").transition({ // opacity: 0.1, // duration: 200, // delay: 40, // easing: 'in', // complete: function() { /* ... */ } // }); // $.fn.transition = $.fn.transit = function(properties, duration, easing, callback) { var self = this; var delay = 0; var queue = true; // Account for `.transition(properties, callback)`. if (typeof duration === 'function') { callback = duration; duration = undefined; } // Account for `.transition(properties, duration, callback)`. if (typeof easing === 'function') { callback = easing; easing = undefined; } // Alternate syntax. if (typeof properties.easing !== 'undefined') { easing = properties.easing; delete properties.easing; } if (typeof properties.duration !== 'undefined') { duration = properties.duration; delete properties.duration; } if (typeof properties.complete !== 'undefined') { callback = properties.complete; delete properties.complete; } if (typeof properties.queue !== 'undefined') { queue = properties.queue; delete properties.queue; } if (properties.delay) { delay = properties.delay; delete properties.delay; } // Set defaults. (`400` duration, `ease` easing) if (typeof duration === 'undefined') { duration = $.fx.speeds._default; } if (typeof easing === 'undefined') { easing = $.cssEase._default; } duration = toMS(duration); // Build the `transition` property. var transitionValue = getTransition(properties, duration, easing, delay); // Compute delay until callback. // If this becomes 0, don't bother setting the transition property. var work = $.transit.enabled && support.transition; var i = work ? (parseInt(duration, 10) + parseInt(delay, 10)) : 0; // If there's nothing to do... if (i === 0) { var fn = function(next) { self.css(properties); if (callback) { callback(); } next(); }; callOrQueue(self, queue, fn); return self; } // Save the old transitions of each element so we can restore it later. var oldTransitions = {}; var run = function(nextCall) { var bound = false; // Prepare the callback. var cb = function() { if (bound) { self.unbind(transitionEnd, cb); } if (i > 0) { self.each(function() { this.style[support.transition] = (oldTransitions[this] || null); }); } if (typeof callback === 'function') { callback.apply(self); } if (typeof nextCall === 'function') { nextCall(); } }; if ((i > 0) && (transitionEnd)) { // Use the 'transitionend' event if it's available. bound = true; self.bind(transitionEnd, cb); } else { // Fallback to timers if the 'transitionend' event isn't supported. window.setTimeout(cb, i); } // Apply transitions. self.each(function() { if (i > 0) { this.style[support.transition] = transitionValue; } $(this).css(properties); }); }; // Defer running. This allows the browser to paint any pending CSS it hasn't // painted yet before doing the transitions. var deferredRun = function(next) { var i = 0; // Durations that are too slow will get transitions mixed up. // (Tested on Mac/FF 7.0.1) if ((support.transition === 'MozTransition') && (i < 25)) { i = 25; } window.setTimeout(function() { run(next); }, i); }; // Use jQuery's fx queue. callOrQueue(self, queue, deferredRun); // Chainability. return this; }; function registerCssHook(prop, isPixels) { // For certain properties, the 'px' should not be implied. if (!isPixels) { $.cssNumber[prop] = true; } $.transit.propertyMap[prop] = support.transform; $.cssHooks[prop] = { get: function(elem) { var t = $(elem).css('transform') || new Transform(); return t.get(prop); }, set: function(elem, value) { var t = $(elem).css('transform') || new Transform(); t.setFromString(prop, value); $(elem).css({ transform: t }); } }; } // ### uncamel(str) // Converts a camelcase string to a dasherized string. // (`marginLeft` => `margin-left`) function uncamel(str) { return str.replace(/([A-Z])/g, function(letter) { return '-' + letter.toLowerCase(); }); } // ### unit(number, unit) // Ensures that number `number` has a unit. If no unit is found, assume the // default is `unit`. // // unit(2, 'px') //=> "2px" // unit("30deg", 'rad') //=> "30deg" // function unit(i, units) { if ((typeof i === "string") && (!i.match(/^[\-0-9\.]+$/))) { return i; } else { return "" + i + units; } } // ### toMS(duration) // Converts given `duration` to a millisecond string. // // toMS('fast') //=> '400ms' // toMS(10) //=> '10ms' // function toMS(duration) { var i = duration; // Allow for string durations like 'fast'. if ($.fx.speeds[i]) { i = $.fx.speeds[i]; } return unit(i, 'ms'); } // Export some functions for testable-ness. $.transit.getTransitionValue = getTransition; })(jQuery);
// Generated by LiveScript 1.2.0 (function(){ module.exports = { createPermit: require('./create_permit'), createRequest: require('./create_request'), createUser: require('./create_user') }; }).call(this);
var fs = require('fs'), util = require('util'), uuid = require('node-uuid'), events = require('events'), Data = require('./data.js').Data; var objects_dir = __dirname + '/../entities/objects/'; var l10n_dir = __dirname + '/../l10n/scripts/objects/'; var objects_scripts_dir = __dirname + '/../scripts/objects/'; var Items = function () { var self = this; self.objects = {}; self.load_count = {}; self.getScriptsDir = function () { return objects_scripts_dir; }; self.getL10nDir = function () { return l10n_dir; }; self.load = function (verbose, callback) { verbose = verbose || false; var log = function (message) { if (verbose) util.log(message); }; var debug = function (message) { if (verbose) util.debug(message); }; log("\tExamining object directory - " + objects_dir); var objects = fs.readdir(objects_dir, function (err, files) { // Load any object files for (j in files) { var object_file = objects_dir + files[j]; if (!fs.statSync(object_file).isFile()) continue; if (!object_file.match(/yml$/)) continue; // parse the object files try { var object_def = require('js-yaml').load(fs.readFileSync(object_file).toString('utf8')); } catch (e) { log("\t\tError loading object - " + object_file + ' - ' + e.message); continue; } // create and load the objects object_def.forEach(function (object) { var validate = ['keywords', 'short_description', 'vnum']; var err = false; for (var v in validate) { if (!(validate[v] in object)) { log("\t\tError loading object in file " + object + ' - no ' + validate[v] + ' specified'); err = true; return; } } if (err) { return; } // max load for items so we don't have 1000 items in a room due to respawn if (self.load_count[object.vnum] && self.load_count[object.vnum] >= object.load_max) { log("\t\tMaxload of " + object.load_max + " hit for object " + object.vnum); return; } object = new Item(object); object.setUuid(uuid.v4()); log("\t\tLoaded item [uuid:" + object.getUuid() + ', vnum:' + object.vnum + ']'); self.addItem(object); }); } if (callback) { callback(); } }); }; /** * Add an item and generate a uuid if necessary * @param Item item */ self.addItem = function (item) { if (!item.getUuid()) { item.setUuid(uuid.v4()); } self.objects[item.getUuid()] = item; self.load_count[item.vnum] = self.load_count[item.vnum] ? self.load_count[item.vnum] + 1 : 1; }; /** * Gets all instance of an object * @param int vnum * @return Item */ self.getByVnum = function (vnum) { var objs = []; self.each(function (o) { if (o.getVnum() === vnum) { objs.push(o); } }); return objs; }; /** * retreive an instance of an object by uuid * @param string uid * @return Item */ self.get = function (uid) { return self.objects[uid]; }; /** * proxy Array.each * @param function callback */ self.each = function (callback) { for (var obj in self.objects) { callback(self.objects[obj]); } }; } var Item = function (config) { var self = this; self.keywords; self.short_description self.description; self.inventory; // Player or Npc object that is holding it self.npc_held; // If it's in an inventory is it an NPC's? self.room; // Room that it's in (vnum) self.container; // Itemception (vnum) self.vnum; self.uuid = null; self.equipped = false; self.script = ''; self.attributes = {}; self.init = function (config) { self.short_description = config.short_description || ''; self.keywords = config.keywords || []; self.description = config.description || ''; self.inventory = config.inventory || null; self.room = config.room || null; self.npc_held = config.npc_held || null; self.equipped = config.equipped || null; self.container = config.container || null; self.uuid = config.uuid || null; self.vnum = config.vnum; self.script = config.script; self.attributes = config.attributes; Data.loadListeners(config, l10n_dir, objects_scripts_dir, Data.loadBehaviors(config, 'objects/', self)); }; /**#@+ * Mutators */ self.getVnum = function () { return self.vnum; }; self.getInv = function () { return self.inventory; }; self.isNpcHeld = function () { return self.npc_held; }; self.isEquipped = function () { return self.equipped; }; self.getRoom = function () { return self.room; }; self.getContainer = function () { return self.container; }; self.getUuid = function () { return self.uuid; }; self.getAttribute = function (attr) { return self.attributes[attr] || false; }; self.setUuid = function (uid) { self.uuid = uid; }; self.setRoom = function (room) { self.room = room; }; self.setInventory = function (identifier) { self.inventory = identifier; }; self.setNpcHeld = function (held) { self.npc_held = held; }; self.setContainer = function (uid) { self.container = uid; }; self.setEquipped = function (equip) { self.equipped = !!equip; }; self.setAttribute = function (attr, val) { self.attributes[attr] = val; }; /**#@-*/ /** * Get the description, localized if possible * @param string locale * @return string */ self.getDescription = function (locale) { return typeof self.description === 'string' ? self.description : (locale in self.description ? self.description[locale] : 'UNTRANSLATED - Contact an admin'); }; /** * Get the title, localized if possible * @param string locale * @return string */ self.getShortDesc = function (locale) { return typeof self.short_description === 'string' ? self.short_description : (locale in self.short_description ? self.short_description[locale] : 'UNTRANSLATED - Contact an admin'); }; /** * Get the title, localized if possible * @param string locale * @return string */ self.getKeywords = function (locale) { return Array.isArray(self.keywords) ? self.keywords : (locale in self.keywords ? self.keywords[locale] : 'UNTRANSLATED - Contact an admin'); } /** * check to see if an item has a specific keyword * @param string keyword * @param string locale * @return boolean */ self.hasKeyword = function (keyword, locale) { return self.getKeywords(locale).some(function (word) { return keyword === word }); }; /** * Used when saving a copy of an item to a player * @return object */ self.flatten = function () { return { uuid: self.uuid, keywords: self.keywords, short_description: self.short_description, description: self.description, inventory: self.inventory, // Player or Npc object that is holding it vnum: self.vnum, script: self.script, equipped: self.equipped, attributes: self.attributes }; }; self.init(config); }; util.inherits(Item, events.EventEmitter); exports.Items = Items; exports.Item = Item;
const fs = require('fs-extra'); const path = require('path'); let prjDir = process.argv[2]; if (!prjDir) { throw new Error('local path required as last argument to "npm run build.link" command'); } prjDir = path.join(__dirname, '../../../', prjDir); copyPackage(prjDir, 'angular'); copyPackage(prjDir, 'core'); function copyPackage(prjDir, pkgName) { const prjDest = path.join(prjDir, 'node_modules', '@ionic', pkgName); const pkgSrcDir = path.join(__dirname, '..', '..', pkgName); const pkgSrcDist = path.join(pkgSrcDir, 'dist'); const pkgJsonPath = path.join(pkgSrcDir, 'package.json'); const pkgJson = require(pkgJsonPath); // make sure this local project exists fs.emptyDirSync(prjDest); pkgJson.files.push('package.json'); pkgJson.files.forEach(f => { const src = path.join(pkgSrcDir, f); const dest = path.join(prjDest, f); console.log('copying:', src, 'to', dest); fs.copySync(src, dest); }); const prjReadme = path.join(prjDest, 'README.md'); console.log('readme:', prjReadme); fs.writeFileSync(prjReadme, '@ionic/' + pkgName + ' copied from ' + pkgSrcDir + ', ' + new Date()); }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.5.5_A1_T2; * @section: 15.5.5; * @assertion: String instance has not [[call]] property; * @description: Checking if creating new "String("a|b")()" fails; */ ////////////////////////////////////////////////////////////////////////////// //CHECK#1 try { String("a|b")(); $FAIL('#1: String("a|b")() lead to throwing exception'); } catch (e) { if (!(e instanceof TypeError)) { $ERROR('#1.1: Exception is instance of TypeError. Actual: exception is '+e); } } // //////////////////////////////////////////////////////////////////////////////
require('./counter');
/*! * filename: ej.localetexts.ro-RO.js * Copyright Syncfusion Inc. 2001 - 2016. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing * licensing@syncfusion.com. Any infringement will be prosecuted under * applicable laws. */ ej.Autocomplete.Locale["ro-RO"] = { addNewText: "Adăuga nou", emptyResultText: "Nu există sugestii", actionFailure: "Câmpul specificat nu există în anumită sursă de date", }; ej.CurrencyTextbox.Locale["ro-RO"] = { watermarkText: "Introdu o valoare", }; ej.DatePicker.Locale["ro-RO"] = { watermarkText: "Selectați data", buttonText: "Astăzi", }; ej.DateTimePicker.Locale["ro-RO"] = { buttonText: { today: "Astăzi", timeNow: "ora este acum", done: "Terminat", timeTitle: "Timp" }, }; ej.datavisualization.Diagram.Locale["ro-RO"] = { cut: "A taia", copy: "Copie", paste: "Pastă", undo: "Anula", redo: "refaceţi", selectAll: "Selectează tot", grouping: "gruparea", group: "grup", ungroup: "Degrupați", order: "Ordin", bringToFront: "BringToFront", moveForward: "Mergi inainte", sendBackward: "trimiteţi în spate", sendToBack: "SendToBack", }; ej.Dialog.Locale["ro-RO"] = { tooltip: { close: "Închide", collapse: "Colaps", restore: "Restabili", maximize: "maximaliza", minimize: "minimaliza", expand: "Extinde", unPin: "Anulează fixarea", pin: "bolț" }, closeIconTooltip: "închide", }; ej.ExcelFilter.Locale["ro-RO"] = { SortNoSmaller: "Sortare Cea mai mică la cea mai mare", SortNoLarger: "Sortare Cel mai mare la cea mai mica", SortTextAscending: "Sortați A la Z", SortTextDescending: "Sortați Z la A", SortDateOldest: "Sortați după cele mai vechi", SortDateNewest: "Sortează după Cele mai noi", SortByColor: "Sortați după culoare", SortByCellColor: "Sortează după Color Cell", SortByFontColor: "Sortează după Font Color", FilterByColor: "Filtrati pe tipuri de culori", CustomSort: "Sortare personalizată", FilterByCellColor: "Filtrul de culoare mobil", FilterByFontColor: "Filtrul de la Font Color", ClearFilter: "Ștergeți filtrul", NumberFilter: "număr filtre", GuidFilter: "Filtre guid", TextFilter: "Filtre de text", DateFilter: "data Filtre", DateTimeFilter: "Filtre Data Ora", SelectAll: "Selectează tot", Blanks: "eboșe", Search: "Căutare", Showrowswhere: "Afișați rânduri în cazul în care", NumericTextboxWaterMark: "Introdu o valoare", StringMenuOptions: [{ text: "Egal", value: "equal" }, { text: "Nu este equal", value: "notequal" }, { text: "Incepe cu", value: "startswith" }, { text: "Se termină cu", value: "endswith" }, { text: "conţine", value: "contains" }, { text: "Filtru personalizat", value: "customfilter" }, ], NumberMenuOptions: [{ text: "Egal", value: "equal" }, { text: "Nu este equal", value: "notequal" }, { text: "Mai puțin decât", value: "lessthan" }, { text: "Mai mic sau equal", value: "lessthanorequal" }, { text: "Mai mare ca", value: "greaterthan" }, { text: "Mai mare sau equal", value: "greaterthanorequal" }, { text: "Între", value: "between" }, { text: "Filtru personalizat", value: "customfilter" }, ], GuidMenuOptions: [{ text: "Egal", value: "equal" }, { text: "Nu este equal", value: "notequal" }, { text: "Filtru personalizat", value: "customfilter" }, ], DateMenuOptions: [{ text: "Egal", value: "equal" }, { text: "Nu este equal", value: "notequal" }, { text: "Mai puțin decât", value: "lessthan" }, { text: "Mai mic sau equal", value: "lessthanorequal" }, { text: "Mai mare ca", value: "greaterthan" }, { text: "Mai mare sau equal", value: "greaterthanorequal" }, { text: "Între", value: "between" }, { text: "Filtru personalizat", value: "customfilter" }, ], DatetimeMenuOptions: [{ text: "Egal", value: "equal" }, { text: "Nu este equal", value: "notequal" }, { text: "Mai puțin decât", value: "lessthan" }, { text: "Mai mic sau equal", value: "lessthanorequal" }, { text: "Mai mare ca", value: "greaterthan" }, { text: "Mai mare sau equal", value: "greaterthanorequal" }, { text: "Între", value: "between" }, { text: "Filtru personalizat", value: "customfilter" }, ], Top10MenuOptions: [{ text: "Top", value: "top" }, { text: "Fund", value: "bottom" }, ], title: "Filtru personalizat", PredicateAnd: "ȘI", PredicateOr: "SAU", Ok: "bine", MatchCase: "meci Case", Cancel: "Anulare", NoResult: "Nu s-a gasit nici o potrivire", CheckBoxStatusMsg: "Nu toate elementele care arată", DatePickerWaterMark: "Selectați data", DateTimePickerWaterMark: "Selectați ora dată", True: "Adevărat", False: "fals", }; ej.FileExplorer.Locale["ro-RO"] = { Back: "Înapoi", Forward: "Redirecţiona", Upward: "În sus", Refresh: "Reîmprospăta", Addressbar: "Bara de adresa", Upload: "Încărcați", Rename: "redenumire", Delete: "Șterge", Download: "Descarca", Error: "Eroare", Cut: "A taia", Copy: "Copie", Paste: "Pastă", Details: "Detalii", Searchbar: "Bara de căutare", Open: "Deschis", Search: "Căutare", NewFolder: "Dosar nou", Size: "mărimea", RenameAlert: "Vă rugăm să introduceți numele nou", NewFolderAlert: "Vă rugăm să introduceți numele nou dosar,", ContextMenuOpen: "Deschis", ContextMenuNewFolder: "Dosar nou", ContextMenuDelete: "Șterge", ContextMenuRename: "redenumire", ContextMenuUpload: "Încărcați", ContextMenuDownload: "Descarca", ContextMenuCut: "A taia", ContextMenuCopy: "Copie", ContextMenuPaste: "Pastă", ContextMenuGetinfo: "Obtine informatii", ContextMenuRefresh: "Reîmprospăta", ContextMenuOpenFolderLocation: "Deschideți Locul de amplasare dosar", Item: "articol", Items: "articole", GeneralError: "Vă rugăm să consultați fereastra consolei browser-ului pentru mai multe informații", DeleteFolder: "ești sigur că vrei să ștergi", CancelPasteAction: "Directorul destinație este un subdirector de director sursa.", OkButton: "bine", CancelButton: "Anulare", YesToAllButton: "da la toate", NoToAllButton: "Nu la toate", YesButton: "da", NoButton: "Nu", SkipButton: "sări", Grid: "Vizualizare grilă", Tile: "Vedere de placi de ceramica", LargeIcons: "pictograme mari", Name: "Nume", Location: "Locație", Type: "Categorie de obiect", Layout: "amplasare", Created: "Creată", Accessed: "accesat la", Modified: "modificată", DialogCloseToolTip: "Închide", UploadSettings: { dropAreaText: "Picătură fișiere sau faceți clic pentru a încărca", filedetail: "Dimensiunea fișierului selectat este prea mare. Vă rugăm să selectați un fișier în dimensiune validă.", denyError: "Fișierele cu extensii #Extension nu sunt permise.", allowError: "sunt permise doar fișierele cu extensiile #Extension.", cancelToolTip: "Anulare", removeToolTip: "Elimina", retryToolTip: "reîncerca", completedToolTip: "terminat", failedToolTip: "A eșuat", closeToolTip: "Închide" }, }; ej.Gantt.Locale["ro-RO"] = { emptyRecord: "Nu exista inregistrari pentru a afișa", alertTexts: { indentAlert: "Nu există nici o înregistrare Gantt este selectat pentru a efectua liniuței", outdentAlert: "Nu există nici o înregistrare Gantt este selectat pentru a efectua fără indentare", predecessorEditingValidationAlert: "Dependență ciclica Au avut loc, vă rugăm să verificați predecesor", predecessorAddingValidationAlert: "Umple toate coloanele din tabelul precedent", idValidationAlert: "dublură ID-ul", dateValidationAlert: "Data de încheiere nevalidă", dialogResourceAlert: "Umple toate coloanele din tabelul de resurse" }, columnHeaderTexts: { taskId: "ID-ul", taskName: "Nume sarcină", startDate: "Data de început", endDate: "Data de încheiere", resourceInfo: "Resurse", duration: "Durată", status: "progres", predecessor: "predecesorii", type: "Tip", offset: "ofset", baselineStartDate: "Dată de referință Start", baselineEndDate: "Momentul inițial Data de încheiere", WBS: "wBS", WBSpredecessor: "wBS predecesor", dialogCustomFieldName: "Nume coloană", dialogCustomFieldValue: "Valoare", notes: "notițe", taskType: "sarcina Tip", work: "Muncă", unit: "Unitate", effortDriven: "efort Driven" }, columnDialogTexts: { field: "Camp", headerText: "Text antet", editType: "Editare tip", filterEditType: "Se filtrează Editare tip", allowFiltering: "permite filtrarea", allowFilteringBlankContent: "Permite filtrarea conținutului Blank", allowSorting: "Se permite sortare", visible: "Vizibil", width: "Lăţime", textAlign: "Aliniere text", headerTextAlign: "Text antet Aliniere", columnsDropdownData: "Coloană Drop Down date", dropdownTableText: "Text", dropdownTableValue: "Valoare", addData: "Adăuga", deleteData: "Elimina", allowCellSelection: "Permite selectarea de celule" }, editDialogTexts: { addFormTitle: "Sarcina noua", editFormTitle: "editaţi sarcina", saveButton: "Salvați", deleteButton: "Șterge", cancelButton: "Anulare", addPredecessor: "Adăuga nou", removePredecessor: "Elimina" }, toolboxTooltipTexts: { addTool: "Adăuga", editTool: "Editați | ×", saveTool: "Actualizați", deleteTool: "Șterge", cancelTool: "Anulare", searchTool: "Căutare", indentTool: "Indentați", outdentTool: "fără indentare", expandAllTool: "Extinde toate", collapseAllTool: "Reduceți totul În această", nextTimeSpanTool: "următor Perioadă de timp", prevTimeSpanTool: "anterioară Durata de timp", criticalPathTool: "Traiectorie critică" }, durationUnitTexts: { days: "zi", hours: "ore", minutes: "minute", day: "zi", hour: "ora", minute: "minut" }, durationUnitEditText: { minute: ["m", "min", "minut", "minute"], hour: ["h", "HR", "ora", "ore"], day: ["d", "dy", "zi", "zi"] }, workUnitTexts: { days: "zi", hours: "ore", minutes: "minute" }, taskTypeTexts: { fixedWork: "lucru fix", fixedUnit: "Unități fixe", fixedDuration: "Durată fixă" }, effortDrivenTexts: { yes: "da", no: "Nu" }, contextMenuTexts: { taskDetailsText: "Sarcina Detalii ...", addNewTaskText: "Adăugați o activitate nouă", indentText: "Indentați", outdentText: "fără indentare", deleteText: "Șterge", aboveText: "De mai sus", belowText: "De mai jos" }, newTaskTexts: { newTaskName: "Sarcina noua" }, columnMenuTexts: { sortAscendingText: "sortare ascendentă", sortDescendingText: "sortează descendent", columnsText: "coloane", insertColumnLeft: "Inserare coloană pe stânga", insertColumnRight: "Inserare coloană pe dreapta", deleteColumn: "ştergeţi coloana", renameColumn: "redenumire coloană" }, taskModeTexts: { manual: "Manual", auto: "Auto" }, columnDialogTitle: { insertColumn: "Inserare coloană", deleteColumn: "ştergeţi coloana", renameColumn: "redenumire coloană" }, deleteColumnText: "Sunteți sigur că doriți să ștergeți această coloană?", okButtonText: "bine", cancelButtonText: "Anulare", confirmDeleteText: "confirmaţi ștergerea", predecessorEditingTexts: { fromText: "Din", toText: "La" }, dialogTabTitleTexts: { generalTabText: "General", predecessorsTabText: "predecesorii", resourcesTabText: "Resurse", customFieldsTabText: "câmpuri customizate", notesTabText: "notițe" } }; ej.Grid.Locale["ro-RO"] = { EmptyRecord: "Nu exista inregistrari pentru a afișa", GroupDropArea: "Trageți o coloană antet aici pentru grup este o coloană", DeleteOperationAlert: "Nu exista inregistrari selectate pentru operație de ștergere", EditOperationAlert: "Nu exista inregistrari selectate pentru operație de editare", SaveButton: "Salvați", OkButton: "bine", CancelButton: "Anulare", EditFormTitle: "detalii de", AddFormTitle: "Adauga o noua înregistrare", Notactionkeyalert: "Această tastă de combinare nu este disponibilă", Keyconfigalerttext: "Această cheie de-combinată a fost deja atribuită", GroupCaptionFormat: "{{:headerText}}: {{:key}} - {{:count}} {{if count == 1 }} articol {{else}} articole {{/if}} ", BatchSaveConfirm: "Sunteți sigur că doriți să salvați modificările?", BatchSaveLostChanges: "Modificările nesalvate vor fi pierdute. Esti sigur ca vrei sa continui?", ConfirmDelete: "Sunteți sigur că doriți să ștergeți Înregistrare?", CancelEdit: "Sunteți sigur că doriți să anulați modificările?", PagerInfo: "{0} din {1} pagini ({2} articole)", FrozenColumnsViewAlert: "coloanele înghețate ar trebui să fie în zona gridview", FrozenColumnsScrollAlert: "Activați permite Defilare în timp ce utilizați coloanele înghețate", FrozenNotSupportedException: "Coloanele congelate și rânduri nu sunt acceptate pentru gruparea, Row Format, Format Detaliu, ierarhie Grid și editare de lot", Add: "Adăuga", Edit: "Editați | ×", Delete: "Șterge", Update: "Actualizați", Cancel: "Anulare", Done: "Terminat", Columns: "coloane", SelectAll: "(Selectează tot)", PrintGrid: "Imprimare", ExcelExport: "Excel Export", WordExport: "cuvânt Export", PdfExport: "Export PDF", StringMenuOptions: [{ text: "Incepe cu", value: "Starts With" }, { text: "Se termină cu", value: "Ends With" }, { text: "conţine", value: "Contains" }, { text: "Egal", value: "Equal" }, { text: "Nu este equal", value: "NotEqual" }, ], NumberMenuOptions: [{ text: "Mai puțin decât", value: "LessThan" }, { text: "Mai mare ca", value: "GreaterThan" }, { text: "Mai mic sau equal", value: "LessThanOrEqual" }, { text: "Mai mare sau equal", value: "GreaterThanOrEqual" }, { text: "Egal", value: "Equal" }, { text: "Nu este equal", value: "NotEqual" }, ], PredicateAnd: "ȘI", PredicateOr: "SAU", Filter: "Filtru", FilterMenuCaption: "Valoarea de filtrare", FilterbarTitle: "celulă bar de filtru s", MatchCase: "meci Case", Clear: "clar", ResponsiveFilter: "Filtru", ResponsiveSorting: "Fel", Search: "Căutare", DatePickerWaterMark: "Selectați data", EmptyDataSource: "DataSource nu trebuie să fie gol la sarcină inițială, deoarece coloanele sunt generate de DATASOURCE în AutoGenerat Coloana grilă", ForeignKeyAlert: "Valoarea actualizată ar trebui să fie o valoare cheie externă validă", True: "Adevărat", False: "fals", UnGroup: "Apasa aici pentru a degrupa", AddRecord: "add record", EditRecord: "edit record", DeleteRecord: "şterge înregistrare", Save: "Salvați", Grouping: "grup", Ungrouping: "Degrupați", SortInAscendingOrder: "Sortare în ordine crescătoare", SortInDescendingOrder: "Sortare în ordine descrescătoare", NextPage: "Pagina următoare", PreviousPage: "Pagina anterioară", FirstPage: "Prima pagina", LastPage: "Ultima pagina", EmptyRowValidationMessage: "Cel puțin un câmp trebuie să fie actualizate", NoResult: "Nu s-a gasit nici o potrivire" }; ; if (ej.mobile !== undefined && ej.mobile.Grid !== undefined) { ej.mobile.Grid.Locale["ro-RO"] = { emptyResult: "Nu exista inregistrari pentru a afișa", filterValidation: "Introduceți date filtru valid", filterTypeValidation: "Introduce date de filtrare valide. Coloana actuală a filtrului este de tip", captionText: "articole", spinnerText: "se incarca...", HideColumnAlert: "Cel puțin o coloană trebuie să fie afișate în grilă", columnSelectorText: "Ascundeți coloana", columnSelectorDone: "bine", columnSelectorCancel: "Anulare", columnSelectorWarning: "Avertizare", filterOk: "Bine", filterWarning: "Avertizare" }; ; } if (ej.mobile !== undefined && ej.mobile.DatePicker !== undefined) { ej.mobile.DatePicker.Locale["ro-RO"] = { confirmText: "Terminat", Windows: { cancelText: "Anulare", headerText: "ALEGE DATA", toolbarConfirmText: "Terminat", toolbarCancelText: "închide" }, }; ; } if (ej.mobile !== undefined && ej.mobile.TimePicker !== undefined) { ej.mobile.TimePicker.Locale["ro-RO"] = { confirmText: "Terminat", AM: "A.M", PM: "P.M", Android: { headerText: "Potriveste ora" }, Windows: { cancelText: "Anulare", headerText: "ALEGE TIME", toolbarCancelText: "închide", toolbarConfirmText: "Terminat" }, }; ; } ej.NumericTextbox.Locale["ro-RO"] = { watermarkText: "Introdu o valoare", }; ej.PivotChart.Locale["ro-RO"] = { Measure: "Măsura", Row: "Rând", Column: "Coloană", Expand: "Extinde", Collapse: "Colaps", Exit: "Ieșire", Value: "Valoare" }; ej.PivotClient.Locale["ro-RO"] = { DeferUpdate: "Amânați Actualizare", MDXQuery: "MDX Solicitare", Column: "Coloană", Row: "Rând", Slicer: "feliator", CubeSelector: "cub Selectare", ReportName: "Raportează Nume", NewReport: "Raport nou", CubeDimensionBrowser: "Cub Dimensiune browser", AddReport: "adăugaţi un raport", RemoveReport: "eliminați rapoarte", CannotRemoveSingleReport: "Nu se poate elimina singur raport", AreYouSureToDeleteTheReport: "Sunteți sigur să ștergeți raportul", RenameReport: "redenumire rapoarte", SaveReport: "Salvați raportul", ChartTypes: "Tipuri de diagramă", ToggleAxis: "Axa de comutare", LoadReport: "încărcare rapoarte", ExportToExcel: "Export în Excel", ExportToWord: "Export Word", ExportToPdf: "Exportă PDF", FullScreen: "Ecran complet", Grid: "Grilă", Chart: "Diagramă", OK: "bine", Cancel: "Anulare", MeasureEditor: "Se măsoară Editor", MemberEditor: "Editor membru", Measures: "măsuri", SortOrFilterColumn: "Sortare / Filtru (Coloana)", SortOrFilterRow: "Sortare / Filtru (Row)", SortingAndFiltering: "Sortare și filtrare", Sorting: "Triere", Measure: "Măsuraţi", Order: "Ordin", Filtering: "filtrarea", Condition: "Starea", PreserveHierarchy: "Păstraţi Ierarhie", Ascending: "Crescător", Descending: "Descendentă", Enable: "Activare", Disable: "Dezactivare", and: "Şi", Line: "Linia", Spline: "Caneluri", Area: "Zonă", SplineArea: "Zona Caneluri", StepLine: "Etapa linie", StepArea: "Zona pas", Pie: "Plăcintă", Bar: "Bari", StackingArea: "Suprafata de stivuire", StackingColumn: "coloană de stivuire", StackingBar: "stivuirea Bari", Pyramid: "Piramidă", Funnel: "Pâlnie", Doughnut: "gogoașă", Scatter: "împrăștia", Sort: "Sortare", SelectField: "Selectare câmp", LabelFilterLabel: "Prezentaţi elementele pentru care eticheta", ValueFilterLabel: "Prezentaţi elementele pentru care", LabelFilters: "Filtrele de etichete", BeginsWith: "Începe cu", NotBeginsWith: "Nu începe cu", EndsWith: "Capetele cu", NotEndsWith: "Nu se termină cu", Contains: "Conţine", NotContains: "Nu conţine", ValueFilters: "Filtrele de valoare", ClearFilter: "Filtrul de clare", Equals: "Este egală cu", NotEquals: "Nu este egală cu", GreaterThan: "Mai Mare Decât", GreaterThanOrEqualTo: "Mai mare sau egal cu", LessThan: "Mai puţin de", LessThanOrEqualTo: "Mai mic sau egal cu", Between: "Între", NotBetween: "Nu este cuprinsă între", Top10: "Contorul de sus", Close: "Închideţi", AddToColumn: "Adăugaţi pentru a coloanei de direcţie", AddToRow: "Adăugaţi la rând", AddToSlicer: "Adăugaţi la feliat", Value: "Valoare", EqualTo: "Egal cu", ReportList: "Listă raport", Bubble: "Bulă", TreeMap: "Copac hartă", Alert: "Alertă", MDXAlertMsg: "Vă rugăm să adăugaţi o măsură, cota sau ierarhie în axa corespunzătoare pentru a vizualiza MDX Query.", FilterSortRowAlertMsg: "Cota nu este găsit în axa de rând. Vă rugăm să adăugaţi cota element în axa de rând pentru sortarea/de filtrare.", FilterSortColumnAlertMsg: "Cota nu este găsit în coloana axa. Vă rugăm să adăugaţi cota axa element în coloana pentru sortarea/de filtrare.", FilterSortcolMeasureAlertMsg: "Vă rugăm să adăugaţi măsuraţi la axa coloanei", FilterSortrowMeasureAlertMsg: "Vă rugăm să adăugaţi măsuraţi la axa de rând", FilterSortElementAlertMsg: "Elementul nu a găsit în coloana axa. Vă rugăm să adăugaţi un element în coloana pentru axa sortarea/de filtrare.", LoadReportAlertMsg: "Vă rugăm să selectaţi un raport de validă", FilterMeasureSelectionAlertMsg: "Vă rugăm să selectaţi o măsură validă.", FilterConditionAlertMsg: "Vă rugăm să setaţi o stare validă.", FilterStartValueAlertMsg: "Vă rugăm să setaţi o valoare de pornire.", FilterEndValueAlertMsg: "Vă rugăm să setaţi o valoare de capăt.", FilterInvalidAlertMsg: "Operaţiune invalidă !" }; ej.PivotGauge.Locale["ro-RO"] = { RevenueGoal: "venituri Obiectiv", RevenueValue: "Valoarea veniturilor" }; ej.Pager.Locale["ro-RO"] = { pagerInfo: "{0} din {1} pagini ({2} articole)", firstPageTooltip: "Du-te la prima pagină", lastPageTooltip: "Mergi la ultima pagină", nextPageTooltip: "Du-te la pagina următoare", previousPageTooltip: "Du-te la pagina anterioară", nextPagerTooltip: "Mergi la pagina următoare", previousPagerTooltip: "Du-te la pagina anterioară", }; ej.PdfViewer.Locale["ro-RO"] = { toolbar: { print: { headerText: "Imprimare", contentText: "Imprima documentul PDF." }, first: { headerText: "Primul", contentText: "Du-te la prima pagină a documentului PDF." }, previous: { headerText: "Anterior", contentText: "Du-te la pagina anterioară a documentului PDF." }, next: { headerText: "Următor →", contentText: "Du-te la pagina următoare a documentului PDF." }, last: { headerText: "Ultimul", contentText: "Du-te la ultima pagină a documentului PDF." }, zoomIn: { headerText: "A mari", contentText: "Zoom in documentul PDF." }, zoomOut: { headerText: "A micsora", contentText: "Zoom out documentului PDF." }, pageIndex: { headerText: "Numărul paginii", contentText: "Numărul paginii curente pentru a vizualiza." }, zoom: { headerText: "zoom", contentText: "Mărirea sau pe documentul PDF." }, fitToWidth: { headerText: 'Fit to Lățime', contentText: 'Potriviți pagina PDF cu lățimea containerului .', }, fitToPage: { headerText: 'Incadrare in pagina', contentText: 'Potriviți pagina PDF la container .', }, }, }; ej.PercentageTextbox.Locale["ro-RO"] = { watermarkText: "Introdu o valoare", }; ej.PivotGrid.Locale["ro-RO"] = { ToolTipRow: "Rând", ToolTipColumn: "Coloană", ToolTipValue: "Valoare", SeriesPage: "seria Pagina", CategoricalPage: "categorială Pagina", DragFieldHere: "câmpuri Drag aici", ColumnArea: "Picătură coloană aici", RowArea: "Picătură rând aici", ValueArea: "Valorile picătură aici", OK: "bine", Cancel: "Anulare", Remove: "Elimina", ConditionalFormatting: "Formatarea condițională", Condition: "condiționată Tip", Value1: "valoare 1", Value2: "valoare 2", Editcondtion: "Condiția de editare", Backcolor: "Culoare spate", Borderrange: "Gama de frontieră", Borderstyle: "Stilul de frontieră", Fontsize: "Mărimea fontului", Fontstyle: "Stilul fontului", Bordercolor: "Culoare chenar", Sort: "Sortare", SelectField: "Selectare câmp", LabelFilterLabel: "Prezentaţi elementele pentru care eticheta", ValueFilterLabel: "Prezentaţi elementele pentru care", LabelFilters: "Filtrele de etichete", BeginsWith: "Începe cu", NotBeginsWith: "Nu începe cu", EndsWith: "Capetele cu", NotEndsWith: "Nu se termină cu", Contains: "Conţine", NotContains: "Nu conţine", ValueFilters: "Filtrele de valoare", ClearFilter: "Filtrul de clare", Equals: "Este egală cu", NotEquals: "Nu este egală cu", GreaterThan: "Mai Mare Decât", GreaterThanOrEqualTo: "Mai mare sau egal cu", LessThan: "Mai puţin de", LessThanOrEqualTo: "Mai mic sau egal cu", Between: "Între", NotBetween: "Nu este cuprinsă între", AddToFilter: "Adăugaţi la filtru", AddToRow: "Adăugaţi la rând", AddToColumn: "Adăugaţi pentru a coloanei de direcţie", AddToValues: "Adăugaţi la valori", Warning: "Avertisment", Error: "Eroare", GroupingBarAlertMsg: "Câmpul de mişcare nu poate fi plasat în zona de raport", Measures: "Măsuri", Expand: "Extindere", Collapse: "Colapsul", NoValue: "Nici o valoare", Close: "Închideţi", Goal: "Obiectiv", Status: "Stare", Trend: "Trend", Value: "Valoare", ConditionalFormattingErrorMsg: "Valoarea dată nu se potrivesc", ConditionalFormattingConformMsg: "Sunteţi sigur că doriţi să scoateţi formatul selectat?", EnterOperand1: "Introduceţi operandul drept1", EnterOperand2: "Introduceţi operandul drept2", ConditionalFormatting: "Conditionat de formatare", AddNew: "Adăugaţi noi", Format: "Format", NoMeasure: "Vă rugăm să adăugaţi orice măsură", AliceBlue: "Alice albastru", Black: "Negru", Blue: "Albastru", Brown: "Culoare maro", Gold: "Aur", Green: "În verde", Lime: "Lămâie verde", Maroon: "Castaniu", Orange: "Portocaliu", Pink: "Roz", Red: "Roşu", Violet: "Violet", White: "Alb", Yellow: "Galben", Solid: "Continuu", Dashed: "Linie întreruptă", Dotted: "Linie punctată", Double: "Dublu", Groove: "Canal", Inset: "Zăcea", Outset: "Început", Ridge: "Muchie", None: "Nici unul", Algerian: "Algerianul", Arial: "Arial", BodoniMT: "Bodoni MT", BritannicBold: "Britannic Bold", Cambria: "Cambria", Calibri: "Calibri", CourierNew: "Curier nou", DejaVuSans: "DejaVu Sans", Forte: "Forte", Gerogia: "Gerogia", Impact: "Şoc", SegoeUI: "Segoe UI", Tahoma: "Tahoma", TimesNewRoman: "Times New Roman", Verdana: "Verdana", CubeDimensionBrowser: "Dimensiune cub de browser", SelectHierarchy: "Selectaţi Ierarhie", CalculatedField: "Calculat Câmp", Name: "Nume:", Add: "Adăugaţi", Formula: "Formula:", Delete: "Ştergere", Fields: "Domenii:", CalculatedFieldNameNotFound: "Date CalculatedField nume nu este găsit", InsertField: "Câmpul de introducere", EmptyField: "Vă rugăm să introduceţi numele câmpului de calculat sau formula", NotValid: "Formula dat nu este validă", NotPresent: "Câmpul Valoare utilizate în orice formula de calculat câmp nu este prezent în PivotGrid", Confirm: "Calculat câmp cu acelaşi nume există deja. Datorită doriţi să înlocuiţi ?", CalcValue: "Calculat câmp poate fi introdusă numai în zona de valoare de câmp" }; ej.PivotPager.Locale["ro-RO"] = { SeriesPage: "seria Pagina", CategoricalPage: "categorială Pagina", Error: "Eroare", OK: "OK", Close: "Închideţi", PageCountErrorMsg: "Introduceţi numărul de pagină validă" }; ej.PivotSchemaDesigner.Locale["ro-RO"] = { PivotTableFieldList: "Listă de câmp PivotTable", ChooseFieldsToAddToReport: "Alege câmpuri pentru a adăuga un raport:", DragFieldBetweenAreasBelow: "câmpuri trageți între zonele de mai jos:", ReportFilter: "raport de filtrare", ColumnLabel: "Etichetă coloană", RowLabel: "rând etichete", Values: "valori", DeferLayoutUpdate: "Amânați Aspect Actualizare", Update: "Actualizați", Sort: "Sortare", SelectField: "Selectare câmp", LabelFilterLabel: "Prezentaţi elementele pentru care eticheta", ValueFilterLabel: "Prezentaţi elementele pentru care", LabelFilters: "Filtrele de etichete", BeginsWith: "Începe cu", NotBeginsWith: "Nu începe cu", EndsWith: "Capetele cu", NotEndsWith: "Nu se termină cu", Contains: "Conţine", NotContains: "Nu conţine", ValueFilters: "Filtrele de valoare", ClearFilter: "Filtrul de clare", Equals: "Este egală cu", NotEquals: "Nu este egală cu", GreaterThan: "Mai Mare Decât", GreaterThanOrEqualTo: "Mai mare sau egal cu", LessThan: "Mai puţin de", LessThanOrEqualTo: "Mai mic sau egal cu", Between: "Între", NotBetween: "Nu este cuprinsă între", Measures: "Măsuri", AlertMsg: "Câmpul de mişcare nu poate fi plasat în zona de raport", Close: "Închideţi", Goal: "Obiectiv", Status: "Stare", Trend: "Trend", Value: "Valoare", AddToFilter: "Adăugaţi la filtru", AddToRow: "Adăugaţi la rând", AddToColumn: "Adăugaţi pentru a coloanei de direcţie", AddToValues: "Adăugaţi la valori", Warning: "Avertisment", OK: "OK", Cancel: "Anula" }; ej.datavisualization.RangeNavigator.Locale["ro-RO"] = { intervals: { quarter: { longQuarters: "Sfert,", shortQuarters: "Q" }, week: { longWeeks: "Săptămână,", shortWeeks: "W" }, }, }; ej.ReportViewer.Locale["ro-RO"] = { toolbar: { print: { headerText: "Imprimare", contentText: "Imprima raportul." }, exportformat: { headerText: "Export", contentText: "Selectați formatul de fișier exportat.", Pdf: "PDF", Excel: "excela", Word: "Cuvânt", Html: "html" }, first: { headerText: "Primul", contentText: "Du-te la prima pagină a raportului." }, previous: { headerText: "Anterior", contentText: "Du-te la pagina anterioară a raportului." }, next: { headerText: "Următor →", contentText: "Du-te la pagina următoare a raportului." }, last: { headerText: "Ultimul", contentText: "Du-te la ultima pagină a raportului." }, documentMap: { headerText: "Harta documentului", contentText: "Afișarea sau ascunderea harta documentului." }, parameter: { headerText: "Parametru", contentText: "Afișarea sau ascunderea panoul de parametri." }, zoomIn: { headerText: "A mari", contentText: "Zoom in raportul." }, zoomOut: { headerText: "A micsora", contentText: "Zoom out a raportului." }, refresh: { headerText: "Reîmprospăta", contentText: "Actualizați raportul." }, printLayout: { headerText: "Aspect imprimare", contentText: "Schimba între aspect al imprimării și modurile normale." }, pageIndex: { headerText: "Numărul paginii", contentText: "Numărul paginii curente pentru a vizualiza." }, zoom: { headerText: "zoom", contentText: "Mărirea sau micșorarea raportului." }, back: { headerText: "Înapoi", contentText: "Du-te înapoi la raportul părinte." }, fittopage: { headerText: "Incadrare in pagina", contentText: "Se montează pagina de raport la container.", pageWidth: "pagina Lățime", pageHeight: "Întreaga pagină" }, pagesetup: { headerText: "Configurare pagina", contentText: "Alegeți din următoarele pagini opțiune de configurare pentru a modifica dimensiunea hârtiei, orientarea și margini." }, }, viewButton: "Vizualizează raportul", }; ej.Ribbon.Locale["ro-RO"] = { CustomizeQuickAccess: "Personalizați Bara de instrumente Acces rapid", RemoveFromQuickAccessToolbar: "Eliminați din Bara de instrumente Acces Rapid", AddToQuickAccessToolbar: "Adauga la bara de instrumente Acces Rapid", ShowAboveTheRibbon: "Deasupra Panglica arată", ShowBelowTheRibbon: "Afișați sub panglica", MoreCommands: "Mai multe comenzi ...", }; ej.Kanban.Locale["ro-RO"] = { EmptyCard: "Nu există carduri pentru a afișa", SaveButton: "Salvați", CancelButton: "Anulare", EditFormTitle: "detalii de ", AddFormTitle: "Adăugați un card nou", SwimlaneCaptionFormat: "- {{:count}}{{if count == 1 }} articol {{else}} articole {{/if}}", FilterSettings: "filtre:", FilterOfText: "de", Max: "max", Min: "min", Cards: " Carduri", ItemsCount: "articole Count :", Unassigned: "Nedesemnată" }; ej.RTE.Locale["ro-RO"] = { bold: "Îndrăzneţ", italic: "Cursiv", underline: "sublinia", strikethrough: "strikethrough", superscript: "exponent", subscript: "subscript", justifyCenter: "Aliniere la centru de text", justifyLeft: "Se aliniază textul din stânga", justifyRight: "Aliniere la dreapta textului", justifyFull: "Justifica", unorderedList: "Inserați lista neordonata", orderedList: "Inserați lista ordonata", indent: "creşte indentarea", fileBrowser: "file browser", outdent: "Scădere Indentați", cut: "A taia", copy: "Copie", paste: "Pastă", paragraph: "Paragraf", undo: "Anula", redo: "refaceţi", upperCase: "Majuscule", lowerCase: "Case inferioară", clearAll: "Curata tot", clearFormat: "Format clar", createLink: "Inserați / Editare hyperlink", removeLink: "hyperlink eliminați", image: "inseraţi o imagine", video: "inseraţi un videoclip", editTable: "Editarea proprietăților de masă", embedVideo: "Inserați codul de mai jos Încorporați", viewHtml: "Vizualizare HTML", fontName: "Selectați familia de fonturi", fontSize: "Selectați dimensiunea fontului", fontColor: "Selectați culoarea", format: "Format", backgroundColor: "Culoare de fundal", style: "stiluri", deleteAlert: "Sunteți sigur că doriți să ștergeți toate conținuturile?", copyAlert: "Browser-ul dumneavoastră nu suportă accesul direct la clipboard. Vă rugăm să folosiți tastatura Ctrl + C de comandă rapidă în loc de operație de copiere.", pasteAlert: "Browser-ul dumneavoastră nu suportă accesul direct la clipboard. Vă rugăm să utilizați comanda rapidă de la tastatură Ctrl + V în loc de funcționare pastă.", cutAlert: "Browser-ul dumneavoastră nu suportă accesul direct la clipboard. Vă rugăm să folosiți Ctrl + X tastatură comenzi rapide în loc de funcționare tăiat.", videoError: "Zona de text nu poate fi goală", imageWebUrl: "Adresa de internet", imageAltText: "text alternativ", dimensions: "dimensiuni", constrainProportions: "proporțiilor", linkWebUrl: "Adresa de internet", imageLink: "Imagine ca link", imageBorder: "Border Imagine", imageStyle: "Stil", linkText: "Text", linkToolTip: "tooltip", html5Support: "Această pictogramă instrument numai activat în HTML5, browserele acceptate", linkOpenInNewWindow: "Deschideți linkul într-o fereastră nouă", tableColumns: "no.of Coloane", tableRows: "Rânduri No.of", tableWidth: "Lăţime", tableHeight: "Înălţime", tableCellSpacing: "cellspacing", tableCellPadding: "cellpadding", tableBorder: "Frontieră", tableCaption: "Legendă", tableAlignment: "Aliniere", textAlign: "Aliniere text", dialogUpdate: "Actualizați", dialogInsert: "Introduce", dialogCancel: "Anulare", dialogApply: "aplica", dialogOk: "Bine", createTable: "inseraţi un tabel", addColumnLeft: "Adăugați o coloană din partea stângă", addColumnRight: "Adăugați coloana din dreapta", addRowAbove: "Adăugați un rând de mai sus", addRowBelow: "Adăugați un rând mai jos", deleteRow: "ştergeţi rândul", deleteColumn: "ştergeţi coloana", deleteTable: "Șterge din tabel", customTable: "Creați tabel personalizat ...", characters: "caractere", words: "cuvinte", general: "General", advanced: "Avansat", table: "Masa", row: "Rând", column: "Coloană", cell: "celulă", solid: "Solid", dotted: "Punctat", dashed: "punctata", doubled: "dublata", maximize: "maximaliza", resize: "minimaliza", swatches: "specimenelor", quotation: "Citat", heading1: "rubrica 1", heading2: "rubrica 2", heading3: "rubrica 3", heading4: "rubrica 4", heading5: "rubrica 5", heading6: "rubrica 6", segoeui: "Segoe UI", arial: "arial", couriernew: "Courier New", georgia: "Georgia", impact: "efect", lucidaconsole: "Lucida Console", tahoma: "Tahoma", timesnewroman: "Times New Roman", trebuchetms: "trebuchet MS", verdana: "Verdana", disc: "Disc", circle: "Cerc", square: "Pătrat", number: "Număr", loweralpha: "Alpha inferior", upperalpha: "Alpha superioară", lowerroman: "Roman inferior", upperroman: "Roman superior", none: "Nici unul", }; ej.RecurrenceEditor.Locale["ro-RO"] = { Repeat: "Repeta", Never: "Nu", Daily: "Zilnic", Weekly: "Săptămânal", Monthly: "Lunar", Yearly: "Anual", First: "Primul", Second: "Al doilea", Third: "Al treilea", Fourth: "Al patrulea", Last: "Ultimul", EveryWeekDay: "în fiecare zi lucrătoare a săptămânii", Every: "Fiecare", RecurrenceDay: "zi", RecurrenceWeek: "săptămâni", RecurrenceMonth: "Luni", RecurrenceYear: "Ani", RepeatOn: "Se repetă", RepeatBy: "Se repetă de", StartsOn: "începe", Times: "ori", Ends: "Se termină", Day: "Zi", The: "The", OfEvery: "De", After: "După", On: "Pe", Occurrence: "Întîmplările" }; ej.Schedule.Locale["ro-RO"] = { ReminderWindowTitle: "fereastră memento", CreateAppointmentTitle: "Creați Numirea", RecurrenceEditTitle: "Se repetă de editare Numirea", RecurrenceEditMessage: "Cum ați dori să schimbați numirea în serie?", RecurrenceEditOnly: "Numai această numire", RecurrenceEditSeries: "serie intreaga", PreviousAppointment: "Numirea anterioară", NextAppointment: "Numirea următor", AppointmentSubject: "Subiect", StartTime: "Timpul de începere", EndTime: "Ora de terminare", AllDay: "Toată ziua", StartTimeZone: "Lansați TimeZone", EndTimeZone: "Sfârșitul Fus orar", Today: "Astăzi", Recurrence: "Repeta", Done: "Terminat", Cancel: "Anulare", Ok: "O.K", Repeat: "Repeta", RepeatBy: "Se repetă de", RepeatEvery: "Se repetă în fiecare", RepeatOn: "Se repetă", StartsOn: "începe", Ends: "Se termină", Summary: "rezumat", Daily: "Zilnic", Weekly: "Săptămânal", Monthly: "Lunar", Yearly: "Anual", Every: "Fiecare", EveryWeekDay: "în fiecare zi lucrătoare a săptămânii", Never: "Nu", After: "După", Occurrence: "Întîmplările", On: "Pe", Edit: "Editați | ×", RecurrenceDay: "zi", RecurrenceWeek: "săptămâni", RecurrenceMonth: "Luni", RecurrenceYear: "Ani", The: "The", OfEvery: "fiecărui", First: "Primul", Second: "Al doilea", Third: "Al treilea", Fourth: "Al patrulea", Last: "Ultimul", WeekDay: "zi de lucru", WeekEndDay: "Ziua week-end", Subject: "Subiect", Categorize: "categorii", DueIn: "Datorate în", DismissAll: "Anuleaza tot", Dismiss: "destitui", OpenItem: "deschis articol", Snooze: "Pui de somn", Day: "Zi", Week: "Săptămână", WorkWeek: "Saptamana de lucru", Month: "Lună", AddEvent: "adăugaţi un eveniment", CustomView: "Vizualizare personalizată", Agenda: "Agendă", Detailed: "edita Numirea", EventBeginsin: "Începe numirea în", Editevent: "edita Numirea", Editseries: "Seria de editare", Times: "ori", Until: "pana cand", Eventwas: "numirea a fost", Hours: "ore", Minutes: "min", Overdue: "Numirea restante", Days: "zi", Event: "Eveniment", Select: "Selectați", Previous: "Anterior", Next: "Următor →", Close: "Închide", Delete: "Șterge", Date: "Data", Showin: "Afișați în", Gotodate: "Salt la data", Resources: "RESURSE", RecurrenceDeleteTitle: "Șterge Repetare Numirea", Location: "Locație", Priority: "Prioritate", RecurrenceAlert: "Alerta", NoTitle: "Fara titlu", OverFlowAppCount: "mai multe numiri", AppointmentIndicator: "Click pentru mai multe numiri", WrongPattern: "Modelul de recurență nu este validă", CreateError: "Durata de numire trebuie să fie mai scurt decât cât de frecvent apare. Scurteze durata, sau schimbați modelul recurență în caseta de dialog Numirea recurență.", DragResizeError: "Nu se poate reprograma o apariție a numirii recurente în cazul în care sare peste o apariție ulterioară a aceleiași numire.", StartEndError: "Ora de încheiere ar trebui să fie mai mare decât ora de începere", MouseOverDeleteTitle: "şterge Numirea", DeleteConfirmation: "Sunteți sigur că doriți să ștergeți această întâlnire?", Time: "Timp", EmptyResultText: "Nu există sugestii", BlockIntervalAlertTitle: "Alerta", BlockIntervalError: "Intervalul de timp selectat a fost blocat și nu este disponibilă pentru selecție." }; ej.Spreadsheet.Locale["ro-RO"] = { Cut: "A taia", Copy: "Copie", FormatPainter: "pictor format", Paste: "Pastă", PasteValues: "Valori pastă Numai", PasteSpecial: "Pastă", Filter: "Filtru", FilterContent: "Activați filtrarea pentru celulele selectate.", FilterSelected: "Filtrul de la valoarea celulei selectate", Sort: "Fel", Clear: "clar", ClearContent: "Șterge tot în celulă, sau doar elimina formatarea, conținutul, comentariile sau hyperlink-uri.", ClearFilter: "Ștergeți filtrul", ClearFilterContent: "Goliți filtrul și sortarea de stat pentru gama curentă de date.", SortAtoZ: "Sortați A la Z", SortAtoZContent: "Cel mai mic la cel mai înalt.", SortZtoA: "Sortați Z la A", SortZtoAContent: "Cea mai mare la cel mai mic.", SortSmallesttoLargest: "Sortare Cea mai mică la cea mai mare", SortLargesttoSmallest: "Sortare Cel mai mare la cea mai mica", SortOldesttoNewest: "Sortare Cele mai vechi la noi", SortNewesttoOldest: "Sortare Cele mai noi la cele mai vechi", Insert: "Introduce", InsertTitle: "insera celule", InsertContent: "Adăugați celule noi, rânduri sau coloane pentru registrul dvs. de lucru <br /> <br /> FYI:. Pentru a introduce mai multe rânduri sau coloane la un moment dat, selectați mai multe rânduri sau coloane în foaia, și faceți clic pe Inserare.", InsertSBContent: "Adăugați celule, rânduri, coloane sau foi pentru registrul de lucru.", Delete: "Șterge", DeleteTitle: "Se elimină celulele", DeleteContent: "Ștergeți celule, rânduri, coloane sau foi din registrul de lucru <br /> <br /> FYI:. Pentru a șterge mai multe rânduri sau coloane la un moment dat, selectați mai multe rânduri sau coloane în foaia, și faceți clic pe Ștergere.", FindSelectTitle: "Selectați Find &", FindSelectContent: "Click aici pentru a vedea opțiunile pentru găsirea unui text în document.", CalculationOptions: "Opțiuni de calcul", CalcOptTitle: "Opțiuni de calcul", CalcOptContent: "Alege să calculeze în mod automat sau manual formule. <br/> Dacă faceți o schimbare care afectează o valoare, Spreadsheet se va recalcula în mod automat.", CalculateSheet: "Se calculează Foaie", CalculateNow: "Se calculează acum", CalculateNowContent: "Se calculează întregul registru de lucru acum. <br/> Trebuie doar să utilizați această opțiune dacă calcularea automată este dezactivată.", CalculateSheetContent: "Se calculează foaia activă acum. <br/> Trebuie doar să utilizați această opțiune dacă calcularea automată este dezactivată.", Title: "spreadsheet", Ok: "bine", Cancel: "Anulare", Alert: "Nu am putut face acest lucru pentru gama de celule selectate. Selectați o singură celulă într-o serie de date și apoi încercați din nou.", HeaderAlert: "Comanda nu a putut fi finalizată în timp ce încercați să filtreze cu antetul filtrului. Selectați o singură celulă în intervalul de filtru și încercați din nou comanda.", FlashFillAlert: "Toate datele de lângă selecția a fost verificată și nu a existat nici un model de completare a valorilor.", Formatcells: "format Cells", FontFamily: "font", FFContent: "Alege un nou font pentru text.", FontSize: "Mărimea fontului", FSContent: "Schimba dimensiunea textului.", IncreaseFontSize: "Mărește dimensiunea fontului", IFSContent: "Asigurați-vă textul un pic mai mare.", DecreaseFontSize: "Micșorează dimensiunea fontului", DFSContent: "Asigurați-vă textul un pic mai mic.", Bold: "Îndrăzneţ", Italic: "Cursiv", Underline: "sublinia", Linethrough: "bifa", FillColor: "Culoarea de umplere", FontColor: "Culoarea fontului", TopAlign: "Sus Aliniere", TopAlignContent: "Se aliniază textul la partea de sus.", MiddleAlign: "Orientul Mijlociu Aliniere", MiddleAlignContent: "Alinierea textului, astfel încât să fie centrat între partea de sus și de jos a celulei.", BottomAlign: "Aliniere fund", BottomAlignContent: "Se aliniază textul la partea de jos.", WrapText: "Încadra textul", WrapTextContent: "Înfășurați de text foarte lung în mai multe linii, astfel încât să puteți vedea toate.", AlignLeft: "Aliniere la stânga", AlignLeftContent: "Aliniază conținutul la stânga.", AlignCenter: "Centru", AlignCenterContent: "Centreaza conținutul.", AlignRight: "Aliniere la dreapta", AlignRightContent: "Aliniază conținutul la dreapta.", Undo: "Anula", Redo: "refaceţi", NumberFormat: "Formatul numerelor", NumberFormatContent: "Alegeți formatul pentru celulele dvs., cum ar fi procentul, moneda, data sau ora.", AccountingStyle: "Stilul de contabilitate", AccountingStyleContent: "Formatul ca format număr de contabilitate dolar.", PercentageStyle: "procente Stil", PercentageStyleContent: "Format ca procent.", CommaStyle: "Stilul virgule", CommaStyleContent: "Formatul fără a mii de separare.", IncreaseDecimal: "Creștere de zecimale", IncreaseDecimalContent: "Afișați mai multe zecimale pentru o valoare mai precisă.", DecreaseDecimal: "Scădere zecimală", DecreaseDecimalContent: "Afișați mai puține zecimale.", AutoSum: "AutoSum", AutoSumTitle: "Sumă", AutoSumContent: "adăugați automat un calcul rapid la foaia de lucru, cum ar fi suma sau media.", Fill: "Completati", ExportXL: "excela", ExportCsv: "CSV", SaveXml: "Salvați XML", BackgroundColor: "Culoarea de umplere", BGContent: "Colora fundalul celulelor pentru a le face să iasă în evidență.", ColorContent: "Schimba culoarea textului.", Border: "Frontieră", BorderContent: "Aplica frontierele la celulele selectate în mod curent.", BottomBorder: "chenar jos", TopBorder: "Border top", LeftBorder: "chenarul din stânga", RightBorder: "Border dreapta", OutsideBorder: "frontierele exterioare", NoBorder: "fără chenar", AllBorder: "toate frontiere", ThickBoxBorder: "Caseta de gros de frontieră", ThickBottomBorder: "Border fund gros", TopandThickBottomBorder: "Sus și Gros chenarul inferior", DrawBorderGrid: "Grila de frontieră remiză", DrawBorder: "Desenați chenarul", TopandBottomBorder: "Sus și chenar jos", BorderColor: "Culoare linie", BorderStyle: "Stil linie", Number: "Numărul este folosit pentru afișarea generală a numerelor. Moneda si oferta de contabilitate specializate de formatare pentru valoarea monetară.", General: "Celulele Formatul general nu au nici un format de număr specific.", Currency: "Formatele sunt utilizate pentru moneda valori monetare generale. Utilizează formate contabile pentru a alinia punctele zecimale într-o coloană.", Accounting: "Formatele contabile se aliniază simbolurile monetare și punctele zecimale într-o coloană.", Text: "Celulele în format de text sunt tratate ca text chiar și atunci când un număr este în celulă. Este afișată celula exact așa cum au intrat.", Percentage: "Formatele procentuale multiplica valoarea celulei cu 100 și afișează rezultatul cu un simbol la sută.", CustomMessage: "Tip de cod formatul numeric, utilizând unul din codul existent ca punct de plecare.", Fraction: " ", Scientific: " ", Type: "Tip:", CustomFormatAlert: "Introduceți un format valid", Date: "Dată formate de afișare a datei și orei numerelor de serie ca valori de dată.", Time: "Ora formatează data de afișare și a numerelor de serie de timp ca valori de date.", File: "FIŞIER", New: "Nou", Open: "Deschis", SaveAs: "Salvează ca", Print: "Imprimare", PrintContent: "Imprimarea paginii curente.", PrintSheet: "Fișa de imprimare", PrintSelected: "imprimare selectat", PrintSelectedContent: "Selectați o zonă de pe foaia pe care doriți să le imprimați.", HighlightVal: "Formatul datelor este nevalid", ClearVal: "Șterge validare", Validation: "Validare", DataValidation: "Data validarii", DVContent: "Alege dintr-o listă de reguli pentru a limita tipul de date care pot fi introduse într-o celulă.", A4: "A4", A3: "A3", Letter: "Scrisoare", PageSize: "Mărimea paginii", PageSizeContent: "Alegeți o dimensiune de pagină pentru documentul.", FormatCells: "format Cells", ConditionalFormat: "Formatarea condițională", CFContent: "ușurință la fața locului tendințe și modele în datele folosind culori pentru a evidenția vizual valori importante.", And: "și", With: "cu", GTTitle: "Mai mare ca", GTContent: "Formatarea celulelor care sunt mai mari:", LTTitle: "Mai puțin decât", LTContent: "Formatarea celulelor, care sunt mai mici:", BWTitle: "Între", BWContent: "Formatarea celulelor care sunt între:", EQTitle: "Egal cu", EQContent: "Formatarea celulelor care sunt la egal cu:", DateTitle: "A Data Aparute", DateContent: "Formatarea celulelor care contin o data:", ContainsTitle: "Text care conține", ContainsContent: "Formatarea celulelor care conțin textul:", GreaterThan: "Mai mare ca", LessThan: "Mai puțin decât", Between: "Între", EqualTo: "Egal cu", TextthatContains: "Textul care conține", DateOccurring: "A Data Aparute", ClearRules: "Reguli clare", ClearRulesfromSelected: "Reguli clare din celule selectate", ClearRulesfromEntireSheets: "Reguli clare din Întreaga foaie", CellStyles: "Stiluri de celule", CellStylesContent: "Un stil plin de culoare este o modalitate foarte bună de a face datele importante să iasă în evidență pe foaie.", CellStyleHeaderText: "Bune, rele și neutre / Titluri și Pozițiile / Cärti Stiluri celulă", Custom: "Tastați codul formatul numeric, utilizând unul dintre codurile existente ca punct de plecare.", CellStyleGBN: "Normal / Bad / Bun / neutru", CellStyleTH: "Rubrica 4 / titlu", CellsStyleTCS: "20% - Accent1 / 20% - Accent2 / 20% - Accent3 / 20% - Accent4 / 60% - Accent1 / 60% - Accent2 / 60% - Accent3 / 60% - Accent4 / Accent1 / Accent2 / Accent3 / Accent4", Style: "Stil", FormatAsTable: "Formatul După cum arată tabelul", FormatasTable: "Formatul ca tabelul", FATContent: "converti rapid o serie de celule la o masă cu propriul său stil.", FATHeaderText: "Lumină / Mediu / inchis", FATNameDlgText: "Nume tabel: / Masa mea are antete", InvalidReference: "Intervalul în care ați specificat este nevalid", ResizeAlert: "Intervalul specificat este nevalid. Partea superioară a tabelului trebuie să rămână în același rând, iar tabelul rezultat trebuie să se suprapună tabelului original. Specificați un interval valid.", RangeNotCreated: "Creșterea rândului dincolo de numărul maxim de rânduri foaie este restricționată în format ca și tabelul.", ResizeRestrictAlert: "Creșterea sau descreșterea numărului coloanei și scăderea numărului de rânduri este restricționată în format ca și tabelul.", FATResizeTableText: "Introdu o nouă gamă de date pentru un tabel:", FATReizeTableNote: "Notă: antetele trebuie să rămână în același rând și intervalul de masă ce rezultă trebuie să se suprapună peste intervalul tabelul original.", FormatAsTableAlert: "Nu se poate crea un tabel cu un singur rând. Un tabel trebuie să aibă cel puțin două rânduri, unul pentru antetul de tabel, și unul pentru date", FormatAsTableTitle: "Lumină 1 / lumină 2 / lumină 3 / lumină 4 / lumină 5 / lumină 6 / lumină 7 / lumină 8 / lumină 9 / lumină 10 / lumină 11 / lumină 12 / Mediu 1 / Mediu 2 / Mediu 3 / Mediu 4 / Mediu 5 / Mediu 6 / Mediu 7 / Mediu 8 / întuneric 1 / întuneric 2 / întuneric 3 / întuneric 4", NewTableStyle: "Nou stil tabel", ResizeTable: "resize Tabel", ResizeTableContent: "Redimensionarea acest tabel prin adăugarea sau eliminarea de rânduri și coloane.", ConvertToRange: "Converti la gama", ConvertToRangeContent: "Converti acest tabel într-un interval normal de celule.", ConverToRangeAlert: "Doriți să convertiți tabelul de la un interval normal?", TableID: "Tabelul ID:", Table: "Masa", TableContent: "Creați un tabel pentru a organiza și a analiza datele aferente.", TableStyleOptions: "Prima coloană / ultima coloană / Total Row / Buton Filtru", Format: "Format", NameManager: "numele managerului", NameManagerContent: "Creați, editați, ștergeți și pentru a găsi toate denumirile utilizate în registrul de lucru. <br /> <br /> Alte denumiri pot fi utilizate în formule ca înlocuitori pentru referințe de celule.", DefinedNames: "Nume definite", DefineName: "definiți Nume", DefineNameContent: "Să definească și să aplice nume.", UseInFormula: "Utilizare în proces cu Formula", UseInFormulaContent: "Alege un nume folosit în acest registru de lucru și introduceți-l în formula actuală.", RefersTo: "Se refera la", Name: "Nume", Scope: "domeniu", NMNameAlert: "Numele pe care l-ați introdus nu este valid./Reason pentru acest lucru poate include: / numele nu începe cu o literă sau o linie de subliniere / numele conține un spațiu sau alte caractere nevalide / nume conflictele cu o foaie de calcul încorporat în numele sau numele unui alt obiect din registrul de lucru, // nu este utilizat complet", NMUniqueNameAlert: "Numele introdus există deja. Introduceți un nume unic.", NMRangeAlert: "Introduceți un interval valid", FORMULAS: "FORMULE", DataValue: "valori:", Value:"valori", Formula: "formulele", MissingParenthesisAlert: "formula dvs. lipsește un parenthesis--) sau (. Verificați cu formula, apoi adăugați paranteze în locul potrivit.", UnsupportedFile: "Fișier neacceptată", IncorrectPassword: "Nu se poate deschide fișierul sau foaia de lucru cu parola dată", InvalidUrl: "Vă rugăm să specificați URL-ul propriu-zis", Up: "Sus", Down: "Jos", Sheet: "Foaie", Workbook: "Workbook", Rows: "pe rânduri", Columns: "pe coloane", FindReplace: "găsi Înlocuire", FindnReplace: "Găsi și înlocuire", Find: "Găsi", Replace: "A inlocui", FindLabel: "Gaseste ce:", ReplaceLabel: "Înlocui cu:", ReplaceAll: "Înlocuiește-le pe toate", Close: "Închide", FindNext: "Găsește următorul", FindPrev: "găsi Prev", Automatic: "Automat", Manual: "Manual", Settings: "setările", MatchCase: "caz meci", MatchAll: "Se potrivesc întregul conținut al celulelor", Within: "În:", Search: "Căutare:", Lookin: "Uită-te în:", ShiftRight: "Celulele Shift din dreapta", ShiftBottom: "Celulele de schimbare în jos", EntireRow: "rând întregul", EntireColumn: "coloană întreagă", ShiftUp: "Celulele Shift sus", ShiftLeft: "Celulele de schimbare din stânga", Direction: "Direcţie:", GoTo: "Mergi la", GoToName: "Mergi la:", Reference: "Referinţă:", Special: "Special", Select: "Selecta", Comments: "Comentarii", Formulas: "formulele", Constants: "constantele", RowDiff: "diferenţele de rând", ColDiff: "diferenţele de coloană", LastCell: "ultima celulă", CFormat: "formate condiționale", Blanks: "eboșe", GotoError: "Eroare", GotoLogicals: "Logicals", GotoNumbers: "numere", GotoText: "Text", FindSelect: "Selectați Find &", Comment: "cometariu", NewComment: "Nou", InsertComment: "inseraţi un comentariu", EditComment: "Editați | ×", DeleteComment: "şterge Comentariu", DeleteCommentContent: "Șterge comentariul selectat.", HideComment: "Ascundeți Comentariu", Next: "Următor →", NextContent: "Salt la comentariul următor.", Previous: "Anterior", PreviousContent: "Salt la comentariul anterior.", ShowHide: "Arată / Ascunde Comentariu", ShowHideContent: "Afișarea sau ascunderea comentariu pe celula activă.", ShowAll: "Afișați toate comentariile", ShowAllContent: "Afișează toate comentariile din foaie.", UserName: "Nume de utilizator", Hide: "Ascunde", Unhide: "Reafișați", Add: "Adăuga", DropAlert: "Doriți să înlocuiți datele existente?", PutCellColor: "Pune-Selected Color Cell Pentru Top", PutFontColor: "Pune-Selected Font Color To The Top", WebPage: "Pagină web", WorkSheet: "Fișa de lucru de referință", SheetReference: "Fișa de referință", InsertHyperLink: "insert Hyperlink", HyperLink: "hipertext", EditLink: "editaţi link", OpenLink: "Deschide link-ul", HyperlinkText: "Text:", RemoveLink: "Elimină linkul", WebAddress: "Adresa de internet:", CellAddress: "Celulă de referință:", SheetIndex: "Selectați un loc în acest document", ClearAll: "Curata tot", ClearFormats: "Formate clare", ClearContents: "Conținut clare", ClearComments: "Șterge Comentarii", ClearHyperLinks: "clar Hyperlinkuri", SortFilter: "Sort & Filter", SortFilterContent: "Organizați-vă datele dvs., astfel încât este mai ușor de analizat.", NumberStart: "Minim:", NumberEnd: "Maxim:", DecimalStart: "Minim:", DecimalEnd: "Maxim:", DateStart: "Data de început:", DateEnd: "Data de încheiere:", ListStart: "Sursă:", FreeText: "Alertă Afișează eroare după ce datele nevalide sunt introduse", ListEnd: "Celulă de referință:", TimeStart: "Timpul de începere:", TimeEnd: "Ora de terminare:", TextLengthStart: "Minim:", TextLengthEnd: "Maxim:", CommentFindEndAlert: "Spreadsheet a ajuns la sfârșitul registrului de lucru. Doriți să continue revizuirea de la începutul registrului de lucru?", InsertSheet: "Introduce", DeleteSheet: "Șterge", RenameSheet: "redenumire", MoveorCopy: "Muta sau Copiere", HideSheet: "Ascunde", UnhideSheet: "Reafișați", SheetRenameAlert: "Acel nume este deja luat. Încercați unul diferit.", SheetRenameEmptyAlert: "Ați introdus un nume nevalid pentru o foaie. Asigurați-vă că: <ul> <li> Numele pe care îl introduceți nu depășește 31 de caractere </ li> <li> Numele nu conține oricare dintre următoarele caractere:. \ /? * [Sau] </ li> <li> nu lăsați numele martor. </ Li> </ ul>", SheetDeleteAlert: "Nu puteți anula ștergerea foi, și s-ar putea fi eliminarea unor date. Daca nu au nevoie de ea, faceți clic pe OK pentru a șterge.", SheetDeleteErrorAlert: "Un registru de lucru trebuie să conțină cel puțin o foaie de lucru vizibil. Pentru a ascunde, șterge, sau mutați foaia selectată, trebuie să introduceți mai întâi o nouă foaie sau o foaie care unhide este deja ascunsă.", CtrlKeyErrorAlert: "Această comandă nu poate fi folosit pe mai multe selecții.", MoveToEnd: "Mutare la sfârșitul", Beforesheet: "Înainte de a foaie:", CreateaCopy: "Creați o copie", AutoFillOptions: "Copiere celule / Fill Series / Fill Formatare numai / Fill Fără formatare / Flash Fill", NumberValidationMsg: "Introduceți numai cifre", DateValidationMsg: "Introdu o dată numai", Required: "Necesar", TimeValidationMsg: "Timpul pe care ați introdus pentru Time este nevalid.", CellAddrsValidationMsg: "De referință nu este validă.", PivotTable: "Masă rotativă", PivotTableContent: "aranja cu ușurință și să rezume date complexe într-un tabel pivot.", NumberTab: "Număr", AlignmentTab: "Aliniere", FontTab: "font", FillTab: "Completati", TextAlignment: "alinierea textului", Horizontal: "Orizontală:", Vertical: "Vertical:", Indent: "Indentați", TextControl: "Controlul textului", FontGroup: "font:", FontStyle: "Stilul fontului:", Size: "Mărimea:", PSize: "Mărimea paginii", Effects: "Efecte:", StrikeThrough: "strikethrough", Overline: "overline", NormalFont: "font normal", Preview: "previzualizare", PreviewText: "AaBbCc ZyZz", Line: "Linia", Presets: "presetari", None: "Nici unul", Outline: "Contur", AllSide: "toate părțile", InsCells: "insera celule", InsRows: "Inserați rânduri de tablă", InsCols: "Se introduce Coloane de tablă", InsSheet: "inseraţi Sheet", DelCells: "Se elimină celulele", DelRows: "Ștergeți rândurile de tablă", DelCols: "Ștergere coloane de tablă", DelSheet: "ştergeţi foaia", HyperLinkAlert: "Adresa acestui site nu este valid.Check adresa și încercați din nou.", ReplaceData: "Totul este gata. Noi am făcut / înlocuiri.", NotFound: "Nu am putut găsi ceea ce căutați. Selectați setări fila pentru mai multe moduri de a căuta", Data: "Date:", Allow: "Permite:", IgnoreBlank: "ignore martor", NotFind: "Nu se poate găsi meciul pentru a înlocui", FreezeRow: "Congela Top Row", FreezeColumn: "Freeze Prima coloană", UnFreezePanes: "dezghețarea panourilor", DestroyAlert: "Sunteți sigur că doriți să distrugă registrul de lucru curent fără a salva și de a crea un nou registru de lucru?", ImageValAlert: "Încărcați numai fișiere imagine", Pictures: "poze", PicturesTitle: "din fișier", PicturesContent: "Insera imagini de la calculator sau de la alte computere pe care sunt conectate.", ImportAlert: "Sunteți sigur că doriți să distrugă registrul de lucru curent fara a salva si deschide un nou registru de lucru?", UnmergeCells: "Anulați îmbinarea celulelor", MergeCells: "Uneste celulele", MergeAcross: "îmbinați", MergeAndCenter: "Îmbinați & Center", MergeAndCenterContent: "Se combină și centru conținutul celulelor selectate într-o nouă celulă mai mare.", MergeCellsAlert: "Contopirea Celulele păstrează valoarea celulei numai din stânga sus și aruncate înapoi în mare celelalte valori.", MergeInsertAlert: "Această operațiune va face ca unele celule au fuzionat pentru a anula îmbinarea. Doriți să continuați?", Axes: "axă", PHAxis: "orizontal primar", PVAxis: "vertical primar", AxisTitle: "Titlu axă", CTNone: "Nici unul", CTCenter: "Centru", CTFar: "Departe", CTNear: "Aproape", DataLabels: "Etichete de date", DLNone: "Nici unul", DLCenter: "Centru", DLIEnd: "în interiorul End", DLIBase: "în interiorul bazei", DLOEnd: "Sfârșitul afara", ErrorBar: "eroare Baruri", Gridline: "Linii de rețea", PMajorH: "Primar Major orizontală", PMajorV: "Primar Major Vertical", PMinorH: "Minor primară orizontală", PMinorV: "Primar Major Vertical", Legend: "legendele", LNone: "Nici unul", LLeft: "Stânga", LRight: "Dreapta", LBottom: "Fund", LTop: "Top", ChartTitleDlgText: "introduceţi titlul", ChartTitle: "Titlu", InvalidTitle: "Ați introdus un nume nevalid pentru titlu.", CorrectFormat: "Selectați formatul de fișier corect", ResetPicture: "reseta imaginea", ResetPictureContent: "Se aruncă toate modificările de formatare aduse de această imagine.", PictureBorder: "Imaginea de frontieră", PictureBorderContent: "Alege culoarea, lățimea și stilul liniei pentru conturul formei.", ResetSize: "Imagine & Dimensiune reinițializa", Height: "Înălţime", Width: "Lăţime", ThemeColor: "Tema Culori", NoOutline: "nr contur", Weight: "Greutate", Dashes: "cratimele", ColumnChart: "2-D Coloana / Coloana 3D", ColumnChartTitle: "Inserare coloană Chart", ColumnChartContent: "Utilizați acest tip de diagramă pentru a compara vizual valori peste câteva categorii.", BarChart: "2-D Bar / Bar 3D", BarChartTitle: "Inserați Bar Chart", BarChartContent: "Utilizați acest tip de diagramă pentru a compara vizual valori peste câteva categorii atunci când diagrama arată durata sau textul categoriei este lung.", StockChart: "Radar", StockChartTitle: "Se introduce Radar Chart", StockChartContent: "Utilizați acest tip de diagramă pentru a arăta valori relative la un punct central.", LineChart: "2-D linie", LineChartTitle: "Inserați Linie Chart", LineChartContent: "Utilizați acest tip de diagramă pentru a arăta tendințele în timp (ani, luni și zile) sau categorii.", AreaChart: "2-D Zona / Zona 3D", AreaChartTitle: "Inserați Zona Grafic", AreaChartContent: "Utilizați acest tip de diagramă pentru a arăta tendințele în timp (ani, luni și zile) sau categorii. L utilizați pentru a evidenția magnitudinea schimbării în timp.", ComboChart: "combo", PieChart: "Plăcintă", PieChartTitle: "Pie inserați / Gogoașă Chart", PieChartContent: "Utilizați acest tip de diagramă pentru a arăta proporțiile unui întreg. Folosiți-l când totalul numerelor este de 100%.", ScatterChart: "Împrăștia", ScatterChartTitle: "Inserați Scatter (X, Y) Grafic", ScatterChartContent: "Utilizați acest tip de diagramă pentru a arăta relația dintre seturi de valori.", ClusteredColumn: "Grupate & nbsp; Coloana", StackedColumn: "Stivuit & nbsp; Coloana", Stacked100Column: "100% & nbsp; grupată & nbsp; Coloana", Cluster3DColumn: "3D & nbsp; & nbsp Clustered; Coloană", Stacked3DColumn: "3D & nbsp; & nbsp grupată; Coloană", Stacked100Column3D: "3D & nbsp; 100% & nbsp; grupată & nbsp; Coloana", ClusteredBar: "Grupate & nbsp; Bar", StackedBar: "Stivuit & nbsp; Bar", Stacked100Bar: "100% & nbsp; grupată & nbsp; Bar", Cluster3DBar: "3D & nbsp; & nbsp Clustered; Bar", Stacked3DBar: "3D & nbsp; grupată & nbsp; Bar", Stacked100Bar3D: "3D & nbsp; 100% & nbsp; grupată & nbsp; Bar", Radar: "Radar", RadarMarkers: "Radar & nbsp; lățime & nbsp; Marcatori", LineMarkers: "Line & nbsp; lățime & nbsp; Marcatori", Area: "Zonă", StackedArea: "Stivuit & nbsp; Zona", Stacked100Area: "100% & nbsp; grupată & nbsp; Zona", Pie: "Plăcintă", Pie3D: "3-D & nbsp; Pie", Doughnut: "Gogoașă", Scatter: "Împrăștia", ChartRange: "Grafic Range", XAxisRange: "Intrați în zona de axa X:", YAxisRange: "Gama Y-introduceți axa:", LegendRange: "Introdu o gama legenda:", YAxisMissing: "Gama Y-introduceți axa pentru a crea diagramă", InvalidYAxis: "Gama axa Y trebuie să fie în intervalul selectat", InvalidXAxis: "Gama de axa X trebuie să fie în intervalul selectat", InvalidLegend: "Gama Legenda trebuie să fie în intervalul selectat", InvalidXAxisColumns: "Gama axa X ar trebui să fie într-o singură coloană", FreezePanes: "Înghețare panouri", FreezePanesContent: "Congela o porțiune a foii să-l păstrați vizibil în timp ce parcurge restul foii.", PasteTitle: "Paste (Ctrl + V)", PasteContent: "Adăugați conținut în Clipboard pentru documentul dumneavoastră.", PasteSplitContent: "Alege o opțiune de pastă, cum ar fi păstrarea formatarea sau lipirea numai conținutul.", CutTitle: "Cut (Ctrl + X)", CutContent: "Înlătura selecția și puneți-l pe Clipboard, astfel încât să puteți lipi în altă parte.", CopyTitle: "Copiere (Ctrl + C)", CopyContent: "Puneți o copie a selecției pe Clipboard, astfel încât să puteți lipi în altă parte.", FPTitle: "pictor format", FPContent: "La fel ca și aspectul unui anumit selecție? Puteți aplica acea privire la alte tipuri de conținut în document.", BoldTitle: "Bold (Ctrl + B)", BoldContent: "Asigurați-vă textul cu caractere aldine.", ItalicTitle: "Italic (Ctrl + I)", ItalicContent: "Italicize textul.", ULineTitle: "Subliniem (Ctrl + U)", ULineContent: "Subliniem textul.", LineTrTitle: "Strikethrough (Ctrl + 5)", LineTrContent: "Centrarea ceva prin tragere la o grevă prin ea.", UndoTitle: "Undo (Ctrl + Z)", UndoContent: "Anulați ultima acțiune.", RedoTitle: "Refaceți (Ctrl + Y)", RedoContent: "Refaceți ultima acțiune.", TableTitle: "Tabel (Ctrl + T)", HyperLinkTitle: "Se adaugă un Hyperlink (Ctrl + K)", HyperLinkContent: "Creați un link în documentul dvs. pentru a avea acces rapid la paginile web și fișiere. <br /> <br /> Hiperlinkurile puteți lua, de asemenea, locuri în documentul.", NewCommentTitle: "Se introduce un comentariu", NewCommentContent: "Adăugați o notă despre această parte a documentului.", RefreshTitle: "Reîmprospăta", RefreshContent: "Obțineți cele mai recente date de la sursa conectată la celula activă", FieldListTitle: "Lista de câmp", FieldListContent: "Afișați sau ascundeți lista de câmpuri. <br /> <br /> Lista câmp vă permite să adăugați și să eliminați câmpurile din raportul PivotTable", AddChartElement: "Add Element Chart", AddChartElementContent: "Adăuga elemente la diagrama creată.", SwitchRowColumn: "Comutator rând / coloană", SwitchRowColumnContent: "Swap datele pe axa.", MergeAlert: "Nu putem face asta într-o celulă îmbinată.", UnhideDlgText: "Fișa Reafișați:", ChartThemes: "Teme diagramă", ChartThemesContent: "Alege o nouă temă pentru diagramă.", ChangePicture: "Schimbați fotografia", ChangePictureContent: "Schimba la o imagine diferită, păstrând formatarea și dimensiunea imaginii curente.", ChangeChartType: "Grafic schimbare Tip", SelectData: "Selectați date", SelectDataContent: "Schimbați intervalul de date incluse în diagramă.", Sum: "Sumă", Average: "In medie", CountNumber: "Numar de numere", Max: "max", Min: "min", ChartType: "Grafic schimbare Tip", ChartTypeContent: "Schimba la un alt tip de diagramă.", AllCharts: "toate Grafice", defaultfont: "Mod implicit", LGeneral: "General", LCurrency: "Valută", LAccounting: "Contabilitate", LDate: "Data", LTime: "Timp", LPercentage: "Procent", LFraction: "Fracțiune", LScientific: "Științific", LText: "Text", LCustom: "Personalizat", FormatSample: "Probă", Category: "Categorie:", Top: "Top", Center: "Centru", Bottom: "Fund", Left: "Stânga (Indentați)", Right: "Dreapta", Justify: "Justifica", GeneralTxt: "Celulele Formatul general nu au nici un format de număr specific.", NegativeNumbersTxt: "Numerele negative", ThousandSeparatorTxt: "1000 Separator folosi", DecimalPlacesTxt: "Zecimale:", TextTxt: "Celulele în format de text sunt tratate ca text chiar și atunci când un număr este în celulă. Este afișată celula exact așa cum au intrat.", BoldItalic: "aldin cursiv", Regular: "Regulat", HyperLinkHide: "<< Selecția în documentul >>", InvalidSheetIndex: "Se specifică SheetIndex corespunzătoare", HugeDataAlert: "Fișierul este prea mare pentru a deschide.", ImportExportUrl: "Dă-import / export, URL-ul și încercați din nou.", TitleColumnChart: "Coloana grupată / Coloana grupată / 100% Coloana grupată grupată / 3D Coloana / Coloana 3D grupată / Coloana 3D 100% grupată", TitleBarChart: "Bar Grupate / Stacked Bar / 100% grupată Bar / 3D Bar Clustered / 3D Stacked Bar / 3D 100% grupată Bar", TitleRadarChart: "Radar / radar cu markeri", TitleLineChart: "Linie / linie cu marcatori", TitleAreaChart: "Zona / grupată Zona / 100% grupată Suprafata", TitlePieChart: "Pie / 3D Pie / Gogoașă", TitleScatterChart: "Împrăștia", BetweenAlert: "Valoarea maximă trebuie să fie mai mare sau egală cu minimum.", BorderStyles: "Solid / Dashed / Punctate", FPaneAlert: "Freeze pane nu se aplică pentru prima celulă", ReplaceNotFound: "Spreadsheet nu poate găsi un meci.", BlankWorkbook: "registru de lucru necompletat", SaveAsExcel: "Salvare Excel", SaveAsCsv: "Salvează ca și CSV", Design: "PROIECTA", NewName: "Nume nou", FormulaBar: "cu formula Bar", NameBox: "numele Caseta", NumberValMsg: "Valorile zecimale nu pot fi utilizate în condiții de numere.", NumberAlertMsg: "Introduceți numai cifre.", ListAlert: "Gama de celule este incorectă, vă rugăm să introduceți intervalul de celule corecte.", ListValAlert: "Sursa de listă trebuie să fie o listă delimitată, sau o trimitere la un singur rând sau coloană.", ListAlertMsg: "Valoarea pe care ați introdus nu este valid", AutoFillTitle: "Opțiuni de completare automată", NewSheet: "Foaie nouă", FullSheetCopyPasteAlert: "Nu putem lipiți deoarece zona de copiere și zona de pastă nu sunt de aceeași dimensiune.", Heading: "rubrici", Gridlines: "Linii de rețea", Firstsheet: "Derulați până la prima foaie", Lastsheet: "Derulați până la ultima foaie", Nextsheet: "Derulați până la următoarea foaie", Prevsheet: "Derulați până la foaia anterioară", ProtectWorkbook: "proteja Workbook", UnProtectWorkbook: "Deprotejează Workbook", ProtectWBContent: "Să păstreze alte persoane să efectueze modificări structurale în registrul de lucru", Password: "Parola", ConfirmPassword: "Re Introduceți parola pentru a continua:", PasswordAlert1: "Parola de confirmare nu este identică.", PasswordAlert2: "Vă rugăm să introduceți o parolă.", PasswordAlert3: "Parola pe care ați furnizat nu este corect. Verificați dacă că tasta CAPS LOCK este oprit și asigurați-vă că pentru a utiliza corect capitalizarea.", Protect: "este protejat.", Lock: "Celula de blocare", Unlock: "deblocați Cell", Protectsheet: "Protejați foaia", ProtectSheeToolTip: "Preveni modificările nedorite de altele prin limitarea capacității acestora de a edita", Unprotect: "Fișa Deprotejează", LockAlert: "Celula pe care încercați să schimbați este pe foaia protejată. Pentru a efectua modificări, faceți clic pe Sheet Deprotejează în fila Revizuire.", CreateRule: "Regula nouă", NewRule: "Noua regula de formatare", NewRuleLabelContent: "Valorile format în cazul în care această formulă este adevărată:", InsertDeleteAlert: "Această operație nu este permisă. Operația este încercarea de a comuta celule într-un tabel de pe foaia de lucru.", ReadOnly: "Zona pe care încercați să schimbați conține citi numai celule.", CreatePivotTable: "Creați Tabel pivot", Range: "Gamă:", ChoosePivotTable: "Alegeți unde doriți ca PivotTable să fie plasat", NewWorksheet: "Foaie de lucru nouă", ExistingWorksheet: "Fișa de lucru existente", Location: "Locație:", Refresh: "Reîmprospăta", PivotRowsAlert: "Această comandă necesită cel puțin două rânduri de date sursă. Nu puteți utiliza comanda pe o selecție într-un singur rând.", PivotLabelsAlert: "Numele câmpului al PivotTable nu este validă, pentru a crea un raport PivotTable, trebuie să utilizați datele care sunt organizate sub forma unei liste cu coloane etichetate. Dacă modificați numele unui câmp pivottable, trebuie să tastați un nume nou pentru câmpul.", FieldList: "Lista de câmp", MergeSortAlert: "Pentru a face acest lucru, toate celulele au fuzionat, au nevoie să fie de aceeași dimensiune.", FormulaSortAlert: "Intervalul de sortare cu formula generală nu pot fi sortate.", MergePreventInsertDelete: "Această operație nu este permisă. Operația este încercarea de a transfera o îmbinare de celule de pe foaia de lucru.", FormulaRuleMsg: "Vă rugăm să introduceți formatul corect.", MovePivotTable: "Mutați Tabel pivot", MovePivotTableContent: "Mutați Pivot Table într-o altă locație din registrul de lucru.", ClearAllContent: "Elimina câmpuri și filtre.", ChangeDataSource: "Modifica", ChangeDataSourceContent: "Schimba datele sursă pentru acest PivotTable", ChangePivotTableDataSource: "Sursa de date PivotTable schimba", TotalRowAlert: "Această operație nu este permisă. Operația este încercarea de a comuta celule într-un tabel de pe foaia de lucru. Faceți clic pe OK pentru a continua cu întreg rând.", CellTypeAlert: "Această operațiune nu este permisă în intervalul aplicat tipul de celule.", PivotOverlapAlert: "Un raport Tabel pivot nu se poate suprapune un alt raport Tabel pivot", NoCellFound: "Nu există celule au fost găsite", }; ej.TreeGrid.Locale["ro-RO"] = { toolboxTooltipTexts: { addTool: "Adăuga", editTool: "Editați | ×", updateTool: "Actualizați", deleteTool: "Șterge", cancelTool: "Anulare", expandAllTool: "Extinde toate", collapseAllTool: "Reduceți totul În această", pdfExportTool: "Export PDF", excelExportTool: "Excel Export" }, contextMenuTexts: { addRowText: "adăugaţi un rând", editText: "Editați | ×", deleteText: "Șterge", saveText: "Salvați", cancelText: "Anulare", aboveText: "De mai sus", belowText: "De mai jos" }, columnMenuTexts: { sortAscendingText: "sortare ascendentă", sortDescendingText: "sortează descendent", columnsText: "coloane", freezeText: "Îngheţa", unfreezeText: "Dezghețați", freezePrecedingColumnsText: "Îngheța coloanele precedente", insertColumnLeft: "Inserare coloană pe stânga", insertColumnRight: "Inserare coloană pe dreapta", deleteColumn: "ştergeţi coloana", renameColumn: "redenumire coloană" }, columnDialogTexts: { field: "Camp", headerText: "Text antet", editType: "Editare tip", filterEditType: "Se filtrează Editare tip", allowFiltering: "permite filtrarea", allowFilteringBlankContent: "Permite filtrarea conținutului Blank", allowSorting: "Se permite sortare", visible: "Vizibil", width: "Lăţime", textAlign: "Aliniere text", headerTextAlign: "Text antet Aliniere", isFrozen: "Este inghetat", allowFreezing: "Se lasă congelare", columnsDropdownData: "Coloană Drop Down date", dropdownTableText: "Text", dropdownTableValue: "Valoare", addData: "Adăuga", deleteData: "Elimina", allowCellSelection: "Permite selectarea de celule" }, columnDialogTitle: { insertColumn: "Inserare coloană", deleteColumn: "ştergeţi coloana", renameColumn: "redenumire coloană" }, deleteColumnText: "Sunteți sigur că doriți să ștergeți această coloană?", okButtonText: "bine", cancelButtonText: "Anulare", confirmDeleteText: "confirmaţi ștergerea", dropDownListBlanksText: "(Blanc)", dropDownListClearText: "(Clear Filter)", trueText: "Adevărat", falseText: "Fals", emptyRecord: "Nu exista inregistrari pentru a afișa", }; ej.Uploadbox.Locale["ro-RO"] = { buttonText: { upload: "Încărcați", browse: "Naviga", cancel: "Anulare", close: "Închide" }, dialogText: { title: "Încărcați Caseta", name: "Nume", size: "mărimea", status: "stare" }, dropAreaText: "Picătură fișiere sau faceți clic pentru a încărca", filedetail: "Dimensiunea fișierului selectat este prea mare. Vă rugăm să selectați un fișier în dimensiune validă.", denyError: "Fișierele cu extensii #Extension nu sunt permise.", allowError: "sunt permise doar fișierele cu extensiile #Extension.", cancelToolTip: "Anulare", removeToolTip: "Elimina", retryToolTip: "reîncerca", completedToolTip: "terminat", failedToolTip: "A eșuat", closeToolTip: "Închide", }; ej.SpellCheck.Locale["ro-RO"] = { SpellCheckButtonText: "Verificare a ortografiei", NotInDictionary: "Nu în dicționar", SuggestionLabel: "sugestii", IgnoreOnceButtonText: "Odată ignorați", IgnoreAllButtonText: "Ignora tot", AddToDictionary: "Adăugați în dicționar", ChangeButtonText: "Schimbare", ChangeAllButtonText: "Toate schimbările", CloseButtonText: "Închide", CompletionPopupMessage: "verificare a ortografiei este completă", ErrorPopupMessage: "verificare a ortografiei nu este finalizat", CompletionPopupTitle: "Ortografiei verifica Alertă", OK: "O.K", NoSuggestionMessage: "Nu există sugestii disponibile", };
import Ember from 'ember-metal/core'; // reexports import compiler from './compiler'; let EmberHandlebars = Ember.Handlebars = Ember.Handlebars || {}; let EmberHTMLBars = Ember.HTMLBars = Ember.HTMLBars || {}; let { precompile, compile, template, registerPlugin } = compiler(); EmberHTMLBars.precompile = EmberHandlebars.precompile = precompile; EmberHTMLBars.compile = EmberHandlebars.compile = compile; EmberHTMLBars.template = EmberHandlebars.template = template; EmberHTMLBars.registerPlugin = registerPlugin;
/* global describe, it */ /* * The MIT License (MIT) * * Copyright (c) 2014 Apigee Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; // Here to quiet down Connect logging errors process.env.NODE_ENV = 'test'; var _ = require('lodash-compat'); var assert = require('assert'); var async = require('async'); var helpers = require('../helpers'); var request = require('supertest'); var petJson = _.cloneDeep(require('../../samples/1.2/pet.json')); var rlJson = _.cloneDeep(require('../../samples/1.2/resource-listing.json')); var storeJson = _.cloneDeep(require('../../samples/1.2/store.json')); var userJson = _.cloneDeep(require('../../samples/1.2/user.json')); var samplePet = { id: 1, name: 'Test Pet' }; describe('Swagger Validator Middleware v1.2', function () { describe('request validation', function () { it('should not validate request when there are no operations', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], {}, function (app) { request(app) .get('/api/foo') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should return an error for invalid request content type based on POST/PUT operation consumes', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], {}, function (app) { request(app) .post('/api/pet/1') .expect(400) .end(helpers.expectContent('Invalid content type (application/octet-stream). These are valid: ' + 'application/x-www-form-urlencoded', done)); }); }); it('should not return an error for invalid request content type for non-POST/PUT', function (done) { var clonedP = _.cloneDeep(petJson); clonedP.consumes = ['application/json']; helpers.createServer([rlJson, [clonedP, storeJson, userJson]], { swaggerRouterOptions: { controllers: { getPetById: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .get('/api/pet/1') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should not return an error for valid request content type', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { updatePetWithForm: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .post('/api/pet/1') .set('Content-Type', 'application/x-www-form-urlencoded') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should not return an error for valid request content type with charset', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { updatePetWithForm: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .post('/api/pet/1') .set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should return an error for missing required parameters', function (done) { var clonedP = _.cloneDeep(petJson); clonedP.apis[0].operations[0].parameters.push({ description: 'Whether or not to use mock mode', name: 'mock', paramType: 'query', required: true, type: 'boolean' }); helpers.createServer([rlJson, [clonedP, storeJson, userJson]], {}, function (app) { request(app) .get('/api/pet/1') .expect(400) .end(helpers.expectContent('Request validation failed: Parameter (mock) is required', done)); }); }); it('should not return an error for missing required parameters with a default value', function (done) { var clonedP = _.cloneDeep(petJson); clonedP.apis[0].operations[0].parameters.push({ description: 'Whether or not to use mock mode', name: 'mock', paramType: 'query', required: true, type: 'boolean', defaultValue: 'false' }); helpers.createServer([rlJson, [clonedP, storeJson, userJson]], { swaggerRouterOptions: { controllers: { getPetById: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .get('/api/pet/1') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should not return an error for provided required parameters', function (done) { var clonedP = _.cloneDeep(petJson); clonedP.apis[0].operations[0].parameters.push({ description: 'Whether or not to use mock mode', name: 'mock', paramType: 'query', required: true, type: 'boolean' }); helpers.createServer([rlJson, [clonedP, storeJson, userJson]], { swaggerRouterOptions: { controllers: { getPetById: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .get('/api/pet/1') .query({mock: 'true'}) .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should return an error for invalid parameter values based on type/format', function (done) { var argName = 'arg0'; var badValue = 'fake'; var testScenarios = [ {paramType: 'query', name: argName, type: 'boolean'}, {paramType: 'query', name: argName, type: 'integer'}, {paramType: 'query', name: argName, type: 'number'}, {paramType: 'query', name: argName, type: 'string', format: 'date'}, {paramType: 'query', name: argName, type: 'string', format: 'date-time'}, {paramType: 'query', name: argName, type: 'array', items: {type: 'integer'}} ]; async.map(testScenarios, function (scenario, callback) { var clonedP = _.cloneDeep(petJson); var clonedS = _.cloneDeep(scenario); var content = {arg0: scenario.type === 'array' ? [1, 'fake'] : badValue}; var expectedMessage; clonedP.apis[0].operations[0].parameters.push(clonedS); if (scenario.type === 'array') { expectedMessage = 'Parameter (' + argName + ') at index 1 is not a valid integer: fake'; } else { expectedMessage = 'Parameter (' + scenario.name + ') is not a valid ' + (_.isUndefined(scenario.format) ? '' : scenario.format + ' ') + scenario.type + ': ' + badValue; } helpers.createServer([rlJson, [clonedP, storeJson, userJson]], { swaggerRouterOptions: { controllers: { getPetById: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .get('/api/pet/1') .query(content) .expect(400) .end(function (err, res) { if (res) { res.expectedMessage = 'Request validation failed: ' + expectedMessage; } callback(err, res); }); }); }, function (err, responses) { if (err) { throw err; } _.each(responses, function (res) { if (res) { helpers.expectContent(res.expectedMessage)(undefined, res); } }); done(); }); }); it('should not return an error for valid parameter values based on type/format', function (done) { var argName = 'arg0'; var testScenarios = [ {paramType: 'query', name: argName, type: 'boolean', defaultValue: 'true'}, {paramType: 'query', name: argName, type: 'integer', defaultValue: '1'}, {paramType: 'query', name: argName, type: 'number', defaultValue: '1.1'}, {paramType: 'query', name: argName, type: 'string', format: 'date', defaultValue: '1981-03-12'}, { paramType: 'query', name: argName, type: 'string', format: 'date-time', defaultValue: '1981-03-12T08:16:00-04:00' }, ]; async.map(testScenarios, function (scenario, oCallback) { var clonedP = _.cloneDeep(petJson); clonedP.apis[0].operations[0].parameters.push(scenario); async.map([0, 1], function (n, callback) { var clonedS = _.cloneDeep(scenario); var content = {}; if (n === 0) { delete clonedS.defaultValue; content = {arg0: scenario.defaultValue}; } helpers.createServer([rlJson, [clonedP, storeJson, userJson]], { swaggerRouterOptions: { controllers: { getPetById: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .get('/api/pet/1') .query(content) .expect(200) .end(callback); }); }, function (err, responses) { if (err) { throw err; } _.each(responses, function (res) { helpers.expectContent('OK')(undefined, res); }); oCallback(); }); }, function (err) { if (err) { throw err; } done(); }); }); it('should return an error for invalid parameter values not based on type/format', function (done) { var argName = 'arg0'; var testScenarios = [ {paramType: 'query', name: argName, enum: ['1', '2', '3'], type: 'string'}, {paramType: 'query', name: argName, minimum: '1.0', type: 'integer'}, {paramType: 'query', name: argName, maximum: '1.0', type: 'integer'}, {paramType: 'query', name: argName, type: 'array', items: {type: 'string'}, uniqueItems: true} ]; var values = [ 'fake', '0', '2', ['fake', 'fake'] ]; var errors = [ 'Parameter (' + argName + ') is not an allowable value (1, 2, 3): fake', 'Parameter (' + argName + ') is less than the configured minimum (1.0): 0', 'Parameter (' + argName + ') is greater than the configured maximum (1.0): 2', 'Parameter (' + argName + ') does not allow duplicate values: fake, fake' ]; var index = 0; async.map(testScenarios, function (scenario, callback) { var clonedP = _.cloneDeep(petJson); var expectedMessage = errors[index]; clonedP.apis[0].operations[0].parameters.push(scenario); helpers.createServer([rlJson, [clonedP, storeJson, userJson]], {}, function (app) { request(app) .get('/api/pet/1') .query({arg0: values[index]}) .expect(400) .end(function (err, res) { if (res) { res.expectedMessage = 'Request validation failed: ' + expectedMessage; } callback(err, res); }); index++; }); }, function (err, responses) { if (err) { throw err; } _.each(responses, function (res) { helpers.expectContent(res.expectedMessage)(undefined, res); }); done(); }); }); it('should not return an error for valid parameter values not based on type/format', function (done) { var argName = 'arg0'; var testScenarios = [ {paramType: 'query', name: argName, enum: ['1', '2', '3'], type: 'string'}, {paramType: 'query', name: argName, minimum: '1.0', type: 'integer'}, {paramType: 'query', name: argName, maximum: '1.0', type: 'integer'}, {paramType: 'query', name: argName, type: 'array', items: {type: 'string'}, uniqueItems: true} ]; var values = [ '1', '2', '1', ['fake', 'fake1'] ]; var index = 0; async.map(testScenarios, function (scenario, callback) { var clonedP = _.cloneDeep(petJson); clonedP.apis[0].operations[0].parameters.push(scenario); helpers.createServer([rlJson, [clonedP, storeJson, userJson]], { swaggerRouterOptions: { controllers: { getPetById: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .get('/api/pet/1') .query({arg0: values[index]}) .expect(200) .end(callback); index++; }); }, function (err, responses) { if (err) { throw err; } _.each(responses, function (res) { helpers.expectContent('OK')(undefined, res); }); done(); }); }); it('should return an error for an invalid model parameter', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], {}, function (app) { request(app) .post('/api/pet') .send({}) .expect(400) .end(helpers.expectContent('Request validation failed: Parameter (body) failed schema validation', done)); }); }); it('should not return an error for a valid model parameter', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { addPet: function (req, res) { res.end('OK'); } } } }, function (app) { request(app) .post('/api/pet') .send({ id: 1, name: 'Test Pet' }) .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should return an error for an invalid model parameter (array)', function (done) { var clonedP = _.cloneDeep(petJson); clonedP.models.Tag.required = ['name']; clonedP.apis.push({ operations: [ { authorizations: {}, method: 'POST', nickname: 'createTag', parameters: [ { name: 'body', paramType: 'body', required: true, type: 'array', items: { $ref: 'Tag' } } ], responseMessages: [ { code: 400, message: 'Invalid tag value' } ], type: 'void' } ], path: '/tags' }); helpers.createServer([rlJson, [clonedP, storeJson, userJson]], {}, function (app) { request(app) .post('/api/tags') .send([ { id: 1 }, { id: 2 } ]) .expect(400) .end(helpers.expectContent('Request validation failed: Parameter (body) failed schema validation', done)); }); }); it('should not return an error for a valid model parameter (array)', function (done) { var clonedP = _.cloneDeep(petJson); clonedP.models.Tag.required = ['name']; clonedP.apis.push({ operations: [ { authorizations: {}, method: 'POST', nickname: 'createTag', parameters: [ { name: 'body', paramType: 'body', required: true, type: 'array', items: { $ref: 'Tag' } } ], responseMessages: [ { code: 400, message: 'Invalid tag value' } ], type: 'void' } ], path: '/tags' }); helpers.createServer([rlJson, [petJson, storeJson, userJson]], {}, function (app) { request(app) .post('/api/tags') .send([ { name: 'Tag 1' }, { name: 'Tag 2' } ]) .expect(200) .end(helpers.expectContent('OK', done)); }); }); }); describe('response validation', function () { it('should not validate response when there are no operations', function (done) { helpers.createServer([rlJson, [petJson, storeJson, userJson]], { swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/foo') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should not validate response when options.validateResponse is false', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { res.end('OK'); } } }, swaggerValidatorOptions: { validateResponse: false } }, function (app) { request(app) .get('/api/pet/1') .expect(200) .end(helpers.expectContent('OK', done)); }); }); it('should return an error for invalid response content type', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { res.setHeader('Content-Type', 'application/x-yaml'); res.end(samplePet); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(500) .end(helpers.expectContent('Response validation failed: invalid content type (application/x-yaml). These ' + 'are valid: application/json, application/xml, text/plain, text/html', done)); }); }); it('should not return error for valid response content type', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { res.setHeader('Content-Type', 'application/json'); res.end(samplePet); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(200) .end(helpers.expectContent(samplePet, done)); }); }); it('should return an error for model type not parsable', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { res.end('OK'); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(500) .end(helpers.expectContent('Response validation failed: value expected to be an array/object but is not', done)); }); }); it('should return an error for an invalid response primitive (void)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[1].nickname = 'Pets_deletePet'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_deletePet': function (req, res) { return res.end('Some value'); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .delete('/api/pet/1') .expect(500) .end(helpers.expectContent('Response validation failed: void does not allow a value', done)); }); }); it('should return an error for an invalid response primitive (non-void)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis.push({ operations: [ { authorizations: {}, method: 'GET', nickname: 'Pets_getCategoryCount', parameters: [], type: 'integer' } ], path: '/pet/categories/count' }); helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getCategoryCount': function (req, res) { return res.end('Some value'); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/categories/count') .expect(500) .end(helpers.expectContent('Response validation failed: not a valid integer: Some value', done)); }); }); it('should not return an error for a valid response primitive (non-void)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis.push({ operations: [ { authorizations: {}, method: 'GET', nickname: 'Pets_getCategoryCount', parameters: [], type: 'integer' } ], path: '/pet/categories/count' }); helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getCategoryCount': function (req, res) { return res.end(new Buffer('1')); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/categories/count') .expect(200) .end(helpers.expectContent('1', done)); }); }); it('should return an error for an invalid response primitive (non-void array)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis.push({ operations: [ { authorizations: {}, method: 'GET', nickname: 'Pets_getCategoryCount', parameters: [], type: 'array', items: { type: 'integer' } } ], path: '/pet/categories/count' }); helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getCategoryCount': function (req, res) { return res.end([1, 'Some value', 3]); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/categories/count') .expect(500) .end(helpers.expectContent('Response validation failed: value at index 1 is not a valid integer: Some value', done)); }); }); it('should not return an error for a valid response primitive (non-void array)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis.push({ operations: [ { authorizations: {}, method: 'GET', nickname: 'Pets_getCategoryCount', parameters: [], type: 'array', items: { type: 'integer' } } ], path: '/pet/categories/count' }); helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getCategoryCount': function (req, res) { return res.end([1, 2, 3]); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/categories/count') .expect(200) .end(helpers.expectContent([1, 2, 3], done)); }); }); it('should return an error for an invalid response model (simple)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { return res.end({}); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(500) .end(helpers.expectContent('Response validation failed: failed schema validation', done)); }); }); it('should not return an error for an valid response model (simple)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { return res.end(samplePet); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(200) .end(helpers.expectContent(samplePet, done)); }); }); it('should return an error for an invalid response model (complex)', function (done) { var cPetJson = _.cloneDeep(petJson); var cSamplePet = _.cloneDeep(samplePet); // Make name required cPetJson.models.Tag.required = ['name']; cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; cSamplePet.tags = [ {id: 1, name: 'Tag 1'}, {id: 2}, {id: 3, name: 'Tag 3'}, ]; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { return res.end(cSamplePet); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(500) .end(helpers.expectContent('Response validation failed: failed schema validation', done)); }); }); it('should return an error for an invalid response model (complex)', function (done) { var cPetJson = _.cloneDeep(petJson); var cSamplePet = _.cloneDeep(samplePet); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; cSamplePet.tags = [ {id: 1, name: 'Tag 1'}, {id: 2}, {id: 3, name: 'Tag 3'}, ]; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { return res.end(cSamplePet); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/1') .expect(200) .end(helpers.expectContent(cSamplePet, done)); }); }); it('should return an error for an invalid response array of models (simple)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[3].operations[0].nickname = 'Pets_getPetsByStatus'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetsByStatus': function (req, res) { return res.end([ samplePet, {}, samplePet ]); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/findByStatus') .query({status: 'available'}) .expect(500) .end(helpers.expectContent('Response validation failed: failed schema validation', done)); }); }); it('should not return an error for an valid response array of models (simple)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[3].operations[0].nickname = 'Pets_getPetsByStatus'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetsByStatus': function (req, res) { return res.end([ samplePet, samplePet, samplePet ]); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/findByStatus') .query({status: 'available'}) .expect(200) .end(helpers.expectContent([ samplePet, samplePet, samplePet ], done)); }); }); it('should return an error for an invalid response array of models (complex)', function (done) { var cPetJson = _.cloneDeep(petJson); var cSamplePet = _.cloneDeep(samplePet); // Make name required cPetJson.models.Tag.required = ['name']; cSamplePet.tags = [ {id: 1, name: 'Tag 1'}, {id: 2}, {id: 3, name: 'Tag 3'}, ]; cPetJson.apis[3].operations[0].nickname = 'Pets_getPetsByStatus'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetsByStatus': function (req, res) { return res.end([ cSamplePet, {}, cSamplePet ]); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/findByStatus') .query({status: 'available'}) .expect(500) .end(helpers.expectContent('Response validation failed: failed schema validation', done)); }); }); it('should not return an error for an valid response array of models (complex)', function (done) { var cPetJson = _.cloneDeep(petJson); var cSamplePet = _.cloneDeep(samplePet); cSamplePet.tags = [ {id: 1, name: 'Tag 1'}, {id: 2}, {id: 3, name: 'Tag 3'}, ]; cPetJson.apis[3].operations[0].nickname = 'Pets_getPetsByStatus'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetsByStatus': function (req, res) { return res.end([ cSamplePet, cSamplePet, cSamplePet ]); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { request(app) .get('/api/pet/findByStatus') .query({status: 'available'}) .expect(200) .end(helpers.expectContent([ cSamplePet, cSamplePet, cSamplePet ], done)); }); }); }); describe('issues', function () { it('should include original response in response validation errors (Issue 82)', function (done) { var cPetJson = _.cloneDeep(petJson); cPetJson.apis[0].operations[0].nickname = 'Pets_getPetById'; helpers.createServer([rlJson, [cPetJson, storeJson, userJson]], { swaggerRouterOptions: { controllers: { 'Pets_getPetById': function (req, res) { res.setHeader('Content-Type', 'application/x-yaml'); res.end(samplePet); } } }, swaggerValidatorOptions: { validateResponse: true } }, function (app) { app.use(function (err, req, res, next) { assert.deepEqual(err.originalResponse, samplePet); next(); }); request(app) .get('/api/pet/1') .expect(500) .end(helpers.expectContent('Response validation failed: invalid content type (application/x-yaml). These ' + 'are valid: application/json, application/xml, text/plain, text/html', done)); }); }); }); });
/** * jsBezier * * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com) * * licensed under the MIT license. * * a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier * curves of arbitrary degree. * * - functions are all in the 'jsBezier' namespace. * * - all input points should be in the format {x:.., y:..}. all output points are in this format too. * * - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ] * * - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length * of the curve. location as output has the same format and meaning. * * * Function List: * -------------- * * distanceFromCurve(point, curve) * * Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier, * so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values * of the curve and the point - it will most likely be pixels. * * gradientAtPoint(curve, location) * * Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive. * * gradientAtPointAlongCurveFrom (curve, location) * * Calculates the gradient at the point on the given curve that is 'distance' units from location. * * nearestPointOnCurve(point, curve) * * Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the *point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }. * * pointOnCurve(curve, location) * * Calculates the coordinates of the point on the given Bezier curve at the given location. * * pointAlongCurveFrom(curve, location, distance) * * Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels. * * locationAlongCurveFrom(curve, location, distance) * * Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels. * * perpendicularToCurveAt(curve, location, length, distance) * * Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered * on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of * the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ]. * * */ (function() { var root = this; if(typeof Math.sgn == "undefined") { Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; }; } var Vectors = { subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; }, dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); }, square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); }, scale : function(v, s) { return {x:v.x * s, y:v.y * s }; } }, maxRecursion = 64, flatnessTolerance = Math.pow(2.0,-maxRecursion-1); /** * Calculates the distance that the point lies from the curve. * * @param point a point in the form {x:567, y:3342} * @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently * hardcoded to assume cubiz beziers, but would be better off supporting any degree. * @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location * argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from * the point to the curve. */ var _distanceFromCurve = function(point, curve) { var candidates = [], w = _convertToBezier(point, curve), degree = curve.length - 1, higherDegree = (2 * degree) - 1, numSolutions = _findRoots(w, higherDegree, candidates, 0), v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0; for (var i = 0; i < numSolutions; i++) { v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null)); var newDist = Vectors.square(v); if (newDist < dist) { dist = newDist; t = candidates[i]; } } v = Vectors.subtract(point, curve[degree]); newDist = Vectors.square(v); if (newDist < dist) { dist = newDist; t = 1.0; } return {location:t, distance:dist}; }; /** * finds the nearest point on the curve to the given point. */ var _nearestPointOnCurve = function(point, curve) { var td = _distanceFromCurve(point, curve); return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location}; }; var _convertToBezier = function(point, curve) { var degree = curve.length - 1, higherDegree = (2 * degree) - 1, c = [], d = [], cdTable = [], w = [], z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ]; for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point); for (var i = 0; i <= degree - 1; i++) { d[i] = Vectors.subtract(curve[i+1], curve[i]); d[i] = Vectors.scale(d[i], 3.0); } for (var row = 0; row <= degree - 1; row++) { for (var column = 0; column <= degree; column++) { if (!cdTable[row]) cdTable[row] = []; cdTable[row][column] = Vectors.dotProduct(d[row], c[column]); } } for (i = 0; i <= higherDegree; i++) { if (!w[i]) w[i] = []; w[i].y = 0.0; w[i].x = parseFloat(i) / higherDegree; } var n = degree, m = degree-1; for (var k = 0; k <= n + m; k++) { var lb = Math.max(0, k - m), ub = Math.min(k, n); for (i = lb; i <= ub; i++) { var j = k - i; w[i+j].y += cdTable[j][i] * z[j][i]; } } return w; }; /** * counts how many roots there are. */ var _findRoots = function(w, degree, t, depth) { var left = [], right = [], left_count, right_count, left_t = [], right_t = []; switch (_getCrossingCount(w, degree)) { case 0 : { return 0; } case 1 : { if (depth >= maxRecursion) { t[0] = (w[0].x + w[degree].x) / 2.0; return 1; } if (_isFlatEnough(w, degree)) { t[0] = _computeXIntercept(w, degree); return 1; } break; } } _bezier(w, degree, 0.5, left, right); left_count = _findRoots(left, degree, left_t, depth+1); right_count = _findRoots(right, degree, right_t, depth+1); for (var i = 0; i < left_count; i++) t[i] = left_t[i]; for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i]; return (left_count+right_count); }; var _getCrossingCount = function(curve, degree) { var n_crossings = 0, sign, old_sign; sign = old_sign = Math.sgn(curve[0].y); for (var i = 1; i <= degree; i++) { sign = Math.sgn(curve[i].y); if (sign != old_sign) n_crossings++; old_sign = sign; } return n_crossings; }; var _isFlatEnough = function(curve, degree) { var error, intercept_1, intercept_2, left_intercept, right_intercept, a, b, c, det, dInv, a1, b1, c1, a2, b2, c2; a = curve[0].y - curve[degree].y; b = curve[degree].x - curve[0].x; c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y; var max_distance_above, max_distance_below; max_distance_above = max_distance_below = 0.0; for (var i = 1; i < degree; i++) { var value = a * curve[i].x + b * curve[i].y + c; if (value > max_distance_above) max_distance_above = value; else if (value < max_distance_below) max_distance_below = value; } a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b; c2 = c - max_distance_above; det = a1 * b2 - a2 * b1; dInv = 1.0/det; intercept_1 = (b1 * c2 - b2 * c1) * dInv; a2 = a; b2 = b; c2 = c - max_distance_below; det = a1 * b2 - a2 * b1; dInv = 1.0/det; intercept_2 = (b1 * c2 - b2 * c1) * dInv; left_intercept = Math.min(intercept_1, intercept_2); right_intercept = Math.max(intercept_1, intercept_2); error = right_intercept - left_intercept; return (error < flatnessTolerance)? 1 : 0; }; var _computeXIntercept = function(curve, degree) { var XLK = 1.0, YLK = 0.0, XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y, XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0, det = XNM*YLK - YNM*XLK, detInv = 1.0/det, S = (XNM*YMK - YNM*XMK) * detInv; return 0.0 + XLK * S; }; var _bezier = function(curve, degree, t, left, right) { var temp = [[]]; for (var j =0; j <= degree; j++) temp[0][j] = curve[j]; for (var i = 1; i <= degree; i++) { for (var j =0 ; j <= degree - i; j++) { if (!temp[i]) temp[i] = []; if (!temp[i][j]) temp[i][j] = {}; temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x; temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y; } } if (left != null) for (j = 0; j <= degree; j++) left[j] = temp[j][0]; if (right != null) for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j]; return (temp[degree][0]); }; var _curveFunctionCache = {}; var _getCurveFunctions = function(order) { var fns = _curveFunctionCache[order]; if (!fns) { fns = []; var f_term = function() { return function(t) { return Math.pow(t, order); }; }, l_term = function() { return function(t) { return Math.pow((1-t), order); }; }, c_term = function(c) { return function(t) { return c; }; }, t_term = function() { return function(t) { return t; }; }, one_minus_t_term = function() { return function(t) { return 1-t; }; }, _termFunc = function(terms) { return function(t) { var p = 1; for (var i = 0; i < terms.length; i++) p = p * terms[i](t); return p; }; }; fns.push(new f_term()); // first is t to the power of the curve order for (var i = 1; i < order; i++) { var terms = [new c_term(order)]; for (var j = 0 ; j < (order - i); j++) terms.push(new t_term()); for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term()); fns.push(new _termFunc(terms)); } fns.push(new l_term()); // last is (1-t) to the power of the curve order _curveFunctionCache[order] = fns; } return fns; }; /** * calculates a point on the curve, for a Bezier of arbitrary order. * @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points. * @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive. */ var _pointOnPath = function(curve, location) { var cc = _getCurveFunctions(curve.length - 1), _x = 0, _y = 0; for (var i = 0; i < curve.length ; i++) { _x = _x + (curve[i].x * cc[i](location)); _y = _y + (curve[i].y * cc[i](location)); } return {x:_x, y:_y}; }; var _dist = function(p1,p2) { return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); }; var _isPoint = function(curve) { return curve[0].x === curve[1].x && curve[0].y === curve[1].y; }; /** * finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also * its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the * point. */ var _pointAlongPath = function(curve, location, distance) { if (_isPoint(curve)) { return { point:curve[0], location:location }; } var prev = _pointOnPath(curve, location), tally = 0, curLoc = location, direction = distance > 0 ? 1 : -1, cur = null; while (tally < Math.abs(distance)) { curLoc += (0.005 * direction); cur = _pointOnPath(curve, curLoc); tally += _dist(cur, prev); prev = cur; } return {point:cur, location:curLoc}; }; var _length = function(curve) { if (_isPoint(curve)) return 0; var prev = _pointOnPath(curve, 0), tally = 0, curLoc = 0, direction = 1, cur = null; while (curLoc < 1) { curLoc += (0.005 * direction); cur = _pointOnPath(curve, curLoc); tally += _dist(cur, prev); prev = cur; } return tally; }; /** * finds the point that is 'distance' along the path from 'location'. */ var _pointAlongPathFrom = function(curve, location, distance) { return _pointAlongPath(curve, location, distance).point; }; /** * finds the location that is 'distance' along the path from 'location'. */ var _locationAlongPathFrom = function(curve, location, distance) { return _pointAlongPath(curve, location, distance).location; }; /** * returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive. * * thanks // http://bimixual.org/AnimationLibrary/beziertangents.html */ var _gradientAtPoint = function(curve, location) { var p1 = _pointOnPath(curve, location), p2 = _pointOnPath(curve.slice(0, curve.length - 1), location), dy = p2.y - p1.y, dx = p2.x - p1.x; return dy === 0 ? Infinity : Math.atan(dy / dx); }; /** returns the gradient of the curve at the point which is 'distance' from the given location. if this point is greater than location 1, the gradient at location 1 is returned. if this point is less than location 0, the gradient at location 0 is returned. */ var _gradientAtPointAlongPathFrom = function(curve, location, distance) { var p = _pointAlongPath(curve, location, distance); if (p.location > 1) p.location = 1; if (p.location < 0) p.location = 0; return _gradientAtPoint(curve, p.location); }; /** * calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location. * if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero). */ var _perpendicularToPathAt = function(curve, location, length, distance) { distance = distance == null ? 0 : distance; var p = _pointAlongPath(curve, location, distance), m = _gradientAtPoint(curve, p.location), _theta2 = Math.atan(-1 / m), y = length / 2 * Math.sin(_theta2), x = length / 2 * Math.cos(_theta2); return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}]; }; /** * Calculates all intersections of the given line with the given curve. * @param x1 * @param y1 * @param x2 * @param y2 * @param curve * @returns {Array} */ var _lineIntersection = function(x1, y1, x2, y2, curve) { var a = y2 - y1, b = x1 - x2, c = (x1 * (y1 - y2)) + (y1 * (x2-x1)), coeffs = _computeCoefficients(curve), p = [ (a*coeffs[0][0]) + (b * coeffs[1][0]), (a*coeffs[0][1])+(b*coeffs[1][1]), (a*coeffs[0][2])+(b*coeffs[1][2]), (a*coeffs[0][3])+(b*coeffs[1][3]) + c ], r = _cubicRoots.apply(null, p), intersections = []; if (r != null) { for (var i = 0; i < 3; i++) { var t = r[i], t2 = Math.pow(t, 2), t3 = Math.pow(t, 3), x = [ (coeffs[0][0] * t3) + (coeffs[0][1] * t2) + (coeffs[0][2] * t) + coeffs[0][3], (coeffs[1][0] * t3) + (coeffs[1][1] * t2) + (coeffs[1][2] * t) + coeffs[1][3] ]; // check bounds of the line var s; if ((x2 - x1) !== 0) { s = (x[0] - x1) / (x2 - x1); } else { s = (x[1] - y1) / (y2 - y1); } if (t >= 0 && t <= 1.0 && s >= 0 && s <= 1.0) { intersections.push(x); } } } return intersections; }; /** * Calculates all intersections of the given box with the given curve. * @param x X position of top left corner of box * @param y Y position of top left corner of box * @param w width of box * @param h height of box * @param curve * @returns {Array} */ var _boxIntersection = function(x, y, w, h, curve) { var i = []; i.push.apply(i, _lineIntersection(x, y, x + w, y, curve)); i.push.apply(i, _lineIntersection(x + w, y, x + w, y + h, curve)); i.push.apply(i, _lineIntersection(x + w, y + h, x, y + h, curve)); i.push.apply(i, _lineIntersection(x, y + h, x, y, curve)); return i; }; /** * Calculates all intersections of the given bounding box with the given curve. * @param boundingBox Bounding box, in { x:.., y:..., w:..., h:... } format. * @param curve * @returns {Array} */ var _boundingBoxIntersection = function(boundingBox, curve) { var i = []; i.push.apply(i, _lineIntersection(boundingBox.x, boundingBox.y, boundingBox.x + boundingBox.w, boundingBox.y, curve)); i.push.apply(i, _lineIntersection(boundingBox.x + boundingBox.w, boundingBox.y, boundingBox.x + boundingBox.w, boundingBox.y + boundingBox.h, curve)); i.push.apply(i, _lineIntersection(boundingBox.x + boundingBox.w, boundingBox.y + boundingBox.h, boundingBox.x, boundingBox.y + boundingBox.h, curve)); i.push.apply(i, _lineIntersection(boundingBox.x, boundingBox.y + boundingBox.h, boundingBox.x, boundingBox.y, curve)); return i; }; function _computeCoefficientsForAxis(curve, axis) { return [ -(curve[0][axis]) + (3*curve[1][axis]) + (-3 * curve[2][axis]) + curve[3][axis], (3*(curve[0][axis])) - (6*(curve[1][axis])) + (3*(curve[2][axis])), -3*curve[0][axis] + 3*curve[1][axis], curve[0][axis] ]; } function _computeCoefficients(curve) { return [ _computeCoefficientsForAxis(curve, "x"), _computeCoefficientsForAxis(curve, "y") ]; } function sgn(x) { return x < 0 ? -1 : x > 0 ? 1 : 0; } function _cubicRoots(a, b, c, d) { var A = b / a, B = c / a, C = d / a, Q = (3*B - Math.pow(A, 2))/9, R = (9*A*B - 27*C - 2*Math.pow(A, 3))/54, D = Math.pow(Q, 3) + Math.pow(R, 2), S, T, t = []; if (D >= 0) // complex or duplicate roots { S = sgn(R + Math.sqrt(D))*Math.pow(Math.abs(R + Math.sqrt(D)),(1/3)); T = sgn(R - Math.sqrt(D))*Math.pow(Math.abs(R - Math.sqrt(D)),(1/3)); t[0] = -A/3 + (S + T); t[1] = -A/3 - (S + T)/2; t[2] = -A/3 - (S + T)/2; /*discard complex roots*/ if (Math.abs(Math.sqrt(3)*(S - T)/2) !== 0) { t[1] = -1; t[2] = -1; } } else // distinct real roots { var th = Math.acos(R/Math.sqrt(-Math.pow(Q, 3))); t[0] = 2*Math.sqrt(-Q)*Math.cos(th/3) - A/3; t[1] = 2*Math.sqrt(-Q)*Math.cos((th + 2*Math.PI)/3) - A/3; t[2] = 2*Math.sqrt(-Q)*Math.cos((th + 4*Math.PI)/3) - A/3; } // discard out of spec roots for (var i = 0; i < 3; i++) { if (t[i] < 0 || t[i] > 1.0) { t[i] = -1; } } return t; } var jsBezier = this.jsBezier = { distanceFromCurve : _distanceFromCurve, gradientAtPoint : _gradientAtPoint, gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom, nearestPointOnCurve : _nearestPointOnCurve, pointOnCurve : _pointOnPath, pointAlongCurveFrom : _pointAlongPathFrom, perpendicularToCurveAt : _perpendicularToPathAt, locationAlongCurveFrom:_locationAlongPathFrom, getLength:_length, lineIntersection:_lineIntersection, boxIntersection:_boxIntersection, boundingBoxIntersection:_boundingBoxIntersection, version:"0.9.0" }; if (typeof exports !== "undefined") { exports.jsBezier = jsBezier; } }).call(typeof window !== 'undefined' ? window : this); /** * Biltong v0.4.0 * * Various geometry functions written as part of jsPlumb and perhaps useful for others. * * Copyright (c) 2017 jsPlumb * https://jsplumbtoolkit.com * * 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. */ ;(function() { "use strict"; var root = this; var Biltong = root.Biltong = { version:"0.4.0" }; if (typeof exports !== "undefined") { exports.Biltong = Biltong; } var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; }, _pointHelper = function(p1, p2, fn) { p1 = _isa(p1) ? p1 : [p1.x, p1.y]; p2 = _isa(p2) ? p2 : [p2.x, p2.y]; return fn(p1, p2); }, /** * @name Biltong.gradient * @function * @desc Calculates the gradient of a line between the two points. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Float} The gradient of a line between the two points. */ _gradient = Biltong.gradient = function(p1, p2) { return _pointHelper(p1, p2, function(_p1, _p2) { if (_p2[0] == _p1[0]) return _p2[1] > _p1[1] ? Infinity : -Infinity; else if (_p2[1] == _p1[1]) return _p2[0] > _p1[0] ? 0 : -0; else return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]); }); }, /** * @name Biltong.normal * @function * @desc Calculates the gradient of a normal to a line between the two points. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Float} The gradient of a normal to a line between the two points. */ _normal = Biltong.normal = function(p1, p2) { return -1 / _gradient(p1, p2); }, /** * @name Biltong.lineLength * @function * @desc Calculates the length of a line between the two points. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Float} The length of a line between the two points. */ _lineLength = Biltong.lineLength = function(p1, p2) { return _pointHelper(p1, p2, function(_p1, _p2) { return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2)); }); }, /** * @name Biltong.quadrant * @function * @desc Calculates the quadrant in which the angle between the two points lies. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Integer} The quadrant - 1 for upper right, 2 for lower right, 3 for lower left, 4 for upper left. */ _quadrant = Biltong.quadrant = function(p1, p2) { return _pointHelper(p1, p2, function(_p1, _p2) { if (_p2[0] > _p1[0]) { return (_p2[1] > _p1[1]) ? 2 : 1; } else if (_p2[0] == _p1[0]) { return _p2[1] > _p1[1] ? 2 : 1; } else { return (_p2[1] > _p1[1]) ? 3 : 4; } }); }, /** * @name Biltong.theta * @function * @desc Calculates the angle between the two points. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Float} The angle between the two points. */ _theta = Biltong.theta = function(p1, p2) { return _pointHelper(p1, p2, function(_p1, _p2) { var m = _gradient(_p1, _p2), t = Math.atan(m), s = _quadrant(_p1, _p2); if ((s == 4 || s== 3)) t += Math.PI; if (t < 0) t += (2 * Math.PI); return t; }); }, /** * @name Biltong.intersects * @function * @desc Calculates whether or not the two rectangles intersect. * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` * @return {Boolean} True if the rectangles intersect, false otherwise. */ _intersects = Biltong.intersects = function(r1, r2) { var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h, a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h; return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) || ( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) || ( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) || ( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) || ( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) || ( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) || ( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) || ( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ); }, /** * @name Biltong.encloses * @function * @desc Calculates whether or not r2 is completely enclosed by r1. * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}` * @param {Boolean} [allowSharedEdges=false] If true, the concept of enclosure allows for one or more edges to be shared by the two rectangles. * @return {Boolean} True if r1 encloses r2, false otherwise. */ _encloses = Biltong.encloses = function(r1, r2, allowSharedEdges) { var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h, a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h, c = function(v1, v2, v3, v4) { return allowSharedEdges ? v1 <= v2 && v3>= v4 : v1 < v2 && v3 > v4; }; return c(x1,a1,x2,a2) && c(y1,b1,y2,b2); }, _segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ], _inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ], /** * @name Biltong.pointOnLine * @function * @desc Calculates a point on the line from `fromPoint` to `toPoint` that is `distance` units along the length of the line. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Point} Point on the line, in the form `{ x:..., y:... }`. */ _pointOnLine = Biltong.pointOnLine = function(fromPoint, toPoint, distance) { var m = _gradient(fromPoint, toPoint), s = _quadrant(fromPoint, toPoint), segmentMultiplier = distance > 0 ? _segmentMultipliers[s] : _inverseSegmentMultipliers[s], theta = Math.atan(m), y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1], x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0]; return { x:fromPoint.x + x, y:fromPoint.y + y }; }, /** * @name Biltong.perpendicularLineTo * @function * @desc Calculates a line of length `length` that is perpendicular to the line from `fromPoint` to `toPoint` and passes through `toPoint`. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties. * @return {Line} Perpendicular line, in the form `[ { x:..., y:... }, { x:..., y:... } ]`. */ _perpendicularLineTo = Biltong.perpendicularLineTo = function(fromPoint, toPoint, length) { var m = _gradient(fromPoint, toPoint), theta2 = Math.atan(-1 / m), y = length / 2 * Math.sin(theta2), x = length / 2 * Math.cos(theta2); return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}]; }; }).call(typeof window !== 'undefined' ? window : this); ; (function () { "use strict"; /** * Creates a Touch object. * @param view * @param target * @param pageX * @param pageY * @param screenX * @param screenY * @param clientX * @param clientY * @returns {Touch} * @private */ function _touch(view, target, pageX, pageY, screenX, screenY, clientX, clientY) { return new Touch({ target:target, identifier:_uuid(), pageX: pageX, pageY: pageY, screenX: screenX, screenY: screenY, clientX: clientX || screenX, clientY: clientY || screenY }); } /** * Create a synthetic touch list from the given list of Touch objects. * @returns {Array} * @private */ function _touchList() { var list = []; Array.prototype.push.apply(list, arguments); list.item = function(index) { return this[index]; }; return list; } /** * Create a Touch object and then insert it into a synthetic touch list, returning the list.s * @param view * @param target * @param pageX * @param pageY * @param screenX * @param screenY * @param clientX * @param clientY * @returns {Array} * @private */ function _touchAndList(view, target, pageX, pageY, screenX, screenY, clientX, clientY) { return _touchList(_touch.apply(null, arguments)); } var root = this, matchesSelector = function (el, selector, ctx) { ctx = ctx || el.parentNode; var possibles = ctx.querySelectorAll(selector); for (var i = 0; i < possibles.length; i++) { if (possibles[i] === el) { return true; } } return false; }, _gel = function (el) { return (typeof el == "string" || el.constructor === String) ? document.getElementById(el) : el; }, _t = function (e) { return e.srcElement || e.target; }, // // gets path info for the given event - the path from target to obj, in the event's bubble chain. if doCompute // is false we just return target for the path. // _pi = function(e, target, obj, doCompute) { if (!doCompute) return { path:[target], end:1 }; else if (typeof e.path !== "undefined" && e.path.indexOf) { return { path: e.path, end: e.path.indexOf(obj) }; } else { var out = { path:[], end:-1 }, _one = function(el) { out.path.push(el); if (el === obj) { out.end = out.path.length - 1; } else if (el.parentNode != null) { _one(el.parentNode) } }; _one(target); return out; } }, _d = function (l, fn) { for (var i = 0, j = l.length; i < j; i++) { if (l[i] == fn) break; } if (i < l.length) l.splice(i, 1); }, guid = 1, // // this function generates a guid for every handler, sets it on the handler, then adds // it to the associated object's map of handlers for the given event. this is what enables us // to unbind all events of some type, or all events (the second of which can be requested by the user, // but it also used by Mottle when an element is removed.) _store = function (obj, event, fn) { var g = guid++; obj.__ta = obj.__ta || {}; obj.__ta[event] = obj.__ta[event] || {}; // store each handler with a unique guid. obj.__ta[event][g] = fn; // set the guid on the handler. fn.__tauid = g; return g; }, _unstore = function (obj, event, fn) { obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid]; // a handler might have attached extra functions, so we unbind those too. if (fn.__taExtra) { for (var i = 0; i < fn.__taExtra.length; i++) { _unbind(obj, fn.__taExtra[i][0], fn.__taExtra[i][1]); } fn.__taExtra.length = 0; } // a handler might have attached an unstore callback fn.__taUnstore && fn.__taUnstore(); }, _curryChildFilter = function (children, obj, fn, evt) { if (children == null) return fn; else { var c = children.split(","), _fn = function (e) { _fn.__tauid = fn.__tauid; var t = _t(e), target = t; // t is the target element on which the event occurred. it is the // element we will wish to pass to any callbacks. var pathInfo = _pi(e, t, obj, children != null) if (pathInfo.end != -1) { for (var p = 0; p < pathInfo.end; p++) { target = pathInfo.path[p]; for (var i = 0; i < c.length; i++) { if (matchesSelector(target, c[i], obj)) { fn.apply(target, arguments); } } } } }; registerExtraFunction(fn, evt, _fn); return _fn; } }, // // registers an 'extra' function on some event listener function we were given - a function that we // created and bound to the element as part of our housekeeping, and which we want to unbind and remove // whenever the given function is unbound. registerExtraFunction = function (fn, evt, newFn) { fn.__taExtra = fn.__taExtra || []; fn.__taExtra.push([evt, newFn]); }, DefaultHandler = function (obj, evt, fn, children) { if (isTouchDevice && touchMap[evt]) { var tfn = _curryChildFilter(children, obj, fn, touchMap[evt]); _bind(obj, touchMap[evt], tfn , fn); } if (evt === "focus" && obj.getAttribute("tabindex") == null) { obj.setAttribute("tabindex", "1"); } _bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn); }, SmartClickHandler = function (obj, evt, fn, children) { if (obj.__taSmartClicks == null) { var down = function (e) { obj.__tad = _pageLocation(e); }, up = function (e) { obj.__tau = _pageLocation(e); }, click = function (e) { if (obj.__tad && obj.__tau && obj.__tad[0] === obj.__tau[0] && obj.__tad[1] === obj.__tau[1]) { for (var i = 0; i < obj.__taSmartClicks.length; i++) obj.__taSmartClicks[i].apply(_t(e), [ e ]); } }; DefaultHandler(obj, "mousedown", down, children); DefaultHandler(obj, "mouseup", up, children); DefaultHandler(obj, "click", click, children); obj.__taSmartClicks = []; } // store in the list of callbacks obj.__taSmartClicks.push(fn); // the unstore function removes this function from the object's listener list for this type. fn.__taUnstore = function () { _d(obj.__taSmartClicks, fn); }; }, _tapProfiles = { "tap": {touches: 1, taps: 1}, "dbltap": {touches: 1, taps: 2}, "contextmenu": {touches: 2, taps: 1} }, TapHandler = function (clickThreshold, dblClickThreshold) { return function (obj, evt, fn, children) { // if event is contextmenu, for devices which are mouse only, we want to // use the default bind. if (evt == "contextmenu" && isMouseDevice) DefaultHandler(obj, evt, fn, children); else { // the issue here is that this down handler gets registered only for the // child nodes in the first registration. in fact it should be registered with // no child selector and then on down we should cycle through the registered // functions to see if one of them matches. on mouseup we should execute ALL of // the functions whose children are either null or match the element. if (obj.__taTapHandler == null) { var tt = obj.__taTapHandler = { tap: [], dbltap: [], contextmenu: [], down: false, taps: 0, downSelectors: [] }; var down = function (e) { var target = _t(e), pathInfo = _pi(e, target, obj, children != null), finished = false; for (var p = 0; p < pathInfo.end; p++) { if (finished) return; target = pathInfo.path[p]; for (var i = 0; i < tt.downSelectors.length; i++) { if (tt.downSelectors[i] == null || matchesSelector(target, tt.downSelectors[i], obj)) { tt.down = true; setTimeout(clearSingle, clickThreshold); setTimeout(clearDouble, dblClickThreshold); finished = true; break; // we only need one match on mousedown } } } }, up = function (e) { if (tt.down) { var target = _t(e), currentTarget, pathInfo; tt.taps++; var tc = _touchCount(e); for (var eventId in _tapProfiles) { if (_tapProfiles.hasOwnProperty(eventId)) { var p = _tapProfiles[eventId]; if (p.touches === tc && (p.taps === 1 || p.taps === tt.taps)) { for (var i = 0; i < tt[eventId].length; i++) { pathInfo = _pi(e, target, obj, tt[eventId][i][1] != null); for (var pLoop = 0; pLoop < pathInfo.end; pLoop++) { currentTarget = pathInfo.path[pLoop]; // this is a single event registration handler. if (tt[eventId][i][1] == null || matchesSelector(currentTarget, tt[eventId][i][1], obj)) { tt[eventId][i][0].apply(currentTarget, [ e ]); break; } } } } } } } }, clearSingle = function () { tt.down = false; }, clearDouble = function () { tt.taps = 0; }; DefaultHandler(obj, "mousedown", down); DefaultHandler(obj, "mouseup", up); } // add this child selector (it can be null, that's fine). obj.__taTapHandler.downSelectors.push(children); obj.__taTapHandler[evt].push([fn, children]); // the unstore function removes this function from the object's listener list for this type. fn.__taUnstore = function () { _d(obj.__taTapHandler[evt], fn); }; } }; }, meeHelper = function (type, evt, obj, target) { for (var i in obj.__tamee[type]) { if (obj.__tamee[type].hasOwnProperty(i)) { obj.__tamee[type][i].apply(target, [ evt ]); } } }, MouseEnterExitHandler = function () { var activeElements = []; return function (obj, evt, fn, children) { if (!obj.__tamee) { // __tamee holds a flag saying whether the mouse is currently "in" the element, and a list of // both mouseenter and mouseexit functions. obj.__tamee = { over: false, mouseenter: [], mouseexit: [] }; // register over and out functions var over = function (e) { var t = _t(e); if ((children == null && (t == obj && !obj.__tamee.over)) || (matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over))) { meeHelper("mouseenter", e, obj, t); t.__tamee = t.__tamee || {}; t.__tamee.over = true; activeElements.push(t); } }, out = function (e) { var t = _t(e); // is the current target one of the activeElements? and is the // related target NOT a descendant of it? for (var i = 0; i < activeElements.length; i++) { if (t == activeElements[i] && !matchesSelector((e.relatedTarget || e.toElement), "*", t)) { t.__tamee.over = false; activeElements.splice(i, 1); meeHelper("mouseexit", e, obj, t); } } }; _bind(obj, "mouseover", _curryChildFilter(children, obj, over, "mouseover"), over); _bind(obj, "mouseout", _curryChildFilter(children, obj, out, "mouseout"), out); } fn.__taUnstore = function () { delete obj.__tamee[evt][fn.__tauid]; }; _store(obj, evt, fn); obj.__tamee[evt][fn.__tauid] = fn; }; }, isTouchDevice = "ontouchstart" in document.documentElement, isMouseDevice = "onmousedown" in document.documentElement, touchMap = { "mousedown": "touchstart", "mouseup": "touchend", "mousemove": "touchmove" }, touchstart = "touchstart", touchend = "touchend", touchmove = "touchmove", iev = (function () { var rv = -1; if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent, re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv; })(), isIELT9 = iev > -1 && iev < 9, _genLoc = function (e, prefix) { if (e == null) return [ 0, 0 ]; var ts = _touches(e), t = _getTouch(ts, 0); return [t[prefix + "X"], t[prefix + "Y"]]; }, _pageLocation = function (e) { if (e == null) return [ 0, 0 ]; if (isIELT9) { return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ]; } else { return _genLoc(e, "page"); } }, _screenLocation = function (e) { return _genLoc(e, "screen"); }, _clientLocation = function (e) { return _genLoc(e, "client"); }, _getTouch = function (touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; }, _touches = function (e) { return e.touches && e.touches.length > 0 ? e.touches : e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches : e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches : [ e ]; }, _touchCount = function (e) { return _touches(e).length; }, //http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html _bind = function (obj, type, fn, originalFn) { _store(obj, type, fn); originalFn.__tauid = fn.__tauid; if (obj.addEventListener) obj.addEventListener(type, fn, false); else if (obj.attachEvent) { var key = type + fn.__tauid; obj["e" + key] = fn; // TODO look at replacing with .call(..) obj[key] = function () { obj["e" + key] && obj["e" + key](window.event); }; obj.attachEvent("on" + type, obj[key]); } }, _unbind = function (obj, type, fn) { if (fn == null) return; _each(obj, function () { var _el = _gel(this); _unstore(_el, type, fn); // it has been bound if there is a tauid. otherwise it was not bound and we can ignore it. if (fn.__tauid != null) { if (_el.removeEventListener) { _el.removeEventListener(type, fn, false); if (isTouchDevice && touchMap[type]) _el.removeEventListener(touchMap[type], fn, false); } else if (this.detachEvent) { var key = type + fn.__tauid; _el[key] && _el.detachEvent("on" + type, _el[key]); _el[key] = null; _el["e" + key] = null; } } // if a touch event was also registered, deregister now. if (fn.__taTouchProxy) { _unbind(obj, fn.__taTouchProxy[1], fn.__taTouchProxy[0]); } }); }, _each = function (obj, fn) { if (obj == null) return; // if a list (or list-like), use it. if a string, get a list // by running the string through querySelectorAll. else, assume // it's an Element. // obj.top is "unknown" in IE8. obj = (typeof Window !== "undefined" && (typeof obj.top !== "unknown" && obj == obj.top)) ? [ obj ] : (typeof obj !== "string") && (obj.tagName == null && obj.length != null) ? obj : typeof obj === "string" ? document.querySelectorAll(obj) : [ obj ]; for (var i = 0; i < obj.length; i++) fn.apply(obj[i]); }, _uuid = function () { return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); })); }; /** * Mottle offers support for abstracting out the differences * between touch and mouse devices, plus "smart click" functionality * (don't fire click if the mouse has moved between mousedown and mouseup), * and synthesized click/tap events. * @class Mottle * @constructor * @param {Object} params Constructor params * @param {Number} [params.clickThreshold=250] Threshold, in milliseconds beyond which a touchstart followed by a touchend is not considered to be a click. * @param {Number} [params.dblClickThreshold=450] Threshold, in milliseconds beyond which two successive tap events are not considered to be a click. * @param {Boolean} [params.smartClicks=false] If true, won't fire click events if the mouse has moved between mousedown and mouseup. Note that this functionality * requires that Mottle consume the mousedown event, and so may not be viable in all use cases. */ root.Mottle = function (params) { params = params || {}; var clickThreshold = params.clickThreshold || 250, dblClickThreshold = params.dblClickThreshold || 450, mouseEnterExitHandler = new MouseEnterExitHandler(), tapHandler = new TapHandler(clickThreshold, dblClickThreshold), _smartClicks = params.smartClicks, _doBind = function (obj, evt, fn, children) { if (fn == null) return; _each(obj, function () { var _el = _gel(this); if (_smartClicks && evt === "click") SmartClickHandler(_el, evt, fn, children); else if (evt === "tap" || evt === "dbltap" || evt === "contextmenu") { tapHandler(_el, evt, fn, children); } else if (evt === "mouseenter" || evt == "mouseexit") mouseEnterExitHandler(_el, evt, fn, children); else DefaultHandler(_el, evt, fn, children); }); }; /** * Removes an element from the DOM, and deregisters all event handlers for it. You should use this * to ensure you don't leak memory. * @method remove * @param {String|Element} el Element, or id of the element, to remove. * @return {Mottle} The current Mottle instance; you can chain this method. */ this.remove = function (el) { _each(el, function () { var _el = _gel(this); if (_el.__ta) { for (var evt in _el.__ta) { if (_el.__ta.hasOwnProperty(evt)) { for (var h in _el.__ta[evt]) { if (_el.__ta[evt].hasOwnProperty(h)) _unbind(_el, evt, _el.__ta[evt][h]); } } } } _el.parentNode && _el.parentNode.removeChild(_el); }); return this; }; /** * Register an event handler, optionally as a delegate for some set of descendant elements. Note * that this method takes either 3 or 4 arguments - if you supply 3 arguments it is assumed you have * omitted the `children` parameter, and that the event handler should be bound directly to the given element. * @method on * @param {Element[]|Element|String} el Either an Element, or a CSS spec for a list of elements, or an array of Elements. * @param {String} [children] Comma-delimited list of selectors identifying allowed children. * @param {String} event Event ID. * @param {Function} fn Event handler function. * @return {Mottle} The current Mottle instance; you can chain this method. */ this.on = function (el, event, children, fn) { var _el = arguments[0], _c = arguments.length == 4 ? arguments[2] : null, _e = arguments[1], _f = arguments[arguments.length - 1]; _doBind(_el, _e, _f, _c); return this; }; /** * Cancel delegate event handling for the given function. Note that unlike with 'on' you do not supply * a list of child selectors here: it removes event delegation from all of the child selectors for which the * given function was registered (if any). * @method off * @param {Element[]|Element|String} el Element - or ID of element - from which to remove event listener. * @param {String} event Event ID. * @param {Function} fn Event handler function. * @return {Mottle} The current Mottle instance; you can chain this method. */ this.off = function (el, event, fn) { _unbind(el, event, fn); return this; }; /** * Triggers some event for a given element. * @method trigger * @param {Element} el Element for which to trigger the event. * @param {String} event Event ID. * @param {Event} originalEvent The original event. Should be optional of course, but currently is not, due * to the jsPlumb use case that caused this method to be added. * @param {Object} [payload] Optional object to set as `payload` on the generated event; useful for message passing. * @return {Mottle} The current Mottle instance; you can chain this method. */ this.trigger = function (el, event, originalEvent, payload) { // MouseEvent undefined in old IE; that's how we know it's a mouse event. A fine Microsoft paradox. var originalIsMouse = isMouseDevice && (typeof MouseEvent === "undefined" || originalEvent == null || originalEvent.constructor === MouseEvent); var eventToBind = (isTouchDevice && !isMouseDevice && touchMap[event]) ? touchMap[event] : event, bindingAMouseEvent = !(isTouchDevice && !isMouseDevice && touchMap[event]); var pl = _pageLocation(originalEvent), sl = _screenLocation(originalEvent), cl = _clientLocation(originalEvent); _each(el, function () { var _el = _gel(this), evt; originalEvent = originalEvent || { screenX: sl[0], screenY: sl[1], clientX: cl[0], clientY: cl[1] }; var _decorate = function (_evt) { if (payload) _evt.payload = payload; }; var eventGenerators = { "TouchEvent": function (evt) { var touchList = _touchAndList(window, _el, 0, pl[0], pl[1], sl[0], sl[1], cl[0], cl[1]), init = evt.initTouchEvent || evt.initEvent; init(eventToBind, true, true, window, null, sl[0], sl[1], cl[0], cl[1], false, false, false, false, touchList, touchList, touchList, 1, 0); }, "MouseEvents": function (evt) { evt.initMouseEvent(eventToBind, true, true, window, 0, sl[0], sl[1], cl[0], cl[1], false, false, false, false, 1, _el); } }; if (document.createEvent) { var ite = !bindingAMouseEvent && !originalIsMouse && (isTouchDevice && touchMap[event]), evtName = ite ? "TouchEvent" : "MouseEvents"; evt = document.createEvent(evtName); eventGenerators[evtName](evt); _decorate(evt); _el.dispatchEvent(evt); } else if (document.createEventObject) { evt = document.createEventObject(); evt.eventType = evt.eventName = eventToBind; evt.screenX = sl[0]; evt.screenY = sl[1]; evt.clientX = cl[0]; evt.clientY = cl[1]; _decorate(evt); _el.fireEvent('on' + eventToBind, evt); } }); return this; } }; /** * Static method to assist in 'consuming' an element: uses `stopPropagation` where available, or sets * `e.returnValue=false` where it is not. * @method Mottle.consume * @param {Event} e Event to consume * @param {Boolean} [doNotPreventDefault=false] If true, does not call `preventDefault()` on the event. */ root.Mottle.consume = function (e, doNotPreventDefault) { if (e.stopPropagation) e.stopPropagation(); else e.returnValue = false; if (!doNotPreventDefault && e.preventDefault) e.preventDefault(); }; /** * Gets the page location corresponding to the given event. For touch events this means get the page location of the first touch. * @method Mottle.pageLocation * @param {Event} e Event to get page location for. * @return {Number[]} [left, top] for the given event. */ root.Mottle.pageLocation = _pageLocation; /** * Forces touch events to be turned "on". Useful for testing: even if you don't have a touch device, you can still * trigger a touch event when this is switched on and it will be captured and acted on. * @method setForceTouchEvents * @param {Boolean} value If true, force touch events to be on. */ root.Mottle.setForceTouchEvents = function (value) { isTouchDevice = value; }; /** * Forces mouse events to be turned "on". Useful for testing: even if you don't have a mouse, you can still * trigger a mouse event when this is switched on and it will be captured and acted on. * @method setForceMouseEvents * @param {Boolean} value If true, force mouse events to be on. */ root.Mottle.setForceMouseEvents = function (value) { isMouseDevice = value; }; root.Mottle.version = "0.8.0"; if (typeof exports !== "undefined") { exports.Mottle = root.Mottle; } }).call(typeof window === "undefined" ? this : window); /** drag/drop functionality for use with jsPlumb but with no knowledge of jsPlumb. supports multiple scopes (separated by whitespace), dragging multiple elements, constrain to parent, drop filters, drag start filters, custom css classes. a lot of the functionality of this script is expected to be plugged in: addClass removeClass addEvent removeEvent getPosition setPosition getSize indexOf intersects the name came from here: http://mrsharpoblunto.github.io/foswig.js/ copyright 2016 jsPlumb */ ;(function() { "use strict"; var root = this; var _suggest = function(list, item, head) { if (list.indexOf(item) === -1) { head ? list.unshift(item) : list.push(item); return true; } return false; }; var _vanquish = function(list, item) { var idx = list.indexOf(item); if (idx !== -1) list.splice(idx, 1); }; var _difference = function(l1, l2) { var d = []; for (var i = 0; i < l1.length; i++) { if (l2.indexOf(l1[i]) === -1) d.push(l1[i]); } return d; }; var _isString = function(f) { return f == null ? false : (typeof f === "string" || f.constructor === String); }; var getOffsetRect = function (elem) { // (1) var box = elem.getBoundingClientRect(), body = document.body, docElem = document.documentElement, // (2) scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop, scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft, // (3) clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, // (4) top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: Math.round(top), left: Math.round(left) }; }; var matchesSelector = function(el, selector, ctx) { ctx = ctx || el.parentNode; var possibles = ctx.querySelectorAll(selector); for (var i = 0; i < possibles.length; i++) { if (possibles[i] === el) return true; } return false; }; var findDelegateElement = function(parentElement, childElement, selector) { if (matchesSelector(childElement, selector, parentElement)) { return childElement; } else { var currentParent = childElement.parentNode; while (currentParent != null && currentParent !== parentElement) { if (matchesSelector(currentParent, selector, parentElement)) { return currentParent; } else { currentParent = currentParent.parentNode; } } } }; var iev = (function() { var rv = -1; if (navigator.appName === 'Microsoft Internet Explorer') { var ua = navigator.userAgent, re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv; })(), DEFAULT_GRID_X = 10, DEFAULT_GRID_Y = 10, isIELT9 = iev > -1 && iev < 9, isIE9 = iev === 9, _pl = function(e) { if (isIELT9) { return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ]; } else { var ts = _touches(e), t = _getTouch(ts, 0); // for IE9 pageX might be null if the event was synthesized. We try for pageX/pageY first, // falling back to clientX/clientY if necessary. In every other browser we want to use pageX/pageY. return isIE9 ? [t.pageX || t.clientX, t.pageY || t.clientY] : [t.pageX, t.pageY]; } }, _getTouch = function(touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; }, _touches = function(e) { return e.touches && e.touches.length > 0 ? e.touches : e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches : e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches : [ e ]; }, _classes = { draggable:"katavorio-draggable", // draggable elements droppable:"katavorio-droppable", // droppable elements drag : "katavorio-drag", // elements currently being dragged selected:"katavorio-drag-selected", // elements in current drag selection active : "katavorio-drag-active", // droppables that are targets of a currently dragged element hover : "katavorio-drag-hover", // droppables over which a matching drag element is hovering noSelect : "katavorio-drag-no-select", // added to the body to provide a hook to suppress text selection ghostProxy:"katavorio-ghost-proxy", // added to a ghost proxy element in use when a drag has exited the bounds of its parent. clonedDrag:"katavorio-clone-drag" // added to a node that is a clone of an element created at the start of a drag }, _defaultScope = "katavorio-drag-scope", _events = [ "stop", "start", "drag", "drop", "over", "out", "beforeStart" ], _devNull = function() {}, _true = function() { return true; }, _foreach = function(l, fn, from) { for (var i = 0; i < l.length; i++) { if (l[i] != from) fn(l[i]); } }, _setDroppablesActive = function(dd, val, andHover, drag) { _foreach(dd, function(e) { e.setActive(val); if (val) e.updatePosition(); if (andHover) e.setHover(drag, val); }); }, _each = function(obj, fn) { if (obj == null) return; obj = !_isString(obj) && (obj.tagName == null && obj.length != null) ? obj : [ obj ]; for (var i = 0; i < obj.length; i++) fn.apply(obj[i], [ obj[i] ]); }, _consume = function(e) { if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } else { e.returnValue = false; } }, _defaultInputFilterSelector = "input,textarea,select,button,option", // // filters out events on all input elements, like textarea, checkbox, input, select. _inputFilter = function(e, el, _katavorio) { var t = e.srcElement || e.target; return !matchesSelector(t, _katavorio.getInputFilterSelector(), el); }; var Super = function(el, params, css, scope) { this.params = params || {}; this.el = el; this.params.addClass(this.el, this._class); this.uuid = _uuid(); var enabled = true; this.setEnabled = function(e) { enabled = e; }; this.isEnabled = function() { return enabled; }; this.toggleEnabled = function() { enabled = !enabled; }; this.setScope = function(scopes) { this.scopes = scopes ? scopes.split(/\s+/) : [ scope ]; }; this.addScope = function(scopes) { var m = {}; _each(this.scopes, function(s) { m[s] = true;}); _each(scopes ? scopes.split(/\s+/) : [], function(s) { m[s] = true;}); this.scopes = []; for (var i in m) this.scopes.push(i); }; this.removeScope = function(scopes) { var m = {}; _each(this.scopes, function(s) { m[s] = true;}); _each(scopes ? scopes.split(/\s+/) : [], function(s) { delete m[s];}); this.scopes = []; for (var i in m) this.scopes.push(i); }; this.toggleScope = function(scopes) { var m = {}; _each(this.scopes, function(s) { m[s] = true;}); _each(scopes ? scopes.split(/\s+/) : [], function(s) { if (m[s]) delete m[s]; else m[s] = true; }); this.scopes = []; for (var i in m) this.scopes.push(i); }; this.setScope(params.scope); this.k = params.katavorio; return params.katavorio; }; var TRUE = function() { return true; }; var FALSE = function() { return false; }; var Drag = function(el, params, css, scope) { this._class = css.draggable; var k = Super.apply(this, arguments); this.rightButtonCanDrag = this.params.rightButtonCanDrag; var downAt = [0,0], posAtDown = null, pagePosAtDown = null, pageDelta = [0,0], moving = false, initialScroll = [0,0], consumeStartEvent = this.params.consumeStartEvent !== false, dragEl = this.el, clone = this.params.clone, scroll = this.params.scroll, _multipleDrop = params.multipleDrop !== false, isConstrained = false, useGhostProxy = params.ghostProxy === true ? TRUE : params.ghostProxy && typeof params.ghostProxy === "function" ? params.ghostProxy : FALSE, ghostProxy = function(el) { return el.cloneNode(true); }, selector = params.selector, elementToDrag = null; var snapThreshold = params.snapThreshold, _snap = function(pos, gridX, gridY, thresholdX, thresholdY) { var _dx = Math.floor(pos[0] / gridX), _dxl = gridX * _dx, _dxt = _dxl + gridX, _x = Math.abs(pos[0] - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos[0]) <= thresholdX ? _dxt : pos[0]; var _dy = Math.floor(pos[1] / gridY), _dyl = gridY * _dy, _dyt = _dyl + gridY, _y = Math.abs(pos[1] - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos[1]) <= thresholdY ? _dyt : pos[1]; return [ _x, _y]; }; this.posses = []; this.posseRoles = {}; this.toGrid = function(pos) { if (this.params.grid == null) { return pos; } else { var tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_X / 2, ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_Y / 2; return _snap(pos, this.params.grid[0], this.params.grid[1], tx, ty); } }; this.snap = function(x, y) { if (dragEl == null) return; x = x || (this.params.grid ? this.params.grid[0] : DEFAULT_GRID_X); y = y || (this.params.grid ? this.params.grid[1] : DEFAULT_GRID_Y); var p = this.params.getPosition(dragEl), tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold, ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold; this.params.setPosition(dragEl, _snap(p, x, y, tx, ty)); }; this.setUseGhostProxy = function(val) { useGhostProxy = val ? TRUE : FALSE; }; var constrain; var negativeFilter = function(pos) { return (params.allowNegative === false) ? [ Math.max (0, pos[0]), Math.max(0, pos[1]) ] : pos; }; var _setConstrain = function(value) { constrain = typeof value === "function" ? value : value ? function(pos, dragEl, _constrainRect, _size) { return negativeFilter([ Math.max(0, Math.min(_constrainRect.w - _size[0], pos[0])), Math.max(0, Math.min(_constrainRect.h - _size[1], pos[1])) ]); }.bind(this) : function(pos) { return negativeFilter(pos); }; }.bind(this); _setConstrain(typeof this.params.constrain === "function" ? this.params.constrain : (this.params.constrain || this.params.containment)); /** * Sets whether or not the Drag is constrained. A value of 'true' means constrain to parent bounds; a function * will be executed and returns true if the position is allowed. * @param value */ this.setConstrain = function(value) { _setConstrain(value); }; var revertFunction; /** * Sets a function to call on drag stop, which, if it returns true, indicates that the given element should * revert to its position before the previous drag. * @param fn */ this.setRevert = function(fn) { revertFunction = fn; }; var _assignId = function(obj) { if (typeof obj === "function") { obj._katavorioId = _uuid(); return obj._katavorioId; } else { return obj; } }, // a map of { spec -> [ fn, exclusion ] } entries. _filters = {}, _testFilter = function(e) { for (var key in _filters) { var f = _filters[key]; var rv = f[0](e); if (f[1]) rv = !rv; if (!rv) return false; } return true; }, _setFilter = this.setFilter = function(f, _exclude) { if (f) { var key = _assignId(f); _filters[key] = [ function(e) { var t = e.srcElement || e.target, m; if (_isString(f)) { m = matchesSelector(t, f, el); } else if (typeof f === "function") { m = f(e, el); } return m; }, _exclude !== false ]; } }, _addFilter = this.addFilter = _setFilter, _removeFilter = this.removeFilter = function(f) { var key = typeof f === "function" ? f._katavorioId : f; delete _filters[key]; }; this.clearAllFilters = function() { _filters = {}; }; this.canDrag = this.params.canDrag || _true; var constrainRect, matchingDroppables = [], intersectingDroppables = []; this.downListener = function(e) { var isNotRightClick = this.rightButtonCanDrag || (e.which !== 3 && e.button !== 2); if (isNotRightClick && this.isEnabled() && this.canDrag()) { var _f = _testFilter(e) && _inputFilter(e, this.el, this.k); if (_f) { if (selector) { elementToDrag = findDelegateElement(this.el, e.target || e.srcElement, selector); if(elementToDrag == null) { return; } } else { elementToDrag = this.el; } if (clone) { dragEl = elementToDrag.cloneNode(true); this.params.addClass(dragEl, _classes.clonedDrag); dragEl.setAttribute("id", null); dragEl.style.position = "absolute"; if (this.params.parent != null) { var p = this.params.getPosition(this.el); dragEl.style.left = p[0] + "px"; dragEl.style.top = p[1] + "px"; this.params.parent.appendChild(dragEl); } else { // the clone node is added to the body; getOffsetRect gives us a value // relative to the body. var b = getOffsetRect(elementToDrag); dragEl.style.left = b.left + "px"; dragEl.style.top = b.top + "px"; document.body.appendChild(dragEl); } } else { dragEl = elementToDrag; } consumeStartEvent && _consume(e); downAt = _pl(e); if (dragEl && dragEl.parentNode) { initialScroll = [dragEl.parentNode.scrollLeft, dragEl.parentNode.scrollTop]; } // this.params.bind(document, "mousemove", this.moveListener); this.params.bind(document, "mouseup", this.upListener); k.markSelection(this); k.markPosses(this); this.params.addClass(document.body, css.noSelect); _dispatch("beforeStart", {el:this.el, pos:posAtDown, e:e, drag:this}); } else if (this.params.consumeFilteredEvents) { _consume(e); } } }.bind(this); this.moveListener = function(e) { if (downAt) { if (!moving) { var _continue = _dispatch("start", {el:this.el, pos:posAtDown, e:e, drag:this}); if (_continue !== false) { if (!downAt) { return; } this.mark(true); moving = true; } else { this.abort(); } } // it is possible that the start event caused the drag to be aborted. So we check // again that we are currently dragging. if (downAt) { intersectingDroppables.length = 0; var pos = _pl(e), dx = pos[0] - downAt[0], dy = pos[1] - downAt[1], z = this.params.ignoreZoom ? 1 : k.getZoom(); if (dragEl && dragEl.parentNode) { dx += dragEl.parentNode.scrollLeft - initialScroll[0]; dy += dragEl.parentNode.scrollTop - initialScroll[1]; } dx /= z; dy /= z; this.moveBy(dx, dy, e); k.updateSelection(dx, dy, this); k.updatePosses(dx, dy, this); } } }.bind(this); this.upListener = function(e) { if (downAt) { downAt = null; this.params.unbind(document, "mousemove", this.moveListener); this.params.unbind(document, "mouseup", this.upListener); this.params.removeClass(document.body, css.noSelect); this.unmark(e); k.unmarkSelection(this, e); k.unmarkPosses(this, e); this.stop(e); //k.notifySelectionDragStop(this, e); removed in 1.1.0 under the "leave it for one release in case it breaks" rule. // it isnt necessary to fire this as the normal stop event now includes a `selection` member that has every dragged element. // firing this event causes consumers who use the `selection` array to process a lot more drag stop events than is necessary k.notifyPosseDragStop(this, e); moving = false; if (clone) { dragEl && dragEl.parentNode && dragEl.parentNode.removeChild(dragEl); dragEl = null; } intersectingDroppables.length = 0; if (revertFunction && revertFunction(this.el, this.params.getPosition(this.el)) === true) { this.params.setPosition(this.el, posAtDown); _dispatch("revert", this.el); } } }.bind(this); this.getFilters = function() { return _filters; }; this.abort = function() { if (downAt != null) { this.upListener(); } }; /** * Returns the element that was last dragged. This may be some original element from the DOM, or if `clone` is * set, then its actually a copy of some original DOM element. In some client calls to this method, it is the * actual element that was dragged that is desired. In others, it is the original DOM element that the user * wishes to get - in which case, pass true for `retrieveOriginalElement`. * * @returns {*} */ this.getDragElement = function(retrieveOriginalElement) { return retrieveOriginalElement ? elementToDrag || this.el : dragEl || this.el; }; var listeners = {"start":[], "drag":[], "stop":[], "over":[], "out":[], "beforeStart":[], "revert":[] }; if (params.events.start) listeners.start.push(params.events.start); if (params.events.beforeStart) listeners.beforeStart.push(params.events.beforeStart); if (params.events.stop) listeners.stop.push(params.events.stop); if (params.events.drag) listeners.drag.push(params.events.drag); if (params.events.revert) listeners.revert.push(params.events.revert); this.on = function(evt, fn) { if (listeners[evt]) listeners[evt].push(fn); }; this.off = function(evt, fn) { if (listeners[evt]) { var l = []; for (var i = 0; i < listeners[evt].length; i++) { if (listeners[evt][i] !== fn) l.push(listeners[evt][i]); } listeners[evt] = l; } }; var _dispatch = function(evt, value) { var result = null; if (listeners[evt]) { for (var i = 0; i < listeners[evt].length; i++) { try { var v = listeners[evt][i](value); if (v != null) { result = v; } } catch (e) { } } } return result; }; this.notifyStart = function(e) { _dispatch("start", {el:this.el, pos:this.params.getPosition(dragEl), e:e, drag:this}); }; this.stop = function(e, force) { if (force || moving) { var positions = [], sel = k.getSelection(), dPos = this.params.getPosition(dragEl); if (sel.length > 1) { for (var i = 0; i < sel.length; i++) { var p = this.params.getPosition(sel[i].el); positions.push([ sel[i].el, { left: p[0], top: p[1] }, sel[i] ]); } } else { positions.push([ dragEl, {left:dPos[0], top:dPos[1]}, this ]); } _dispatch("stop", { el: dragEl, pos: ghostProxyOffsets || dPos, finalPos:dPos, e: e, drag: this, selection:positions }); } }; this.mark = function(andNotify) { posAtDown = this.params.getPosition(dragEl); pagePosAtDown = this.params.getPosition(dragEl, true); pageDelta = [pagePosAtDown[0] - posAtDown[0], pagePosAtDown[1] - posAtDown[1]]; this.size = this.params.getSize(dragEl); matchingDroppables = k.getMatchingDroppables(this); _setDroppablesActive(matchingDroppables, true, false, this); this.params.addClass(dragEl, this.params.dragClass || css.drag); var cs; if (this.params.getConstrainingRectangle) { cs = this.params.getConstrainingRectangle(dragEl) } else { cs = this.params.getSize(dragEl.parentNode); } constrainRect = {w: cs[0], h: cs[1]}; if (andNotify) { k.notifySelectionDragStart(this); } }; var ghostProxyOffsets; this.unmark = function(e, doNotCheckDroppables) { _setDroppablesActive(matchingDroppables, false, true, this); if (isConstrained && useGhostProxy(elementToDrag)) { ghostProxyOffsets = [dragEl.offsetLeft, dragEl.offsetTop]; elementToDrag.parentNode.removeChild(dragEl); dragEl = elementToDrag; } else { ghostProxyOffsets = null; } this.params.removeClass(dragEl, this.params.dragClass || css.drag); matchingDroppables.length = 0; isConstrained = false; if (!doNotCheckDroppables) { if (intersectingDroppables.length > 0 && ghostProxyOffsets) { params.setPosition(elementToDrag, ghostProxyOffsets); } intersectingDroppables.sort(_rankSort); for (var i = 0; i < intersectingDroppables.length; i++) { var retVal = intersectingDroppables[i].drop(this, e); if (retVal === true) break; } } }; this.moveBy = function(dx, dy, e) { intersectingDroppables.length = 0; var desiredLoc = this.toGrid([posAtDown[0] + dx, posAtDown[1] + dy]), cPos = constrain(desiredLoc, dragEl, constrainRect, this.size); if (useGhostProxy(this.el)) { if (desiredLoc[0] !== cPos[0] || desiredLoc[1] !== cPos[1]) { if (!isConstrained) { var gp = ghostProxy(elementToDrag); params.addClass(gp, _classes.ghostProxy); elementToDrag.parentNode.appendChild(gp); dragEl = gp; isConstrained = true; } cPos = desiredLoc; } else { if (isConstrained) { elementToDrag.parentNode.removeChild(dragEl); dragEl = elementToDrag; isConstrained = false; } } } var rect = { x:cPos[0], y:cPos[1], w:this.size[0], h:this.size[1]}, pageRect = { x:rect.x + pageDelta[0], y:rect.y + pageDelta[1], w:rect.w, h:rect.h}, focusDropElement = null; this.params.setPosition(dragEl, cPos); for (var i = 0; i < matchingDroppables.length; i++) { var r2 = { x:matchingDroppables[i].pagePosition[0], y:matchingDroppables[i].pagePosition[1], w:matchingDroppables[i].size[0], h:matchingDroppables[i].size[1]}; if (this.params.intersects(pageRect, r2) && (_multipleDrop || focusDropElement == null || focusDropElement === matchingDroppables[i].el) && matchingDroppables[i].canDrop(this)) { if (!focusDropElement) focusDropElement = matchingDroppables[i].el; intersectingDroppables.push(matchingDroppables[i]); matchingDroppables[i].setHover(this, true, e); } else if (matchingDroppables[i].isHover()) { matchingDroppables[i].setHover(this, false, e); } } _dispatch("drag", {el:this.el, pos:cPos, e:e, drag:this}); /* test to see if the parent needs to be scrolled (future) if (scroll) { var pnsl = dragEl.parentNode.scrollLeft, pnst = dragEl.parentNode.scrollTop; console.log("scroll!", pnsl, pnst); }*/ }; this.destroy = function() { this.params.unbind(this.el, "mousedown", this.downListener); this.params.unbind(document, "mousemove", this.moveListener); this.params.unbind(document, "mouseup", this.upListener); this.downListener = null; this.upListener = null; this.moveListener = null; }; // init:register mousedown, and perhaps set a filter this.params.bind(this.el, "mousedown", this.downListener); // if handle provded, use that. otherwise, try to set a filter. // note that a `handle` selector always results in filterExclude being set to false, ie. // the selector defines the handle element(s). if (this.params.handle) _setFilter(this.params.handle, false); else _setFilter(this.params.filter, this.params.filterExclude); }; var Drop = function(el, params, css, scope) { this._class = css.droppable; this.params = params || {}; this.rank = params.rank || 0; this._activeClass = this.params.activeClass || css.active; this._hoverClass = this.params.hoverClass || css.hover; Super.apply(this, arguments); var hover = false; this.allowLoopback = this.params.allowLoopback !== false; this.setActive = function(val) { this.params[val ? "addClass" : "removeClass"](this.el, this._activeClass); }; this.updatePosition = function() { this.position = this.params.getPosition(this.el); this.pagePosition = this.params.getPosition(this.el, true); this.size = this.params.getSize(this.el); }; this.canDrop = this.params.canDrop || function(drag) { return true; }; this.isHover = function() { return hover; }; this.setHover = function(drag, val, e) { // if turning off hover but this was not the drag that caused the hover, ignore. if (val || this.el._katavorioDragHover == null || this.el._katavorioDragHover === drag.el._katavorio) { this.params[val ? "addClass" : "removeClass"](this.el, this._hoverClass); this.el._katavorioDragHover = val ? drag.el._katavorio : null; if (hover !== val) { this.params.events[val ? "over" : "out"]({el: this.el, e: e, drag: drag, drop: this}); } hover = val; } }; /** * A drop event. `drag` is the corresponding Drag object, which may be a Drag for some specific element, or it * may be a Drag on some element acting as a delegate for elements contained within it. * @param drag * @param event * @returns {*} */ this.drop = function(drag, event) { return this.params.events["drop"]({ drag:drag, e:event, drop:this }); }; this.destroy = function() { this._class = null; this._activeClass = null; this._hoverClass = null; hover = null; }; }; var _uuid = function() { return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); })); }; var _rankSort = function(a,b) { return a.rank < b.rank ? 1 : a.rank > b.rank ? -1 : 0; }; var _gel = function(el) { if (el == null) return null; el = (typeof el === "string" || el.constructor === String) ? document.getElementById(el) : el; if (el == null) return null; el._katavorio = el._katavorio || _uuid(); return el; }; root.Katavorio = function(katavorioParams) { var _selection = [], _selectionMap = {}; this._dragsByScope = {}; this._dropsByScope = {}; var _zoom = 1, _reg = function(obj, map) { _each(obj, function(_obj) { for(var i = 0; i < _obj.scopes.length; i++) { map[_obj.scopes[i]] = map[_obj.scopes[i]] || []; map[_obj.scopes[i]].push(_obj); } }); }, _unreg = function(obj, map) { var c = 0; _each(obj, function(_obj) { for(var i = 0; i < _obj.scopes.length; i++) { if (map[_obj.scopes[i]]) { var idx = katavorioParams.indexOf(map[_obj.scopes[i]], _obj); if (idx !== -1) { map[_obj.scopes[i]].splice(idx, 1); c++; } } } }); return c > 0 ; }, _getMatchingDroppables = this.getMatchingDroppables = function(drag) { var dd = [], _m = {}; for (var i = 0; i < drag.scopes.length; i++) { var _dd = this._dropsByScope[drag.scopes[i]]; if (_dd) { for (var j = 0; j < _dd.length; j++) { if (_dd[j].canDrop(drag) && !_m[_dd[j].uuid] && (_dd[j].allowLoopback || _dd[j].el !== drag.el)) { _m[_dd[j].uuid] = true; dd.push(_dd[j]); } } } } dd.sort(_rankSort); return dd; }, _prepareParams = function(p) { p = p || {}; var _p = { events:{} }, i; for (i in katavorioParams) _p[i] = katavorioParams[i]; for (i in p) _p[i] = p[i]; // events for (i = 0; i < _events.length; i++) { _p.events[_events[i]] = p[_events[i]] || _devNull; } _p.katavorio = this; return _p; }.bind(this), _mistletoe = function(existingDrag, params) { for (var i = 0; i < _events.length; i++) { if (params[_events[i]]) { existingDrag.on(_events[i], params[_events[i]]); } } }.bind(this), _css = {}, overrideCss = katavorioParams.css || {}, _scope = katavorioParams.scope || _defaultScope; // prepare map of css classes based on defaults frst, then optional overrides for (var i in _classes) _css[i] = _classes[i]; for (var i in overrideCss) _css[i] = overrideCss[i]; var inputFilterSelector = katavorioParams.inputFilterSelector || _defaultInputFilterSelector; /** * Gets the selector identifying which input elements to filter from drag events. * @method getInputFilterSelector * @return {String} Current input filter selector. */ this.getInputFilterSelector = function() { return inputFilterSelector; }; /** * Sets the selector identifying which input elements to filter from drag events. * @method setInputFilterSelector * @param {String} selector Input filter selector to set. * @return {Katavorio} Current instance; method may be chained. */ this.setInputFilterSelector = function(selector) { inputFilterSelector = selector; return this; }; /** * Either makes the given element draggable, or identifies it as an element inside which some identified list * of elements may be draggable. * @param el * @param params * @returns {Array} */ this.draggable = function(el, params) { var o = []; _each(el, function (_el) { _el = _gel(_el); if (_el != null) { if (_el._katavorioDrag == null) { var p = _prepareParams(params); _el._katavorioDrag = new Drag(_el, p, _css, _scope); _reg(_el._katavorioDrag, this._dragsByScope); o.push(_el._katavorioDrag); katavorioParams.addClass(_el, _css.draggable); } else { _mistletoe(_el._katavorioDrag, params); } } }.bind(this)); return o; }; this.droppable = function(el, params) { var o = []; _each(el, function(_el) { _el = _gel(_el); if (_el != null) { var drop = new Drop(_el, _prepareParams(params), _css, _scope); _el._katavorioDrop = _el._katavorioDrop || []; _el._katavorioDrop.push(drop); _reg(drop, this._dropsByScope); o.push(drop); katavorioParams.addClass(_el, _css.droppable); } }.bind(this)); return o; }; /** * @name Katavorio#select * @function * @desc Adds an element to the current selection (for multiple node drag) * @param {Element|String} DOM element - or id of the element - to add. */ this.select = function(el) { _each(el, function() { var _el = _gel(this); if (_el && _el._katavorioDrag) { if (!_selectionMap[_el._katavorio]) { _selection.push(_el._katavorioDrag); _selectionMap[_el._katavorio] = [ _el, _selection.length - 1 ]; katavorioParams.addClass(_el, _css.selected); } } }); return this; }; /** * @name Katavorio#deselect * @function * @desc Removes an element from the current selection (for multiple node drag) * @param {Element|String} DOM element - or id of the element - to remove. */ this.deselect = function(el) { _each(el, function() { var _el = _gel(this); if (_el && _el._katavorio) { var e = _selectionMap[_el._katavorio]; if (e) { var _s = []; for (var i = 0; i < _selection.length; i++) if (_selection[i].el !== _el) _s.push(_selection[i]); _selection = _s; delete _selectionMap[_el._katavorio]; katavorioParams.removeClass(_el, _css.selected); } } }); return this; }; this.deselectAll = function() { for (var i in _selectionMap) { var d = _selectionMap[i]; katavorioParams.removeClass(d[0], _css.selected); } _selection.length = 0; _selectionMap = {}; }; this.markSelection = function(drag) { _foreach(_selection, function(e) { e.mark(); }, drag); }; this.markPosses = function(drag) { if (drag.posses) { _each(drag.posses, function(p) { if (drag.posseRoles[p] && _posses[p]) { _foreach(_posses[p].members, function (d) { d.mark(); }, drag); } }) } }; this.unmarkSelection = function(drag, event) { _foreach(_selection, function(e) { e.unmark(event); }, drag); }; this.unmarkPosses = function(drag, event) { if (drag.posses) { _each(drag.posses, function(p) { if (drag.posseRoles[p] && _posses[p]) { _foreach(_posses[p].members, function (d) { d.unmark(event, true); }, drag); } }); } }; this.getSelection = function() { return _selection.slice(0); }; this.updateSelection = function(dx, dy, drag) { _foreach(_selection, function(e) { e.moveBy(dx, dy); }, drag); }; var _posseAction = function(fn, drag) { if (drag.posses) { _each(drag.posses, function(p) { if (drag.posseRoles[p] && _posses[p]) { _foreach(_posses[p].members, function (e) { fn(e); }, drag); } }); } }; this.updatePosses = function(dx, dy, drag) { _posseAction(function(e) { e.moveBy(dx, dy); }, drag); }; this.notifyPosseDragStop = function(drag, evt) { _posseAction(function(e) { e.stop(evt, true); }, drag); }; this.notifySelectionDragStop = function(drag, evt) { _foreach(_selection, function(e) { e.stop(evt, true); }, drag); }; this.notifySelectionDragStart = function(drag, evt) { _foreach(_selection, function(e) { e.notifyStart(evt);}, drag); }; this.setZoom = function(z) { _zoom = z; }; this.getZoom = function() { return _zoom; }; // does the work of changing scopes var _scopeManip = function(kObj, scopes, map, fn) { _each(kObj, function(_kObj) { _unreg(_kObj, map); // deregister existing scopes _kObj[fn](scopes); // set scopes _reg(_kObj, map); // register new ones }); }; _each([ "set", "add", "remove", "toggle"], function(v) { this[v + "Scope"] = function(el, scopes) { _scopeManip(el._katavorioDrag, scopes, this._dragsByScope, v + "Scope"); _scopeManip(el._katavorioDrop, scopes, this._dropsByScope, v + "Scope"); }.bind(this); this[v + "DragScope"] = function(el, scopes) { _scopeManip(el.constructor === Drag ? el : el._katavorioDrag, scopes, this._dragsByScope, v + "Scope"); }.bind(this); this[v + "DropScope"] = function(el, scopes) { _scopeManip(el.constructor === Drop ? el : el._katavorioDrop, scopes, this._dropsByScope, v + "Scope"); }.bind(this); }.bind(this)); this.snapToGrid = function(x, y) { for (var s in this._dragsByScope) { _foreach(this._dragsByScope[s], function(d) { d.snap(x, y); }); } }; this.getDragsForScope = function(s) { return this._dragsByScope[s]; }; this.getDropsForScope = function(s) { return this._dropsByScope[s]; }; var _destroy = function(el, type, map) { el = _gel(el); if (el[type]) { // remove from selection, if present. var selIdx = _selection.indexOf(el[type]); if (selIdx >= 0) { _selection.splice(selIdx, 1); } if (_unreg(el[type], map)) { _each(el[type], function(kObj) { kObj.destroy() }); } delete el[type]; } }; var _removeListener = function(el, type, evt, fn) { el = _gel(el); if (el[type]) { el[type].off(evt, fn); } }; this.elementRemoved = function(el) { this.destroyDraggable(el); this.destroyDroppable(el); }; /** * Either completely remove drag functionality from the given element, or remove a specific event handler. If you * call this method with a single argument - the element - all drag functionality is removed from it. Otherwise, if * you provide an event name and listener function, this function is de-registered (if found). * @param el Element to update * @param {string} [evt] Optional event name to unsubscribe * @param {Function} [fn] Optional function to unsubscribe */ this.destroyDraggable = function(el, evt, fn) { if (arguments.length === 1) { _destroy(el, "_katavorioDrag", this._dragsByScope); } else { _removeListener(el, "_katavorioDrag", evt, fn); } }; /** * Either completely remove drop functionality from the given element, or remove a specific event handler. If you * call this method with a single argument - the element - all drop functionality is removed from it. Otherwise, if * you provide an event name and listener function, this function is de-registered (if found). * @param el Element to update * @param {string} [evt] Optional event name to unsubscribe * @param {Function} [fn] Optional function to unsubscribe */ this.destroyDroppable = function(el, evt, fn) { if (arguments.length === 1) { _destroy(el, "_katavorioDrop", this._dropsByScope); } else { _removeListener(el, "_katavorioDrop", evt, fn); } }; this.reset = function() { this._dragsByScope = {}; this._dropsByScope = {}; _selection = []; _selectionMap = {}; _posses = {}; }; // ----- groups var _posses = {}; var _processOneSpec = function(el, _spec, dontAddExisting) { var posseId = _isString(_spec) ? _spec : _spec.id; var active = _isString(_spec) ? true : _spec.active !== false; var posse = _posses[posseId] || (function() { var g = {name:posseId, members:[]}; _posses[posseId] = g; return g; })(); _each(el, function(_el) { if (_el._katavorioDrag) { if (dontAddExisting && _el._katavorioDrag.posseRoles[posse.name] != null) return; _suggest(posse.members, _el._katavorioDrag); _suggest(_el._katavorioDrag.posses, posse.name); _el._katavorioDrag.posseRoles[posse.name] = active; } }); return posse; }; /** * Add the given element to the posse with the given id, creating the group if it at first does not exist. * @method addToPosse * @param {Element} el Element to add. * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating * the ID of a Posse to which the element should be added as an active participant, or an Object containing * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be * true. * @returns {Posse|Posse[]} The Posse(s) to which the element(s) was/were added. */ this.addToPosse = function(el, spec) { var posses = []; for (var i = 1; i < arguments.length; i++) { posses.push(_processOneSpec(el, arguments[i])); } return posses.length === 1 ? posses[0] : posses; }; /** * Sets the posse(s) for the element with the given id, creating those that do not yet exist, and removing from * the element any current Posses that are not specified by this method call. This method will not change the * active/passive state if it is given a posse in which the element is already a member. * @method setPosse * @param {Element} el Element to set posse(s) on. * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating * the ID of a Posse to which the element should be added as an active participant, or an Object containing * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be * true. * @returns {Posse|Posse[]} The Posse(s) to which the element(s) now belongs. */ this.setPosse = function(el, spec) { var posses = []; for (var i = 1; i < arguments.length; i++) { posses.push(_processOneSpec(el, arguments[i], true).name); } _each(el, function(_el) { if (_el._katavorioDrag) { var diff = _difference(_el._katavorioDrag.posses, posses); var p = []; Array.prototype.push.apply(p, _el._katavorioDrag.posses); for (var i = 0; i < diff.length; i++) { this.removeFromPosse(_el, diff[i]); } } }.bind(this)); return posses.length === 1 ? posses[0] : posses; }; /** * Remove the given element from the given posse(s). * @method removeFromPosse * @param {Element} el Element to remove. * @param {String...} posseId Varargs parameter: one value for each posse to remove the element from. */ this.removeFromPosse = function(el, posseId) { if (arguments.length < 2) throw new TypeError("No posse id provided for remove operation"); for(var i = 1; i < arguments.length; i++) { posseId = arguments[i]; _each(el, function (_el) { if (_el._katavorioDrag && _el._katavorioDrag.posses) { var d = _el._katavorioDrag; _each(posseId, function (p) { _vanquish(_posses[p].members, d); _vanquish(d.posses, p); delete d.posseRoles[p]; }); } }); } }; /** * Remove the given element from all Posses to which it belongs. * @method removeFromAllPosses * @param {Element|Element[]} el Element to remove from Posses. */ this.removeFromAllPosses = function(el) { _each(el, function(_el) { if (_el._katavorioDrag && _el._katavorioDrag.posses) { var d = _el._katavorioDrag; _each(d.posses, function(p) { _vanquish(_posses[p].members, d); }); d.posses.length = 0; d.posseRoles = {}; } }); }; /** * Changes the participation state for the element in the Posse with the given ID. * @param {Element|Element[]} el Element(s) to change state for. * @param {String} posseId ID of the Posse to change element state for. * @param {Boolean} state True to make active, false to make passive. */ this.setPosseState = function(el, posseId, state) { var posse = _posses[posseId]; if (posse) { _each(el, function(_el) { if (_el._katavorioDrag && _el._katavorioDrag.posses) { _el._katavorioDrag.posseRoles[posse.name] = state; } }); } }; }; root.Katavorio.version = "1.0.0"; if (typeof exports !== "undefined") { exports.Katavorio = root.Katavorio; } }).call(typeof window !== 'undefined' ? window : this); (function() { var root = this; root.jsPlumbUtil = root.jsPlumbUtil || {}; var jsPlumbUtil = root.jsPlumbUtil; if (typeof exports !=='undefined') { exports.jsPlumbUtil = jsPlumbUtil;} function isArray(a) { return Object.prototype.toString.call(a) === "[object Array]"; } jsPlumbUtil.isArray = isArray; function isNumber(n) { return Object.prototype.toString.call(n) === "[object Number]"; } jsPlumbUtil.isNumber = isNumber; function isString(s) { return typeof s === "string"; } jsPlumbUtil.isString = isString; function isBoolean(s) { return typeof s === "boolean"; } jsPlumbUtil.isBoolean = isBoolean; function isNull(s) { return s == null; } jsPlumbUtil.isNull = isNull; function isObject(o) { return o == null ? false : Object.prototype.toString.call(o) === "[object Object]"; } jsPlumbUtil.isObject = isObject; function isDate(o) { return Object.prototype.toString.call(o) === "[object Date]"; } jsPlumbUtil.isDate = isDate; function isFunction(o) { return Object.prototype.toString.call(o) === "[object Function]"; } jsPlumbUtil.isFunction = isFunction; function isNamedFunction(o) { return isFunction(o) && o.name != null && o.name.length > 0; } jsPlumbUtil.isNamedFunction = isNamedFunction; function isEmpty(o) { for (var i in o) { if (o.hasOwnProperty(i)) { return false; } } return true; } jsPlumbUtil.isEmpty = isEmpty; function clone(a) { if (isString(a)) { return "" + a; } else if (isBoolean(a)) { return !!a; } else if (isDate(a)) { return new Date(a.getTime()); } else if (isFunction(a)) { return a; } else if (isArray(a)) { var b = []; for (var i = 0; i < a.length; i++) { b.push(clone(a[i])); } return b; } else if (isObject(a)) { var c = {}; for (var j in a) { c[j] = clone(a[j]); } return c; } else { return a; } } jsPlumbUtil.clone = clone; function merge(a, b, collations, overwrites) { // first change the collations array - if present - into a lookup table, because its faster. var cMap = {}, ar, i, oMap = {}; collations = collations || []; overwrites = overwrites || []; for (i = 0; i < collations.length; i++) { cMap[collations[i]] = true; } for (i = 0; i < overwrites.length; i++) { oMap[overwrites[i]] = true; } var c = clone(a); for (i in b) { if (c[i] == null || oMap[i]) { c[i] = b[i]; } else if (isString(b[i]) || isBoolean(b[i])) { if (!cMap[i]) { c[i] = b[i]; // if we dont want to collate, just copy it in. } else { ar = []; // if c's object is also an array we can keep its values. ar.push.apply(ar, isArray(c[i]) ? c[i] : [c[i]]); ar.push.apply(ar, isBoolean(b[i]) ? b[i] : [b[i]]); c[i] = ar; } } else { if (isArray(b[i])) { ar = []; // if c's object is also an array we can keep its values. if (isArray(c[i])) { ar.push.apply(ar, c[i]); } ar.push.apply(ar, b[i]); c[i] = ar; } else if (isObject(b[i])) { // overwrite c's value with an object if it is not already one. if (!isObject(c[i])) { c[i] = {}; } for (var j in b[i]) { c[i][j] = b[i][j]; } } } } return c; } jsPlumbUtil.merge = merge; function replace(inObj, path, value) { if (inObj == null) { return; } var q = inObj, t = q; path.replace(/([^\.])+/g, function (term, lc, pos, str) { var array = term.match(/([^\[0-9]+){1}(\[)([0-9+])/), last = pos + term.length >= str.length, _getArray = function () { return t[array[1]] || (function () { t[array[1]] = []; return t[array[1]]; })(); }; if (last) { // set term = value on current t, creating term as array if necessary. if (array) { _getArray()[array[3]] = value; } else { t[term] = value; } } else { // set to current t[term], creating t[term] if necessary. if (array) { var a_1 = _getArray(); t = a_1[array[3]] || (function () { a_1[array[3]] = {}; return a_1[array[3]]; })(); } else { t = t[term] || (function () { t[term] = {}; return t[term]; })(); } } return ""; }); return inObj; } jsPlumbUtil.replace = replace; // // chain a list of functions, supplied by [ object, method name, args ], and return on the first // one that returns the failValue. if none return the failValue, return the successValue. // function functionChain(successValue, failValue, fns) { for (var i = 0; i < fns.length; i++) { var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]); if (o === failValue) { return o; } } return successValue; } jsPlumbUtil.functionChain = functionChain; /** * * Take the given model and expand out any parameters. 'functionPrefix' is optional, and if present, helps jsplumb figure out what to do if a value is a Function. * if you do not provide it (and doNotExpandFunctions is null, or false), jsplumb will run the given values through any functions it finds, and use the function's * output as the value in the result. if you do provide the prefix, only functions that are named and have this prefix * will be executed; other functions will be passed as values to the output. * * @param model * @param values * @param functionPrefix * @param doNotExpandFunctions * @returns {any} */ function populate(model, values, functionPrefix, doNotExpandFunctions) { // for a string, see if it has parameter matches, and if so, try to make the substitutions. var getValue = function (fromString) { var matches = fromString.match(/(\${.*?})/g); if (matches != null) { for (var i = 0; i < matches.length; i++) { var val = values[matches[i].substring(2, matches[i].length - 1)] || ""; if (val != null) { fromString = fromString.replace(matches[i], val); } } } return fromString; }; // process one entry. var _one = function (d) { if (d != null) { if (isString(d)) { return getValue(d); } else if (isFunction(d) && !doNotExpandFunctions && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) { return d(values); } else if (isArray(d)) { var r = []; for (var i = 0; i < d.length; i++) { r.push(_one(d[i])); } return r; } else if (isObject(d)) { var s = {}; for (var j in d) { s[j] = _one(d[j]); } return s; } else { return d; } } }; return _one(model); } jsPlumbUtil.populate = populate; function findWithFunction(a, f) { if (a) { for (var i = 0; i < a.length; i++) { if (f(a[i])) { return i; } } } return -1; } jsPlumbUtil.findWithFunction = findWithFunction; function removeWithFunction(a, f) { var idx = findWithFunction(a, f); if (idx > -1) { a.splice(idx, 1); } return idx !== -1; } jsPlumbUtil.removeWithFunction = removeWithFunction; function remove(l, v) { var idx = l.indexOf(v); if (idx > -1) { l.splice(idx, 1); } return idx !== -1; } jsPlumbUtil.remove = remove; function addWithFunction(list, item, hashFunction) { if (findWithFunction(list, hashFunction) === -1) { list.push(item); } } jsPlumbUtil.addWithFunction = addWithFunction; function addToList(map, key, value, insertAtStart) { var l = map[key]; if (l == null) { l = []; map[key] = l; } l[insertAtStart ? "unshift" : "push"](value); return l; } jsPlumbUtil.addToList = addToList; function suggest(list, item, insertAtHead) { if (list.indexOf(item) === -1) { if (insertAtHead) { list.unshift(item); } else { list.push(item); } return true; } return false; } jsPlumbUtil.suggest = suggest; // // extends the given obj (which can be an array) with the given constructor function, prototype functions, and // class members, any of which may be null. // function extend(child, parent, _protoFn) { var i; parent = isArray(parent) ? parent : [parent]; var _copyProtoChain = function (focus) { var proto = focus.__proto__; while (proto != null) { if (proto.prototype != null) { for (var j in proto.prototype) { if (proto.prototype.hasOwnProperty(j) && !child.prototype.hasOwnProperty(j)) { child.prototype[j] = proto.prototype[j]; } } proto = proto.prototype.__proto__; } else { proto = null; } } }; for (i = 0; i < parent.length; i++) { for (var j in parent[i].prototype) { if (parent[i].prototype.hasOwnProperty(j) && !child.prototype.hasOwnProperty(j)) { child.prototype[j] = parent[i].prototype[j]; } } _copyProtoChain(parent[i]); } var _makeFn = function (name, protoFn) { return function () { for (i = 0; i < parent.length; i++) { if (parent[i].prototype[name]) { parent[i].prototype[name].apply(this, arguments); } } return protoFn.apply(this, arguments); }; }; var _oneSet = function (fns) { for (var k in fns) { child.prototype[k] = _makeFn(k, fns[k]); } }; if (arguments.length > 2) { for (i = 2; i < arguments.length; i++) { _oneSet(arguments[i]); } } return child; } jsPlumbUtil.extend = extend; function uuid() { return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); })); } jsPlumbUtil.uuid = uuid; function fastTrim(s) { if (s == null) { return null; } var str = s.replace(/^\s\s*/, ''), ws = /\s/, i = str.length; while (ws.test(str.charAt(--i))) { } return str.slice(0, i + 1); } jsPlumbUtil.fastTrim = fastTrim; function each(obj, fn) { obj = obj.length == null || typeof obj === "string" ? [obj] : obj; for (var i = 0; i < obj.length; i++) { fn(obj[i]); } } jsPlumbUtil.each = each; function map(obj, fn) { var o = []; for (var i = 0; i < obj.length; i++) { o.push(fn(obj[i])); } return o; } jsPlumbUtil.map = map; function mergeWithParents(type, map, parentAttribute) { parentAttribute = parentAttribute || "parent"; var _def = function (id) { return id ? map[id] : null; }; var _parent = function (def) { return def ? _def(def[parentAttribute]) : null; }; var _one = function (parent, def) { if (parent == null) { return def; } else { var d_1 = merge(parent, def); return _one(_parent(parent), d_1); } }; var _getDef = function (t) { if (t == null) { return {}; } if (typeof t === "string") { return _def(t); } else if (t.length) { var done = false, i = 0, _dd = void 0; while (!done && i < t.length) { _dd = _getDef(t[i]); if (_dd) { done = true; } else { i++; } } return _dd; } }; var d = _getDef(type); if (d) { return _one(_parent(d), d); } else { return {}; } } jsPlumbUtil.mergeWithParents = mergeWithParents; jsPlumbUtil.logEnabled = true; function log() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (jsPlumbUtil.logEnabled && typeof console !== "undefined") { try { var msg = arguments[arguments.length - 1]; console.log(msg); } catch (e) { } } } jsPlumbUtil.log = log; /** * Wraps one function with another, creating a placeholder for the * wrapped function if it was null. this is used to wrap the various * drag/drop event functions - to allow jsPlumb to be notified of * important lifecycle events without imposing itself on the user's * drag/drop functionality. * @method jsPlumbUtil.wrap * @param {Function} wrappedFunction original function to wrap; may be null. * @param {Function} newFunction function to wrap the original with. * @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should * not be executed if the newFunction returns a value matching 'returnOnThisValue'. * note that this is a simple comparison and only works for primitives right now. */ function wrap(wrappedFunction, newFunction, returnOnThisValue) { return function () { var r = null; try { if (newFunction != null) { r = newFunction.apply(this, arguments); } } catch (e) { log("jsPlumb function failed : " + e); } if ((wrappedFunction != null) && (returnOnThisValue == null || (r !== returnOnThisValue))) { try { r = wrappedFunction.apply(this, arguments); } catch (e) { log("wrapped function failed : " + e); } } return r; }; } jsPlumbUtil.wrap = wrap; var EventGenerator = /** @class */ (function () { function EventGenerator() { var _this = this; this._listeners = {}; this.eventsSuspended = false; this.tick = false; // this is a list of events that should re-throw any errors that occur during their dispatch. this.eventsToDieOn = { "ready": true }; this.queue = []; this.bind = function (event, listener, insertAtStart) { var _one = function (evt) { addToList(_this._listeners, evt, listener, insertAtStart); listener.__jsPlumb = listener.__jsPlumb || {}; listener.__jsPlumb[uuid()] = evt; }; if (typeof event === "string") { _one(event); } else if (event.length != null) { for (var i = 0; i < event.length; i++) { _one(event[i]); } } return _this; }; this.fire = function (event, value, originalEvent) { if (!this.tick) { this.tick = true; if (!this.eventsSuspended && this._listeners[event]) { var l = this._listeners[event].length, i = 0, _gone = false, ret = null; if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) { while (!_gone && i < l && ret !== false) { // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this // method will have the whole call stack available in the debugger. if (this.eventsToDieOn[event]) { this._listeners[event][i].apply(this, [value, originalEvent]); } else { try { ret = this._listeners[event][i].apply(this, [value, originalEvent]); } catch (e) { log("jsPlumb: fire failed for event " + event + " : " + e); } } i++; if (this._listeners == null || this._listeners[event] == null) { _gone = true; } } } } this.tick = false; this._drain(); } else { this.queue.unshift(arguments); } return this; }; this._drain = function () { var n = _this.queue.pop(); if (n) { _this.fire.apply(_this, n); } }; this.unbind = function (eventOrListener, listener) { if (arguments.length === 0) { this._listeners = {}; } else if (arguments.length === 1) { if (typeof eventOrListener === "string") { delete this._listeners[eventOrListener]; } else if (eventOrListener.__jsPlumb) { var evt = void 0; for (var i in eventOrListener.__jsPlumb) { evt = eventOrListener.__jsPlumb[i]; remove(this._listeners[evt] || [], eventOrListener); } } } else if (arguments.length === 2) { remove(this._listeners[eventOrListener] || [], listener); } return this; }; this.getListener = function (forEvent) { return _this._listeners[forEvent]; }; this.setSuspendEvents = function (val) { _this.eventsSuspended = val; }; this.isSuspendEvents = function () { return _this.eventsSuspended; }; this.silently = function (fn) { _this.setSuspendEvents(true); try { fn(); } catch (e) { log("Cannot execute silent function " + e); } _this.setSuspendEvents(false); }; this.cleanupListeners = function () { for (var i in _this._listeners) { _this._listeners[i] = null; } }; } return EventGenerator; }()); jsPlumbUtil.EventGenerator = EventGenerator; }).call(typeof window !== 'undefined' ? window : this); /* * This file contains utility functions that run in browsers only. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { "use strict"; var root = this; root.jsPlumbUtil.matchesSelector = function(el, selector, ctx) { ctx = ctx || el.parentNode; var possibles = ctx.querySelectorAll(selector); for (var i = 0; i < possibles.length; i++) { if (possibles[i] === el) { return true; } } return false; }; root.jsPlumbUtil.consume = function(e, doNotPreventDefault) { if (e.stopPropagation) { e.stopPropagation(); } else { e.returnValue = false; } if (!doNotPreventDefault && e.preventDefault){ e.preventDefault(); } }; /* * Function: sizeElement * Helper to size and position an element. You would typically use * this when writing your own Connector or Endpoint implementation. * * Parameters: * x - [int] x position for the element origin * y - [int] y position for the element origin * w - [int] width of the element * h - [int] height of the element * */ root.jsPlumbUtil.sizeElement = function(el, x, y, w, h) { if (el) { el.style.height = h + "px"; el.height = h; el.style.width = w + "px"; el.width = w; el.style.left = x + "px"; el.style.top = y + "px"; } }; }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the core code. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function () { "use strict"; var root = this; var _ju = root.jsPlumbUtil, /** * creates a timestamp, using milliseconds since 1970, but as a string. */ _timestamp = function () { return "" + (new Date()).getTime(); }, // helper method to update the hover style whenever it, or paintStyle, changes. // we use paintStyle as the foundation and merge hoverPaintStyle over the // top. _updateHoverStyle = function (component) { if (component._jsPlumb.paintStyle && component._jsPlumb.hoverPaintStyle) { var mergedHoverStyle = {}; jsPlumb.extend(mergedHoverStyle, component._jsPlumb.paintStyle); jsPlumb.extend(mergedHoverStyle, component._jsPlumb.hoverPaintStyle); delete component._jsPlumb.hoverPaintStyle; // we want the fill of paintStyle to override a gradient, if possible. if (mergedHoverStyle.gradient && component._jsPlumb.paintStyle.fill) { delete mergedHoverStyle.gradient; } component._jsPlumb.hoverPaintStyle = mergedHoverStyle; } }, events = ["tap", "dbltap", "click", "dblclick", "mouseover", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ], eventFilters = { "mouseout": "mouseleave", "mouseexit": "mouseleave" }, _updateAttachedElements = function (component, state, timestamp, sourceElement) { var affectedElements = component.getAttachedElements(); if (affectedElements) { for (var i = 0, j = affectedElements.length; i < j; i++) { if (!sourceElement || sourceElement !== affectedElements[i]) { affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements. } } } }, _splitType = function (t) { return t == null ? null : t.split(" "); }, _mapType = function(map, obj, typeId) { for (var i in obj) { map[i] = typeId; } }, _each = function(fn, obj) { obj = _ju.isArray(obj) || (obj.length != null && !_ju.isString(obj)) ? obj : [ obj ]; for (var i = 0; i < obj.length; i++) { try { fn.apply(obj[i], [ obj[i] ]); } catch (e) { _ju.log(".each iteration failed : " + e); } } }, _applyTypes = function (component, params, doNotRepaint) { if (component.getDefaultType) { var td = component.getTypeDescriptor(), map = {}; var defType = component.getDefaultType(); var o = _ju.merge({}, defType); _mapType(map, defType, "__default"); for (var i = 0, j = component._jsPlumb.types.length; i < j; i++) { var tid = component._jsPlumb.types[i]; if (tid !== "__default") { var _t = component._jsPlumb.instance.getType(tid, td); if (_t != null) { o = _ju.merge(o, _t, [ "cssClass" ], [ "connector" ]); _mapType(map, _t, tid); } } } if (params) { o = _ju.populate(o, params, "_"); } component.applyType(o, doNotRepaint, map); if (!doNotRepaint) { component.repaint(); } } }, // ------------------------------ BEGIN jsPlumbUIComponent -------------------------------------------- jsPlumbUIComponent = root.jsPlumbUIComponent = function (params) { _ju.EventGenerator.apply(this, arguments); var self = this, a = arguments, idPrefix = self.idPrefix, id = idPrefix + (new Date()).getTime(); this._jsPlumb = { instance: params._jsPlumb, parameters: params.parameters || {}, paintStyle: null, hoverPaintStyle: null, paintStyleInUse: null, hover: false, beforeDetach: params.beforeDetach, beforeDrop: params.beforeDrop, overlayPlacements: [], hoverClass: params.hoverClass || params._jsPlumb.Defaults.HoverClass, types: [], typeCache:{} }; this.cacheTypeItem = function(key, item, typeId) { this._jsPlumb.typeCache[typeId] = this._jsPlumb.typeCache[typeId] || {}; this._jsPlumb.typeCache[typeId][key] = item; }; this.getCachedTypeItem = function(key, typeId) { return this._jsPlumb.typeCache[typeId] ? this._jsPlumb.typeCache[typeId][key] : null; }; this.getId = function () { return id; }; // ----------------------------- default type -------------------------------------------- var o = params.overlays || [], oo = {}; if (this.defaultOverlayKeys) { for (var i = 0; i < this.defaultOverlayKeys.length; i++) { Array.prototype.push.apply(o, this._jsPlumb.instance.Defaults[this.defaultOverlayKeys[i]] || []); } for (i = 0; i < o.length; i++) { // if a string, convert to object representation so that we can store the typeid on it. // also assign an id. var fo = jsPlumb.convertToFullOverlaySpec(o[i]); oo[fo[1].id] = fo; } } var _defaultType = { overlays:oo, parameters: params.parameters || {}, scope: params.scope || this._jsPlumb.instance.getDefaultScope() }; this.getDefaultType = function() { return _defaultType; }; this.appendToDefaultType = function(obj) { for (var i in obj) { _defaultType[i] = obj[i]; } }; // ----------------------------- end default type -------------------------------------------- // all components can generate events if (params.events) { for (var evtName in params.events) { self.bind(evtName, params.events[evtName]); } } // all components get this clone function. // TODO issue 116 showed a problem with this - it seems 'a' that is in // the clone function's scope is shared by all invocations of it, the classic // JS closure problem. for now, jsPlumb does a version of this inline where // it used to call clone. but it would be nice to find some time to look // further at this. this.clone = function () { var o = Object.create(this.constructor.prototype); this.constructor.apply(o, a); return o; }.bind(this); // user can supply a beforeDetach callback, which will be executed before a detach // is performed; returning false prevents the detach. this.isDetachAllowed = function (connection) { var r = true; if (this._jsPlumb.beforeDetach) { try { r = this._jsPlumb.beforeDetach(connection); } catch (e) { _ju.log("jsPlumb: beforeDetach callback failed", e); } } return r; }; // user can supply a beforeDrop callback, which will be executed before a dropped // connection is confirmed. user can return false to reject connection. this.isDropAllowed = function (sourceId, targetId, scope, connection, dropEndpoint, source, target) { var r = this._jsPlumb.instance.checkCondition("beforeDrop", { sourceId: sourceId, targetId: targetId, scope: scope, connection: connection, dropEndpoint: dropEndpoint, source: source, target: target }); if (this._jsPlumb.beforeDrop) { try { r = this._jsPlumb.beforeDrop({ sourceId: sourceId, targetId: targetId, scope: scope, connection: connection, dropEndpoint: dropEndpoint, source: source, target: target }); } catch (e) { _ju.log("jsPlumb: beforeDrop callback failed", e); } } return r; }; var domListeners = []; // sets the component associated with listener events. for instance, an overlay delegates // its events back to a connector. but if the connector is swapped on the underlying connection, // then this component must be changed. This is called by setConnector in the Connection class. this.setListenerComponent = function (c) { for (var i = 0; i < domListeners.length; i++) { domListeners[i][3] = c; } }; }; var _removeTypeCssHelper = function (component, typeIndex) { var typeId = component._jsPlumb.types[typeIndex], type = component._jsPlumb.instance.getType(typeId, component.getTypeDescriptor()); if (type != null && type.cssClass && component.canvas) { component._jsPlumb.instance.removeClass(component.canvas, type.cssClass); } }; _ju.extend(root.jsPlumbUIComponent, _ju.EventGenerator, { getParameter: function (name) { return this._jsPlumb.parameters[name]; }, setParameter: function (name, value) { this._jsPlumb.parameters[name] = value; }, getParameters: function () { return this._jsPlumb.parameters; }, setParameters: function (p) { this._jsPlumb.parameters = p; }, getClass:function() { return jsPlumb.getClass(this.canvas); }, hasClass:function(clazz) { return jsPlumb.hasClass(this.canvas, clazz); }, addClass: function (clazz) { jsPlumb.addClass(this.canvas, clazz); }, removeClass: function (clazz) { jsPlumb.removeClass(this.canvas, clazz); }, updateClasses: function (classesToAdd, classesToRemove) { jsPlumb.updateClasses(this.canvas, classesToAdd, classesToRemove); }, setType: function (typeId, params, doNotRepaint) { this.clearTypes(); this._jsPlumb.types = _splitType(typeId) || []; _applyTypes(this, params, doNotRepaint); }, getType: function () { return this._jsPlumb.types; }, reapplyTypes: function (params, doNotRepaint) { _applyTypes(this, params, doNotRepaint); }, hasType: function (typeId) { return this._jsPlumb.types.indexOf(typeId) !== -1; }, addType: function (typeId, params, doNotRepaint) { var t = _splitType(typeId), _cont = false; if (t != null) { for (var i = 0, j = t.length; i < j; i++) { if (!this.hasType(t[i])) { this._jsPlumb.types.push(t[i]); _cont = true; } } if (_cont) { _applyTypes(this, params, doNotRepaint); } } }, removeType: function (typeId, params, doNotRepaint) { var t = _splitType(typeId), _cont = false, _one = function (tt) { var idx = this._jsPlumb.types.indexOf(tt); if (idx !== -1) { // remove css class if necessary _removeTypeCssHelper(this, idx); this._jsPlumb.types.splice(idx, 1); return true; } return false; }.bind(this); if (t != null) { for (var i = 0, j = t.length; i < j; i++) { _cont = _one(t[i]) || _cont; } if (_cont) { _applyTypes(this, params, doNotRepaint); } } }, clearTypes: function (params, doNotRepaint) { var i = this._jsPlumb.types.length; for (var j = 0; j < i; j++) { _removeTypeCssHelper(this, 0); this._jsPlumb.types.splice(0, 1); } _applyTypes(this, params, doNotRepaint); }, toggleType: function (typeId, params, doNotRepaint) { var t = _splitType(typeId); if (t != null) { for (var i = 0, j = t.length; i < j; i++) { var idx = this._jsPlumb.types.indexOf(t[i]); if (idx !== -1) { _removeTypeCssHelper(this, idx); this._jsPlumb.types.splice(idx, 1); } else { this._jsPlumb.types.push(t[i]); } } _applyTypes(this, params, doNotRepaint); } }, applyType: function (t, doNotRepaint) { this.setPaintStyle(t.paintStyle, doNotRepaint); this.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint); if (t.parameters) { for (var i in t.parameters) { this.setParameter(i, t.parameters[i]); } } this._jsPlumb.paintStyleInUse = this.getPaintStyle(); }, setPaintStyle: function (style, doNotRepaint) { // this._jsPlumb.paintStyle = jsPlumb.extend({}, style); // TODO figure out if we want components to clone paintStyle so as not to share it. this._jsPlumb.paintStyle = style; this._jsPlumb.paintStyleInUse = this._jsPlumb.paintStyle; _updateHoverStyle(this); if (!doNotRepaint) { this.repaint(); } }, getPaintStyle: function () { return this._jsPlumb.paintStyle; }, setHoverPaintStyle: function (style, doNotRepaint) { //this._jsPlumb.hoverPaintStyle = jsPlumb.extend({}, style); // TODO figure out if we want components to clone paintStyle so as not to share it. this._jsPlumb.hoverPaintStyle = style; _updateHoverStyle(this); if (!doNotRepaint) { this.repaint(); } }, getHoverPaintStyle: function () { return this._jsPlumb.hoverPaintStyle; }, destroy: function (force) { if (force || this.typeId == null) { this.cleanupListeners(); // this is on EventGenerator this.clone = null; this._jsPlumb = null; } }, isHover: function () { return this._jsPlumb.hover; }, setHover: function (hover, ignoreAttachedElements, timestamp) { // while dragging, we ignore these events. this keeps the UI from flashing and // swishing and whatevering. if (this._jsPlumb && !this._jsPlumb.instance.currentlyDragging && !this._jsPlumb.instance.isHoverSuspended()) { this._jsPlumb.hover = hover; var method = hover ? "addClass" : "removeClass"; if (this.canvas != null) { if (this._jsPlumb.instance.hoverClass != null) { this._jsPlumb.instance[method](this.canvas, this._jsPlumb.instance.hoverClass); } if (this._jsPlumb.hoverClass != null) { this._jsPlumb.instance[method](this.canvas, this._jsPlumb.hoverClass); } } if (this._jsPlumb.hoverPaintStyle != null) { this._jsPlumb.paintStyleInUse = hover ? this._jsPlumb.hoverPaintStyle : this._jsPlumb.paintStyle; if (!this._jsPlumb.instance.isSuspendDrawing()) { timestamp = timestamp || _timestamp(); this.repaint({timestamp: timestamp, recalc: false}); } } // get the list of other affected elements, if supported by this component. // for a connection, its the endpoints. for an endpoint, its the connections! surprise. if (this.getAttachedElements && !ignoreAttachedElements) { _updateAttachedElements(this, hover, _timestamp(), this); } } } }); // ------------------------------ END jsPlumbUIComponent -------------------------------------------- var _jsPlumbInstanceIndex = 0, getInstanceIndex = function () { var i = _jsPlumbInstanceIndex + 1; _jsPlumbInstanceIndex++; return i; }; var jsPlumbInstance = root.jsPlumbInstance = function (_defaults) { this.version = "2.8.6"; this.Defaults = { Anchor: "Bottom", Anchors: [ null, null ], ConnectionsDetachable: true, ConnectionOverlays: [ ], Connector: "Bezier", Container: null, DoNotThrowErrors: false, DragOptions: { }, DropOptions: { }, Endpoint: "Dot", EndpointOverlays: [ ], Endpoints: [ null, null ], EndpointStyle: { fill: "#456" }, EndpointStyles: [ null, null ], EndpointHoverStyle: null, EndpointHoverStyles: [ null, null ], HoverPaintStyle: null, LabelStyle: { color: "black" }, LogEnabled: false, Overlays: [ ], MaxConnections: 1, PaintStyle: { "stroke-width": 4, stroke: "#456" }, ReattachConnections: false, RenderMode: "svg", Scope: "jsPlumb_DefaultScope" }; if (_defaults) { jsPlumb.extend(this.Defaults, _defaults); } this.logEnabled = this.Defaults.LogEnabled; this._connectionTypes = {}; this._endpointTypes = {}; _ju.EventGenerator.apply(this); var _currentInstance = this, _instanceIndex = getInstanceIndex(), _bb = _currentInstance.bind, _initialDefaults = {}, _zoom = 1, _info = function (el) { if (el == null) { return null; } else if (el.nodeType === 3 || el.nodeType === 8) { return { el:el, text:true }; } else { var _el = _currentInstance.getElement(el); return { el: _el, id: (_ju.isString(el) && _el == null) ? el : _getId(_el) }; } }; this.getInstanceIndex = function () { return _instanceIndex; }; // CONVERTED this.setZoom = function (z, repaintEverything) { _zoom = z; _currentInstance.fire("zoom", _zoom); if (repaintEverything) { _currentInstance.repaintEverything(); } return true; }; // CONVERTED this.getZoom = function () { return _zoom; }; for (var i in this.Defaults) { _initialDefaults[i] = this.Defaults[i]; } var _container, _containerDelegations = []; this.unbindContainer = function() { if (_container != null && _containerDelegations.length > 0) { for (var i = 0; i < _containerDelegations.length; i++) { _currentInstance.off(_container, _containerDelegations[i][0], _containerDelegations[i][1]); } } }; this.setContainer = function (c) { this.unbindContainer(); // get container as dom element. c = this.getElement(c); // move existing connections and endpoints, if any. this.select().each(function (conn) { conn.moveParent(c); }); this.selectEndpoints().each(function (ep) { ep.moveParent(c); }); // set container. var previousContainer = _container; _container = c; _containerDelegations.length = 0; var eventAliases = { "endpointclick":"endpointClick", "endpointdblclick":"endpointDblClick" }; var _oneDelegateHandler = function (id, e, componentType) { var t = e.srcElement || e.target, jp = (t && t.parentNode ? t.parentNode._jsPlumb : null) || (t ? t._jsPlumb : null) || (t && t.parentNode && t.parentNode.parentNode ? t.parentNode.parentNode._jsPlumb : null); if (jp) { jp.fire(id, jp, e); var alias = componentType ? eventAliases[componentType + id] || id : id; // jsplumb also fires every event coming from components/overlays. That's what the test for `jp.component` is for. _currentInstance.fire(alias, jp.component || jp, e); } }; var _addOneDelegate = function(eventId, selector, fn) { _containerDelegations.push([eventId, fn]); _currentInstance.on(_container, eventId, selector, fn); }; // delegate one event on the container to jsplumb elements. it might be possible to // abstract this out: each of endpoint, connection and overlay could register themselves with // jsplumb as "component types" or whatever, and provide a suitable selector. this would be // done by the renderer (although admittedly from 2.0 onwards we're not supporting vml anymore) var _oneDelegate = function (id) { // connections. _addOneDelegate(id, ".jtk-connector", function (e) { _oneDelegateHandler(id, e); }); // endpoints. note they can have an enclosing div, or not. _addOneDelegate(id, ".jtk-endpoint", function (e) { _oneDelegateHandler(id, e, "endpoint"); }); // overlays _addOneDelegate(id, ".jtk-overlay", function (e) { _oneDelegateHandler(id, e); }); }; for (var i = 0; i < events.length; i++) { _oneDelegate(events[i]); } // managed elements for (var elId in managedElements) { var el = managedElements[elId].el; if (el.parentNode === previousContainer) { previousContainer.removeChild(el); _container.appendChild(el); } } }; this.getContainer = function () { return _container; }; this.bind = function (event, fn) { if ("ready" === event && initialized) { fn(); } else { _bb.apply(_currentInstance, [event, fn]); } }; _currentInstance.importDefaults = function (d) { for (var i in d) { _currentInstance.Defaults[i] = d[i]; } if (d.Container) { _currentInstance.setContainer(d.Container); } return _currentInstance; }; _currentInstance.restoreDefaults = function () { _currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults); return _currentInstance; }; var log = null, initialized = false, // TODO remove from window scope connections = [], // map of element id -> endpoint lists. an element can have an arbitrary // number of endpoints on it, and not all of them have to be connected // to anything. endpointsByElement = {}, endpointsByUUID = {}, managedElements = {}, offsets = {}, offsetTimestamps = {}, draggableStates = {}, connectionBeingDragged = false, sizes = [], _suspendDrawing = false, _suspendedAt = null, DEFAULT_SCOPE = this.Defaults.Scope, _curIdStamp = 1, _idstamp = function () { return "" + _curIdStamp++; }, // // appends an element to some other element, which is calculated as follows: // // 1. if Container exists, use that element. // 2. if the 'parent' parameter exists, use that. // 3. otherwise just use the root element. // // _appendElement = function (el, parent) { if (_container) { _container.appendChild(el); } else if (!parent) { this.appendToRoot(el); } else { this.getElement(parent).appendChild(el); } }.bind(this), // // Draws an endpoint and its connections. this is the main entry point into drawing connections as well // as endpoints, since jsPlumb is endpoint-centric under the hood. // // @param element element to draw (of type library specific element object) // @param ui UI object from current library's event system. optional. // @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do. // @param clearEdits defaults to false; indicates that mouse edits for connectors should be cleared /// _draw = function (element, ui, timestamp, clearEdits) { if (!_suspendDrawing) { var id = _getId(element), repaintEls, dm = _currentInstance.getDragManager(); if (dm) { repaintEls = dm.getElementsForDraggable(id); } if (timestamp == null) { timestamp = _timestamp(); } // update the offset of everything _before_ we try to draw anything. var o = _updateOffset({ elId: id, offset: ui, recalc: false, timestamp: timestamp }); if (repaintEls && o && o.o) { for (var i in repaintEls) { _updateOffset({ elId: repaintEls[i].id, offset: { left: o.o.left + repaintEls[i].offset.left, top: o.o.top + repaintEls[i].offset.top }, recalc: false, timestamp: timestamp }); } } _currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits); if (repaintEls) { for (var j in repaintEls) { _currentInstance.anchorManager.redraw(repaintEls[j].id, ui, timestamp, repaintEls[j].offset, clearEdits, true); } } } }, // // gets an Endpoint by uuid. // _getEndpoint = function (uuid) { return endpointsByUUID[uuid]; }, /** * inits a draggable if it's not already initialised. * TODO: somehow abstract this to the adapter, because the concept of "draggable" has no * place on the server. */ _initDraggableIfNecessary = function (element, isDraggable, dragOptions, id, fireEvent) { // move to DragManager? if (!jsPlumb.headless) { var _draggable = isDraggable == null ? false : isDraggable; if (_draggable) { if (jsPlumb.isDragSupported(element, _currentInstance)) { var options = dragOptions || _currentInstance.Defaults.DragOptions; options = jsPlumb.extend({}, options); // make a copy. if (!jsPlumb.isAlreadyDraggable(element, _currentInstance)) { var dragEvent = jsPlumb.dragEvents.drag, stopEvent = jsPlumb.dragEvents.stop, startEvent = jsPlumb.dragEvents.start, _started = false; _manage(id, element); options[startEvent] = _ju.wrap(options[startEvent], function () { _currentInstance.setHoverSuspended(true); _currentInstance.select({source: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); _currentInstance.select({target: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); _currentInstance.setConnectionBeingDragged(true); if (options.canDrag) { return dragOptions.canDrag(); } }, false); options[dragEvent] = _ju.wrap(options[dragEvent], function () { var ui = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()); if (ui != null) { _draw(element, ui, null, true); if (_started) { _currentInstance.addClass(element, "jtk-dragged"); } _started = true; } }); options[stopEvent] = _ju.wrap(options[stopEvent], function () { var elements = arguments[0].selection, uip; var _one = function (_e) { if (_e[1] != null) { // run the reported offset through the code that takes parent containers // into account, to adjust if necessary (issue 554) uip = _currentInstance.getUIPosition([{ el:_e[2].el, pos:[_e[1].left, _e[1].top] }]); _draw(_e[2].el, uip); } _currentInstance.removeClass(_e[0], "jtk-dragged"); _currentInstance.select({source: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); _currentInstance.select({target: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); _currentInstance.getDragManager().dragEnded(_e[2].el); }; for (var i = 0; i < elements.length; i++) { _one(elements[i]); } _started = false; _currentInstance.setHoverSuspended(false); _currentInstance.setConnectionBeingDragged(false); }); var elId = _getId(element); // need ID draggableStates[elId] = true; var draggable = draggableStates[elId]; options.disabled = draggable == null ? false : !draggable; _currentInstance.initDraggable(element, options); _currentInstance.getDragManager().register(element); if (fireEvent) { _currentInstance.fire("elementDraggable", {el:element, options:options}); } } else { // already draggable. attach any start, drag or stop listeners to the current Drag. if (dragOptions.force) { _currentInstance.initDraggable(element, options); } } } } } }, _scopeMatch = function (e1, e2) { var s1 = e1.scope.split(/\s/), s2 = e2.scope.split(/\s/); for (var i = 0; i < s1.length; i++) { for (var j = 0; j < s2.length; j++) { if (s2[j] === s1[i]) { return true; } } } return false; }, _mergeOverrides = function (def, values) { var m = jsPlumb.extend({}, def); for (var i in values) { if (values[i]) { m[i] = values[i]; } } return m; }, /* * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc. */ _prepareConnectionParams = function (params, referenceParams) { var _p = jsPlumb.extend({ }, params); if (referenceParams) { jsPlumb.extend(_p, referenceParams); } // hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively. if (_p.source) { if (_p.source.endpoint) { _p.sourceEndpoint = _p.source; } else { _p.source = _currentInstance.getElement(_p.source); } } if (_p.target) { if (_p.target.endpoint) { _p.targetEndpoint = _p.target; } else { _p.target = _currentInstance.getElement(_p.target); } } // test for endpoint uuids to connect if (params.uuids) { _p.sourceEndpoint = _getEndpoint(params.uuids[0]); _p.targetEndpoint = _getEndpoint(params.uuids[1]); } // now ensure that if we do have Endpoints already, they're not full. // source: if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) { _ju.log(_currentInstance, "could not add connection; source endpoint is full"); return; } // target: if (_p.targetEndpoint && _p.targetEndpoint.isFull()) { _ju.log(_currentInstance, "could not add connection; target endpoint is full"); return; } // if source endpoint mandates connection type and nothing specified in our params, use it. if (!_p.type && _p.sourceEndpoint) { _p.type = _p.sourceEndpoint.connectionType; } // copy in any connectorOverlays that were specified on the source endpoint. // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not. if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) { _p.overlays = _p.overlays || []; for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) { _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]); } } // scope if (_p.sourceEndpoint && _p.sourceEndpoint.scope) { _p.scope = _p.sourceEndpoint.scope; } // pointer events if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents) { _p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents; } var _addEndpoint = function (el, def, idx) { return _currentInstance.addEndpoint(el, _mergeOverrides(def, { anchor: _p.anchors ? _p.anchors[idx] : _p.anchor, endpoint: _p.endpoints ? _p.endpoints[idx] : _p.endpoint, paintStyle: _p.endpointStyles ? _p.endpointStyles[idx] : _p.endpointStyle, hoverPaintStyle: _p.endpointHoverStyles ? _p.endpointHoverStyles[idx] : _p.endpointHoverStyle })); }; // check for makeSource/makeTarget specs. var _oneElementDef = function (type, idx, defs, matchType) { if (_p[type] && !_p[type].endpoint && !_p[type + "Endpoint"] && !_p.newConnection) { var tid = _getId(_p[type]), tep = defs[tid]; tep = tep ? tep[matchType] : null; if (tep) { // if not enabled, return. if (!tep.enabled) { return false; } var newEndpoint = tep.endpoint != null && tep.endpoint._jsPlumb ? tep.endpoint : _addEndpoint(_p[type], tep.def, idx); if (newEndpoint.isFull()) { return false; } _p[type + "Endpoint"] = newEndpoint; if (!_p.scope && tep.def.scope) { _p.scope = tep.def.scope; } // provide scope if not already provided and endpoint def has one. if (tep.uniqueEndpoint) { if (!tep.endpoint) { tep.endpoint = newEndpoint; newEndpoint.setDeleteOnEmpty(false); } else { newEndpoint.finalEndpoint = tep.endpoint; } } else { newEndpoint.setDeleteOnEmpty(true); } // // copy in connector overlays if present on the source definition. // if (idx === 0 && tep.def.connectorOverlays) { _p.overlays = _p.overlays || []; Array.prototype.push.apply(_p.overlays, tep.def.connectorOverlays); } } } }; if (_oneElementDef("source", 0, this.sourceEndpointDefinitions, _p.type || "default") === false) { return; } if (_oneElementDef("target", 1, this.targetEndpointDefinitions, _p.type || "default") === false) { return; } // last, ensure scopes match if (_p.sourceEndpoint && _p.targetEndpoint) { if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) { _p = null; } } return _p; }.bind(_currentInstance), _newConnection = function (params) { var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(); params._jsPlumb = _currentInstance; params.newConnection = _newConnection; params.newEndpoint = _newEndpoint; params.endpointsByUUID = endpointsByUUID; params.endpointsByElement = endpointsByElement; params.finaliseConnection = _finaliseConnection; params.id = "con_" + _idstamp(); var con = new connectionFunc(params); // if the connection is draggable, then maybe we need to tell the target endpoint to init the // dragging code. it won't run again if it already configured to be draggable. if (con.isDetachable()) { con.endpoints[0].initDraggable("_jsPlumbSource"); con.endpoints[1].initDraggable("_jsPlumbTarget"); } return con; }, // // adds the connection to the backing model, fires an event if necessary and then redraws // _finaliseConnection = _currentInstance.finaliseConnection = function (jpc, params, originalEvent, doInformAnchorManager) { params = params || {}; // add to list of connections (by scope). if (!jpc.suspendedEndpoint) { connections.push(jpc); } jpc.pending = null; // turn off isTemporarySource on the source endpoint (only viable on first draw) jpc.endpoints[0].isTemporarySource = false; // always inform the anchor manager // except that if jpc has a suspended endpoint it's not true to say the // connection is new; it has just (possibly) moved. the question is whether // to make that call here or in the anchor manager. i think perhaps here. if (doInformAnchorManager !== false) { _currentInstance.anchorManager.newConnection(jpc); } // force a paint _draw(jpc.source); // fire an event if (!params.doNotFireConnectionEvent && params.fireEvent !== false) { var eventArgs = { connection: jpc, source: jpc.source, target: jpc.target, sourceId: jpc.sourceId, targetId: jpc.targetId, sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1] }; _currentInstance.fire("connection", eventArgs, originalEvent); } }, /* factory method to prepare a new endpoint. this should always be used instead of creating Endpoints manually, since this method attaches event listeners and an id. */ _newEndpoint = function (params, id) { var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint; var _p = jsPlumb.extend({}, params); _p._jsPlumb = _currentInstance; _p.newConnection = _newConnection; _p.newEndpoint = _newEndpoint; _p.endpointsByUUID = endpointsByUUID; _p.endpointsByElement = endpointsByElement; _p.fireDetachEvent = fireDetachEvent; _p.elementId = id || _getId(_p.source); var ep = new endpointFunc(_p); ep.id = "ep_" + _idstamp(); _manage(_p.elementId, _p.source); if (!jsPlumb.headless) { _currentInstance.getDragManager().endpointAdded(_p.source, id); } return ep; }, /* * performs the given function operation on all the connections found * for the given element id; this means we find all the endpoints for * the given element, and then for each endpoint find the connectors * connected to it. then we pass each connection in to the given * function. */ _operation = function (elId, func, endpointFunc) { var endpoints = endpointsByElement[elId]; if (endpoints && endpoints.length) { for (var i = 0, ii = endpoints.length; i < ii; i++) { for (var j = 0, jj = endpoints[i].connections.length; j < jj; j++) { var retVal = func(endpoints[i].connections[j]); // if the function passed in returns true, we exit. // most functions return false. if (retVal) { return; } } if (endpointFunc) { endpointFunc(endpoints[i]); } } } }, _setDraggable = function (element, draggable) { return jsPlumb.each(element, function (el) { if (_currentInstance.isDragSupported(el)) { draggableStates[_currentInstance.getAttribute(el, "id")] = draggable; _currentInstance.setElementDraggable(el, draggable); } }); }, /* * private method to do the business of hiding/showing. * * @param el * either Id of the element in question or a library specific * object for the element. * @param state * String specifying a value for the css 'display' property * ('block' or 'none'). */ _setVisible = function (el, state, alsoChangeEndpoints) { state = state === "block"; var endpointFunc = null; if (alsoChangeEndpoints) { endpointFunc = function (ep) { ep.setVisible(state, true, true); }; } var info = _info(el); _operation(info.id, function (jpc) { if (state && alsoChangeEndpoints) { // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility. // this block will only set a connection to be visible if the other endpoint in the connection is also visible. var oidx = jpc.sourceId === info.id ? 1 : 0; if (jpc.endpoints[oidx].isVisible()) { jpc.setVisible(true); } } else { // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever. jpc.setVisible(state); } }, endpointFunc); }, /* * toggles the draggable state of the given element(s). * el is either an id, or an element object, or a list of ids/element objects. */ _toggleDraggable = function (el) { var state; jsPlumb.each(el, function (el) { var elId = _currentInstance.getAttribute(el, "id"); state = draggableStates[elId] == null ? false : draggableStates[elId]; state = !state; draggableStates[elId] = state; _currentInstance.setDraggable(el, state); return state; }.bind(this)); return state; }, /** * private method to do the business of toggling hiding/showing. */ _toggleVisible = function (elId, changeEndpoints) { var endpointFunc = null; if (changeEndpoints) { endpointFunc = function (ep) { var state = ep.isVisible(); ep.setVisible(!state); }; } _operation(elId, function (jpc) { var state = jpc.isVisible(); jpc.setVisible(!state); }, endpointFunc); }, // TODO comparison performance _getCachedData = function (elId) { var o = offsets[elId]; if (!o) { return _updateOffset({elId: elId}); } else { return {o: o, s: sizes[elId]}; } }, /** * gets an id for the given element, creating and setting one if * necessary. the id is of the form * * jsPlumb_<instance index>_<index in instance> * * where "index in instance" is a monotonically increasing integer that starts at 0, * for each instance. this method is used not only to assign ids to elements that do not * have them but also to connections and endpoints. */ _getId = function (element, uuid, doNotCreateIfNotFound) { if (_ju.isString(element)) { return element; } if (element == null) { return null; } var id = _currentInstance.getAttribute(element, "id"); if (!id || id === "undefined") { // check if fixed uuid parameter is given if (arguments.length === 2 && arguments[1] !== undefined) { id = uuid; } else if (arguments.length === 1 || (arguments.length === 3 && !arguments[2])) { id = "jsPlumb_" + _instanceIndex + "_" + _idstamp(); } if (!doNotCreateIfNotFound) { _currentInstance.setAttribute(element, "id", id); } } return id; }; this.setConnectionBeingDragged = function (v) { connectionBeingDragged = v; }; this.isConnectionBeingDragged = function () { return connectionBeingDragged; }; /** * Returns a map of all the elements this jsPlumbInstance is currently managing. * @returns {Object} Map of [id-> {el, endpoint[], connection, position}] information. */ this.getManagedElements = function() { return managedElements; }; this.connectorClass = "jtk-connector"; this.connectorOutlineClass = "jtk-connector-outline"; this.connectedClass = "jtk-connected"; this.hoverClass = "jtk-hover"; this.endpointClass = "jtk-endpoint"; this.endpointConnectedClass = "jtk-endpoint-connected"; this.endpointFullClass = "jtk-endpoint-full"; this.endpointDropAllowedClass = "jtk-endpoint-drop-allowed"; this.endpointDropForbiddenClass = "jtk-endpoint-drop-forbidden"; this.overlayClass = "jtk-overlay"; this.draggingClass = "jtk-dragging";// CONVERTED this.elementDraggingClass = "jtk-element-dragging";// CONVERTED this.sourceElementDraggingClass = "jtk-source-element-dragging"; // CONVERTED this.targetElementDraggingClass = "jtk-target-element-dragging";// CONVERTED this.endpointAnchorClassPrefix = "jtk-endpoint-anchor"; this.hoverSourceClass = "jtk-source-hover"; this.hoverTargetClass = "jtk-target-hover"; this.dragSelectClass = "jtk-drag-select"; this.Anchors = {}; this.Connectors = { "svg": {} }; this.Endpoints = { "svg": {} }; this.Overlays = { "svg": {} } ; this.ConnectorRenderers = {}; this.SVG = "svg"; // --------------------------- jsPlumbInstance public API --------------------------------------------------------- this.addEndpoint = function (el, params, referenceParams) { referenceParams = referenceParams || {}; var p = jsPlumb.extend({}, referenceParams); jsPlumb.extend(p, params); p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint; p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle; var results = [], inputs = (_ju.isArray(el) || (el.length != null && !_ju.isString(el))) ? el : [ el ]; for (var i = 0, j = inputs.length; i < j; i++) { p.source = _currentInstance.getElement(inputs[i]); _ensureContainer(p.source); var id = _getId(p.source), e = _newEndpoint(p, id); // ensure element is managed. var myOffset = _manage(id, p.source).info.o; _ju.addToList(endpointsByElement, id, e); if (!_suspendDrawing) { e.paint({ anchorLoc: e.anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: sizes[id], element: e, timestamp: _suspendedAt }), timestamp: _suspendedAt }); } results.push(e); } return results.length === 1 ? results[0] : results; }; this.addEndpoints = function (el, endpoints, referenceParams) { var results = []; for (var i = 0, j = endpoints.length; i < j; i++) { var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams); if (_ju.isArray(e)) { Array.prototype.push.apply(results, e); } else { results.push(e); } } return results; }; this.animate = function (el, properties, options) { if (!this.animationSupported) { return false; } options = options || {}; var del = _currentInstance.getElement(el), id = _getId(del), stepFunction = jsPlumb.animEvents.step, completeFunction = jsPlumb.animEvents.complete; options[stepFunction] = _ju.wrap(options[stepFunction], function () { _currentInstance.revalidate(id); }); // onComplete repaints, just to make sure everything looks good at the end of the animation. options[completeFunction] = _ju.wrap(options[completeFunction], function () { _currentInstance.revalidate(id); }); _currentInstance.doAnimate(del, properties, options); }; /** * checks for a listener for the given condition, executing it if found, passing in the given value. * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition" * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these * condition events anyway. */ this.checkCondition = function (conditionName, args) { var l = _currentInstance.getListener(conditionName), r = true; if (l && l.length > 0) { var values = Array.prototype.slice.call(arguments, 1); try { for (var i = 0, j = l.length; i < j; i++) { r = r && l[i].apply(l[i], values); } } catch (e) { _ju.log(_currentInstance, "cannot check condition [" + conditionName + "]" + e); } } return r; }; this.connect = function (params, referenceParams) { // prepare a final set of parameters to create connection with var _p = _prepareConnectionParams(params, referenceParams), jpc; // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams // will return null (and log something) if either endpoint was full. what would be nicer is to // create a dedicated 'error' object. if (_p) { if (_p.source == null && _p.sourceEndpoint == null) { _ju.log("Cannot establish connection - source does not exist"); return; } if (_p.target == null && _p.targetEndpoint == null) { _ju.log("Cannot establish connection - target does not exist"); return; } _ensureContainer(_p.source); // create the connection. it is not yet registered jpc = _newConnection(_p); // now add it the model, fire an event, and redraw _finaliseConnection(jpc, _p); } return jpc; }; var stTypes = [ { el: "source", elId: "sourceId", epDefs: "sourceEndpointDefinitions" }, { el: "target", elId: "targetId", epDefs: "targetEndpointDefinitions" } ]; var _set = function (c, el, idx, doNotRepaint) { var ep, _st = stTypes[idx], cId = c[_st.elId], cEl = c[_st.el], sid, sep, oldEndpoint = c.endpoints[idx]; var evtParams = { index: idx, originalSourceId: idx === 0 ? cId : c.sourceId, newSourceId: c.sourceId, originalTargetId: idx === 1 ? cId : c.targetId, newTargetId: c.targetId, connection: c }; if (el.constructor === jsPlumb.Endpoint) { ep = el; ep.addConnection(c); el = ep.element; } else { sid = _getId(el); sep = this[_st.epDefs][sid]; if (sid === c[_st.elId]) { ep = null; // dont change source/target if the element is already the one given. } else if (sep) { for (var t in sep) { if (!sep[t].enabled) { return; } ep = sep[t].endpoint != null && sep[t].endpoint._jsPlumb ? sep[t].endpoint : this.addEndpoint(el, sep[t].def); if (sep[t].uniqueEndpoint) { sep[t].endpoint = ep; } ep.addConnection(c); } } else { ep = c.makeEndpoint(idx === 0, el, sid); } } if (ep != null) { oldEndpoint.detachFromConnection(c); c.endpoints[idx] = ep; c[_st.el] = ep.element; c[_st.elId] = ep.elementId; evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId; fireMoveEvent(evtParams); if (!doNotRepaint) { c.repaint(); } } evtParams.element = el; return evtParams; }.bind(this); this.setSource = function (connection, el, doNotRepaint) { var p = _set(connection, el, 0, doNotRepaint); this.anchorManager.sourceChanged(p.originalSourceId, p.newSourceId, connection, p.el); }; this.setTarget = function (connection, el, doNotRepaint) { var p = _set(connection, el, 1, doNotRepaint); this.anchorManager.updateOtherEndpoint(p.originalSourceId, p.originalTargetId, p.newTargetId, connection); }; this.deleteEndpoint = function (object, dontUpdateHover, deleteAttachedObjects) { var endpoint = (typeof object === "string") ? endpointsByUUID[object] : object; if (endpoint) { _currentInstance.deleteObject({ endpoint: endpoint, dontUpdateHover: dontUpdateHover, deleteAttachedObjects:deleteAttachedObjects }); } return _currentInstance; }; this.deleteEveryEndpoint = function () { var _is = _currentInstance.setSuspendDrawing(true); for (var id in endpointsByElement) { var endpoints = endpointsByElement[id]; if (endpoints && endpoints.length) { for (var i = 0, j = endpoints.length; i < j; i++) { _currentInstance.deleteEndpoint(endpoints[i], true); } } } endpointsByElement = {}; managedElements = {}; endpointsByUUID = {}; offsets = {}; offsetTimestamps = {}; _currentInstance.anchorManager.reset(); var dm = _currentInstance.getDragManager(); if (dm) { dm.reset(); } if (!_is) { _currentInstance.setSuspendDrawing(false); } return _currentInstance; }; var fireDetachEvent = function (jpc, doFireEvent, originalEvent) { // may have been given a connection, or in special cases, an object var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(), argIsConnection = jpc.constructor === connType, params = argIsConnection ? { connection: jpc, source: jpc.source, target: jpc.target, sourceId: jpc.sourceId, targetId: jpc.targetId, sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1] } : jpc; if (doFireEvent) { _currentInstance.fire("connectionDetached", params, originalEvent); } // always fire this. used by internal jsplumb stuff. _currentInstance.fire("internal.connectionDetached", params, originalEvent); _currentInstance.anchorManager.connectionDetached(params); }; var fireMoveEvent = _currentInstance.fireMoveEvent = function (params, evt) { _currentInstance.fire("connectionMoved", params, evt); }; this.unregisterEndpoint = function (endpoint) { if (endpoint._jsPlumb.uuid) { endpointsByUUID[endpoint._jsPlumb.uuid] = null; } _currentInstance.anchorManager.deleteEndpoint(endpoint); // TODO at least replace this with a removeWithFunction call. for (var e in endpointsByElement) { var endpoints = endpointsByElement[e]; if (endpoints) { var newEndpoints = []; for (var i = 0, j = endpoints.length; i < j; i++) { if (endpoints[i] !== endpoint) { newEndpoints.push(endpoints[i]); } } endpointsByElement[e] = newEndpoints; } if (endpointsByElement[e].length < 1) { delete endpointsByElement[e]; } } }; var IS_DETACH_ALLOWED = "isDetachAllowed"; var BEFORE_DETACH = "beforeDetach"; var CHECK_CONDITION = "checkCondition"; /** * Deletes a Connection. * @method deleteConnection * @param connection Connection to delete * @param {Object} [params] Optional delete parameters * @param {Boolean} [params.doNotFireEvent=false] If true, a connection detached event will not be fired. Otherwise one will. * @param {Boolean} [params.force=false] If true, the connection will be deleted even if a beforeDetach interceptor tries to stop the deletion. * @returns {Boolean} True if the connection was deleted, false otherwise. */ this.deleteConnection = function(connection, params) { if (connection != null) { params = params || {}; if (params.force || _ju.functionChain(true, false, [ [ connection.endpoints[0], IS_DETACH_ALLOWED, [ connection ] ], [ connection.endpoints[1], IS_DETACH_ALLOWED, [ connection ] ], [ connection, IS_DETACH_ALLOWED, [ connection ] ], [ _currentInstance, CHECK_CONDITION, [ BEFORE_DETACH, connection ] ] ])) { connection.setHover(false); fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent); connection.endpoints[0].detachFromConnection(connection); connection.endpoints[1].detachFromConnection(connection); _ju.removeWithFunction(connections, function (_c) { return connection.id === _c.id; }); connection.cleanup(); connection.destroy(); return true; } } return false; }; /** * Remove all Connections from all elements, but leaves Endpoints in place ((unless a connection is set to auto delete its Endpoints). * @method deleteEveryConnection * @param {Object} [params] optional params object for the call * @param {Boolean} [params.fireEvent=true] Whether or not to fire detach events * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors. * @returns {Number} The number of connections that were deleted. */ this.deleteEveryConnection = function (params) { params = params || {}; var count = connections.length, deletedCount = 0; _currentInstance.batch(function () { for (var i = 0; i < count; i++) { deletedCount += _currentInstance.deleteConnection(connections[0], params) ? 1 : 0; } }); return deletedCount; }; /** * Removes all an element's Connections. * @method deleteConnectionsForElement * @param {Object} el Either the id of the element, or a selector for the element. * @param {Object} [params] Optional parameters. * @param {Boolean} [params.fireEvent=true] Whether or not to fire the detach event. * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors. * @return {jsPlumbInstance} The current jsPlumb instance. */ this.deleteConnectionsForElement = function (el, params) { params = params || {}; el = _currentInstance.getElement(el); var id = _getId(el), endpoints = endpointsByElement[id]; if (endpoints && endpoints.length) { for (var i = 0, j = endpoints.length; i < j; i++) { endpoints[i].deleteEveryConnection(params); } } return _currentInstance; }; /// not public. but of course its exposed. how to change this. this.deleteObject = function (params) { var result = { endpoints: {}, connections: {}, endpointCount: 0, connectionCount: 0 }, deleteAttachedObjects = params.deleteAttachedObjects !== false; var unravelConnection = function (connection) { if (connection != null && result.connections[connection.id] == null) { if (!params.dontUpdateHover && connection._jsPlumb != null) { connection.setHover(false); } result.connections[connection.id] = connection; result.connectionCount++; } }; var unravelEndpoint = function (endpoint) { if (endpoint != null && result.endpoints[endpoint.id] == null) { if (!params.dontUpdateHover && endpoint._jsPlumb != null) { endpoint.setHover(false); } result.endpoints[endpoint.id] = endpoint; result.endpointCount++; if (deleteAttachedObjects) { for (var i = 0; i < endpoint.connections.length; i++) { var c = endpoint.connections[i]; unravelConnection(c); } } } }; if (params.connection) { unravelConnection(params.connection); } else { unravelEndpoint(params.endpoint); } // loop through connections for (var i in result.connections) { var c = result.connections[i]; if (c._jsPlumb) { _ju.removeWithFunction(connections, function (_c) { return c.id === _c.id; }); fireDetachEvent(c, params.fireEvent === false ? false : !c.pending, params.originalEvent); var doNotCleanup = params.deleteAttachedObjects == null ? null : !params.deleteAttachedObjects; c.endpoints[0].detachFromConnection(c, null, doNotCleanup); c.endpoints[1].detachFromConnection(c, null, doNotCleanup); c.cleanup(true); c.destroy(true); } } // loop through endpoints for (var j in result.endpoints) { var e = result.endpoints[j]; if (e._jsPlumb) { _currentInstance.unregisterEndpoint(e); // FIRE some endpoint deleted event? e.cleanup(true); e.destroy(true); } } return result; }; this.draggable = function (el, options) { var info; _each(function(_el) { info = _info(_el); if (info.el) { _initDraggableIfNecessary(info.el, true, options, info.id, true); } }, el); return _currentInstance; }; this.droppable = function(el, options) { var info; options = options || {}; options.allowLoopback = false; _each(function(_el) { info = _info(_el); if (info.el) { _currentInstance.initDroppable(info.el, options); } }, el); return _currentInstance; }; // helpers for select/selectEndpoints var _setOperation = function (list, func, args, selector) { for (var i = 0, j = list.length; i < j; i++) { list[i][func].apply(list[i], args); } return selector(list); }, _getOperation = function (list, func, args) { var out = []; for (var i = 0, j = list.length; i < j; i++) { out.push([ list[i][func].apply(list[i], args), list[i] ]); } return out; }, setter = function (list, func, selector) { return function () { return _setOperation(list, func, arguments, selector); }; }, getter = function (list, func) { return function () { return _getOperation(list, func, arguments); }; }, prepareList = function (input, doNotGetIds) { var r = []; if (input) { if (typeof input === 'string') { if (input === "*") { return input; } r.push(input); } else { if (doNotGetIds) { r = input; } else { if (input.length) { for (var i = 0, j = input.length; i < j; i++) { r.push(_info(input[i]).id); } } else { r.push(_info(input).id); } } } } return r; }, filterList = function (list, value, missingIsFalse) { if (list === "*") { return true; } return list.length > 0 ? list.indexOf(value) !== -1 : !missingIsFalse; }; // get some connections, specifying source/target/scope this.getConnections = function (options, flat) { if (!options) { options = {}; } else if (options.constructor === String) { options = { "scope": options }; } var scope = options.scope || _currentInstance.getDefaultScope(), scopes = prepareList(scope, true), sources = prepareList(options.source), targets = prepareList(options.target), results = (!flat && scopes.length > 1) ? {} : [], _addOne = function (scope, obj) { if (!flat && scopes.length > 1) { var ss = results[scope]; if (ss == null) { ss = results[scope] = []; } ss.push(obj); } else { results.push(obj); } }; for (var j = 0, jj = connections.length; j < jj; j++) { var c = connections[j], sourceId = c.proxies && c.proxies[0] ? c.proxies[0].originalEp.elementId : c.sourceId, targetId = c.proxies && c.proxies[1] ? c.proxies[1].originalEp.elementId : c.targetId; if (filterList(scopes, c.scope) && filterList(sources, sourceId) && filterList(targets, targetId)) { _addOne(c.scope, c); } } return results; }; var _curryEach = function (list, executor) { return function (f) { for (var i = 0, ii = list.length; i < ii; i++) { f(list[i]); } return executor(list); }; }, _curryGet = function (list) { return function (idx) { return list[idx]; }; }; var _makeCommonSelectHandler = function (list, executor) { var out = { length: list.length, each: _curryEach(list, executor), get: _curryGet(list) }, setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay", "removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle", "setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible", "repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ], getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle", "getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ], i, ii; for (i = 0, ii = setters.length; i < ii; i++) { out[setters[i]] = setter(list, setters[i], executor); } for (i = 0, ii = getters.length; i < ii; i++) { out[getters[i]] = getter(list, getters[i]); } return out; }; var _makeConnectionSelectHandler = function (list) { var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler); return jsPlumb.extend(common, { // setters setDetachable: setter(list, "setDetachable", _makeConnectionSelectHandler), setReattach: setter(list, "setReattach", _makeConnectionSelectHandler), setConnector: setter(list, "setConnector", _makeConnectionSelectHandler), delete: function () { for (var i = 0, ii = list.length; i < ii; i++) { _currentInstance.deleteConnection(list[i]); } }, // getters isDetachable: getter(list, "isDetachable"), isReattach: getter(list, "isReattach") }); }; var _makeEndpointSelectHandler = function (list) { var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler); return jsPlumb.extend(common, { setEnabled: setter(list, "setEnabled", _makeEndpointSelectHandler), setAnchor: setter(list, "setAnchor", _makeEndpointSelectHandler), isEnabled: getter(list, "isEnabled"), deleteEveryConnection: function () { for (var i = 0, ii = list.length; i < ii; i++) { list[i].deleteEveryConnection(); } }, "delete": function () { for (var i = 0, ii = list.length; i < ii; i++) { _currentInstance.deleteEndpoint(list[i]); } } }); }; this.select = function (params) { params = params || {}; params.scope = params.scope || "*"; return _makeConnectionSelectHandler(params.connections || _currentInstance.getConnections(params, true)); }; this.selectEndpoints = function (params) { params = params || {}; params.scope = params.scope || "*"; var noElementFilters = !params.element && !params.source && !params.target, elements = noElementFilters ? "*" : prepareList(params.element), sources = noElementFilters ? "*" : prepareList(params.source), targets = noElementFilters ? "*" : prepareList(params.target), scopes = prepareList(params.scope, true); var ep = []; for (var el in endpointsByElement) { var either = filterList(elements, el, true), source = filterList(sources, el, true), sourceMatchExact = sources !== "*", target = filterList(targets, el, true), targetMatchExact = targets !== "*"; // if they requested 'either' then just match scope. otherwise if they requested 'source' (not as a wildcard) then we have to match only endpoints that have isSource set to to true, and the same thing with isTarget. if (either || source || target) { inner: for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) { var _ep = endpointsByElement[el][i]; if (filterList(scopes, _ep.scope, true)) { var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource), noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget); if (noMatchSource || noMatchTarget) { continue inner; } ep.push(_ep); } } } } return _makeEndpointSelectHandler(ep); }; // get all connections managed by the instance of jsplumb. this.getAllConnections = function () { return connections; }; this.getDefaultScope = function () { return DEFAULT_SCOPE; }; // get an endpoint by uuid. this.getEndpoint = _getEndpoint; /** * Gets the list of Endpoints for a given element. * @method getEndpoints * @param {String|Element|Selector} el The element to get endpoints for. * @return {Endpoint[]} An array of Endpoints for the specified element. */ this.getEndpoints = function (el) { return endpointsByElement[_info(el).id] || []; }; // gets the default endpoint type. used when subclassing. see wiki. this.getDefaultEndpointType = function () { return jsPlumb.Endpoint; }; // gets the default connection type. used when subclassing. see wiki. this.getDefaultConnectionType = function () { return jsPlumb.Connection; }; /* * Gets an element's id, creating one if necessary. really only exposed * for the lib-specific functionality to access; would be better to pass * the current instance into the lib-specific code (even though this is * a static call. i just don't want to expose it to the public API). */ this.getId = _getId; this.appendElement = _appendElement; var _hoverSuspended = false; this.isHoverSuspended = function () { return _hoverSuspended; }; this.setHoverSuspended = function (s) { _hoverSuspended = s; }; // set an element's connections to be hidden this.hide = function (el, changeEndpoints) { _setVisible(el, "none", changeEndpoints); return _currentInstance; }; // exposed for other objects to use to get a unique id. this.idstamp = _idstamp; // this.connectorsInitialized = false; // this.registerConnectorType = function (connector, name) { // connectorTypes.push([connector, name]); // }; // ensure that, if the current container exists, it is a DOM element and not a selector. // if it does not exist and `candidate` is supplied, the offset parent of that element will be set as the Container. // this is used to do a better default behaviour for the case that the user has not set a container: // addEndpoint, makeSource, makeTarget and connect all call this method with the offsetParent of the // element in question (for connect it is the source element). So if no container is set, it is inferred // to be the offsetParent of the first element the user tries to connect. var _ensureContainer = function (candidate) { if (!_container && candidate) { var can = _currentInstance.getElement(candidate); if (can.offsetParent) { _currentInstance.setContainer(can.offsetParent); } } }; var _getContainerFromDefaults = function () { if (_currentInstance.Defaults.Container) { _currentInstance.setContainer(_currentInstance.Defaults.Container); } }; // check if a given element is managed or not. if not, add to our map. if drawing is not suspended then // we'll also stash its dimensions; otherwise we'll do this in a lazy way through updateOffset. var _manage = _currentInstance.manage = function (id, element, _transient) { if (!managedElements[id]) { managedElements[id] = { el: element, endpoints: [], connections: [] }; managedElements[id].info = _updateOffset({ elId: id, timestamp: _suspendedAt }); if (!_transient) { _currentInstance.fire("manageElement", { id:id, info:managedElements[id].info, el:element }); } } return managedElements[id]; }; var _unmanage = function(id) { if (managedElements[id]) { delete managedElements[id]; _currentInstance.fire("unmanageElement", id); } }; /** * updates the offset and size for a given element, and stores the * values. if 'offset' is not null we use that (it would have been * passed in from a drag call) because it's faster; but if it is null, * or if 'recalc' is true in order to force a recalculation, we get the current values. * @method updateOffset */ var _updateOffset = function (params) { var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId, s; if (_suspendDrawing && !timestamp) { timestamp = _suspendedAt; } if (!recalc) { if (timestamp && timestamp === offsetTimestamps[elId]) { return {o: params.offset || offsets[elId], s: sizes[elId]}; } } if (recalc || (!offset && offsets[elId] == null)) { // if forced repaint or no offset available, we recalculate. // get the current size and offset, and store them s = managedElements[elId] ? managedElements[elId].el : null; if (s != null) { sizes[elId] = _currentInstance.getSize(s); offsets[elId] = _currentInstance.getOffset(s); offsetTimestamps[elId] = timestamp; } } else { offsets[elId] = offset || offsets[elId]; if (sizes[elId] == null) { s = managedElements[elId].el; if (s != null) { sizes[elId] = _currentInstance.getSize(s); } } offsetTimestamps[elId] = timestamp; } if (offsets[elId] && !offsets[elId].right) { offsets[elId].right = offsets[elId].left + sizes[elId][0]; offsets[elId].bottom = offsets[elId].top + sizes[elId][1]; offsets[elId].width = sizes[elId][0]; offsets[elId].height = sizes[elId][1]; offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2); offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2); } return {o: offsets[elId], s: sizes[elId]}; }; this.updateOffset = _updateOffset; /** * callback from the current library to tell us to prepare ourselves (attach * mouse listeners etc; can't do that until the library has provided a bind method) */ this.init = function () { if (!initialized) { _getContainerFromDefaults(); _currentInstance.anchorManager = new root.jsPlumb.AnchorManager({jsPlumbInstance: _currentInstance}); initialized = true; _currentInstance.fire("ready", _currentInstance); } }.bind(this); this.log = log; this.jsPlumbUIComponent = jsPlumbUIComponent; /* * Creates an anchor with the given params. * * * Returns: The newly created Anchor. * Throws: an error if a named anchor was not found. */ this.makeAnchor = function () { var pp, _a = function (t, p) { if (root.jsPlumb.Anchors[t]) { return new root.jsPlumb.Anchors[t](p); } if (!_currentInstance.Defaults.DoNotThrowErrors) { throw { msg: "jsPlumb: unknown anchor type '" + t + "'" }; } }; if (arguments.length === 0) { return null; } var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null; // if it appears to be an anchor already... if (specimen.compute && specimen.getOrientation) { return specimen; } //TODO hazy here about whether it should be added or is already added somehow. // is it the name of an anchor type? else if (typeof specimen === "string") { newAnchor = _a(arguments[0], {elementId: elementId, jsPlumbInstance: _currentInstance}); } // is it an array? it will be one of: // an array of [spec, params] - this defines a single anchor, which may be dynamic, but has parameters. // an array of arrays - this defines some dynamic anchors // an array of numbers - this defines a single anchor. else if (_ju.isArray(specimen)) { if (_ju.isArray(specimen[0]) || _ju.isString(specimen[0])) { // if [spec, params] format if (specimen.length === 2 && _ju.isObject(specimen[1])) { // if first arg is a string, its a named anchor with params if (_ju.isString(specimen[0])) { pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance}, specimen[1]); newAnchor = _a(specimen[0], pp); } // otherwise first arg is array, second is params. we treat as a dynamic anchor, which is fine // even if the first arg has only one entry. you could argue all anchors should be implicitly dynamic in fact. else { pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance, anchors: specimen[0]}, specimen[1]); newAnchor = new root.jsPlumb.DynamicAnchor(pp); } } else { newAnchor = new jsPlumb.DynamicAnchor({anchors: specimen, selector: null, elementId: elementId, jsPlumbInstance: _currentInstance}); } } else { var anchorParams = { x: specimen[0], y: specimen[1], orientation: (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0, 0], offsets: (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ], elementId: elementId, jsPlumbInstance: _currentInstance, cssClass: specimen.length === 7 ? specimen[6] : null }; newAnchor = new root.jsPlumb.Anchor(anchorParams); newAnchor.clone = function () { return new root.jsPlumb.Anchor(anchorParams); }; } } if (!newAnchor.id) { newAnchor.id = "anchor_" + _idstamp(); } return newAnchor; }; /** * makes a list of anchors from the given list of types or coords, eg * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ] */ this.makeAnchors = function (types, elementId, jsPlumbInstance) { var r = []; for (var i = 0, ii = types.length; i < ii; i++) { if (typeof types[i] === "string") { r.push(root.jsPlumb.Anchors[types[i]]({elementId: elementId, jsPlumbInstance: jsPlumbInstance})); } else if (_ju.isArray(types[i])) { r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance)); } } return r; }; /** * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will * not need to provide this - i think). */ this.makeDynamicAnchor = function (anchors, anchorSelector) { return new root.jsPlumb.DynamicAnchor({anchors: anchors, selector: anchorSelector, elementId: null, jsPlumbInstance: _currentInstance}); }; // --------------------- makeSource/makeTarget ---------------------------------------------- this.targetEndpointDefinitions = {}; this.sourceEndpointDefinitions = {}; var selectorFilter = function (evt, _el, selector, _instance, negate) { var t = evt.target || evt.srcElement, ok = false, sel = _instance.getSelector(_el, selector); for (var j = 0; j < sel.length; j++) { if (sel[j] === t) { ok = true; break; } } return negate ? !ok : ok; }; var _makeElementDropHandler = function (elInfo, p, dropOptions, isSource, isTarget) { var proxyComponent = new jsPlumbUIComponent(p); var _drop = p._jsPlumb.EndpointDropHandler({ jsPlumb: _currentInstance, enabled: function () { return elInfo.def.enabled; }, isFull: function () { var targetCount = _currentInstance.select({target: elInfo.id}).length; return elInfo.def.maxConnections > 0 && targetCount >= elInfo.def.maxConnections; }, element: elInfo.el, elementId: elInfo.id, isSource: isSource, isTarget: isTarget, addClass: function (clazz) { _currentInstance.addClass(elInfo.el, clazz); }, removeClass: function (clazz) { _currentInstance.removeClass(elInfo.el, clazz); }, onDrop: function (jpc) { var source = jpc.endpoints[0]; source.anchor.unlock(); }, isDropAllowed: function () { return proxyComponent.isDropAllowed.apply(proxyComponent, arguments); }, isRedrop:function(jpc) { return (jpc.suspendedElement != null && jpc.suspendedEndpoint != null && jpc.suspendedEndpoint.element === elInfo.el); }, getEndpoint: function (jpc) { // make a new Endpoint for the target, or get it from the cache if uniqueEndpoint // is set. if its a redrop the new endpoint will be immediately cleaned up. var newEndpoint = elInfo.def.endpoint; // if no cached endpoint, or there was one but it has been cleaned up // (ie. detached), create a new one if (newEndpoint == null || newEndpoint._jsPlumb == null) { var eps = _currentInstance.deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true); var pp = eps.endpoints ? root.jsPlumb.extend(p, { endpoint:elInfo.def.def.endpoint || eps.endpoints[1] }) :p; if (eps.anchors) { pp = root.jsPlumb.extend(pp, { anchor:elInfo.def.def.anchor || eps.anchors[1] }); } newEndpoint = _currentInstance.addEndpoint(elInfo.el, pp); newEndpoint._mtNew = true; } if (p.uniqueEndpoint) { elInfo.def.endpoint = newEndpoint; } newEndpoint.setDeleteOnEmpty(true); // if connection is detachable, init the new endpoint to be draggable, to support that happening. if (jpc.isDetachable()) { newEndpoint.initDraggable(); } // if the anchor has a 'positionFinder' set, then delegate to that function to find // out where to locate the anchor. if (newEndpoint.anchor.positionFinder != null) { var dropPosition = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()), elPosition = _currentInstance.getOffset(elInfo.el), elSize = _currentInstance.getSize(elInfo.el), ap = dropPosition == null ? [0,0] : newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams); newEndpoint.anchor.x = ap[0]; newEndpoint.anchor.y = ap[1]; // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which // the target is furthest away from the source. } return newEndpoint; }, maybeCleanup: function (ep) { if (ep._mtNew && ep.connections.length === 0) { _currentInstance.deleteObject({endpoint: ep}); } else { delete ep._mtNew; } } }); // wrap drop events as needed and initialise droppable var dropEvent = root.jsPlumb.dragEvents.drop; dropOptions.scope = dropOptions.scope || (p.scope || _currentInstance.Defaults.Scope); dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], _drop, true); dropOptions.rank = p.rank || 0; // if target, return true from the over event. this will cause katavorio to stop setting drops to hover // if multipleDrop is set to false. if (isTarget) { dropOptions[root.jsPlumb.dragEvents.over] = function () { return true; }; } // vanilla jsplumb only if (p.allowLoopback === false) { dropOptions.canDrop = function (_drag) { var de = _drag.getDragElement()._jsPlumbRelatedElement; return de !== elInfo.el; }; } _currentInstance.initDroppable(elInfo.el, dropOptions, "internal"); return _drop; }; // see API docs this.makeTarget = function (el, params, referenceParams) { // put jsplumb ref into params without altering the params passed in var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams); root.jsPlumb.extend(p, params); var maxConnections = p.maxConnections || -1, _doOne = function (el) { // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these, // and use the endpoint definition if found. // decode the info for this element (id and element) var elInfo = _info(el), elid = elInfo.id, dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}), type = p.connectionType || "default"; this.targetEndpointDefinitions[elid] = this.targetEndpointDefinitions[elid] || {}; _ensureContainer(elid); // if this is a group and the user has not mandated a rank, set to -1 so that Nodes takes // precedence. if (elInfo.el._isJsPlumbGroup && dropOptions.rank == null) { dropOptions.rank = -1; } // store the definition var _def = { def: root.jsPlumb.extend({}, p), uniqueEndpoint: p.uniqueEndpoint, maxConnections: maxConnections, enabled: true }; if (p.createEndpoint) { _def.uniqueEndpoint = true; _def.endpoint = _currentInstance.addEndpoint(el, _def.def); _def.endpoint.setDeleteOnEmpty(false); } elInfo.def = _def; this.targetEndpointDefinitions[elid][type] = _def; _makeElementDropHandler(elInfo, p, dropOptions, p.isSource === true, true); // stash the definition on the drop elInfo.el._katavorioDrop[elInfo.el._katavorioDrop.length - 1].targetDef = _def; }.bind(this); // make an array if only given one element var inputs = el.length && el.constructor !== String ? el : [ el ]; // register each one in the list. for (var i = 0, ii = inputs.length; i < ii; i++) { _doOne(inputs[i]); } return this; }; // see api docs this.unmakeTarget = function (el, doNotClearArrays) { var info = _info(el); _currentInstance.destroyDroppable(info.el, "internal"); if (!doNotClearArrays) { delete this.targetEndpointDefinitions[info.id]; } return this; }; // see api docs this.makeSource = function (el, params, referenceParams) { var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams); root.jsPlumb.extend(p, params); var type = p.connectionType || "default"; var aae = _currentInstance.deriveEndpointAndAnchorSpec(type); p.endpoint = p.endpoint || aae.endpoints[0]; p.anchor = p.anchor || aae.anchors[0]; var maxConnections = p.maxConnections || -1, onMaxConnections = p.onMaxConnections, _doOne = function (elInfo) { // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these, // and use the endpoint definition if found. var elid = elInfo.id, _del = this.getElement(elInfo.el); this.sourceEndpointDefinitions[elid] = this.sourceEndpointDefinitions[elid] || {}; _ensureContainer(elid); var _def = { def:root.jsPlumb.extend({}, p), uniqueEndpoint: p.uniqueEndpoint, maxConnections: maxConnections, enabled: true }; if (p.createEndpoint) { _def.uniqueEndpoint = true; _def.endpoint = _currentInstance.addEndpoint(el, _def.def); _def.endpoint.setDeleteOnEmpty(false); } this.sourceEndpointDefinitions[elid][type] = _def; elInfo.def = _def; var stopEvent = root.jsPlumb.dragEvents.stop, dragEvent = root.jsPlumb.dragEvents.drag, dragOptions = root.jsPlumb.extend({ }, p.dragOptions || {}), existingDrag = dragOptions.drag, existingStop = dragOptions.stop, ep = null, endpointAddedButNoDragYet = false; // set scope if its not set in dragOptions but was passed in in params dragOptions.scope = dragOptions.scope || p.scope; dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], function () { if (existingDrag) { existingDrag.apply(this, arguments); } endpointAddedButNoDragYet = false; }); dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], function () { if (existingStop) { existingStop.apply(this, arguments); } this.currentlyDragging = false; if (ep._jsPlumb != null) { // if not cleaned up... // reset the anchor to the anchor that was initially provided. the one we were using to drag // the connection was just a placeholder that was located at the place the user pressed the // mouse button to initiate the drag. var anchorDef = p.anchor || this.Defaults.Anchor, oldAnchor = ep.anchor, oldConnection = ep.connections[0]; var newAnchor = this.makeAnchor(anchorDef, elid, this), _el = ep.element; // if the anchor has a 'positionFinder' set, then delegate to that function to find // out where to locate the anchor. issue 117. if (newAnchor.positionFinder != null) { var elPosition = _currentInstance.getOffset(_el), elSize = this.getSize(_el), dropPosition = { left: elPosition.left + (oldAnchor.x * elSize[0]), top: elPosition.top + (oldAnchor.y * elSize[1]) }, ap = newAnchor.positionFinder(dropPosition, elPosition, elSize, newAnchor.constructorParams); newAnchor.x = ap[0]; newAnchor.y = ap[1]; } ep.setAnchor(newAnchor, true); ep.repaint(); this.repaint(ep.elementId); if (oldConnection != null) { this.repaint(oldConnection.targetId); } } }.bind(this)); // when the user presses the mouse, add an Endpoint, if we are enabled. var mouseDownListener = function (e) { // on right mouse button, abort. if (e.which === 3 || e.button === 2) { return; } // TODO store def on element. var def = this.sourceEndpointDefinitions[elid][type]; // if disabled, return. if (!def.enabled) { return; } elid = this.getId(this.getElement(elInfo.el)); // elid might have changed since this method was called to configure the element. // if a filter was given, run it, and return if it says no. if (p.filter) { var r = _ju.isString(p.filter) ? selectorFilter(e, elInfo.el, p.filter, this, p.filterExclude) : p.filter(e, elInfo.el); if (r === false) { return; } } // if maxConnections reached var sourceCount = this.select({source: elid}).length; if (def.maxConnections >= 0 && (sourceCount >= def.maxConnections)) { if (onMaxConnections) { onMaxConnections({ element: elInfo.el, maxConnections: maxConnections }, e); } return false; } // find the position on the element at which the mouse was pressed; this is where the endpoint // will be located. var elxy = root.jsPlumb.getPositionOnElement(e, _del, _zoom); // we need to override the anchor in here, and force 'isSource', but we don't want to mess with // the params passed in, because after a connection is established we're going to reset the endpoint // to have the anchor we were given. var tempEndpointParams = {}; root.jsPlumb.extend(tempEndpointParams, p); tempEndpointParams.isTemporarySource = true; tempEndpointParams.anchor = [ elxy[0], elxy[1] , 0, 0]; tempEndpointParams.dragOptions = dragOptions; if (def.def.scope) { tempEndpointParams.scope = def.def.scope; } ep = this.addEndpoint(elid, tempEndpointParams); endpointAddedButNoDragYet = true; ep.setDeleteOnEmpty(true); // if unique endpoint and it's already been created, push it onto the endpoint we create. at the end // of a successful connection we'll switch to that endpoint. // TODO this is the same code as the programmatic endpoints create on line 1050 ish if (def.uniqueEndpoint) { if (!def.endpoint) { def.endpoint = ep; ep.setDeleteOnEmpty(false); } else { ep.finalEndpoint = def.endpoint; } } var _delTempEndpoint = function () { // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools // it is fired even if dragging has occurred, in which case we would blow away a perfectly // legitimate endpoint, were it not for this check. the flag is set after adding an // endpoint and cleared in a drag listener we set in the dragOptions above. _currentInstance.off(ep.canvas, "mouseup", _delTempEndpoint); _currentInstance.off(elInfo.el, "mouseup", _delTempEndpoint); if (endpointAddedButNoDragYet) { endpointAddedButNoDragYet = false; _currentInstance.deleteEndpoint(ep); } }; _currentInstance.on(ep.canvas, "mouseup", _delTempEndpoint); _currentInstance.on(elInfo.el, "mouseup", _delTempEndpoint); // optionally check for attributes to extract from the source element var payload = {}; if (def.def.extract) { for (var att in def.def.extract) { var v = (e.srcElement || e.target).getAttribute(att); if (v) { payload[def.def.extract[att]] = v; } } } // and then trigger its mousedown event, which will kick off a drag, which will start dragging // a new connection from this endpoint. _currentInstance.trigger(ep.canvas, "mousedown", e, payload); _ju.consume(e); }.bind(this); this.on(elInfo.el, "mousedown", mouseDownListener); _def.trigger = mouseDownListener; // if a filter was provided, set it as a dragFilter on the element, // to prevent the element drag function from kicking in when we want to // drag a new connection if (p.filter && (_ju.isString(p.filter) || _ju.isFunction(p.filter))) { _currentInstance.setDragFilter(elInfo.el, p.filter); } var dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}); _makeElementDropHandler(elInfo, p, dropOptions, true, p.isTarget === true); }.bind(this); var inputs = el.length && el.constructor !== String ? el : [ el ]; for (var i = 0, ii = inputs.length; i < ii; i++) { _doOne(_info(inputs[i])); } return this; }; // see api docs this.unmakeSource = function (el, connectionType, doNotClearArrays) { var info = _info(el); _currentInstance.destroyDroppable(info.el, "internal"); var eldefs = this.sourceEndpointDefinitions[info.id]; if (eldefs) { for (var def in eldefs) { if (connectionType == null || connectionType === def) { var mouseDownListener = eldefs[def].trigger; if (mouseDownListener) { _currentInstance.off(info.el, "mousedown", mouseDownListener); } if (!doNotClearArrays) { delete this.sourceEndpointDefinitions[info.id][def]; } } } } return this; }; // see api docs this.unmakeEverySource = function () { for (var i in this.sourceEndpointDefinitions) { _currentInstance.unmakeSource(i, null, true); } this.sourceEndpointDefinitions = {}; return this; }; var _getScope = function (el, types, connectionType) { types = _ju.isArray(types) ? types : [ types ]; var id = _getId(el); connectionType = connectionType || "default"; for (var i = 0; i < types.length; i++) { var eldefs = this[types[i]][id]; if (eldefs && eldefs[connectionType]) { return eldefs[connectionType].def.scope || this.Defaults.Scope; } } }.bind(this); var _setScope = function (el, scope, types, connectionType) { types = _ju.isArray(types) ? types : [ types ]; var id = _getId(el); connectionType = connectionType || "default"; for (var i = 0; i < types.length; i++) { var eldefs = this[types[i]][id]; if (eldefs && eldefs[connectionType]) { eldefs[connectionType].def.scope = scope; } } }.bind(this); this.getScope = function (el, scope) { return _getScope(el, [ "sourceEndpointDefinitions", "targetEndpointDefinitions" ]); }; this.getSourceScope = function (el) { return _getScope(el, "sourceEndpointDefinitions"); }; this.getTargetScope = function (el) { return _getScope(el, "targetEndpointDefinitions"); }; this.setScope = function (el, scope, connectionType) { this.setSourceScope(el, scope, connectionType); this.setTargetScope(el, scope, connectionType); }; this.setSourceScope = function (el, scope, connectionType) { _setScope(el, scope, "sourceEndpointDefinitions", connectionType); // we get the source scope during the mousedown event, but we also want to set this. this.setDragScope(el, scope); }; this.setTargetScope = function (el, scope, connectionType) { _setScope(el, scope, "targetEndpointDefinitions", connectionType); this.setDropScope(el, scope); }; // see api docs this.unmakeEveryTarget = function () { for (var i in this.targetEndpointDefinitions) { _currentInstance.unmakeTarget(i, true); } this.targetEndpointDefinitions = {}; return this; }; // does the work of setting a source enabled or disabled. var _setEnabled = function (type, el, state, toggle, connectionType) { var a = type === "source" ? this.sourceEndpointDefinitions : this.targetEndpointDefinitions, originalState, info, newState; connectionType = connectionType || "default"; // a selector or an array if (el.length && !_ju.isString(el)) { originalState = []; for (var i = 0, ii = el.length; i < ii; i++) { info = _info(el[i]); if (a[info.id] && a[info.id][connectionType]) { originalState[i] = a[info.id][connectionType].enabled; newState = toggle ? !originalState[i] : state; a[info.id][connectionType].enabled = newState; _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled"); } } } // otherwise a DOM element or a String ID. else { info = _info(el); var id = info.id; if (a[id] && a[id][connectionType]) { originalState = a[id][connectionType].enabled; newState = toggle ? !originalState : state; a[id][connectionType].enabled = newState; _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled"); } } return originalState; }.bind(this); var _first = function (el, fn) { if (_ju.isString(el) || !el.length) { return fn.apply(this, [ el ]); } else if (el.length) { return fn.apply(this, [ el[0] ]); } }.bind(this); this.toggleSourceEnabled = function (el, connectionType) { _setEnabled("source", el, null, true, connectionType); return this.isSourceEnabled(el, connectionType); }; this.setSourceEnabled = function (el, state, connectionType) { return _setEnabled("source", el, state, null, connectionType); }; this.isSource = function (el, connectionType) { connectionType = connectionType || "default"; return _first(el, function (_el) { var eldefs = this.sourceEndpointDefinitions[_info(_el).id]; return eldefs != null && eldefs[connectionType] != null; }.bind(this)); }; this.isSourceEnabled = function (el, connectionType) { connectionType = connectionType || "default"; return _first(el, function (_el) { var sep = this.sourceEndpointDefinitions[_info(_el).id]; return sep && sep[connectionType] && sep[connectionType].enabled === true; }.bind(this)); }; this.toggleTargetEnabled = function (el, connectionType) { _setEnabled("target", el, null, true, connectionType); return this.isTargetEnabled(el, connectionType); }; this.isTarget = function (el, connectionType) { connectionType = connectionType || "default"; return _first(el, function (_el) { var eldefs = this.targetEndpointDefinitions[_info(_el).id]; return eldefs != null && eldefs[connectionType] != null; }.bind(this)); }; this.isTargetEnabled = function (el, connectionType) { connectionType = connectionType || "default"; return _first(el, function (_el) { var tep = this.targetEndpointDefinitions[_info(_el).id]; return tep && tep[connectionType] && tep[connectionType].enabled === true; }.bind(this)); }; this.setTargetEnabled = function (el, state, connectionType) { return _setEnabled("target", el, state, null, connectionType); }; // --------------------- end makeSource/makeTarget ---------------------------------------------- this.ready = function (fn) { _currentInstance.bind("ready", fn); }; var _elEach = function(el, fn) { // support both lists... if (typeof el === 'object' && el.length) { for (var i = 0, ii = el.length; i < ii; i++) { fn(el[i]); } } else {// ...and single strings or elements. fn(el); } return _currentInstance; }; // repaint some element's endpoints and connections this.repaint = function (el, ui, timestamp) { return _elEach(el, function(_el) { _draw(_el, ui, timestamp); }); }; this.revalidate = function (el, timestamp, isIdAlready) { return _elEach(el, function(_el) { var elId = isIdAlready ? _el : _currentInstance.getId(_el); _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp:timestamp }); var dm = _currentInstance.getDragManager(); if (dm) { dm.updateOffsets(elId); } _currentInstance.repaint(_el); }); }; // repaint every endpoint and connection. this.repaintEverything = function () { // TODO this timestamp causes continuous anchors to not repaint properly. // fix this. do not just take out the timestamp. it runs a lot faster with // the timestamp included. var timestamp = _timestamp(), elId; for (elId in endpointsByElement) { _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp: timestamp }); } for (elId in endpointsByElement) { _draw(elId, null, timestamp); } return this; }; this.removeAllEndpoints = function (el, recurse, affectedElements) { affectedElements = affectedElements || []; var _one = function (_el) { var info = _info(_el), ebe = endpointsByElement[info.id], i, ii; if (ebe) { affectedElements.push(info); for (i = 0, ii = ebe.length; i < ii; i++) { _currentInstance.deleteEndpoint(ebe[i], false); } } delete endpointsByElement[info.id]; if (recurse) { if (info.el && info.el.nodeType !== 3 && info.el.nodeType !== 8) { for (i = 0, ii = info.el.childNodes.length; i < ii; i++) { _one(info.el.childNodes[i]); } } } }; _one(el); return this; }; var _doRemove = function(info, affectedElements) { _currentInstance.removeAllEndpoints(info.id, true, affectedElements); var dm = _currentInstance.getDragManager(); var _one = function(_info) { if (dm) { dm.elementRemoved(_info.id); } _currentInstance.anchorManager.clearFor(_info.id); _currentInstance.anchorManager.removeFloatingConnection(_info.id); if (_currentInstance.isSource(_info.el)) { _currentInstance.unmakeSource(_info.el); } if (_currentInstance.isTarget(_info.el)) { _currentInstance.unmakeTarget(_info.el); } _currentInstance.destroyDraggable(_info.el); _currentInstance.destroyDroppable(_info.el); delete _currentInstance.floatingConnections[_info.id]; delete managedElements[_info.id]; delete offsets[_info.id]; if (_info.el) { _currentInstance.removeElement(_info.el); _info.el._jsPlumb = null; } }; // remove all affected child elements for (var ae = 1; ae < affectedElements.length; ae++) { _one(affectedElements[ae]); } // and always remove the requested one from the dom. _one(info); }; /** * Remove the given element, including cleaning up all endpoints registered for it. * This is exposed in the public API but also used internally by jsPlumb when removing the * element associated with a connection drag. */ this.remove = function (el, doNotRepaint) { var info = _info(el), affectedElements = []; if (info.text) { info.el.parentNode.removeChild(info.el); } else if (info.id) { _currentInstance.batch(function () { _doRemove(info, affectedElements); }, doNotRepaint === true); } return _currentInstance; }; this.empty = function (el, doNotRepaint) { var affectedElements = []; var _one = function(el, dontRemoveFocus) { var info = _info(el); if (info.text) { info.el.parentNode.removeChild(info.el); } else if (info.el) { while(info.el.childNodes.length > 0) { _one(info.el.childNodes[0]); } if (!dontRemoveFocus) { _doRemove(info, affectedElements); } } }; _currentInstance.batch(function() { _one(el, true); }, doNotRepaint === false); return _currentInstance; }; this.reset = function (doNotUnbindInstanceEventListeners) { _currentInstance.silently(function() { _hoverSuspended = false; _currentInstance.removeAllGroups(); _currentInstance.removeGroupManager(); _currentInstance.deleteEveryEndpoint(); if (!doNotUnbindInstanceEventListeners) { _currentInstance.unbind(); } this.targetEndpointDefinitions = {}; this.sourceEndpointDefinitions = {}; connections.length = 0; if (this.doReset) { this.doReset(); } }.bind(this)); }; var _clearObject = function (obj) { if (obj.canvas && obj.canvas.parentNode) { obj.canvas.parentNode.removeChild(obj.canvas); } obj.cleanup(); obj.destroy(); }; this.clear = function () { _currentInstance.select().each(_clearObject); _currentInstance.selectEndpoints().each(_clearObject); endpointsByElement = {}; endpointsByUUID = {}; }; this.setDefaultScope = function (scope) { DEFAULT_SCOPE = scope; return _currentInstance; }; // sets whether or not some element should be currently draggable. this.setDraggable = _setDraggable; this.deriveEndpointAndAnchorSpec = function(type, dontPrependDefault) { var bits = ((dontPrependDefault ? "" : "default ") + type).split(/[\s]/), eps = null, ep = null, a = null, as = null; for (var i = 0; i < bits.length; i++) { var _t = _currentInstance.getType(bits[i], "connection"); if (_t) { if (_t.endpoints) { eps = _t.endpoints; } if (_t.endpoint) { ep = _t.endpoint; } if (_t.anchors) { as = _t.anchors; } if (_t.anchor) { a = _t.anchor; } } } return { endpoints: eps ? eps : [ ep, ep ], anchors: as ? as : [a, a ]}; }; // sets the id of some element, changing whatever we need to to keep track. this.setId = function (el, newId, doNotSetAttribute) { // var id; if (_ju.isString(el)) { id = el; } else { el = this.getElement(el); id = this.getId(el); } var sConns = this.getConnections({source: id, scope: '*'}, true), tConns = this.getConnections({target: id, scope: '*'}, true); newId = "" + newId; if (!doNotSetAttribute) { el = this.getElement(id); this.setAttribute(el, "id", newId); } else { el = this.getElement(newId); } endpointsByElement[newId] = endpointsByElement[id] || []; for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) { endpointsByElement[newId][i].setElementId(newId); endpointsByElement[newId][i].setReferenceElement(el); } delete endpointsByElement[id]; this.sourceEndpointDefinitions[newId] = this.sourceEndpointDefinitions[id]; delete this.sourceEndpointDefinitions[id]; this.targetEndpointDefinitions[newId] = this.targetEndpointDefinitions[id]; delete this.targetEndpointDefinitions[id]; this.anchorManager.changeId(id, newId); var dm = this.getDragManager(); if (dm) { dm.changeId(id, newId); } managedElements[newId] = managedElements[id]; delete managedElements[id]; var _conns = function (list, epIdx, type) { for (var i = 0, ii = list.length; i < ii; i++) { list[i].endpoints[epIdx].setElementId(newId); list[i].endpoints[epIdx].setReferenceElement(el); list[i][type + "Id"] = newId; list[i][type] = el; } }; _conns(sConns, 0, "source"); _conns(tConns, 1, "target"); this.repaint(newId); }; this.setDebugLog = function (debugLog) { log = debugLog; }; this.setSuspendDrawing = function (val, repaintAfterwards) { var curVal = _suspendDrawing; _suspendDrawing = val; if (val) { _suspendedAt = new Date().getTime(); } else { _suspendedAt = null; } if (repaintAfterwards) { this.repaintEverything(); } return curVal; }; // returns whether or not drawing is currently suspended. this.isSuspendDrawing = function () { return _suspendDrawing; }; // return timestamp for when drawing was suspended. this.getSuspendedAt = function () { return _suspendedAt; }; this.batch = function (fn, doNotRepaintAfterwards) { var _wasSuspended = this.isSuspendDrawing(); if (!_wasSuspended) { this.setSuspendDrawing(true); } try { fn(); } catch (e) { _ju.log("Function run while suspended failed", e); } if (!_wasSuspended) { this.setSuspendDrawing(false, !doNotRepaintAfterwards); } }; this.doWhileSuspended = this.batch; this.getCachedData = _getCachedData; this.timestamp = _timestamp; this.show = function (el, changeEndpoints) { _setVisible(el, "block", changeEndpoints); return _currentInstance; }; // TODO: update this method to return the current state. this.toggleVisible = _toggleVisible; this.toggleDraggable = _toggleDraggable; this.addListener = this.bind; var floatingConnections = []; this.registerFloatingConnection = function(info, conn, ep) { floatingConnections[info.id] = conn; // only register for the target endpoint; we will not be dragging the source at any time // before this connection is either discarded or made into a permanent connection. _ju.addToList(endpointsByElement, info.id, ep); }; this.getFloatingConnectionFor = function(id) { return floatingConnections[id]; }; }; _ju.extend(root.jsPlumbInstance, _ju.EventGenerator, { setAttribute: function (el, a, v) { this.setAttribute(el, a, v); }, getAttribute: function (el, a) { return this.getAttribute(root.jsPlumb.getElement(el), a); }, convertToFullOverlaySpec: function(spec) { if (_ju.isString(spec)) { spec = [ spec, { } ]; } spec[1].id = spec[1].id || _ju.uuid(); return spec; }, registerConnectionType: function (id, type) { this._connectionTypes[id] = root.jsPlumb.extend({}, type); if (type.overlays) { var to = {}; for (var i = 0; i < type.overlays.length; i++) { // if a string, convert to object representation so that we can store the typeid on it. // also assign an id. var fo = this.convertToFullOverlaySpec(type.overlays[i]); to[fo[1].id] = fo; } this._connectionTypes[id].overlays = to; } }, registerConnectionTypes: function (types) { for (var i in types) { this.registerConnectionType(i, types[i]); } }, registerEndpointType: function (id, type) { this._endpointTypes[id] = root.jsPlumb.extend({}, type); if (type.overlays) { var to = {}; for (var i = 0; i < type.overlays.length; i++) { // if a string, convert to object representation so that we can store the typeid on it. // also assign an id. var fo = this.convertToFullOverlaySpec(type.overlays[i]); to[fo[1].id] = fo; } this._endpointTypes[id].overlays = to; } }, registerEndpointTypes: function (types) { for (var i in types) { this.registerEndpointType(i, types[i]); } }, getType: function (id, typeDescriptor) { return typeDescriptor === "connection" ? this._connectionTypes[id] : this._endpointTypes[id]; }, setIdChanged: function (oldId, newId) { this.setId(oldId, newId, true); }, // set parent: change the parent for some node and update all the registrations we need to. setParent: function (el, newParent) { var _dom = this.getElement(el), _id = this.getId(_dom), _pdom = this.getElement(newParent), _pid = this.getId(_pdom), dm = this.getDragManager(); _dom.parentNode.removeChild(_dom); _pdom.appendChild(_dom); if (dm) { dm.setParent(_dom, _id, _pdom, _pid); } }, extend: function (o1, o2, names) { var i; if (names) { for (i = 0; i < names.length; i++) { o1[names[i]] = o2[names[i]]; } } else { for (i in o2) { o1[i] = o2[i]; } } return o1; }, floatingConnections: {}, getFloatingAnchorIndex: function (jpc) { return jpc.endpoints[0].isFloating() ? 0 : jpc.endpoints[1].isFloating() ? 1 : -1; } }); // --------------------- static instance + module registration ------------------------------------------- // create static instance and assign to window if window exists. var jsPlumb = new jsPlumbInstance(); // register on 'root' (lets us run on server or browser) root.jsPlumb = jsPlumb; // add 'getInstance' method to static instance jsPlumb.getInstance = function (_defaults, overrideFns) { var j = new jsPlumbInstance(_defaults); if (overrideFns) { for (var ovf in overrideFns) { j[ovf] = overrideFns[ovf]; } } j.init(); return j; }; jsPlumb.each = function (spec, fn) { if (spec == null) { return; } if (typeof spec === "string") { fn(jsPlumb.getElement(spec)); } else if (spec.length != null) { for (var i = 0; i < spec.length; i++) { fn(jsPlumb.getElement(spec[i])); } } else { fn(spec); } // assume it's an element. }; // CommonJS if (typeof exports !== 'undefined') { exports.jsPlumb = jsPlumb; } // --------------------- end static instance + AMD registration ------------------------------------------- }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the base functionality for DOM type adapters. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { var root = this, _ju = root.jsPlumbUtil; var _genLoc = function (prefix, e) { if (e == null) { return [ 0, 0 ]; } var ts = _touches(e), t = _getTouch(ts, 0); return [t[prefix + "X"], t[prefix + "Y"]]; }, _pageLocation = _genLoc.bind(this, "page"), _screenLocation = _genLoc.bind(this, "screen"), _clientLocation = _genLoc.bind(this, "client"), _getTouch = function (touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; }, _touches = function (e) { return e.touches && e.touches.length > 0 ? e.touches : e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches : e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches : [ e ]; }; /** Manages dragging for some instance of jsPlumb. TODO instead of this being accessed directly, it should subscribe to events on the jsPlumb instance: every method in here is called directly by jsPlumb. But what should happen is that we have unpublished events that this listens to. The only trick is getting one of these instantiated with every jsPlumb instance: it needs to have a hook somehow. Basically the general idea is to pull ALL the drag code out (prototype method registrations plus this) into a dedicated drag script), that does not necessarily need to be included. */ var DragManager = function (_currentInstance) { var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {}, // elementids mapped to the draggable to which they belong. _draggablesForElements = {}; /** register some element as draggable. right now the drag init stuff is done elsewhere, and it is possible that will continue to be the case. */ this.register = function (el) { var id = _currentInstance.getId(el), parentOffset; if (!_draggables[id]) { _draggables[id] = el; _dlist.push(el); _delements[id] = {}; } // look for child elements that have endpoints and register them against this draggable. var _oneLevel = function (p) { if (p) { for (var i = 0; i < p.childNodes.length; i++) { if (p.childNodes[i].nodeType !== 3 && p.childNodes[i].nodeType !== 8) { var cEl = jsPlumb.getElement(p.childNodes[i]), cid = _currentInstance.getId(p.childNodes[i], null, true); if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) { if (!parentOffset) { parentOffset = _currentInstance.getOffset(el); } var cOff = _currentInstance.getOffset(cEl); _delements[id][cid] = { id: cid, offset: { left: cOff.left - parentOffset.left, top: cOff.top - parentOffset.top } }; _draggablesForElements[cid] = id; } _oneLevel(p.childNodes[i]); } } } }; _oneLevel(el); }; // refresh the offsets for child elements of this element. this.updateOffsets = function (elId, childOffsetOverrides) { if (elId != null) { childOffsetOverrides = childOffsetOverrides || {}; var domEl = jsPlumb.getElement(elId), id = _currentInstance.getId(domEl), children = _delements[id], parentOffset; if (children) { for (var i in children) { if (children.hasOwnProperty(i)) { var cel = jsPlumb.getElement(i), cOff = childOffsetOverrides[i] || _currentInstance.getOffset(cel); // do not update if we have a value already and we'd just be writing 0,0 if (cel.offsetParent == null && _delements[id][i] != null) { continue; } if (!parentOffset) { parentOffset = _currentInstance.getOffset(domEl); } _delements[id][i] = { id: i, offset: { left: cOff.left - parentOffset.left, top: cOff.top - parentOffset.top } }; _draggablesForElements[i] = id; } } } } }; /** notification that an endpoint was added to the given el. we go up from that el's parent node, looking for a parent that has been registered as a draggable. if we find one, we add this el to that parent's list of elements to update on drag (if it is not there already) */ this.endpointAdded = function (el, id) { id = id || _currentInstance.getId(el); var b = document.body, p = el.parentNode; _elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1; while (p != null && p !== b) { var pid = _currentInstance.getId(p, null, true); if (pid && _draggables[pid]) { var pLoc = _currentInstance.getOffset(p); if (_delements[pid][id] == null) { var cLoc = _currentInstance.getOffset(el); _delements[pid][id] = { id: id, offset: { left: cLoc.left - pLoc.left, top: cLoc.top - pLoc.top } }; _draggablesForElements[id] = pid; } break; } p = p.parentNode; } }; this.endpointDeleted = function (endpoint) { if (_elementsWithEndpoints[endpoint.elementId]) { _elementsWithEndpoints[endpoint.elementId]--; if (_elementsWithEndpoints[endpoint.elementId] <= 0) { for (var i in _delements) { if (_delements.hasOwnProperty(i) && _delements[i]) { delete _delements[i][endpoint.elementId]; delete _draggablesForElements[endpoint.elementId]; } } } } }; this.changeId = function (oldId, newId) { _delements[newId] = _delements[oldId]; _delements[oldId] = {}; _draggablesForElements[newId] = _draggablesForElements[oldId]; _draggablesForElements[oldId] = null; }; this.getElementsForDraggable = function (id) { return _delements[id]; }; this.elementRemoved = function (elementId) { var elId = _draggablesForElements[elementId]; if (elId) { delete _delements[elId][elementId]; delete _draggablesForElements[elementId]; } }; this.reset = function () { _draggables = {}; _dlist = []; _delements = {}; _elementsWithEndpoints = {}; }; // // notification drag ended. We check automatically if need to update some // ancestor's offsets. // this.dragEnded = function (el) { if (el.offsetParent != null) { var id = _currentInstance.getId(el), ancestor = _draggablesForElements[id]; if (ancestor) { this.updateOffsets(ancestor); } } }; this.setParent = function (el, elId, p, pId, currentChildLocation) { var current = _draggablesForElements[elId]; if (!_delements[pId]) { _delements[pId] = {}; } var pLoc = _currentInstance.getOffset(p), cLoc = currentChildLocation || _currentInstance.getOffset(el); if (current && _delements[current]) { delete _delements[current][elId]; } _delements[pId][elId] = { id:elId, offset : { left: cLoc.left - pLoc.left, top: cLoc.top - pLoc.top } }; _draggablesForElements[elId] = pId; }; this.clearParent = function(el, elId) { var current = _draggablesForElements[elId]; if (current) { delete _delements[current][elId]; delete _draggablesForElements[elId]; } }; this.revalidateParent = function(el, elId, childOffset) { var current = _draggablesForElements[elId]; if (current) { var co = {}; co[elId] = childOffset; this.updateOffsets(current, co); _currentInstance.revalidate(current); } }; this.getDragAncestor = function (el) { var de = jsPlumb.getElement(el), id = _currentInstance.getId(de), aid = _draggablesForElements[id]; if (aid) { return jsPlumb.getElement(aid); } else { return null; } }; }; var trim = function (str) { return str == null ? null : (str.replace(/^\s\s*/, '').replace(/\s\s*$/, '')); }, _setClassName = function (el, cn, classList) { cn = trim(cn); if (typeof el.className.baseVal !== "undefined") { el.className.baseVal = cn; } else { el.className = cn; } // recent (i currently have 61.0.3163.100) version of chrome do not update classList when you set the base val // of an svg element's className. in the long run we'd like to move to just using classList anyway try { var cl = el.classList; if (cl != null) { while (cl.length > 0) { cl.remove(cl.item(0)); } for (var i = 0; i < classList.length; i++) { if (classList[i]) { cl.add(classList[i]); } } } } catch(e) { // not fatal jsPlumbUtil.log("JSPLUMB: cannot set class list", e); } }, _getClassName = function (el) { return (typeof el.className.baseVal === "undefined") ? el.className : el.className.baseVal; }, _classManip = function (el, classesToAdd, classesToRemove) { classesToAdd = classesToAdd == null ? [] : _ju.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/); classesToRemove = classesToRemove == null ? [] : _ju.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/); var className = _getClassName(el), curClasses = className.split(/\s+/); var _oneSet = function (add, classes) { for (var i = 0; i < classes.length; i++) { if (add) { if (curClasses.indexOf(classes[i]) === -1) { curClasses.push(classes[i]); } } else { var idx = curClasses.indexOf(classes[i]); if (idx !== -1) { curClasses.splice(idx, 1); } } } }; _oneSet(true, classesToAdd); _oneSet(false, classesToRemove); _setClassName(el, curClasses.join(" "), curClasses); }; root.jsPlumb.extend(root.jsPlumbInstance.prototype, { headless: false, pageLocation: _pageLocation, screenLocation: _screenLocation, clientLocation: _clientLocation, getDragManager:function() { if (this.dragManager == null) { this.dragManager = new DragManager(this); } return this.dragManager; }, // NEVER CALLED IN THE CURRENT JS recalculateOffsets:function(elId) { this.getDragManager().updateOffsets(elId); }, // CONVERTED createElement:function(tag, style, clazz, atts) { return this.createElementNS(null, tag, style, clazz, atts); }, // CONVERTED createElementNS:function(ns, tag, style, clazz, atts) { var e = ns == null ? document.createElement(tag) : document.createElementNS(ns, tag); var i; style = style || {}; for (i in style) { e.style[i] = style[i]; } if (clazz) { e.className = clazz; } atts = atts || {}; for (i in atts) { e.setAttribute(i, "" + atts[i]); } return e; }, // CONVERTED getAttribute: function (el, attName) { return el.getAttribute != null ? el.getAttribute(attName) : null; }, // CONVERTED setAttribute: function (el, a, v) { if (el.setAttribute != null) { el.setAttribute(a, v); } }, // CONVERTED setAttributes: function (el, atts) { for (var i in atts) { if (atts.hasOwnProperty(i)) { el.setAttribute(i, atts[i]); } } }, appendToRoot: function (node) { document.body.appendChild(node); }, getRenderModes: function () { return [ "svg" ]; }, getClass:_getClassName, addClass: function (el, clazz) { jsPlumb.each(el, function (e) { _classManip(e, clazz); }); }, hasClass: function (el, clazz) { el = jsPlumb.getElement(el); if (el.classList) { return el.classList.contains(clazz); } else { return _getClassName(el).indexOf(clazz) !== -1; } }, removeClass: function (el, clazz) { jsPlumb.each(el, function (e) { _classManip(e, null, clazz); }); }, toggleClass:function(el, clazz) { if (jsPlumb.hasClass(el, clazz)) { jsPlumb.removeClass(el, clazz); } else { jsPlumb.addClass(el, clazz); } }, updateClasses: function (el, toAdd, toRemove) { jsPlumb.each(el, function (e) { _classManip(e, toAdd, toRemove); }); }, setClass: function (el, clazz) { if (clazz != null) { jsPlumb.each(el, function (e) { _setClassName(e, clazz, clazz.split(/\s+/)); }); } }, setPosition: function (el, p) { el.style.left = p.left + "px"; el.style.top = p.top + "px"; }, getPosition: function (el) { var _one = function (prop) { var v = el.style[prop]; return v ? v.substring(0, v.length - 2) : 0; }; return { left: _one("left"), top: _one("top") }; }, getStyle:function(el, prop) { if (typeof window.getComputedStyle !== 'undefined') { return getComputedStyle(el, null).getPropertyValue(prop); } else { return el.currentStyle[prop]; } }, getSelector: function (ctx, spec) { var sel = null; if (arguments.length === 1) { sel = ctx.nodeType != null ? ctx : document.querySelectorAll(ctx); } else { sel = ctx.querySelectorAll(spec); } return sel; }, getOffset:function(el, relativeToRoot, container) { el = jsPlumb.getElement(el); container = container || this.getContainer(); var out = { left: el.offsetLeft, top: el.offsetTop }, op = (relativeToRoot || (container != null && (el !== container && el.offsetParent !== container))) ? el.offsetParent : null, _maybeAdjustScroll = function(offsetParent) { if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) { out.left -= offsetParent.scrollLeft; out.top -= offsetParent.scrollTop; } }.bind(this); while (op != null) { out.left += op.offsetLeft; out.top += op.offsetTop; _maybeAdjustScroll(op); op = relativeToRoot ? op.offsetParent : op.offsetParent === container ? null : op.offsetParent; } // if container is scrolled and the element (or its offset parent) is not absolute or fixed, adjust accordingly. if (container != null && !relativeToRoot && (container.scrollTop > 0 || container.scrollLeft > 0)) { var pp = el.offsetParent != null ? this.getStyle(el.offsetParent, "position") : "static", p = this.getStyle(el, "position"); if (p !== "absolute" && p !== "fixed" && pp !== "absolute" && pp !== "fixed") { out.left -= container.scrollLeft; out.top -= container.scrollTop; } } return out; }, // // return x+y proportion of the given element's size corresponding to the location of the given event. // getPositionOnElement: function (evt, el, zoom) { var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 }, body = document.body, docElem = document.documentElement, scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop, scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, pst = 0, psl = 0, top = box.top + scrollTop - clientTop + (pst * zoom), left = box.left + scrollLeft - clientLeft + (psl * zoom), cl = jsPlumb.pageLocation(evt), w = box.width || (el.offsetWidth * zoom), h = box.height || (el.offsetHeight * zoom), x = (cl[0] - left) / w, y = (cl[1] - top) / h; return [ x, y ]; }, /** * Gets the absolute position of some element as read from the left/top properties in its style. * @method getAbsolutePosition * @param {Element} el The element to retrieve the absolute coordinates from. **Note** this is a DOM element, not a selector from the underlying library. * @return {Number[]} [left, top] pixel values. */ getAbsolutePosition: function (el) { var _one = function (s) { var ss = el.style[s]; if (ss) { return parseFloat(ss.substring(0, ss.length - 2)); } }; return [ _one("left"), _one("top") ]; }, /** * Sets the absolute position of some element by setting the left/top properties in its style. * @method setAbsolutePosition * @param {Element} el The element to set the absolute coordinates on. **Note** this is a DOM element, not a selector from the underlying library. * @param {Number[]} xy x and y coordinates * @param {Number[]} [animateFrom] Optional previous xy to animate from. * @param {Object} [animateOptions] Options for the animation. */ setAbsolutePosition: function (el, xy, animateFrom, animateOptions) { if (animateFrom) { this.animate(el, { left: "+=" + (xy[0] - animateFrom[0]), top: "+=" + (xy[1] - animateFrom[1]) }, animateOptions); } else { el.style.left = xy[0] + "px"; el.style.top = xy[1] + "px"; } }, /** * gets the size for the element, in an array : [ width, height ]. */ getSize: function (el) { return [ el.offsetWidth, el.offsetHeight ]; }, getWidth: function (el) { return el.offsetWidth; }, getHeight: function (el) { return el.offsetHeight; }, getRenderMode : function() { return "svg"; } }); }).call(typeof window !== 'undefined' ? window : this); /* * 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; // ------------------------------ BEGIN OverlayCapablejsPlumbUIComponent -------------------------------------------- var _internalLabelOverlayId = "__label", // this is a shortcut helper method to let people add a label as // overlay. _makeLabelOverlay = function (component, params) { var _params = { cssClass: params.cssClass, labelStyle: component.labelStyle, id: _internalLabelOverlayId, component: component, _jsPlumb: component._jsPlumb.instance // TODO not necessary, since the instance can be accessed through the component. }, mergedParams = _jp.extend(_params, params); return new _jp.Overlays[component._jsPlumb.instance.getRenderMode()].Label(mergedParams); }, _processOverlay = function (component, o) { var _newOverlay = null; if (_ju.isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax // there's also a three arg version: // ["Arrow", { width:50 }, {location:0.7}] // which merges the 3rd arg into the 2nd. var type = o[0], // make a copy of the object so as not to mess up anyone else's reference... p = _jp.extend({component: component, _jsPlumb: component._jsPlumb.instance}, o[1]); if (o.length === 3) { _jp.extend(p, o[2]); } _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][type](p); } else if (o.constructor === String) { _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][o]({component: component, _jsPlumb: component._jsPlumb.instance}); } else { _newOverlay = o; } _newOverlay.id = _newOverlay.id || _ju.uuid(); component.cacheTypeItem("overlay", _newOverlay, _newOverlay.id); component._jsPlumb.overlays[_newOverlay.id] = _newOverlay; return _newOverlay; }; _jp.OverlayCapableJsPlumbUIComponent = function (params) { root.jsPlumbUIComponent.apply(this, arguments); this._jsPlumb.overlays = {}; this._jsPlumb.overlayPositions = {}; if (params.label) { this.getDefaultType().overlays[_internalLabelOverlayId] = ["Label", { label: params.label, location: params.labelLocation || this.defaultLabelLocation || 0.5, labelStyle: params.labelStyle || this._jsPlumb.instance.Defaults.LabelStyle, id:_internalLabelOverlayId }]; } this.setListenerComponent = function (c) { if (this._jsPlumb) { for (var i in this._jsPlumb.overlays) { this._jsPlumb.overlays[i].setListenerComponent(c); } } }; }; _jp.OverlayCapableJsPlumbUIComponent.applyType = function (component, t) { if (t.overlays) { // loop through the ones in the type. if already present on the component, // dont remove or re-add. var keep = {}, i; for (i in t.overlays) { var existing = component._jsPlumb.overlays[t.overlays[i][1].id]; if (existing) { // maybe update from data, if there were parameterised values for instance. existing.updateFrom(t.overlays[i][1]); keep[t.overlays[i][1].id] = true; } else { var c = component.getCachedTypeItem("overlay", t.overlays[i][1].id); if (c != null) { c.reattach(component._jsPlumb.instance, component); c.setVisible(true); // maybe update from data, if there were parameterised values for instance. c.updateFrom(t.overlays[i][1]); component._jsPlumb.overlays[c.id] = c; } else { c = component.addOverlay(t.overlays[i], true); } keep[c.id] = true; } } // now loop through the full overlays and remove those that we dont want to keep for (i in component._jsPlumb.overlays) { if (keep[component._jsPlumb.overlays[i].id] == null) { component.removeOverlay(component._jsPlumb.overlays[i].id, true); // remove overlay but dont clean it up. // that would remove event listeners etc; overlays are never discarded by the types stuff, they are // just detached/reattached. } } } }; _ju.extend(_jp.OverlayCapableJsPlumbUIComponent, root.jsPlumbUIComponent, { setHover: function (hover, ignoreAttachedElements) { if (this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) { for (var i in this._jsPlumb.overlays) { this._jsPlumb.overlays[i][hover ? "addClass" : "removeClass"](this._jsPlumb.instance.hoverClass); } } }, addOverlay: function (overlay, doNotRepaint) { var o = _processOverlay(this, overlay); if (!doNotRepaint) { this.repaint(); } return o; }, getOverlay: function (id) { return this._jsPlumb.overlays[id]; }, getOverlays: function () { return this._jsPlumb.overlays; }, hideOverlay: function (id) { var o = this.getOverlay(id); if (o) { o.hide(); } }, hideOverlays: function () { for (var i in this._jsPlumb.overlays) { this._jsPlumb.overlays[i].hide(); } }, showOverlay: function (id) { var o = this.getOverlay(id); if (o) { o.show(); } }, showOverlays: function () { for (var i in this._jsPlumb.overlays) { this._jsPlumb.overlays[i].show(); } }, removeAllOverlays: function (doNotRepaint) { for (var i in this._jsPlumb.overlays) { if (this._jsPlumb.overlays[i].cleanup) { this._jsPlumb.overlays[i].cleanup(); } } this._jsPlumb.overlays = {}; this._jsPlumb.overlayPositions = null; this._jsPlumb.overlayPlacements= {}; if (!doNotRepaint) { this.repaint(); } }, removeOverlay: function (overlayId, dontCleanup) { var o = this._jsPlumb.overlays[overlayId]; if (o) { o.setVisible(false); if (!dontCleanup && o.cleanup) { o.cleanup(); } delete this._jsPlumb.overlays[overlayId]; if (this._jsPlumb.overlayPositions) { delete this._jsPlumb.overlayPositions[overlayId]; } if (this._jsPlumb.overlayPlacements) { delete this._jsPlumb.overlayPlacements[overlayId]; } } }, removeOverlays: function () { for (var i = 0, j = arguments.length; i < j; i++) { this.removeOverlay(arguments[i]); } }, moveParent: function (newParent) { if (this.bgCanvas) { this.bgCanvas.parentNode.removeChild(this.bgCanvas); newParent.appendChild(this.bgCanvas); } if (this.canvas && this.canvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas); newParent.appendChild(this.canvas); for (var i in this._jsPlumb.overlays) { if (this._jsPlumb.overlays[i].isAppendedAtTopLevel) { var el = this._jsPlumb.overlays[i].getElement(); el.parentNode.removeChild(el); newParent.appendChild(el); } } } }, getLabel: function () { var lo = this.getOverlay(_internalLabelOverlayId); return lo != null ? lo.getLabel() : null; }, getLabelOverlay: function () { return this.getOverlay(_internalLabelOverlayId); }, setLabel: function (l) { var lo = this.getOverlay(_internalLabelOverlayId); if (!lo) { var params = l.constructor === String || l.constructor === Function ? { label: l } : l; lo = _makeLabelOverlay(this, params); this._jsPlumb.overlays[_internalLabelOverlayId] = lo; } else { if (l.constructor === String || l.constructor === Function) { lo.setLabel(l); } else { if (l.label) { lo.setLabel(l.label); } if (l.location) { lo.setLocation(l.location); } } } if (!this._jsPlumb.instance.isSuspendDrawing()) { this.repaint(); } }, cleanup: function (force) { for (var i in this._jsPlumb.overlays) { this._jsPlumb.overlays[i].cleanup(force); this._jsPlumb.overlays[i].destroy(force); } if (force) { this._jsPlumb.overlays = {}; this._jsPlumb.overlayPositions = null; } }, setVisible: function (v) { this[v ? "showOverlays" : "hideOverlays"](); }, setAbsoluteOverlayPosition: function (overlay, xy) { this._jsPlumb.overlayPositions[overlay.id] = xy; }, getAbsoluteOverlayPosition: function (overlay) { return this._jsPlumb.overlayPositions ? this._jsPlumb.overlayPositions[overlay.id] : null; }, _clazzManip:function(action, clazz, dontUpdateOverlays) { if (!dontUpdateOverlays) { for (var i in this._jsPlumb.overlays) { this._jsPlumb.overlays[i][action + "Class"](clazz); } } }, addClass:function(clazz, dontUpdateOverlays) { this._clazzManip("add", clazz, dontUpdateOverlays); }, removeClass:function(clazz, dontUpdateOverlays) { this._clazzManip("remove", clazz, dontUpdateOverlays); } }); // ------------------------------ END OverlayCapablejsPlumbUIComponent -------------------------------------------- }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the code for Endpoints. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; // create the drag handler for a connection var _makeConnectionDragHandler = function (endpoint, placeholder, _jsPlumb) { var stopped = false; return { drag: function () { if (stopped) { stopped = false; return true; } if (placeholder.element) { var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom()); if (_ui != null) { _jsPlumb.setPosition(placeholder.element, _ui); } _jsPlumb.repaint(placeholder.element, _ui); // always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint // to be repainted, so static anchors need to be told (or the endpoint gets dragged around) endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint})}); } }, stopDrag: function () { stopped = true; } }; }; // creates a placeholder div for dragging purposes, adds it, and pre-computes its offset. var _makeDraggablePlaceholder = function (placeholder, _jsPlumb, ipco, ips) { var n = _jsPlumb.createElement("div", { position : "absolute" }); _jsPlumb.appendElement(n); var id = _jsPlumb.getId(n); _jsPlumb.setPosition(n, ipco); n.style.width = ips[0] + "px"; n.style.height = ips[1] + "px"; _jsPlumb.manage(id, n, true); // TRANSIENT MANAGE // create and assign an id, and initialize the offset. placeholder.id = id; placeholder.element = n; }; // create a floating endpoint (for drag connections) var _makeFloatingEndpoint = function (paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint, scope) { var floatingAnchor = new _jp.FloatingAnchor({ reference: referenceAnchor, referenceCanvas: referenceCanvas, jsPlumbInstance: _jsPlumb }); //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not // adding the floating endpoint as a droppable. that makes more sense anyway! // TRANSIENT MANAGE return _newEndpoint({ paintStyle: paintStyle, endpoint: endpoint, anchor: floatingAnchor, source: sourceElement, scope: scope }); }; var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays", "connector", "connectionType", "connectorClass", "connectorHoverClass" ]; // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null, // or no connection to it is found, we return the first connection in our list. var findConnectionToUseForDynamicAnchor = function (ep, elementWithPrecedence) { var idx = 0; if (elementWithPrecedence != null) { for (var i = 0; i < ep.connections.length; i++) { if (ep.connections[i].sourceId === elementWithPrecedence || ep.connections[i].targetId === elementWithPrecedence) { idx = i; break; } } } return ep.connections[idx]; }; _jp.Endpoint = function (params) { var _jsPlumb = params._jsPlumb, _newConnection = params.newConnection, _newEndpoint = params.newEndpoint; this.idPrefix = "_jsplumb_e_"; this.defaultLabelLocation = [ 0.5, 0.5 ]; this.defaultOverlayKeys = ["Overlays", "EndpointOverlays"]; _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments); // TYPE this.appendToDefaultType({ connectionType:params.connectionType, maxConnections: params.maxConnections == null ? this._jsPlumb.instance.Defaults.MaxConnections : params.maxConnections, // maximum number of connections this endpoint can be the source of., paintStyle: params.endpointStyle || params.paintStyle || params.style || this._jsPlumb.instance.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle, hoverPaintStyle: params.endpointHoverStyle || params.hoverPaintStyle || this._jsPlumb.instance.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle, connectorStyle: params.connectorStyle, connectorHoverStyle: params.connectorHoverStyle, connectorClass: params.connectorClass, connectorHoverClass: params.connectorHoverClass, connectorOverlays: params.connectorOverlays, connector: params.connector, connectorTooltip: params.connectorTooltip }); // END TYPE this._jsPlumb.enabled = !(params.enabled === false); this._jsPlumb.visible = true; this.element = _jp.getElement(params.source); this._jsPlumb.uuid = params.uuid; this._jsPlumb.floatingEndpoint = null; var inPlaceCopy = null; if (this._jsPlumb.uuid) { params.endpointsByUUID[this._jsPlumb.uuid] = this; } this.elementId = params.elementId; this.dragProxy = params.dragProxy; this._jsPlumb.connectionCost = params.connectionCost; this._jsPlumb.connectionsDirected = params.connectionsDirected; this._jsPlumb.currentAnchorClass = ""; this._jsPlumb.events = {}; var deleteOnEmpty = params.deleteOnEmpty === true; this.setDeleteOnEmpty = function(d) { deleteOnEmpty = d; }; var _updateAnchorClass = function () { // stash old, get new var oldAnchorClass = _jsPlumb.endpointAnchorClassPrefix + "-" + this._jsPlumb.currentAnchorClass; this._jsPlumb.currentAnchorClass = this.anchor.getCssClass(); var anchorClass = _jsPlumb.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : ""); this.removeClass(oldAnchorClass); this.addClass(anchorClass); // add and remove at the same time to reduce the number of reflows. _jp.updateClasses(this.element, anchorClass, oldAnchorClass); }.bind(this); this.prepareAnchor = function(anchorParams) { var a = this._jsPlumb.instance.makeAnchor(anchorParams, this.elementId, _jsPlumb); a.bind("anchorChanged", function (currentAnchor) { this.fire("anchorChanged", {endpoint: this, anchor: currentAnchor}); _updateAnchorClass(); }.bind(this)); return a; }; this.setPreparedAnchor = function(anchor, doNotRepaint) { this._jsPlumb.instance.continuousAnchorFactory.clear(this.elementId); this.anchor = anchor; _updateAnchorClass(); if (!doNotRepaint) { this._jsPlumb.instance.repaint(this.elementId); } return this; }; this.setAnchor = function (anchorParams, doNotRepaint) { var a = this.prepareAnchor(anchorParams); this.setPreparedAnchor(a, doNotRepaint); return this; }; var internalHover = function (state) { if (this.connections.length > 0) { for (var i = 0; i < this.connections.length; i++) { this.connections[i].setHover(state, false); } } else { this.setHover(state); } }.bind(this); this.bind("mouseover", function () { internalHover(true); }); this.bind("mouseout", function () { internalHover(false); }); // ANCHOR MANAGER if (!params._transient) { // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted. this._jsPlumb.instance.anchorManager.add(this, this.elementId); } this.prepareEndpoint = function(ep, typeId) { var _e = function (t, p) { var rm = _jsPlumb.getRenderMode(); if (_jp.Endpoints[rm][t]) { return new _jp.Endpoints[rm][t](p); } if (!_jsPlumb.Defaults.DoNotThrowErrors) { throw { msg: "jsPlumb: unknown endpoint type '" + t + "'" }; } }; var endpointArgs = { _jsPlumb: this._jsPlumb.instance, cssClass: params.cssClass, container: params.container, tooltip: params.tooltip, connectorTooltip: params.connectorTooltip, endpoint: this }; var endpoint; if (_ju.isString(ep)) { endpoint = _e(ep, endpointArgs); } else if (_ju.isArray(ep)) { endpointArgs = _ju.merge(ep[1], endpointArgs); endpoint = _e(ep[0], endpointArgs); } else { endpoint = ep.clone(); } // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned, // and the clone is left in its place while the original one goes off on a magical journey. // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by // the whole world. //var argsForClone = jsPlumb.extend({}, endpointArgs); endpoint.clone = function () { // TODO this, and the code above, can be refactored to be more dry. if (_ju.isString(ep)) { return _e(ep, endpointArgs); } else if (_ju.isArray(ep)) { endpointArgs = _ju.merge(ep[1], endpointArgs); return _e(ep[0], endpointArgs); } }.bind(this); endpoint.typeId = typeId; return endpoint; }; this.setEndpoint = function(ep, doNotRepaint) { var _ep = this.prepareEndpoint(ep); this.setPreparedEndpoint(_ep, true); }; this.setPreparedEndpoint = function (ep, doNotRepaint) { if (this.endpoint != null) { this.endpoint.cleanup(); this.endpoint.destroy(); } this.endpoint = ep; this.type = this.endpoint.type; this.canvas = this.endpoint.canvas; }; _jp.extend(this, params, typeParameters); this.isSource = params.isSource || false; this.isTemporarySource = params.isTemporarySource || false; this.isTarget = params.isTarget || false; this.connections = params.connections || []; this.connectorPointerEvents = params["connector-pointer-events"]; this.scope = params.scope || _jsPlumb.getDefaultScope(); this.timestamp = null; this.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections; this.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable; if (params.connectionsDetachable === false || params.detachable === false) { this.connectionsDetachable = false; } this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false; if (params.onMaxConnections) { this.bind("maxConnections", params.onMaxConnections); } // // add a connection. not part of public API. // this.addConnection = function (connection) { this.connections.push(connection); this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); }; this.detachFromConnection = function (connection, idx, doNotCleanup) { idx = idx == null ? this.connections.indexOf(connection) : idx; if (idx >= 0) { this.connections.splice(idx, 1); this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass); this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass); } if (!doNotCleanup && deleteOnEmpty && this.connections.length === 0) { _jsPlumb.deleteObject({ endpoint: this, fireEvent: false, deleteAttachedObjects: doNotCleanup !== true }); } }; this.deleteEveryConnection = function(params) { var c = this.connections.length; for (var i = 0; i < c; i++) { _jsPlumb.deleteConnection(this.connections[0], params); } }; this.detachFrom = function (targetEndpoint, fireEvent, originalEvent) { var c = []; for (var i = 0; i < this.connections.length; i++) { if (this.connections[i].endpoints[1] === targetEndpoint || this.connections[i].endpoints[0] === targetEndpoint) { c.push(this.connections[i]); } } for (var j = 0, count = c.length; j < count; j++) { _jsPlumb.deleteConnection(c[0]); } return this; }; this.getElement = function () { return this.element; }; this.setElement = function (el) { var parentId = this._jsPlumb.instance.getId(el), curId = this.elementId; // remove the endpoint from the list for the current endpoint's element _ju.removeWithFunction(params.endpointsByElement[this.elementId], function (e) { return e.id === this.id; }.bind(this)); this.element = _jp.getElement(el); this.elementId = _jsPlumb.getId(this.element); _jsPlumb.anchorManager.rehomeEndpoint(this, curId, this.element); _jsPlumb.dragManager.endpointAdded(this.element); _ju.addToList(params.endpointsByElement, parentId, this); return this; }; /** * private but must be exposed. */ this.makeInPlaceCopy = function () { var loc = this.anchor.getCurrentLocation({element: this}), o = this.anchor.getOrientation(this), acc = this.anchor.getCssClass(), inPlaceAnchor = { bind: function () { }, compute: function () { return [ loc[0], loc[1] ]; }, getCurrentLocation: function () { return [ loc[0], loc[1] ]; }, getOrientation: function () { return o; }, getCssClass: function () { return acc; } }; return _newEndpoint({ dropOptions: params.dropOptions, anchor: inPlaceAnchor, source: this.element, paintStyle: this.getPaintStyle(), endpoint: params.hideOnDrag ? "Blank" : this.endpoint, _transient: true, scope: this.scope, reference:this }); }; /** * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can. */ this.connectorSelector = function () { return this.connections[0]; }; this.setStyle = this.setPaintStyle; this.paint = function (params) { params = params || {}; var timestamp = params.timestamp, recalc = !(params.recalc === false); if (!timestamp || this.timestamp !== timestamp) { var info = _jsPlumb.updateOffset({ elId: this.elementId, timestamp: timestamp }); var xy = params.offset ? params.offset.o : info.o; if (xy != null) { var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle; if (ap == null) { var wh = params.dimensions || info.s, anchorParams = { xy: [ xy.left, xy.top ], wh: wh, element: this, timestamp: timestamp }; if (recalc && this.anchor.isDynamic && this.connections.length > 0) { var c = findConnectionToUseForDynamicAnchor(this, params.elementWithPrecedence), oIdx = c.endpoints[0] === this ? 1 : 0, oId = oIdx === 0 ? c.sourceId : c.targetId, oInfo = _jsPlumb.getCachedData(oId), oOffset = oInfo.o, oWH = oInfo.s; anchorParams.index = oIdx === 0 ? 1 : 0; anchorParams.connection = c; anchorParams.txy = [ oOffset.left, oOffset.top ]; anchorParams.twh = oWH; anchorParams.tElement = c.endpoints[oIdx]; } else if (this.connections.length > 0) { anchorParams.connection = this.connections[0]; } ap = this.anchor.compute(anchorParams); } this.endpoint.compute(ap, this.anchor.getOrientation(this), this._jsPlumb.paintStyleInUse, connectorPaintStyle || this.paintStyleInUse); this.endpoint.paint(this._jsPlumb.paintStyleInUse, this.anchor); this.timestamp = timestamp; // paint overlays for (var i in this._jsPlumb.overlays) { if (this._jsPlumb.overlays.hasOwnProperty(i)) { var o = this._jsPlumb.overlays[i]; if (o.isVisible()) { this._jsPlumb.overlayPlacements[i] = o.draw(this.endpoint, this._jsPlumb.paintStyleInUse); o.paint(this._jsPlumb.overlayPlacements[i]); } } } } } }; this.getTypeDescriptor = function () { return "endpoint"; }; this.isVisible = function () { return this._jsPlumb.visible; }; this.repaint = this.paint; var draggingInitialised = false; this.initDraggable = function () { // is this a connection source? we make it draggable and have the // drag listener maintain a connection with a floating endpoint. if (!draggingInitialised && _jp.isDragSupported(this.element)) { var placeholderInfo = { id: null, element: null }, jpc = null, existingJpc = false, existingJpcParams = null, _dragHandler = _makeConnectionDragHandler(this, placeholderInfo, _jsPlumb), dragOptions = params.dragOptions || {}, defaultOpts = {}, startEvent = _jp.dragEvents.start, stopEvent = _jp.dragEvents.stop, dragEvent = _jp.dragEvents.drag, beforeStartEvent = _jp.dragEvents.beforeStart, payload; // respond to beforeStart from katavorio; this will have, optionally, a payload of attribute values // that were placed there by the makeSource mousedown listener. var beforeStart = function(beforeStartParams) { payload = beforeStartParams.e.payload || {}; }; var start = function (startParams) { // ------------- first, get a connection to drag. this may be null, in which case we are dragging a new one. jpc = this.connectorSelector(); // -------------------------------- now a bunch of tests about whether or not to proceed ------------------------- var _continue = true; // if not enabled, return if (!this.isEnabled()) { _continue = false; } // if no connection and we're not a source - or temporarily a source, as is the case with makeSource - return. if (jpc == null && !this.isSource && !this.isTemporarySource) { _continue = false; } // otherwise if we're full and not allowed to drag, also return false. if (this.isSource && this.isFull() && !(jpc != null && this.dragAllowedWhenFull)) { _continue = false; } // if the connection was setup as not detachable or one of its endpoints // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable // is set to false... if (jpc != null && !jpc.isDetachable(this)) { // .. and the endpoint is full if (this.isFull()) { _continue = false; } else { // otherwise, if not full, set the connection to null, and we will now proceed // to drag a new connection. jpc = null; } } var beforeDrag = _jsPlumb.checkCondition(jpc == null ? "beforeDrag" : "beforeStartDetach", { endpoint:this, source:this.element, sourceId:this.elementId, connection:jpc }); if (beforeDrag === false) { _continue = false; } // else we might have been given some data. we'll pass it in to a new connection as 'data'. // here we also merge in the optional payload we were given on mousedown. else if (typeof beforeDrag === "object") { _jp.extend(beforeDrag, payload || {}); } else { // or if no beforeDrag data, maybe use the payload on its own. beforeDrag = payload || {}; } if (_continue === false) { // this is for mootools and yui. returning false from this causes jquery to stop drag. // the events are wrapped in both mootools and yui anyway, but i don't think returning // false from the start callback would stop a drag. if (_jsPlumb.stopDrag) { _jsPlumb.stopDrag(this.canvas); } _dragHandler.stopDrag(); return false; } // --------------------------------------------------------------------------------------------------------------------- // ok to proceed. // clear hover for all connections for this endpoint before continuing. for (var i = 0; i < this.connections.length; i++) { this.connections[i].setHover(false); } this.addClass("endpointDrag"); _jsPlumb.setConnectionBeingDragged(true); // if we're not full but there was a connection, make it null. we'll create a new one. if (jpc && !this.isFull() && this.isSource) { jpc = null; } _jsPlumb.updateOffset({ elId: this.elementId }); // ---------------- make the element we will drag around, and position it ----------------------------- var ipco = this._jsPlumb.instance.getOffset(this.canvas), canvasElement = this.canvas, ips = this._jsPlumb.instance.getSize(this.canvas); _makeDraggablePlaceholder(placeholderInfo, _jsPlumb, ipco, ips); // store the id of the dragging div and the source element. the drop function will pick these up. _jsPlumb.setAttributes(this.canvas, { "dragId": placeholderInfo.id, "elId": this.elementId }); // ------------------- create an endpoint that will be our floating endpoint ------------------------------------ var endpointToFloat = this.dragProxy || this.endpoint; if (this.dragProxy == null && this.connectionType != null) { var aae = this._jsPlumb.instance.deriveEndpointAndAnchorSpec(this.connectionType); if (aae.endpoints[1]) { endpointToFloat = aae.endpoints[1]; } } var centerAnchor = this._jsPlumb.instance.makeAnchor("Center"); centerAnchor.isFloating = true; this._jsPlumb.floatingEndpoint = _makeFloatingEndpoint(this.getPaintStyle(), centerAnchor, endpointToFloat, this.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint, this.scope); var _savedAnchor = this._jsPlumb.floatingEndpoint.anchor; if (jpc == null) { this.setHover(false, false); // create a connection. one end is this endpoint, the other is a floating endpoint. jpc = _newConnection({ sourceEndpoint: this, targetEndpoint: this._jsPlumb.floatingEndpoint, source: this.element, // for makeSource with parent option. ensure source element is represented correctly. target: placeholderInfo.element, anchors: [ this.anchor, this._jsPlumb.floatingEndpoint.anchor ], paintStyle: params.connectorStyle, // this can be null. Connection will use the default. hoverPaintStyle: params.connectorHoverStyle, connector: params.connector, // this can also be null. Connection will use the default. overlays: params.connectorOverlays, type: this.connectionType, cssClass: this.connectorClass, hoverClass: this.connectorHoverClass, scope:params.scope, data:beforeDrag }); jpc.pending = true; jpc.addClass(_jsPlumb.draggingClass); this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass); this._jsPlumb.floatingEndpoint.anchor = _savedAnchor; // fire an event that informs that a connection is being dragged _jsPlumb.fire("connectionDrag", jpc); // register the new connection on the drag manager. This connection, at this point, is 'pending', // and has as its target a temporary element (the 'placeholder'). If the connection subsequently // becomes established, the anchor manager is informed that the target of the connection has // changed. _jsPlumb.anchorManager.newConnection(jpc); } else { existingJpc = true; jpc.setHover(false); // new anchor idx var anchorIdx = jpc.endpoints[0].id === this.id ? 0 : 1; this.detachFromConnection(jpc, null, true); // detach from the connection while dragging is occurring. but dont cleanup automatically. // store the original scope (issue 57) var dragScope = _jsPlumb.getDragScope(canvasElement); _jsPlumb.setAttribute(this.canvas, "originalScope", dragScope); // fire an event that informs that a connection is being dragged. we do this before // replacing the original target with the floating element info. _jsPlumb.fire("connectionDrag", jpc); // now we replace ourselves with the temporary div we created above: if (anchorIdx === 0) { existingJpcParams = [ jpc.source, jpc.sourceId, canvasElement, dragScope ]; _jsPlumb.anchorManager.sourceChanged(jpc.endpoints[anchorIdx].elementId, placeholderInfo.id, jpc, placeholderInfo.element); } else { existingJpcParams = [ jpc.target, jpc.targetId, canvasElement, dragScope ]; jpc.target = placeholderInfo.element; jpc.targetId = placeholderInfo.id; _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.endpoints[anchorIdx].elementId, jpc.targetId, jpc); } // store the original endpoint and assign the new floating endpoint for the drag. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx]; // PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39) jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement(); jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId; jpc.suspendedElementType = anchorIdx === 0 ? "source" : "target"; jpc.suspendedEndpoint.setHover(false); this._jsPlumb.floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint; jpc.endpoints[anchorIdx] = this._jsPlumb.floatingEndpoint; jpc.addClass(_jsPlumb.draggingClass); this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass); } _jsPlumb.registerFloatingConnection(placeholderInfo, jpc, this._jsPlumb.floatingEndpoint); // // register it and register connection on it. // _jsPlumb.floatingConnections[placeholderInfo.id] = jpc; // // // only register for the target endpoint; we will not be dragging the source at any time // // before this connection is either discarded or made into a permanent connection. // _ju.addToList(params.endpointsByElement, placeholderInfo.id, this._jsPlumb.floatingEndpoint); // tell jsplumb about it _jsPlumb.currentlyDragging = true; }.bind(this); var stop = function () { _jsPlumb.setConnectionBeingDragged(false); if (jpc && jpc.endpoints != null) { // get the actual drop event (decode from library args to stop function) var originalEvent = _jsPlumb.getDropEvent(arguments); // unlock the other endpoint (if it is dynamic, it would have been locked at drag start) var idx = _jsPlumb.getFloatingAnchorIndex(jpc); jpc.endpoints[idx === 0 ? 1 : 0].anchor.unlock(); // TODO: Dont want to know about css classes inside jsplumb, ideally. jpc.removeClass(_jsPlumb.draggingClass); // if we have the floating endpoint then the connection has not been dropped // on another endpoint. If it is a new connection we throw it away. If it is an // existing connection we check to see if we should reattach it, throwing it away // if not. if (this._jsPlumb && (jpc.deleteConnectionNow || jpc.endpoints[idx] === this._jsPlumb.floatingEndpoint)) { // 6a. if the connection was an existing one... if (existingJpc && jpc.suspendedEndpoint) { // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the // floating endpoint has been replaced. if (idx === 0) { jpc.floatingElement = jpc.source; jpc.floatingId = jpc.sourceId; jpc.floatingEndpoint = jpc.endpoints[0]; jpc.floatingIndex = 0; jpc.source = existingJpcParams[0]; jpc.sourceId = existingJpcParams[1]; } else { // keep a copy of the floating element; the anchor manager will want to clean up. jpc.floatingElement = jpc.target; jpc.floatingId = jpc.targetId; jpc.floatingEndpoint = jpc.endpoints[1]; jpc.floatingIndex = 1; jpc.target = existingJpcParams[0]; jpc.targetId = existingJpcParams[1]; } var fe = this._jsPlumb.floatingEndpoint; // store for later removal. // restore the original scope (issue 57) _jsPlumb.setDragScope(existingJpcParams[2], existingJpcParams[3]); jpc.endpoints[idx] = jpc.suspendedEndpoint; // if the connection should be reattached, or the other endpoint refuses detach, then // reset the connection to its original state if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !_jsPlumb.deleteConnection(jpc, {originalEvent: originalEvent})) { jpc.setHover(false); jpc._forceDetach = null; jpc._forceReattach = null; this._jsPlumb.floatingEndpoint.detachFromConnection(jpc); jpc.suspendedEndpoint.addConnection(jpc); // TODO this code is duplicated in lots of places...and there is nothing external // in the code; it all refers to the connection itself. we could add a // `checkSanity(connection)` method to anchorManager that did this. if (idx === 1) { _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc); } else { _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source); } _jsPlumb.repaint(existingJpcParams[1]); } else { _jsPlumb.deleteObject({endpoint: fe}); } } } // makeTargets sets this flag, to tell us we have been replaced and should delete this object. if (this.deleteAfterDragStop) { _jsPlumb.deleteObject({endpoint: this}); } else { if (this._jsPlumb) { this.paint({recalc: false}); } } // although the connection is no longer valid, there are use cases where this is useful. _jsPlumb.fire("connectionDragStop", jpc, originalEvent); // fire this event to give people more fine-grained control (connectionDragStop fires a lot) if (jpc.pending) { _jsPlumb.fire("connectionAborted", jpc, originalEvent); } // tell jsplumb that dragging is finished. _jsPlumb.currentlyDragging = false; jpc.suspendedElement = null; jpc.suspendedEndpoint = null; jpc = null; } // if no endpoints, jpc already cleaned up. but still we want to ensure we're reset properly. // remove the element associated with the floating endpoint // (and its associated floating endpoint and visual artefacts) if (placeholderInfo && placeholderInfo.element) { _jsPlumb.remove(placeholderInfo.element, false, false); } // remove the inplace copy if (inPlaceCopy) { _jsPlumb.deleteObject({endpoint: inPlaceCopy}); } if (this._jsPlumb) { // make our canvas visible (TODO: hand off to library; we should not know about DOM) this.canvas.style.visibility = "visible"; // unlock our anchor this.anchor.unlock(); // clear floating anchor. this._jsPlumb.floatingEndpoint = null; } }.bind(this); dragOptions = _jp.extend(defaultOpts, dragOptions); dragOptions.scope = this.scope || dragOptions.scope; dragOptions[beforeStartEvent] = _ju.wrap(dragOptions[beforeStartEvent], beforeStart, false); dragOptions[startEvent] = _ju.wrap(dragOptions[startEvent], start, false); // extracted drag handler function so can be used by makeSource dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], _dragHandler.drag); dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], stop); dragOptions.multipleDrop = false; dragOptions.canDrag = function () { return this.isSource || this.isTemporarySource || (this.connections.length > 0 && this.connectionsDetachable !== false); }.bind(this); _jsPlumb.initDraggable(this.canvas, dragOptions, "internal"); this.canvas._jsPlumbRelatedElement = this.element; draggingInitialised = true; } }; var ep = params.endpoint || this._jsPlumb.instance.Defaults.Endpoint || _jp.Defaults.Endpoint; this.setEndpoint(ep, true); var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top"); this.setAnchor(anchorParamsToUse, true); // finally, set type if it was provided var type = [ "default", (params.type || "")].join(" "); this.addType(type, params.data, true); this.canvas = this.endpoint.canvas; this.canvas._jsPlumb = this; this.initDraggable(); // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections // back onto the endpoint you detached it from. var _initDropTarget = function (canvas, isTransient, endpoint, referenceEndpoint) { if (_jp.isDropSupported(this.element)) { var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || _jp.Defaults.DropOptions; dropOptions = _jp.extend({}, dropOptions); dropOptions.scope = dropOptions.scope || this.scope; var dropEvent = _jp.dragEvents.drop, overEvent = _jp.dragEvents.over, outEvent = _jp.dragEvents.out, _ep = this, drop = _jsPlumb.EndpointDropHandler({ getEndpoint: function () { return _ep; }, jsPlumb: _jsPlumb, enabled: function () { return endpoint != null ? endpoint.isEnabled() : true; }, isFull: function () { return endpoint.isFull(); }, element: this.element, elementId: this.elementId, isSource: this.isSource, isTarget: this.isTarget, addClass: function (clazz) { _ep.addClass(clazz); }, removeClass: function (clazz) { _ep.removeClass(clazz); }, isDropAllowed: function () { return _ep.isDropAllowed.apply(_ep, arguments); }, reference:referenceEndpoint, isRedrop:function(jpc, dhParams) { return jpc.suspendedEndpoint && dhParams.reference && (jpc.suspendedEndpoint.id === dhParams.reference.id); } }); dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], drop, true); dropOptions[overEvent] = _ju.wrap(dropOptions[overEvent], function () { var draggable = _jp.getDragObject(arguments), id = _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"), _jpc = _jsPlumb.getFloatingConnectionFor(id);//_jsPlumb.floatingConnections[id]; if (_jpc != null) { var idx = _jsPlumb.getFloatingAnchorIndex(_jpc); // here we should fire the 'over' event if we are a target and this is a new connection, // or we are the same as the floating endpoint. var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id); if (_cont) { var bb = _jsPlumb.checkCondition("checkDropAllowed", { sourceEndpoint: _jpc.endpoints[idx], targetEndpoint: this, connection: _jpc }); this[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass); this[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass); _jpc.endpoints[idx].anchor.over(this.anchor, this); } } }.bind(this)); dropOptions[outEvent] = _ju.wrap(dropOptions[outEvent], function () { var draggable = _jp.getDragObject(arguments), id = draggable == null ? null : _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"), _jpc = id ? _jsPlumb.getFloatingConnectionFor(id) : null; if (_jpc != null) { var idx = _jsPlumb.getFloatingAnchorIndex(_jpc); var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id); if (_cont) { this.removeClass(_jsPlumb.endpointDropAllowedClass); this.removeClass(_jsPlumb.endpointDropForbiddenClass); _jpc.endpoints[idx].anchor.out(); } } }.bind(this)); _jsPlumb.initDroppable(canvas, dropOptions, "internal", isTransient); } }.bind(this); // Initialise the endpoint's canvas as a drop target. The drop handler will take care of the logic of whether // something can actually be dropped. if (!this.anchor.isFloating) { _initDropTarget(this.canvas, !(params._transient || this.anchor.isFloating), this, params.reference); } return this; }; _ju.extend(_jp.Endpoint, _jp.OverlayCapableJsPlumbUIComponent, { setVisible: function (v, doNotChangeConnections, doNotNotifyOtherEndpoint) { this._jsPlumb.visible = v; if (this.canvas) { this.canvas.style.display = v ? "block" : "none"; } this[v ? "showOverlays" : "hideOverlays"](); if (!doNotChangeConnections) { for (var i = 0; i < this.connections.length; i++) { this.connections[i].setVisible(v); if (!doNotNotifyOtherEndpoint) { var oIdx = this === this.connections[i].endpoints[0] ? 1 : 0; // only change the other endpoint if this is its only connection. if (this.connections[i].endpoints[oIdx].connections.length === 1) { this.connections[i].endpoints[oIdx].setVisible(v, true, true); } } } } }, getAttachedElements: function () { return this.connections; }, applyType: function (t, doNotRepaint) { this.setPaintStyle(t.endpointStyle || t.paintStyle, doNotRepaint); this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle, doNotRepaint); if (t.maxConnections != null) { this._jsPlumb.maxConnections = t.maxConnections; } if (t.scope) { this.scope = t.scope; } _jp.extend(this, t, typeParameters); if (t.cssClass != null && this.canvas) { this._jsPlumb.instance.addClass(this.canvas, t.cssClass); } _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t); }, isEnabled: function () { return this._jsPlumb.enabled; }, setEnabled: function (e) { this._jsPlumb.enabled = e; }, cleanup: function () { var anchorClass = this._jsPlumb.instance.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : ""); _jp.removeClass(this.element, anchorClass); this.anchor = null; this.endpoint.cleanup(true); this.endpoint.destroy(); this.endpoint = null; // drag/drop this._jsPlumb.instance.destroyDraggable(this.canvas, "internal"); this._jsPlumb.instance.destroyDroppable(this.canvas, "internal"); }, setHover: function (h) { if (this.endpoint && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) { this.endpoint.setHover(h); } }, isFull: function () { return this._jsPlumb.maxConnections === 0 ? true : !(this.isFloating() || this._jsPlumb.maxConnections < 0 || this.connections.length < this._jsPlumb.maxConnections); }, /** * private but needs to be exposed. */ isFloating: function () { return this.anchor != null && this.anchor.isFloating; }, isConnectedTo: function (endpoint) { var found = false; if (endpoint) { for (var i = 0; i < this.connections.length; i++) { if (this.connections[i].endpoints[1] === endpoint || this.connections[i].endpoints[0] === endpoint) { found = true; break; } } } return found; }, getConnectionCost: function () { return this._jsPlumb.connectionCost; }, setConnectionCost: function (c) { this._jsPlumb.connectionCost = c; }, areConnectionsDirected: function () { return this._jsPlumb.connectionsDirected; }, setConnectionsDirected: function (b) { this._jsPlumb.connectionsDirected = b; }, setElementId: function (_elId) { this.elementId = _elId; this.anchor.elementId = _elId; }, setReferenceElement: function (_el) { this.element = _jp.getElement(_el); }, setDragAllowedWhenFull: function (allowed) { this.dragAllowedWhenFull = allowed; }, equals: function (endpoint) { return this.anchor.equals(endpoint.anchor); }, getUuid: function () { return this._jsPlumb.uuid; }, computeAnchor: function (params) { return this.anchor.compute(params); } }); root.jsPlumbInstance.prototype.EndpointDropHandler = function (dhParams) { return function (e) { var _jsPlumb = dhParams.jsPlumb; // remove the classes that are added dynamically. drop is neither forbidden nor allowed now that // the drop is finishing. dhParams.removeClass(_jsPlumb.endpointDropAllowedClass); dhParams.removeClass(_jsPlumb.endpointDropForbiddenClass); var originalEvent = _jsPlumb.getDropEvent(arguments), draggable = _jsPlumb.getDragObject(arguments), id = _jsPlumb.getAttribute(draggable, "dragId"), elId = _jsPlumb.getAttribute(draggable, "elId"), scope = _jsPlumb.getAttribute(draggable, "originalScope"), jpc = _jsPlumb.getFloatingConnectionFor(id); // if no active connection, bail. if (jpc == null) { return; } // calculate if this is an existing connection. var existingConnection = jpc.suspendedEndpoint != null; // if suspended endpoint exists but has been cleaned up, bail. This means it's an existing connection // that has been detached and will shortly be discarded. if (existingConnection && jpc.suspendedEndpoint._jsPlumb == null) { return; } // get the drop endpoint. for a normal connection this is just the one that would replace the currently // floating endpoint. for a makeTarget this is a new endpoint that is created on drop. But we leave that to // the handler to figure out. var _ep = dhParams.getEndpoint(jpc); // If we're not given an endpoint to use, bail. if (_ep == null) { return; } // if this is a drop back where the connection came from, mark it force reattach and // return; the stop handler will reattach. without firing an event. if (dhParams.isRedrop(jpc, dhParams)) { jpc._forceReattach = true; jpc.setHover(false); if (dhParams.maybeCleanup) { dhParams.maybeCleanup(_ep); } return; } // ensure we dont bother trying to drop sources on non-source eps, and same for target. var idx = _jsPlumb.getFloatingAnchorIndex(jpc); if ((idx === 0 && !dhParams.isSource)|| (idx === 1 && !dhParams.isTarget)){ if (dhParams.maybeCleanup) { dhParams.maybeCleanup(_ep); } return; } if (dhParams.onDrop) { dhParams.onDrop(jpc); } // restore the original scope if necessary (issue 57) if (scope) { _jsPlumb.setDragScope(draggable, scope); } // if the target of the drop is full, fire an event (we abort below) // makeTarget: keep. var isFull = dhParams.isFull(e); if (isFull) { _ep.fire("maxConnections", { endpoint: this, connection: jpc, maxConnections: _ep._jsPlumb.maxConnections }, originalEvent); } // // if endpoint enabled, not full, and matches the index of the floating endpoint... if (!isFull && dhParams.enabled()) { var _doContinue = true; // before testing for beforeDrop, reset the connection's source/target to be the actual DOM elements // involved (that is, stash any temporary stuff used for dragging. but we need to keep it around in // order that the anchor manager can clean things up properly). if (idx === 0) { jpc.floatingElement = jpc.source; jpc.floatingId = jpc.sourceId; jpc.floatingEndpoint = jpc.endpoints[0]; jpc.floatingIndex = 0; jpc.source = dhParams.element; jpc.sourceId = dhParams.elementId; } else { jpc.floatingElement = jpc.target; jpc.floatingId = jpc.targetId; jpc.floatingEndpoint = jpc.endpoints[1]; jpc.floatingIndex = 1; jpc.target = dhParams.element; jpc.targetId = dhParams.elementId; } // if this is an existing connection and detach is not allowed we won't continue. The connection's // endpoints have been reinstated; everything is back to how it was. if (existingConnection && jpc.suspendedEndpoint.id !== _ep.id) { if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc)) { _doContinue = false; } } // ------------ wrap the execution path in a function so we can support asynchronous beforeDrop var continueFunction = function (optionalData) { // remove this jpc from the current endpoint, which is a floating endpoint that we will // subsequently discard. jpc.endpoints[idx].detachFromConnection(jpc); // if there's a suspended endpoint, detach it from the connection. if (jpc.suspendedEndpoint) { jpc.suspendedEndpoint.detachFromConnection(jpc); } jpc.endpoints[idx] = _ep; _ep.addConnection(jpc); // copy our parameters in to the connection: var params = _ep.getParameters(); for (var aParam in params) { jpc.setParameter(aParam, params[aParam]); } if (!existingConnection) { // if not an existing connection and if (params.draggable) { _jsPlumb.initDraggable(this.element, dhParams.dragOptions, "internal", _jsPlumb); } } else { var suspendedElementId = jpc.suspendedEndpoint.elementId; _jsPlumb.fireMoveEvent({ index: idx, originalSourceId: idx === 0 ? suspendedElementId : jpc.sourceId, newSourceId: idx === 0 ? _ep.elementId : jpc.sourceId, originalTargetId: idx === 1 ? suspendedElementId : jpc.targetId, newTargetId: idx === 1 ? _ep.elementId : jpc.targetId, originalSourceEndpoint: idx === 0 ? jpc.suspendedEndpoint : jpc.endpoints[0], newSourceEndpoint: idx === 0 ? _ep : jpc.endpoints[0], originalTargetEndpoint: idx === 1 ? jpc.suspendedEndpoint : jpc.endpoints[1], newTargetEndpoint: idx === 1 ? _ep : jpc.endpoints[1], connection: jpc }, originalEvent); } if (idx === 1) { _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc); } else { _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source); } // when makeSource has uniqueEndpoint:true, we want to create connections with new endpoints // that are subsequently deleted. So makeSource sets `finalEndpoint`, which is the Endpoint to // which the connection should be attached. The `detachFromConnection` call below results in the // temporary endpoint being cleaned up. if (jpc.endpoints[0].finalEndpoint) { var _toDelete = jpc.endpoints[0]; _toDelete.detachFromConnection(jpc); jpc.endpoints[0] = jpc.endpoints[0].finalEndpoint; jpc.endpoints[0].addConnection(jpc); } // if optionalData was given, merge it onto the connection's data. if (_ju.isObject(optionalData)) { jpc.mergeData(optionalData); } // finalise will inform the anchor manager and also add to // connectionsByScope if necessary. _jsPlumb.finaliseConnection(jpc, null, originalEvent, false); jpc.setHover(false); // SP continuous anchor flush _jsPlumb.revalidate(jpc.endpoints[0].element); }.bind(this); var dontContinueFunction = function () { // otherwise just put it back on the endpoint it was on before the drag. if (jpc.suspendedEndpoint) { jpc.endpoints[idx] = jpc.suspendedEndpoint; jpc.setHover(false); jpc._forceDetach = true; if (idx === 0) { jpc.source = jpc.suspendedEndpoint.element; jpc.sourceId = jpc.suspendedEndpoint.elementId; } else { jpc.target = jpc.suspendedEndpoint.element; jpc.targetId = jpc.suspendedEndpoint.elementId; } jpc.suspendedEndpoint.addConnection(jpc); // TODO checkSanity if (idx === 1) { _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc); } else { _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source); } _jsPlumb.repaint(jpc.sourceId); jpc._forceDetach = false; } }; // -------------------------------------- // now check beforeDrop. this will be available only on Endpoints that are setup to // have a beforeDrop condition (although, secretly, under the hood all Endpoints and // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because // it only makes sense to have it on a target endpoint. _doContinue = _doContinue && dhParams.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, _ep);// && jpc.pending; if (_doContinue) { continueFunction(_doContinue); return true; } else { dontContinueFunction(); } } if (dhParams.maybeCleanup) { dhParams.maybeCleanup(_ep); } _jsPlumb.currentlyDragging = false; }; }; }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the code for Connections. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) { // first make sure we have a cache for the specified renderer _jp.Connectors[renderMode] = _jp.Connectors[renderMode] || {}; // now see if the one we want exists; if not we will try to make it if (_jp.Connectors[renderMode][connectorName] == null) { if (_jp.Connectors[connectorName] == null) { if (!_jsPlumb.Defaults.DoNotThrowErrors) { throw new TypeError("jsPlumb: unknown connector type '" + connectorName + "'"); } else { return null; } } _jp.Connectors[renderMode][connectorName] = function() { _jp.Connectors[connectorName].apply(this, arguments); _jp.ConnectorRenderers[renderMode].apply(this, arguments); }; _ju.extend(_jp.Connectors[renderMode][connectorName], [ _jp.Connectors[connectorName], _jp.ConnectorRenderers[renderMode]]); } return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent); }, _makeAnchor = function (anchorParams, elementId, _jsPlumb) { return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null; }, _updateConnectedClass = function (conn, element, _jsPlumb, remove) { if (element != null) { element._jsPlumbConnections = element._jsPlumbConnections || {}; if (remove) { delete element._jsPlumbConnections[conn.id]; } else { element._jsPlumbConnections[conn.id] = true; } if (_ju.isEmpty(element._jsPlumbConnections)) { _jsPlumb.removeClass(element, _jsPlumb.connectedClass); } else { _jsPlumb.addClass(element, _jsPlumb.connectedClass); } } }; _jp.Connection = function (params) { var _newEndpoint = params.newEndpoint; this.id = params.id; this.connector = null; this.idPrefix = "_jsplumb_c_"; this.defaultLabelLocation = 0.5; this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"]; // if a new connection is the result of moving some existing connection, params.previousConnection // will have that Connection in it. listeners for the jsPlumbConnection event can look for that // member and take action if they need to. this.previousConnection = params.previousConnection; this.source = _jp.getElement(params.source); this.target = _jp.getElement(params.target); _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments); // sourceEndpoint and targetEndpoint override source/target, if they are present. but // source is not overridden if the Endpoint has declared it is not the final target of a connection; // instead we use the source that the Endpoint declares will be the final source element. if (params.sourceEndpoint) { this.source = params.sourceEndpoint.getElement(); this.sourceId = params.sourceEndpoint.elementId; } else { this.sourceId = this._jsPlumb.instance.getId(this.source); } if (params.targetEndpoint) { this.target = params.targetEndpoint.getElement(); this.targetId = params.targetEndpoint.elementId; } else { this.targetId = this._jsPlumb.instance.getId(this.target); } this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints. this.endpoints = []; this.endpointStyles = []; var _jsPlumb = this._jsPlumb.instance; _jsPlumb.manage(this.sourceId, this.source); _jsPlumb.manage(this.targetId, this.target); this._jsPlumb.visible = true; this._jsPlumb.params = { cssClass: params.cssClass, container: params.container, "pointer-events": params["pointer-events"], editorParams: params.editorParams, overlays: params.overlays }; this._jsPlumb.lastPaintedAt = null; // listen to mouseover and mouseout events passed from the container delegate. this.bind("mouseover", function () { this.setHover(true); }.bind(this)); this.bind("mouseout", function () { this.setHover(false); }.bind(this)); // INITIALISATION CODE this.makeEndpoint = function (isSource, el, elId, ep) { elId = elId || this._jsPlumb.instance.getId(el); return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId); }; // if type given, get the endpoint definitions mapping to that type from the jsplumb instance, and use those. // we apply types at the end of this constructor but endpoints are only honoured in a type definition at // create time. if (params.type) { params.endpoints = params.endpoints || this._jsPlumb.instance.deriveEndpointAndAnchorSpec(params.type).endpoints; } var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint), eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint); if (eS) { _ju.addToList(params.endpointsByElement, this.sourceId, eS); } if (eT) { _ju.addToList(params.endpointsByElement, this.targetId, eT); } // if scope not set, set it to be the scope for the source endpoint. if (!this.scope) { this.scope = this.endpoints[0].scope; } // if explicitly told to (or not to) delete endpoints when empty, override endpoint's preferences if (params.deleteEndpointsOnEmpty != null) { this.endpoints[0].setDeleteOnEmpty(params.deleteEndpointsOnEmpty); this.endpoints[1].setDeleteOnEmpty(params.deleteEndpointsOnEmpty); } // -------------------------- DEFAULT TYPE --------------------------------------------- // DETACHABLE var _detachable = _jsPlumb.Defaults.ConnectionsDetachable; if (params.detachable === false) { _detachable = false; } if (this.endpoints[0].connectionsDetachable === false) { _detachable = false; } if (this.endpoints[1].connectionsDetachable === false) { _detachable = false; } // REATTACH var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections; this.appendToDefaultType({ detachable: _detachable, reattach: _reattach, paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || _jp.Defaults.PaintStyle, hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || _jp.Defaults.HoverPaintStyle }); var _suspendedAt = _jsPlumb.getSuspendedAt(); if (!_jsPlumb.isSuspendDrawing()) { // paint the endpoints var myInfo = _jsPlumb.getCachedData(this.sourceId), myOffset = myInfo.o, myWH = myInfo.s, otherInfo = _jsPlumb.getCachedData(this.targetId), otherOffset = otherInfo.o, otherWH = otherInfo.s, initialTimestamp = _suspendedAt || _jsPlumb.timestamp(), anchorLoc = this.endpoints[0].anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0], elementId: this.endpoints[0].elementId, txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1], timestamp: initialTimestamp }); this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp }); anchorLoc = this.endpoints[1].anchor.compute({ xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1], elementId: this.endpoints[1].elementId, txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0], timestamp: initialTimestamp }); this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp }); } this.getTypeDescriptor = function () { return "connection"; }; this.getAttachedElements = function () { return this.endpoints; }; this.isDetachable = function (ep) { return ep != null ? ep.connectionsDetachable === true : this._jsPlumb.detachable === true; }; this.setDetachable = function (detachable) { this._jsPlumb.detachable = detachable === true; }; this.isReattach = function () { return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true; }; this.setReattach = function (reattach) { this._jsPlumb.reattach = reattach === true; }; // END INITIALISATION CODE // COST + DIRECTIONALITY // if cost not supplied, try to inherit from source endpoint this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost(); this._jsPlumb.directed = params.directed; // inherit directed flag if set no source endpoint if (params.directed == null) { this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected(); } // END COST + DIRECTIONALITY // PARAMETERS // merge all the parameters objects into the connection. parameters set // on the connection take precedence; then source endpoint params, then // finally target endpoint params. var _p = _jp.extend({}, this.endpoints[1].getParameters()); _jp.extend(_p, this.endpoints[0].getParameters()); _jp.extend(_p, this.getParameters()); this.setParameters(_p); // END PARAMETERS // PAINTING this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true); var data = params.data == null || !_ju.isObject(params.data) ? {} : params.data; this.getData = function() { return data; }; this.setData = function(d) { data = d || {}; }; this.mergeData = function(d) { data = _jp.extend(data, d); }; // the very last thing we do is apply types, if there are any. var _types = [ "default", this.endpoints[0].connectionType, this.endpoints[1].connectionType, params.type ].join(" "); if (/[^\s]/.test(_types)) { this.addType(_types, params.data, true); } this.updateConnectedClass(); // END PAINTING }; _ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, { applyType: function (t, doNotRepaint, typeMap) { var _connector = null; if (t.connector != null) { _connector = this.getCachedTypeItem("connector", typeMap.connector); if (_connector == null) { _connector = this.prepareConnector(t.connector, typeMap.connector); this.cacheTypeItem("connector", _connector, typeMap.connector); } this.setPreparedConnector(_connector); } // none of these things result in the creation of objects so can be ignored. if (t.detachable != null) { this.setDetachable(t.detachable); } if (t.reattach != null) { this.setReattach(t.reattach); } if (t.scope) { this.scope = t.scope; } if (t.cssClass != null && this.canvas) { this._jsPlumb.instance.addClass(this.canvas, t.cssClass); } var _anchors = null; // this also results in the creation of objects. if (t.anchor) { // note that even if the param was anchor, we store `anchors`. _anchors = this.getCachedTypeItem("anchors", typeMap.anchor); if (_anchors == null) { _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ]; this.cacheTypeItem("anchors", _anchors, typeMap.anchor); } } else if (t.anchors) { _anchors = this.getCachedTypeItem("anchors", typeMap.anchors); if (_anchors == null) { _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchors[0]), this._jsPlumb.instance.makeAnchor(t.anchors[1]) ]; this.cacheTypeItem("anchors", _anchors, typeMap.anchors); } } if (_anchors != null) { this.endpoints[0].anchor = _anchors[0]; this.endpoints[1].anchor = _anchors[1]; if (this.endpoints[1].anchor.isDynamic) { this._jsPlumb.instance.repaint(this.endpoints[1].elementId); } } _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t); }, addClass: function (c, informEndpoints) { if (informEndpoints) { this.endpoints[0].addClass(c); this.endpoints[1].addClass(c); if (this.suspendedEndpoint) { this.suspendedEndpoint.addClass(c); } } if (this.connector) { this.connector.addClass(c); } }, removeClass: function (c, informEndpoints) { if (informEndpoints) { this.endpoints[0].removeClass(c); this.endpoints[1].removeClass(c); if (this.suspendedEndpoint) { this.suspendedEndpoint.removeClass(c); } } if (this.connector) { this.connector.removeClass(c); } }, isVisible: function () { return this._jsPlumb.visible; }, setVisible: function (v) { this._jsPlumb.visible = v; if (this.connector) { this.connector.setVisible(v); } this.repaint(); }, cleanup: function () { this.updateConnectedClass(true); this.endpoints = null; this.source = null; this.target = null; if (this.connector != null) { this.connector.cleanup(true); this.connector.destroy(true); } this.connector = null; }, updateConnectedClass:function(remove) { if (this._jsPlumb) { _updateConnectedClass(this, this.source, this._jsPlumb.instance, remove); _updateConnectedClass(this, this.target, this._jsPlumb.instance, remove); } }, setHover: function (state) { if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) { this.connector.setHover(state); root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass); root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass); } }, getUuids:function() { return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ]; }, getCost: function () { return this._jsPlumb ? this._jsPlumb.cost : -Infinity; }, setCost: function (c) { this._jsPlumb.cost = c; }, isDirected: function () { return this._jsPlumb.directed; }, getConnector: function () { return this.connector; }, prepareConnector:function(connectorSpec, typeId) { var connectorArgs = { _jsPlumb: this._jsPlumb.instance, cssClass: this._jsPlumb.params.cssClass, container: this._jsPlumb.params.container, "pointer-events": this._jsPlumb.params["pointer-events"] }, renderMode = this._jsPlumb.instance.getRenderMode(), connector; if (_ju.isString(connectorSpec)) { connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this); } // lets you use a string as shorthand. else if (_ju.isArray(connectorSpec)) { if (connectorSpec.length === 1) { connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this); } else { connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this); } } if (typeId != null) { connector.typeId = typeId; } return connector; }, setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) { if (this.connector !== connector) { var previous, previousClasses = ""; // the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it // and we havent passed in `true` for "force" here. if (this.connector != null) { previous = this.connector; previousClasses = previous.getClass(); this.connector.cleanup(); this.connector.destroy(); } this.connector = connector; if (typeId) { this.cacheTypeItem("connector", connector, typeId); } this.canvas = this.connector.canvas; this.bgCanvas = this.connector.bgCanvas; // put classes from prior connector onto the canvas this.addClass(previousClasses); // new: instead of binding listeners per connector, we now just have one delegate on the container. // so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and // bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards. if (this.canvas) { this.canvas._jsPlumb = this; } if (this.bgCanvas) { this.bgCanvas._jsPlumb = this; } if (previous != null) { var o = this.getOverlays(); for (var i = 0; i < o.length; i++) { if (o[i].transfer) { o[i].transfer(this.connector); } } } if (!doNotChangeListenerComponent) { this.setListenerComponent(this.connector); } if (!doNotRepaint) { this.repaint(); } } }, setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) { var connector = this.prepareConnector(connectorSpec, typeId); this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId); }, paint: function (params) { if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) { params = params || {}; var timestamp = params.timestamp, // if the moving object is not the source we must transpose the two references. swap = false, tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId, tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0; if (timestamp == null || timestamp !== this._jsPlumb.lastPaintedAt) { var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o, targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o, sE = this.endpoints[sIdx], tE = this.endpoints[tIdx]; var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}), tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp}); this.connector.resetBounds(); this.connector.compute({ sourcePos: sAnchorP, targetPos: tAnchorP, sourceOrientation:sE.anchor.getOrientation(sE), targetOrientation:tE.anchor.getOrientation(tE), sourceEndpoint: this.endpoints[sIdx], targetEndpoint: this.endpoints[tIdx], "stroke-width": this._jsPlumb.paintStyleInUse.strokeWidth, sourceInfo: sourceInfo, targetInfo: targetInfo }); var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; // compute overlays. we do this first so we can get their placements, and adjust the // container if needs be (if an overlay would be clipped) for (var i in this._jsPlumb.overlays) { if (this._jsPlumb.overlays.hasOwnProperty(i)) { var o = this._jsPlumb.overlays[i]; if (o.isVisible()) { this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o)); overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX); overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX); overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY); overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY); } } } var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 1) / 2, outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 0), extents = { xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX), ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY), xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX), ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY) }; // paint the connector. this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents); // and then the overlays for (var j in this._jsPlumb.overlays) { if (this._jsPlumb.overlays.hasOwnProperty(j)) { var p = this._jsPlumb.overlays[j]; if (p.isVisible()) { p.paint(this._jsPlumb.overlayPlacements[j], extents); } } } } this._jsPlumb.lastPaintedAt = timestamp; } }, repaint: function (params) { var p = jsPlumb.extend(params || {}, {}); p.elId = this.sourceId; this.paint(p); }, prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) { var e; if (existing) { conn.endpoints[index] = existing; existing.addConnection(conn); } else { if (!params.endpoints) { params.endpoints = [ null, null ]; } var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || _jp.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || _jp.Defaults.Endpoint; if (!params.endpointStyles) { params.endpointStyles = [ null, null ]; } if (!params.endpointHoverStyles) { params.endpointHoverStyles = [ null, null ]; } var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || _jp.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle; // Endpoints derive their fill from the connector's stroke, if no fill was specified. if (es.fill == null && params.paintStyle != null) { es.fill = params.paintStyle.stroke; } if (es.outlineStroke == null && params.paintStyle != null) { es.outlineStroke = params.paintStyle.outlineStroke; } if (es.outlineWidth == null && params.paintStyle != null) { es.outlineWidth = params.paintStyle.outlineWidth; } var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || _jp.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle; // endpoint hover fill style is derived from connector's hover stroke style if (params.hoverPaintStyle != null) { if (ehs == null) { ehs = {}; } if (ehs.fill == null) { ehs.fill = params.hoverPaintStyle.stroke; } } var a = params.anchors ? params.anchors[index] : params.anchor ? params.anchor : _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) || _makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) || _makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) || _makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb), u = params.uuids ? params.uuids[index] : null; e = _newEndpoint({ paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ], uuid: u, anchor: a, source: element, scope: params.scope, reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections, detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable }); if (existing == null) { e.setDeleteOnEmpty(true); } conn.endpoints[index] = e; if (params.drawEndpoints === false) { e.setVisible(false, true, true); } } return e; } }); // END Connection class }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the code for creating and manipulating anchors. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _ju = root.jsPlumbUtil, _jp = root.jsPlumb; // // manages anchors for all elements. // _jp.AnchorManager = function (params) { var _amEndpoints = {}, continuousAnchorLocations = {}, continuousAnchorOrientations = {}, connectionsByElementId = {}, self = this, anchorLists = {}, jsPlumbInstance = params.jsPlumbInstance, floatingConnections = {}, // used by placeAnchors function placeAnchorsOnLine = function (desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) { var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1); for (var i = 0; i < connections.length; i++) { var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0]; if (reverse) { val = elementDimensions[horizontal ? 0 : 1] - val; } var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0], dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1]; a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]); } return a; }, // used by edgeSortFunctions currySort = function (reverseAngles) { return function (a, b) { var r = true; if (reverseAngles) { r = a[0][0] < b[0][0]; } else { r = a[0][0] > b[0][0]; } return r === false ? -1 : 1; }; }, // used by edgeSortFunctions leftSort = function (a, b) { // first get adjusted values var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0], p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0]; if (p1 > p2) { return 1; } else { return -1; } }, // used by placeAnchors edgeSortFunctions = { "top": function (a, b) { return a[0] > b[0] ? 1 : -1; }, "right": currySort(true), "bottom": currySort(true), "left": leftSort }, // used by placeAnchors _sortHelper = function (_array, _fn) { return _array.sort(_fn); }, // used by AnchorManager.redraw placeAnchors = function (elementId, _anchorLists) { var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o, placeSomeAnchors = function (desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) { if (unsortedConnections.length > 0) { var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen reverse = desc === "right" || desc === "top", anchors = placeAnchorsOnLine(desc, elementDimensions, elementPosition, sc, isHorizontal, otherMultiplier, reverse); // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it. var _setAnchorLocation = function (endpoint, anchorPos) { continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ]; continuousAnchorOrientations[endpoint.id] = orientation; }; for (var i = 0; i < anchors.length; i++) { var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId; if (weAreSource) { _setAnchorLocation(c.endpoints[0], anchors[i]); } if (weAreTarget) { _setAnchorLocation(c.endpoints[1], anchors[i]); } } } }; placeSomeAnchors("bottom", sS, [sO.left, sO.top], _anchorLists.bottom, true, 1, [0, 1]); placeSomeAnchors("top", sS, [sO.left, sO.top], _anchorLists.top, true, 0, [0, -1]); placeSomeAnchors("left", sS, [sO.left, sO.top], _anchorLists.left, false, 0, [-1, 0]); placeSomeAnchors("right", sS, [sO.left, sO.top], _anchorLists.right, false, 1, [1, 0]); }; this.reset = function () { _amEndpoints = {}; connectionsByElementId = {}; anchorLists = {}; }; this.addFloatingConnection = function (key, conn) { floatingConnections[key] = conn; }; this.removeFloatingConnection = function (key) { delete floatingConnections[key]; }; this.newConnection = function (conn) { var sourceId = conn.sourceId, targetId = conn.targetId, ep = conn.endpoints, doRegisterTarget = true, registerConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) { if ((sourceId === targetId) && otherAnchor.isContinuous) { // remove the target endpoint's canvas. we dont need it. conn._jsPlumb.instance.removeElement(ep[1].canvas); doRegisterTarget = false; } _ju.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor === _jp.DynamicAnchor]); }; registerConnection(0, ep[0], ep[0].anchor, targetId, conn); if (doRegisterTarget) { registerConnection(1, ep[1], ep[1].anchor, sourceId, conn); } }; var removeEndpointFromAnchorLists = function (endpoint) { (function (list, eId) { if (list) { // transient anchors dont get entries in this list. var f = function (e) { return e[4] === eId; }; _ju.removeWithFunction(list.top, f); _ju.removeWithFunction(list.left, f); _ju.removeWithFunction(list.bottom, f); _ju.removeWithFunction(list.right, f); } })(anchorLists[endpoint.elementId], endpoint.id); }; this.connectionDetached = function (connInfo, doNotRedraw) { var connection = connInfo.connection || connInfo, sourceId = connInfo.sourceId, targetId = connInfo.targetId, ep = connection.endpoints, removeConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) { _ju.removeWithFunction(connectionsByElementId[elId], function (_c) { return _c[0].id === c.id; }); }; removeConnection(1, ep[1], ep[1].anchor, sourceId, connection); removeConnection(0, ep[0], ep[0].anchor, targetId, connection); if (connection.floatingId) { removeConnection(connection.floatingIndex, connection.floatingEndpoint, connection.floatingEndpoint.anchor, connection.floatingId, connection); removeEndpointFromAnchorLists(connection.floatingEndpoint); } // remove from anchorLists removeEndpointFromAnchorLists(connection.endpoints[0]); removeEndpointFromAnchorLists(connection.endpoints[1]); if (!doNotRedraw) { self.redraw(connection.sourceId); if (connection.targetId !== connection.sourceId) { self.redraw(connection.targetId); } } }; this.add = function (endpoint, elementId) { _ju.addToList(_amEndpoints, elementId, endpoint); }; this.changeId = function (oldId, newId) { connectionsByElementId[newId] = connectionsByElementId[oldId]; _amEndpoints[newId] = _amEndpoints[oldId]; delete connectionsByElementId[oldId]; delete _amEndpoints[oldId]; }; this.getConnectionsFor = function (elementId) { return connectionsByElementId[elementId] || []; }; this.getEndpointsFor = function (elementId) { return _amEndpoints[elementId] || []; }; this.deleteEndpoint = function (endpoint) { _ju.removeWithFunction(_amEndpoints[endpoint.elementId], function (e) { return e.id === endpoint.id; }); removeEndpointFromAnchorLists(endpoint); }; this.clearFor = function (elementId) { delete _amEndpoints[elementId]; _amEndpoints[elementId] = []; }; // updates the given anchor list by either updating an existing anchor's info, or adding it. this function // also removes the anchor from its previous list, if the edge it is on has changed. // all connections found along the way (those that are connected to one of the faces this function // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint // them wthout having to calculate anything else about them. var _updateAnchorList = function (lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) { // first try to find the exact match, but keep track of the first index of a matching element id along the way.s var exactIdx = -1, firstMatchingElIdx = -1, endpoint = conn.endpoints[idx], endpointId = endpoint.id, oIdx = [1, 0][idx], values = [ [ theta, order ], conn, aBoolean, otherElId, endpointId ], listToAddTo = lists[edgeId], listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null, i, candidate; if (listToRemoveFrom) { var rIdx = _ju.findWithFunction(listToRemoveFrom, function (e) { return e[4] === endpointId; }); if (rIdx !== -1) { listToRemoveFrom.splice(rIdx, 1); // get all connections from this list for (i = 0; i < listToRemoveFrom.length; i++) { candidate = listToRemoveFrom[i][1]; _ju.addWithFunction(connsToPaint, candidate, function (c) { return c.id === candidate.id; }); _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function (e) { return e.id === candidate.endpoints[idx].id; }); _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function (e) { return e.id === candidate.endpoints[oIdx].id; }); } } } for (i = 0; i < listToAddTo.length; i++) { candidate = listToAddTo[i][1]; if (params.idx === 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx === -1) { firstMatchingElIdx = i; } _ju.addWithFunction(connsToPaint, candidate, function (c) { return c.id === candidate.id; }); _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function (e) { return e.id === candidate.endpoints[idx].id; }); _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function (e) { return e.id === candidate.endpoints[oIdx].id; }); } if (exactIdx !== -1) { listToAddTo[exactIdx] = values; } else { var insertIdx = reverse ? firstMatchingElIdx !== -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly. listToAddTo.splice(insertIdx, 0, values); } // store this for next time. endpoint._continuousAnchorEdge = edgeId; }; // // find the entry in an endpoint's list for this connection and update its target endpoint // with the current target in the connection. // This method and sourceChanged need to be folder into one. // this.updateOtherEndpoint = function (sourceElId, oldTargetId, newTargetId, connection) { var sIndex = _ju.findWithFunction(connectionsByElementId[sourceElId], function (i) { return i[0].id === connection.id; }), tIndex = _ju.findWithFunction(connectionsByElementId[oldTargetId], function (i) { return i[0].id === connection.id; }); // update or add data for source if (sIndex !== -1) { connectionsByElementId[sourceElId][sIndex][0] = connection; connectionsByElementId[sourceElId][sIndex][1] = connection.endpoints[1]; connectionsByElementId[sourceElId][sIndex][2] = connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor; } // remove entry for previous target (if there) if (tIndex > -1) { connectionsByElementId[oldTargetId].splice(tIndex, 1); // add entry for new target _ju.addToList(connectionsByElementId, newTargetId, [connection, connection.endpoints[0], connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor]); } connection.updateConnectedClass(); }; // // notification that the connection given has changed source from the originalId to the newId. // This involves: // 1. removing the connection from the list of connections stored for the originalId // 2. updating the source information for the target of the connection // 3. re-registering the connection in connectionsByElementId with the newId // this.sourceChanged = function (originalId, newId, connection, newElement) { if (originalId !== newId) { connection.sourceId = newId; connection.source = newElement; // remove the entry that points from the old source to the target _ju.removeWithFunction(connectionsByElementId[originalId], function (info) { return info[0].id === connection.id; }); // find entry for target and update it var tIdx = _ju.findWithFunction(connectionsByElementId[connection.targetId], function (i) { return i[0].id === connection.id; }); if (tIdx > -1) { connectionsByElementId[connection.targetId][tIdx][0] = connection; connectionsByElementId[connection.targetId][tIdx][1] = connection.endpoints[0]; connectionsByElementId[connection.targetId][tIdx][2] = connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor; } // add entry for new source _ju.addToList(connectionsByElementId, newId, [connection, connection.endpoints[1], connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor]); // TODO SP not final on this yet. when a user drags an existing connection and it turns into a self // loop, then this code hides the target endpoint (by removing it from the DOM) But I think this should // occur only if the anchor is Continuous if (connection.endpoints[1].anchor.isContinuous) { if (connection.source === connection.target) { connection._jsPlumb.instance.removeElement(connection.endpoints[1].canvas); } else { if (connection.endpoints[1].canvas.parentNode == null) { connection._jsPlumb.instance.appendElement(connection.endpoints[1].canvas); } } } connection.updateConnectedClass(); } }; // // moves the given endpoint from `currentId` to `element`. // This involves: // // 1. changing the key in _amEndpoints under which the endpoint is stored // 2. changing the source or target values in all of the endpoint's connections // 3. changing the array in connectionsByElementId in which the endpoint's connections // are stored (done by either sourceChanged or updateOtherEndpoint) // this.rehomeEndpoint = function (ep, currentId, element) { var eps = _amEndpoints[currentId] || [], elementId = jsPlumbInstance.getId(element); if (elementId !== currentId) { var idx = eps.indexOf(ep); if (idx > -1) { var _ep = eps.splice(idx, 1)[0]; self.add(_ep, elementId); } } for (var i = 0; i < ep.connections.length; i++) { if (ep.connections[i].sourceId === currentId) { self.sourceChanged(currentId, ep.elementId, ep.connections[i], ep.element); } else if (ep.connections[i].targetId === currentId) { ep.connections[i].targetId = ep.elementId; ep.connections[i].target = ep.element; self.updateOtherEndpoint(ep.connections[i].sourceId, currentId, ep.elementId, ep.connections[i]); } } }; this.redraw = function (elementId, ui, timestamp, offsetToUI, clearEdits, doNotRecalcEndpoint) { if (!jsPlumbInstance.isSuspendDrawing()) { // get all the endpoints for this element var ep = _amEndpoints[elementId] || [], endpointConnections = connectionsByElementId[elementId] || [], connectionsToPaint = [], endpointsToPaint = [], anchorsToUpdate = []; timestamp = timestamp || jsPlumbInstance.timestamp(); // offsetToUI are values that would have been calculated in the dragManager when registering // an endpoint for an element that had a parent (somewhere in the hierarchy) that had been // registered as draggable. offsetToUI = offsetToUI || {left: 0, top: 0}; if (ui) { ui = { left: ui.left + offsetToUI.left, top: ui.top + offsetToUI.top }; } // valid for one paint cycle. var myOffset = jsPlumbInstance.updateOffset({ elId: elementId, offset: ui, recalc: false, timestamp: timestamp }), orientationCache = {}; // actually, first we should compute the orientation of this element to all other elements to which // this element is connected with a continuous anchor (whether both ends of the connection have // a continuous anchor or just one) for (var i = 0; i < endpointConnections.length; i++) { var conn = endpointConnections[i][0], sourceId = conn.sourceId, targetId = conn.targetId, sourceContinuous = conn.endpoints[0].anchor.isContinuous, targetContinuous = conn.endpoints[1].anchor.isContinuous; if (sourceContinuous || targetContinuous) { var oKey = sourceId + "_" + targetId, o = orientationCache[oKey], oIdx = conn.sourceId === elementId ? 1 : 0; if (sourceContinuous && !anchorLists[sourceId]) { anchorLists[sourceId] = { top: [], right: [], bottom: [], left: [] }; } if (targetContinuous && !anchorLists[targetId]) { anchorLists[targetId] = { top: [], right: [], bottom: [], left: [] }; } if (elementId !== targetId) { jsPlumbInstance.updateOffset({ elId: targetId, timestamp: timestamp }); } if (elementId !== sourceId) { jsPlumbInstance.updateOffset({ elId: sourceId, timestamp: timestamp }); } var td = jsPlumbInstance.getCachedData(targetId), sd = jsPlumbInstance.getCachedData(sourceId); if (targetId === sourceId && (sourceContinuous || targetContinuous)) { // here we may want to improve this by somehow determining the face we'd like // to put the connector on. ideally, when drawing, the face should be calculated // by determining which face is closest to the point at which the mouse button // was released. for now, we're putting it on the top face. _updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint); _updateAnchorList( anchorLists[targetId], -Math.PI / 2, 0, conn, false, sourceId, 1, false, "top", targetId, connectionsToPaint, endpointsToPaint); } else { if (!o) { o = this.calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor, conn); orientationCache[oKey] = o; // this would be a performance enhancement, but the computed angles need to be clamped to //the (-PI/2 -> PI/2) range in order for the sorting to work properly. /* orientationCache[oKey2] = { orientation:o.orientation, a:[o.a[1], o.a[0]], theta:o.theta + Math.PI, theta2:o.theta2 + Math.PI };*/ } if (sourceContinuous) { _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint); } if (targetContinuous) { _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint); } } if (sourceContinuous) { _ju.addWithFunction(anchorsToUpdate, sourceId, function (a) { return a === sourceId; }); } if (targetContinuous) { _ju.addWithFunction(anchorsToUpdate, targetId, function (a) { return a === targetId; }); } _ju.addWithFunction(connectionsToPaint, conn, function (c) { return c.id === conn.id; }); if ((sourceContinuous && oIdx === 0) || (targetContinuous && oIdx === 1)) { _ju.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function (e) { return e.id === conn.endpoints[oIdx].id; }); } } } // place Endpoints whose anchors are continuous but have no Connections for (i = 0; i < ep.length; i++) { if (ep[i].connections.length === 0 && ep[i].anchor.isContinuous) { if (!anchorLists[elementId]) { anchorLists[elementId] = { top: [], right: [], bottom: [], left: [] }; } _updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints: [ep[i], ep[i]], paint: function () { }}, false, elementId, 0, false, ep[i].anchor.getDefaultFace(), elementId, connectionsToPaint, endpointsToPaint); _ju.addWithFunction(anchorsToUpdate, elementId, function (a) { return a === elementId; }); } } // now place all the continuous anchors we need to; for (i = 0; i < anchorsToUpdate.length; i++) { placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]); } // now that continuous anchors have been placed, paint all the endpoints for this element for (i = 0; i < ep.length; i++) { ep[i].paint({ timestamp: timestamp, offset: myOffset, dimensions: myOffset.s, recalc: doNotRecalcEndpoint !== true }); } // ... and any other endpoints we came across as a result of the continuous anchors. for (i = 0; i < endpointsToPaint.length; i++) { var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId); //endpointsToPaint[i].paint({ timestamp: timestamp, offset: cd, dimensions: cd.s }); endpointsToPaint[i].paint({ timestamp: null, offset: cd, dimensions: cd.s }); } // paint all the standard and "dynamic connections", which are connections whose other anchor is // static and therefore does need to be recomputed; we make sure that happens only one time. // TODO we could have compiled a list of these in the first pass through connections; might save some time. for (i = 0; i < endpointConnections.length; i++) { var otherEndpoint = endpointConnections[i][1]; if (otherEndpoint.anchor.constructor === _jp.DynamicAnchor) { otherEndpoint.paint({ elementWithPrecedence: elementId, timestamp: timestamp }); _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) { return c.id === endpointConnections[i][0].id; }); // all the connections for the other endpoint now need to be repainted for (var k = 0; k < otherEndpoint.connections.length; k++) { if (otherEndpoint.connections[k] !== endpointConnections[i][0]) { _ju.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function (c) { return c.id === otherEndpoint.connections[k].id; }); } } } else { _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) { return c.id === endpointConnections[i][0].id; }); } } // paint current floating connection for this element, if there is one. var fc = floatingConnections[elementId]; if (fc) { fc.paint({timestamp: timestamp, recalc: false, elId: elementId}); } // paint all the connections for (i = 0; i < connectionsToPaint.length; i++) { connectionsToPaint[i].paint({elId: elementId, timestamp: null, recalc: false, clearEdits: clearEdits}); } } }; var ContinuousAnchor = function (anchorParams) { _ju.EventGenerator.apply(this); this.type = "Continuous"; this.isDynamic = true; this.isContinuous = true; var faces = anchorParams.faces || ["top", "right", "bottom", "left"], clockwise = !(anchorParams.clockwise === false), availableFaces = { }, opposites = { "top": "bottom", "right": "left", "left": "right", "bottom": "top" }, clockwiseOptions = { "top": "right", "right": "bottom", "left": "top", "bottom": "left" }, antiClockwiseOptions = { "top": "left", "right": "top", "left": "bottom", "bottom": "right" }, secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions, lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions, cssClass = anchorParams.cssClass || "", _currentFace = null, _lockedFace = null, X_AXIS_FACES = ["left", "right"], Y_AXIS_FACES = ["top", "bottom"], _lockedAxis = null; for (var i = 0; i < faces.length; i++) { availableFaces[faces[i]] = true; } this.getDefaultFace = function () { return faces.length === 0 ? "top" : faces[0]; }; this.isRelocatable = function() { return true; }; this.isSnapOnRelocate = function() { return true; }; // if the given edge is supported, returns it. otherwise looks for a substitute that _is_ // supported. if none supported we also return the request edge. this.verifyEdge = function (edge) { if (availableFaces[edge]) { return edge; } else if (availableFaces[opposites[edge]]) { return opposites[edge]; } else if (availableFaces[secondBest[edge]]) { return secondBest[edge]; } else if (availableFaces[lastChoice[edge]]) { return lastChoice[edge]; } return edge; // we have to give them something. }; this.isEdgeSupported = function (edge) { return _lockedAxis == null ? (_lockedFace == null ? availableFaces[edge] === true : _lockedFace === edge) : _lockedAxis.indexOf(edge) !== -1; }; this.setCurrentFace = function(face, overrideLock) { _currentFace = face; // if currently locked, and the user wants to override, do that. if (overrideLock && _lockedFace != null) { _lockedFace = _currentFace; } }; this.getCurrentFace = function() { return _currentFace; }; this.getSupportedFaces = function() { var af = []; for (var k in availableFaces) { if (availableFaces[k]) { af.push(k); } } return af; }; this.lock = function() { _lockedFace = _currentFace; }; this.unlock = function() { _lockedFace = null; }; this.isLocked = function() { return _lockedFace != null; }; this.lockCurrentAxis = function() { if (_currentFace != null) { _lockedAxis = (_currentFace === "left" || _currentFace === "right") ? X_AXIS_FACES : Y_AXIS_FACES; } }; this.unlockCurrentAxis = function() { _lockedAxis = null; }; this.compute = function (params) { return continuousAnchorLocations[params.element.id] || [0, 0]; }; this.getCurrentLocation = function (params) { return continuousAnchorLocations[params.element.id] || [0, 0]; }; this.getOrientation = function (endpoint) { return continuousAnchorOrientations[endpoint.id] || [0, 0]; }; this.getCssClass = function () { return cssClass; }; }; // continuous anchors jsPlumbInstance.continuousAnchorFactory = { get: function (params) { return new ContinuousAnchor(params); }, clear: function (elementId) { delete continuousAnchorLocations[elementId]; } }; }; _jp.AnchorManager.prototype.calculateOrientation = function (sourceId, targetId, sd, td, sourceAnchor, targetAnchor) { var Orientation = { HORIZONTAL: "horizontal", VERTICAL: "vertical", DIAGONAL: "diagonal", IDENTITY: "identity" }, axes = ["left", "top", "right", "bottom"]; if (sourceId === targetId) { return { orientation: Orientation.IDENTITY, a: ["top", "top"] }; } var theta = Math.atan2((td.centery - sd.centery), (td.centerx - sd.centerx)), theta2 = Math.atan2((sd.centery - td.centery), (sd.centerx - td.centerx)); // -------------------------------------------------------------------------------------- // improved face calculation. get midpoints of each face for source and target, then put in an array with all combinations of // source/target faces. sort this array by distance between midpoints. the entry at index 0 is our preferred option. we can // go through the array one by one until we find an entry in which each requested face is supported. var candidates = [], midpoints = { }; (function (types, dim) { for (var i = 0; i < types.length; i++) { midpoints[types[i]] = { "left": [ dim[i].left, dim[i].centery ], "right": [ dim[i].right, dim[i].centery ], "top": [ dim[i].centerx, dim[i].top ], "bottom": [ dim[i].centerx , dim[i].bottom] }; } })([ "source", "target" ], [ sd, td ]); for (var sf = 0; sf < axes.length; sf++) { for (var tf = 0; tf < axes.length; tf++) { candidates.push({ source: axes[sf], target: axes[tf], dist: Biltong.lineLength(midpoints.source[axes[sf]], midpoints.target[axes[tf]]) }); } } candidates.sort(function (a, b) { return a.dist < b.dist ? -1 : a.dist > b.dist ? 1 : 0; }); // now go through this list and try to get an entry that satisfies both (there will be one, unless one of the anchors // declares no available faces) var sourceEdge = candidates[0].source, targetEdge = candidates[0].target; for (var i = 0; i < candidates.length; i++) { if (!sourceAnchor.isContinuous || sourceAnchor.isEdgeSupported(candidates[i].source)) { sourceEdge = candidates[i].source; } else { sourceEdge = null; } if (!targetAnchor.isContinuous || targetAnchor.isEdgeSupported(candidates[i].target)) { targetEdge = candidates[i].target; } else { targetEdge = null; } if (sourceEdge != null && targetEdge != null) { break; } } if (sourceAnchor.isContinuous) { sourceAnchor.setCurrentFace(sourceEdge); } if (targetAnchor.isContinuous) { targetAnchor.setCurrentFace(targetEdge); } // -------------------------------------------------------------------------------------- return { a: [ sourceEdge, targetEdge ], theta: theta, theta2: theta2 }; }; /** * Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user * was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"), * or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the * creation of Anchors without user intervention. */ _jp.Anchor = function (params) { this.x = params.x || 0; this.y = params.y || 0; this.elementId = params.elementId; this.cssClass = params.cssClass || ""; this.userDefinedLocation = null; this.orientation = params.orientation || [ 0, 0 ]; this.lastReturnValue = null; this.offsets = params.offsets || [ 0, 0 ]; this.timestamp = null; var relocatable = params.relocatable !== false; this.isRelocatable = function() { return relocatable; }; this.setRelocatable = function(_relocatable) { relocatable = _relocatable; }; var snapOnRelocate = params.snapOnRelocate !== false; this.isSnapOnRelocate = function() { return snapOnRelocate; }; var locked = false; this.lock = function() { locked = true; }; this.unlock = function() { locked = false; }; this.isLocked = function() { return locked; }; _ju.EventGenerator.apply(this); this.compute = function (params) { var xy = params.xy, wh = params.wh, timestamp = params.timestamp; if (params.clearUserDefinedLocation) { this.userDefinedLocation = null; } if (timestamp && timestamp === this.timestamp) { return this.lastReturnValue; } if (this.userDefinedLocation != null) { this.lastReturnValue = this.userDefinedLocation; } else { this.lastReturnValue = [ xy[0] + (this.x * wh[0]) + this.offsets[0], xy[1] + (this.y * wh[1]) + this.offsets[1], this.x, this.y ]; } this.timestamp = timestamp; return this.lastReturnValue; }; this.getCurrentLocation = function (params) { params = params || {}; return (this.lastReturnValue == null || (params.timestamp != null && this.timestamp !== params.timestamp)) ? this.compute(params) : this.lastReturnValue; }; this.setPosition = function(x, y, ox, oy, overrideLock) { if (!locked || overrideLock) { this.x = x; this.y = y; this.orientation = [ ox, oy ]; this.lastReturnValue = null; } }; }; _ju.extend(_jp.Anchor, _ju.EventGenerator, { equals: function (anchor) { if (!anchor) { return false; } var ao = anchor.getOrientation(), o = this.getOrientation(); return this.x === anchor.x && this.y === anchor.y && this.offsets[0] === anchor.offsets[0] && this.offsets[1] === anchor.offsets[1] && o[0] === ao[0] && o[1] === ao[1]; }, getUserDefinedLocation: function () { return this.userDefinedLocation; }, setUserDefinedLocation: function (l) { this.userDefinedLocation = l; }, clearUserDefinedLocation: function () { this.userDefinedLocation = null; }, getOrientation: function () { return this.orientation; }, getCssClass: function () { return this.cssClass; } }); /** * An Anchor that floats. its orientation is computed dynamically from * its position relative to the anchor it is floating relative to. It is used when creating * a connection through drag and drop. * * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly. */ _jp.FloatingAnchor = function (params) { _jp.Anchor.apply(this, arguments); // this is the anchor that this floating anchor is referenced to for // purposes of calculating the orientation. var ref = params.reference, // the canvas this refers to. refCanvas = params.referenceCanvas, size = _jp.getSize(refCanvas), // these are used to store the current relative position of our // anchor wrt the reference anchor. they only indicate // direction, so have a value of 1 or -1 (or, very rarely, 0). these // values are written by the compute method, and read // by the getOrientation method. xDir = 0, yDir = 0, // temporary member used to store an orientation when the floating // anchor is hovering over another anchor. orientation = null, _lastResult = null; // clear from parent. we want floating anchor orientation to always be computed. this.orientation = null; // set these to 0 each; they are used by certain types of connectors in the loopback case, // when the connector is trying to clear the element it is on. but for floating anchor it's not // very important. this.x = 0; this.y = 0; this.isFloating = true; this.compute = function (params) { var xy = params.xy, result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy. _lastResult = result; return result; }; this.getOrientation = function (_endpoint) { if (orientation) { return orientation; } else { var o = ref.getOrientation(_endpoint); // here we take into account the orientation of the other // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense. return [ Math.abs(o[0]) * xDir * -1, Math.abs(o[1]) * yDir * -1 ]; } }; /** * notification the endpoint associated with this anchor is hovering * over another anchor; we want to assume that anchor's orientation * for the duration of the hover. */ this.over = function (anchor, endpoint) { orientation = anchor.getOrientation(endpoint); }; /** * notification the endpoint associated with this anchor is no * longer hovering over another anchor; we should resume calculating * orientation as we normally do. */ this.out = function () { orientation = null; }; this.getCurrentLocation = function (params) { return _lastResult == null ? this.compute(params) : _lastResult; }; }; _ju.extend(_jp.FloatingAnchor, _jp.Anchor); var _convertAnchor = function (anchor, jsPlumbInstance, elementId) { return anchor.constructor === _jp.Anchor ? anchor : jsPlumbInstance.makeAnchor(anchor, elementId, jsPlumbInstance); }; /* * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles * through at compute time to find the one that is located closest to * the center of the target element, and returns that Anchor's compute * method result. this causes endpoints to follow each other with * respect to the orientation of their target elements, which is a useful * feature for some applications. * */ _jp.DynamicAnchor = function (params) { _jp.Anchor.apply(this, arguments); this.isDynamic = true; this.anchors = []; this.elementId = params.elementId; this.jsPlumbInstance = params.jsPlumbInstance; for (var i = 0; i < params.anchors.length; i++) { this.anchors[i] = _convertAnchor(params.anchors[i], this.jsPlumbInstance, this.elementId); } this.getAnchors = function () { return this.anchors; }; var _curAnchor = this.anchors.length > 0 ? this.anchors[0] : null, _lastAnchor = _curAnchor, self = this, // helper method to calculate the distance between the centers of the two elements. _distance = function (anchor, cx, cy, xy, wh) { var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]), acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2); return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) + Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2))); }, // default method uses distance between element centers. you can provide your own method in the dynamic anchor // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays: // xy - xy loc of the anchor's element // wh - anchor's element's dimensions // txy - xy loc of the element of the other anchor in the connection // twh - dimensions of the element of the other anchor in the connection. // anchors - the list of selectable anchors _anchorSelector = params.selector || function (xy, wh, txy, twh, anchors) { var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2); var minIdx = -1, minDist = Infinity; for (var i = 0; i < anchors.length; i++) { var d = _distance(anchors[i], cx, cy, xy, wh); if (d < minDist) { minIdx = i + 0; minDist = d; } } return anchors[minIdx]; }; this.compute = function (params) { var xy = params.xy, wh = params.wh, txy = params.txy, twh = params.twh; this.timestamp = params.timestamp; var udl = self.getUserDefinedLocation(); if (udl != null) { return udl; } // if anchor is locked or an opposite element was not given, we // maintain our state. anchor will be locked // if it is the source of a drag and drop. if (this.isLocked() || txy == null || twh == null) { return _curAnchor.compute(params); } else { params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute. } _curAnchor = _anchorSelector(xy, wh, txy, twh, this.anchors); this.x = _curAnchor.x; this.y = _curAnchor.y; if (_curAnchor !== _lastAnchor) { this.fire("anchorChanged", _curAnchor); } _lastAnchor = _curAnchor; return _curAnchor.compute(params); }; this.getCurrentLocation = function (params) { return this.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation(params) : null); }; this.getOrientation = function (_endpoint) { return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ]; }; this.over = function (anchor, endpoint) { if (_curAnchor != null) { _curAnchor.over(anchor, endpoint); } }; this.out = function () { if (_curAnchor != null) { _curAnchor.out(); } }; this.setAnchor = function(a) { _curAnchor = a; }; this.getCssClass = function () { return (_curAnchor && _curAnchor.getCssClass()) || ""; }; /** * Attempt to match an anchor with the given coordinates and then set it. * @param coords * @returns true if matching anchor found, false otherwise. */ this.setAnchorCoordinates = function(coords) { var idx = jsPlumbUtil.findWithFunction(this.anchors, function(a) { return a.x === coords[0] && a.y === coords[1]; }); if (idx !== -1) { this.setAnchor(this.anchors[idx]); return true; } else { return false; } }; }; _ju.extend(_jp.DynamicAnchor, _jp.Anchor); // -------- basic anchors ------------------ var _curryAnchor = function (x, y, ox, oy, type, fnInit) { _jp.Anchors[type] = function (params) { var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance); a.type = type; if (fnInit) { fnInit(a, params); } return a; }; }; _curryAnchor(0.5, 0, 0, -1, "TopCenter"); _curryAnchor(0.5, 1, 0, 1, "BottomCenter"); _curryAnchor(0, 0.5, -1, 0, "LeftMiddle"); _curryAnchor(1, 0.5, 1, 0, "RightMiddle"); _curryAnchor(0.5, 0, 0, -1, "Top"); _curryAnchor(0.5, 1, 0, 1, "Bottom"); _curryAnchor(0, 0.5, -1, 0, "Left"); _curryAnchor(1, 0.5, 1, 0, "Right"); _curryAnchor(0.5, 0.5, 0, 0, "Center"); _curryAnchor(1, 0, 0, -1, "TopRight"); _curryAnchor(1, 1, 0, 1, "BottomRight"); _curryAnchor(0, 0, 0, -1, "TopLeft"); _curryAnchor(0, 1, 0, 1, "BottomLeft"); // ------- dynamic anchors ------------------- // default dynamic anchors chooses from Top, Right, Bottom, Left _jp.Defaults.DynamicAnchors = function (params) { return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance); }; // default dynamic anchors bound to name 'AutoDefault' _jp.Anchors.AutoDefault = function (params) { var a = params.jsPlumbInstance.makeDynamicAnchor(_jp.Defaults.DynamicAnchors(params)); a.type = "AutoDefault"; return a; }; // ------- continuous anchors ------------------- var _curryContinuousAnchor = function (type, faces) { _jp.Anchors[type] = function (params) { var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces: faces }], params.elementId, params.jsPlumbInstance); a.type = type; return a; }; }; _jp.Anchors.Continuous = function (params) { return params.jsPlumbInstance.continuousAnchorFactory.get(params); }; _curryContinuousAnchor("ContinuousLeft", ["left"]); _curryContinuousAnchor("ContinuousTop", ["top"]); _curryContinuousAnchor("ContinuousBottom", ["bottom"]); _curryContinuousAnchor("ContinuousRight", ["right"]); // ------- position assign anchors ------------------- // this anchor type lets you assign the position at connection time. _curryAnchor(0, 0, 0, 0, "Assign", function (anchor, params) { // find what to use as the "position finder". the user may have supplied a String which represents // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the // position finder as a function. we find out what to use and then set it on the anchor. var pf = params.position || "Fixed"; anchor.positionFinder = pf.constructor === String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf; // always set the constructor params; the position finder might need them later (the Grid one does, // for example) anchor.constructorParams = params; }); // these are the default anchor positions finders, which are used by the makeTarget function. supplying // a position finder argument to that function allows you to specify where the resulting anchor will // be located root.jsPlumbInstance.prototype.AnchorPositionFinders = { "Fixed": function (dp, ep, es) { return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ]; }, "Grid": function (dp, ep, es, params) { var dx = dp.left - ep.left, dy = dp.top - ep.top, gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]), mx = Math.floor(dx / gx), my = Math.floor(dy / gy); return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ]; } }; // ------- perimeter anchors ------------------- _jp.Anchors.Perimeter = function (params) { params = params || {}; var anchorCount = params.anchorCount || 60, shape = params.shape; if (!shape) { throw new Error("no shape supplied to Perimeter Anchor type"); } var _circle = function () { var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = []; for (var i = 0; i < anchorCount; i++) { var x = r + (r * Math.sin(current)), y = r + (r * Math.cos(current)); a.push([ x, y, 0, 0 ]); current += step; } return a; }, _path = function (segments) { var anchorsPerFace = anchorCount / segments.length, a = [], _computeFace = function (x1, y1, x2, y2, fractionalLength) { anchorsPerFace = anchorCount * fractionalLength; var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace; for (var i = 0; i < anchorsPerFace; i++) { a.push([ x1 + (dx * i), y1 + (dy * i), 0, 0 ]); } }; for (var i = 0; i < segments.length; i++) { _computeFace.apply(null, segments[i]); } return a; }, _shape = function (faces) { var s = []; for (var i = 0; i < faces.length; i++) { s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]); } return _path(s); }, _rectangle = function () { return _shape([ [ 0, 0, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ] ]); }; var _shapes = { "Circle": _circle, "Ellipse": _circle, "Diamond": function () { return _shape([ [ 0.5, 0, 1, 0.5 ], [ 1, 0.5, 0.5, 1 ], [ 0.5, 1, 0, 0.5 ], [ 0, 0.5, 0.5, 0 ] ]); }, "Rectangle": _rectangle, "Square": _rectangle, "Triangle": function () { return _shape([ [ 0.5, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0.5, 0] ]); }, "Path": function (params) { var points = params.points, p = [], tl = 0; for (var i = 0; i < points.length - 1; i++) { var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1])); tl += l; p.push([points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], l]); } for (var j = 0; j < p.length; j++) { p[j][4] = p[j][4] / tl; } return _path(p); } }, _rotate = function (points, amountInDegrees) { var o = [], theta = amountInDegrees / 180 * Math.PI; for (var i = 0; i < points.length; i++) { var _x = points[i][0] - 0.5, _y = points[i][1] - 0.5; o.push([ 0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))), 0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))), points[i][2], points[i][3] ]); } return o; }; if (!_shapes[shape]) { throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type"); } var da = _shapes[shape](params); if (params.rotation) { da = _rotate(da, params.rotation); } var a = params.jsPlumbInstance.makeDynamicAnchor(da); a.type = "Perimeter"; return a; }; }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the default Connectors, Endpoint and Overlay definitions. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jg = root.Biltong; _jp.Segments = { /* * Class: AbstractSegment * A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc', * 'Bezier'. This is new from 1.4.2, and gives us a lot more flexibility when drawing connections: things such * as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are * much easier to do now. * * A Segment is responsible for providing coordinates for painting it, and also must be able to report its length. * */ AbstractSegment: function (params) { this.params = params; /** * Function: findClosestPointOnPath * Finds the closest point on this segment to the given [x, y], * returning both the x and y of the point plus its distance from * the supplied point, and its location along the length of the * path inscribed by the segment. This implementation returns * Infinity for distance and null values for everything else; * subclasses are expected to override. */ this.findClosestPointOnPath = function (x, y) { return { d: Infinity, x: null, y: null, l: null }; }; this.getBounds = function () { return { minX: Math.min(params.x1, params.x2), minY: Math.min(params.y1, params.y2), maxX: Math.max(params.x1, params.x2), maxY: Math.max(params.y1, params.y2) }; }; /** * Computes the list of points on the segment that intersect the given line. * @method lineIntersection * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @returns {Array<[number, number]>} */ this.lineIntersection = function(x1, y1, x2, y2) { return []; }; /** * Computes the list of points on the segment that intersect the box with the given origin and size. * @method boxIntersection * @param {number} x1 * @param {number} y1 * @param {number} w * @param {number} h * @returns {Array<[number, number]>} */ this.boxIntersection = function(x, y, w, h) { var a = []; a.push.apply(a, this.lineIntersection(x, y, x + w, y)); a.push.apply(a, this.lineIntersection(x + w, y, x + w, y + h)); a.push.apply(a, this.lineIntersection(x + w, y + h, x, y + h)); a.push.apply(a, this.lineIntersection(x, y + h, x, y)); return a; }; /** * Computes the list of points on the segment that intersect the given bounding box, which is an object of the form { x:.., y:.., w:.., h:.. }. * @method lineIntersection * @param {BoundingRectangle} box * @returns {Array<[number, number]>} */ this.boundingBoxIntersection = function(box) { return this.boxIntersection(box.x, box.y, box.w, box.y); }; }, Straight: function (params) { var _super = _jp.Segments.AbstractSegment.apply(this, arguments), length, m, m2, x1, x2, y1, y2, _recalc = function () { length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); m = _jg.gradient({x: x1, y: y1}, {x: x2, y: y2}); m2 = -1 / m; }; this.type = "Straight"; this.getLength = function () { return length; }; this.getGradient = function () { return m; }; this.getCoordinates = function () { return { x1: x1, y1: y1, x2: x2, y2: y2 }; }; this.setCoordinates = function (coords) { x1 = coords.x1; y1 = coords.y1; x2 = coords.x2; y2 = coords.y2; _recalc(); }; this.setCoordinates({x1: params.x1, y1: params.y1, x2: params.x2, y2: params.y2}); this.getBounds = function () { return { minX: Math.min(x1, x2), minY: Math.min(y1, y2), maxX: Math.max(x1, x2), maxY: Math.max(y1, y2) }; }; /** * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from * 0 to 1 inclusive. for the straight line segment this is simple maths. */ this.pointOnPath = function (location, absolute) { if (location === 0 && !absolute) { return { x: x1, y: y1 }; } else if (location === 1 && !absolute) { return { x: x2, y: y2 }; } else { var l = absolute ? location > 0 ? location : length + location : location * length; return _jg.pointOnLine({x: x1, y: y1}, {x: x2, y: y2}, l); } }; /** * returns the gradient of the segment at the given point - which for us is constant. */ this.gradientAtPoint = function (_) { return m; }; /** * returns the point on the segment's path that is 'distance' along the length of the path from 'location', where * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels. * this hands off to jsPlumbUtil to do the maths, supplying two points and the distance. */ this.pointAlongPathFrom = function (location, distance, absolute) { var p = this.pointOnPath(location, absolute), farAwayPoint = distance <= 0 ? {x: x1, y: y1} : {x: x2, y: y2 }; /* location == 1 ? { x:x1 + ((x2 - x1) * 10), y:y1 + ((y1 - y2) * 10) } : */ if (distance <= 0 && Math.abs(distance) > 1) { distance *= -1; } return _jg.pointOnLine(p, farAwayPoint, distance); }; // is c between a and b? var within = function (a, b, c) { return c >= Math.min(a, b) && c <= Math.max(a, b); }; // find which of a and b is closest to c var closest = function (a, b, c) { return Math.abs(c - a) < Math.abs(c - b) ? a : b; }; /** Function: findClosestPointOnPath Finds the closest point on this segment to [x,y]. See notes on this method in AbstractSegment. */ this.findClosestPointOnPath = function (x, y) { var out = { d: Infinity, x: null, y: null, l: null, x1: x1, x2: x2, y1: y1, y2: y2 }; if (m === 0) { out.y = y1; out.x = within(x1, x2, x) ? x : closest(x1, x2, x); } else if (m === Infinity || m === -Infinity) { out.x = x1; out.y = within(y1, y2, y) ? y : closest(y1, y2, y); } else { // closest point lies on normal from given point to this line. var b = y1 - (m * x1), b2 = y - (m2 * x), // y1 = m.x1 + b and y1 = m2.x1 + b2 // so m.x1 + b = m2.x1 + b2 // x1(m - m2) = b2 - b // x1 = (b2 - b) / (m - m2) _x1 = (b2 - b) / (m - m2), _y1 = (m * _x1) + b; out.x = within(x1, x2, _x1) ? _x1 : closest(x1, x2, _x1);//_x1; out.y = within(y1, y2, _y1) ? _y1 : closest(y1, y2, _y1);//_y1; } var fractionInSegment = _jg.lineLength([ out.x, out.y ], [ x1, y1 ]); out.d = _jg.lineLength([x, y], [out.x, out.y]); out.l = fractionInSegment / length; return out; }; var _pointLiesBetween = function(q, p1, p2) { return (p2 > p1) ? (p1 <= q && q <= p2) : (p1 >= q && q >= p2); }, _plb = _pointLiesBetween; /** * Calculates all intersections of the given line with this segment. * @param _x1 * @param _y1 * @param _x2 * @param _y2 * @returns {Array} */ this.lineIntersection = function(_x1, _y1, _x2, _y2) { var m2 = Math.abs(_jg.gradient({x: _x1, y: _y1}, {x: _x2, y: _y2})), m1 = Math.abs(m), b = m1 === Infinity ? x1 : y1 - (m1 * x1), out = [], b2 = m2 === Infinity ? _x1 : _y1 - (m2 * _x1); // if lines parallel, no intersection if (m2 !== m1) { // perpendicular, segment horizontal if(m2 === Infinity && m1 === 0) { if (_plb(_x1, x1, x2) && _plb(y1, _y1, _y2)) { out = [ _x1, y1 ]; // we return X on the incident line and Y from the segment } } else if(m2 === 0 && m1 === Infinity) { // perpendicular, segment vertical if(_plb(_y1, y1, y2) && _plb(x1, _x1, _x2)) { out = [x1, _y1]; // we return X on the segment and Y from the incident line } } else { var X, Y; if (m2 === Infinity) { // test line is a vertical line. where does it cross the segment? X = _x1; if (_plb(X, x1, x2)) { Y = (m1 * _x1) + b; if (_plb(Y, _y1, _y2)) { out = [ X, Y ]; } } } else if (m2 === 0) { Y = _y1; // test line is a horizontal line. where does it cross the segment? if (_plb(Y, y1, y2)) { X = (_y1 - b) / m1; if (_plb(X, _x1, _x2)) { out = [ X, Y ]; } } } else { // mX + b = m2X + b2 // mX - m2X = b2 - b // X(m - m2) = b2 - b // X = (b2 - b) / (m - m2) // Y = mX + b X = (b2 - b) / (m1 - m2); Y = (m1 * X) + b; if(_plb(X, x1, x2) && _plb(Y, y1, y2)) { out = [ X, Y]; } } } } return out; }; /** * Calculates all intersections of the given box with this segment. By default this method simply calls `lineIntersection` with each of the four * faces of the box; subclasses can override this if they think there's a faster way to compute the entire box at once. * @param x X position of top left corner of box * @param y Y position of top left corner of box * @param w width of box * @param h height of box * @returns {Array} */ this.boxIntersection = function(x, y, w, h) { var a = []; a.push.apply(a, this.lineIntersection(x, y, x + w, y)); a.push.apply(a, this.lineIntersection(x + w, y, x + w, y + h)); a.push.apply(a, this.lineIntersection(x + w, y + h, x, y + h)); a.push.apply(a, this.lineIntersection(x, y + h, x, y)); return a; }; /** * Calculates all intersections of the given bounding box with this segment. By default this method simply calls `lineIntersection` with each of the four * faces of the box; subclasses can override this if they think there's a faster way to compute the entire box at once. * @param box Bounding box, in { x:.., y:..., w:..., h:... } format. * @returns {Array} */ this.boundingBoxIntersection = function(box) { return this.boxIntersection(box.x, box.y, box.w, box.h); }; }, /* Arc Segment. You need to supply: r - radius cx - center x for the arc cy - center y for the arc ac - whether the arc is anticlockwise or not. default is clockwise. and then either: startAngle - startAngle for the arc. endAngle - endAngle for the arc. or: x1 - x for start point y1 - y for start point x2 - x for end point y2 - y for end point */ Arc: function (params) { var _super = _jp.Segments.AbstractSegment.apply(this, arguments), _calcAngle = function (_x, _y) { return _jg.theta([params.cx, params.cy], [_x, _y]); }, _calcAngleForLocation = function (segment, location) { if (segment.anticlockwise) { var sa = segment.startAngle < segment.endAngle ? segment.startAngle + TWO_PI : segment.startAngle, s = Math.abs(sa - segment.endAngle); return sa - (s * location); } else { var ea = segment.endAngle < segment.startAngle ? segment.endAngle + TWO_PI : segment.endAngle, ss = Math.abs(ea - segment.startAngle); return segment.startAngle + (ss * location); } }, TWO_PI = 2 * Math.PI; this.radius = params.r; this.anticlockwise = params.ac; this.type = "Arc"; if (params.startAngle && params.endAngle) { this.startAngle = params.startAngle; this.endAngle = params.endAngle; this.x1 = params.cx + (this.radius * Math.cos(params.startAngle)); this.y1 = params.cy + (this.radius * Math.sin(params.startAngle)); this.x2 = params.cx + (this.radius * Math.cos(params.endAngle)); this.y2 = params.cy + (this.radius * Math.sin(params.endAngle)); } else { this.startAngle = _calcAngle(params.x1, params.y1); this.endAngle = _calcAngle(params.x2, params.y2); this.x1 = params.x1; this.y1 = params.y1; this.x2 = params.x2; this.y2 = params.y2; } if (this.endAngle < 0) { this.endAngle += TWO_PI; } if (this.startAngle < 0) { this.startAngle += TWO_PI; } // segment is used by vml //this.segment = _jg.quadrant([this.x1, this.y1], [this.x2, this.y2]); // we now have startAngle and endAngle as positive numbers, meaning the // absolute difference (|d|) between them is the sweep (s) of this arc, unless the // arc is 'anticlockwise' in which case 's' is given by 2PI - |d|. var ea = this.endAngle < this.startAngle ? this.endAngle + TWO_PI : this.endAngle; this.sweep = Math.abs(ea - this.startAngle); if (this.anticlockwise) { this.sweep = TWO_PI - this.sweep; } var circumference = 2 * Math.PI * this.radius, frac = this.sweep / TWO_PI, length = circumference * frac; this.getLength = function () { return length; }; this.getBounds = function () { return { minX: params.cx - params.r, maxX: params.cx + params.r, minY: params.cy - params.r, maxY: params.cy + params.r }; }; var VERY_SMALL_VALUE = 0.0000000001, gentleRound = function (n) { var f = Math.floor(n), r = Math.ceil(n); if (n - f < VERY_SMALL_VALUE) { return f; } else if (r - n < VERY_SMALL_VALUE) { return r; } return n; }; /** * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from * 0 to 1 inclusive. */ this.pointOnPath = function (location, absolute) { if (location === 0) { return { x: this.x1, y: this.y1, theta: this.startAngle }; } else if (location === 1) { return { x: this.x2, y: this.y2, theta: this.endAngle }; } if (absolute) { location = location / length; } var angle = _calcAngleForLocation(this, location), _x = params.cx + (params.r * Math.cos(angle)), _y = params.cy + (params.r * Math.sin(angle)); return { x: gentleRound(_x), y: gentleRound(_y), theta: angle }; }; /** * returns the gradient of the segment at the given point. */ this.gradientAtPoint = function (location, absolute) { var p = this.pointOnPath(location, absolute); var m = _jg.normal([ params.cx, params.cy ], [p.x, p.y ]); if (!this.anticlockwise && (m === Infinity || m === -Infinity)) { m *= -1; } return m; }; this.pointAlongPathFrom = function (location, distance, absolute) { var p = this.pointOnPath(location, absolute), arcSpan = distance / circumference * 2 * Math.PI, dir = this.anticlockwise ? -1 : 1, startAngle = p.theta + (dir * arcSpan), startX = params.cx + (this.radius * Math.cos(startAngle)), startY = params.cy + (this.radius * Math.sin(startAngle)); return {x: startX, y: startY}; }; // TODO: lineIntersection }, Bezier: function (params) { this.curve = [ { x: params.x1, y: params.y1}, { x: params.cp1x, y: params.cp1y }, { x: params.cp2x, y: params.cp2y }, { x: params.x2, y: params.y2 } ]; var _super = _jp.Segments.AbstractSegment.apply(this, arguments); // although this is not a strictly rigorous determination of bounds // of a bezier curve, it works for the types of curves that this segment // type produces. this.bounds = { minX: Math.min(params.x1, params.x2, params.cp1x, params.cp2x), minY: Math.min(params.y1, params.y2, params.cp1y, params.cp2y), maxX: Math.max(params.x1, params.x2, params.cp1x, params.cp2x), maxY: Math.max(params.y1, params.y2, params.cp1y, params.cp2y) }; this.type = "Bezier"; var _translateLocation = function (_curve, location, absolute) { if (absolute) { location = root.jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location); } return location; }; /** * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from * 0 to 1 inclusive. */ this.pointOnPath = function (location, absolute) { location = _translateLocation(this.curve, location, absolute); return root.jsBezier.pointOnCurve(this.curve, location); }; /** * returns the gradient of the segment at the given point. */ this.gradientAtPoint = function (location, absolute) { location = _translateLocation(this.curve, location, absolute); return root.jsBezier.gradientAtPoint(this.curve, location); }; this.pointAlongPathFrom = function (location, distance, absolute) { location = _translateLocation(this.curve, location, absolute); return root.jsBezier.pointAlongCurveFrom(this.curve, location, distance); }; this.getLength = function () { return root.jsBezier.getLength(this.curve); }; this.getBounds = function () { return this.bounds; }; this.findClosestPointOnPath = function (x, y) { var p = root.jsBezier.nearestPointOnCurve({x:x,y:y}, this.curve); return { d:Math.sqrt(Math.pow(p.point.x - x, 2) + Math.pow(p.point.y - y, 2)), x:p.point.x, y:p.point.y, l:p.location, s:this }; }; this.lineIntersection = function(x1, y1, x2, y2) { return root.jsBezier.lineIntersection(x1, y1, x2, y2, this.curve); }; } }; _jp.SegmentRenderer = { getPath: function (segment, isFirstSegment) { return ({ "Straight": function (isFirstSegment) { var d = segment.getCoordinates(); return (isFirstSegment ? "M " + d.x1 + " " + d.y1 + " " : "") + "L " + d.x2 + " " + d.y2; }, "Bezier": function (isFirstSegment) { var d = segment.params; return (isFirstSegment ? "M " + d.x2 + " " + d.y2 + " " : "") + "C " + d.cp2x + " " + d.cp2y + " " + d.cp1x + " " + d.cp1y + " " + d.x1 + " " + d.y1; }, "Arc": function (isFirstSegment) { var d = segment.params, laf = segment.sweep > Math.PI ? 1 : 0, sf = segment.anticlockwise ? 0 : 1; return (isFirstSegment ? "M" + segment.x1 + " " + segment.y1 + " " : "") + "A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2; } })[segment.type](isFirstSegment); } }; /* Class: UIComponent Superclass for Connector and AbstractEndpoint. */ var AbstractComponent = function () { this.resetBounds = function () { this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; }; this.resetBounds(); }; /* * Class: Connector * Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it * can be accessed from other files. You should not try to instantiate one of these directly. * * When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch * that request to. This is done by keeping track of the total connector length as segments are added, and also * their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching * the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.) */ _jp.Connectors.AbstractConnector = function (params) { AbstractComponent.apply(this, arguments); var segments = [], totalLength = 0, segmentProportions = [], segmentProportionalLengths = [], stub = params.stub || 0, sourceStub = _ju.isArray(stub) ? stub[0] : stub, targetStub = _ju.isArray(stub) ? stub[1] : stub, gap = params.gap || 0, sourceGap = _ju.isArray(gap) ? gap[0] : gap, targetGap = _ju.isArray(gap) ? gap[1] : gap, userProvidedSegments = null, paintInfo = null; this.getPathData = function() { var p = ""; for (var i = 0; i < segments.length; i++) { p += _jp.SegmentRenderer.getPath(segments[i], i === 0); p += " "; } return p; }; /** * Function: findSegmentForPoint * Returns the segment that is closest to the given [x,y], * null if nothing found. This function returns a JS * object with: * * d - distance from segment * l - proportional location in segment * x - x point on the segment * y - y point on the segment * s - the segment itself. */ this.findSegmentForPoint = function (x, y) { var out = { d: Infinity, s: null, x: null, y: null, l: null }; for (var i = 0; i < segments.length; i++) { var _s = segments[i].findClosestPointOnPath(x, y); if (_s.d < out.d) { out.d = _s.d; out.l = _s.l; out.x = _s.x; out.y = _s.y; out.s = segments[i]; out.x1 = _s.x1; out.x2 = _s.x2; out.y1 = _s.y1; out.y2 = _s.y2; out.index = i; } } return out; }; this.lineIntersection = function(x1, y1, x2, y2) { var out = []; for (var i = 0; i < segments.length; i++) { out.push.apply(out, segments[i].lineIntersection(x1, y1, x2, y2)); } return out; }; this.boxIntersection = function(x, y, w, h) { var out = []; for (var i = 0; i < segments.length; i++) { out.push.apply(out, segments[i].boxIntersection(x, y, w, h)); } return out; }; this.boundingBoxIntersection = function(box) { var out = []; for (var i = 0; i < segments.length; i++) { out.push.apply(out, segments[i].boundingBoxIntersection(box)); } return out; }; var _updateSegmentProportions = function () { var curLoc = 0; for (var i = 0; i < segments.length; i++) { var sl = segments[i].getLength(); segmentProportionalLengths[i] = sl / totalLength; segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ]; } }, /** * returns [segment, proportion of travel in segment, segment index] for the segment * that contains the point which is 'location' distance along the entire path, where * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths * are made up of a list of segments, each of which contributes some fraction to * the total length. * From 1.3.10 this also supports the 'absolute' property, which lets us specify a location * as the absolute distance in pixels, rather than a proportion of the total path. */ _findSegmentForLocation = function (location, absolute) { if (absolute) { location = location > 0 ? location / totalLength : (totalLength + location) / totalLength; } var idx = segmentProportions.length - 1, inSegmentProportion = 1; for (var i = 0; i < segmentProportions.length; i++) { if (segmentProportions[i][1] >= location) { idx = i; // todo is this correct for all connector path types? inSegmentProportion = location === 1 ? 1 : location === 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i]; break; } } return { segment: segments[idx], proportion: inSegmentProportion, index: idx }; }, _addSegment = function (conn, type, params) { if (params.x1 === params.x2 && params.y1 === params.y2) { return; } var s = new _jp.Segments[type](params); segments.push(s); totalLength += s.getLength(); conn.updateBounds(s); }, _clearSegments = function () { totalLength = segments.length = segmentProportions.length = segmentProportionalLengths.length = 0; }; this.setSegments = function (_segs) { userProvidedSegments = []; totalLength = 0; for (var i = 0; i < _segs.length; i++) { userProvidedSegments.push(_segs[i]); totalLength += _segs[i].getLength(); } }; this.getLength = function() { return totalLength; }; var _prepareCompute = function (params) { this.strokeWidth = params.strokeWidth; var segment = _jg.quadrant(params.sourcePos, params.targetPos), swapX = params.targetPos[0] < params.sourcePos[0], swapY = params.targetPos[1] < params.sourcePos[1], lw = params.strokeWidth || 1, so = params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint), to = params.targetEndpoint.anchor.getOrientation(params.targetEndpoint), x = swapX ? params.targetPos[0] : params.sourcePos[0], y = swapY ? params.targetPos[1] : params.sourcePos[1], w = Math.abs(params.targetPos[0] - params.sourcePos[0]), h = Math.abs(params.targetPos[1] - params.sourcePos[1]); // if either anchor does not have an orientation set, we derive one from their relative // positions. we fix the axis to be the one in which the two elements are further apart, and // point each anchor at the other element. this is also used when dragging a new connection. if (so[0] === 0 && so[1] === 0 || to[0] === 0 && to[1] === 0) { var index = w > h ? 0 : 1, oIndex = [1, 0][index]; so = []; to = []; so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1; to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1; so[oIndex] = 0; to[oIndex] = 0; } var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0], sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1], tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]), ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]), oProduct = ((so[0] * to[0]) + (so[1] * to[1])); var result = { sx: sx, sy: sy, tx: tx, ty: ty, lw: lw, xSpan: Math.abs(tx - sx), ySpan: Math.abs(ty - sy), mx: (sx + tx) / 2, my: (sy + ty) / 2, so: so, to: to, x: x, y: y, w: w, h: h, segment: segment, startStubX: sx + (so[0] * sourceStub), startStubY: sy + (so[1] * sourceStub), endStubX: tx + (to[0] * targetStub), endStubY: ty + (to[1] * targetStub), isXGreaterThanStubTimes2: Math.abs(sx - tx) > (sourceStub + targetStub), isYGreaterThanStubTimes2: Math.abs(sy - ty) > (sourceStub + targetStub), opposite: oProduct === -1, perpendicular: oProduct === 0, orthogonal: oProduct === 1, sourceAxis: so[0] === 0 ? "y" : "x", points: [x, y, w, h, sx, sy, tx, ty ], stubs:[sourceStub, targetStub] }; result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular"; return result; }; this.getSegments = function () { return segments; }; this.updateBounds = function (segment) { var segBounds = segment.getBounds(); this.bounds.minX = Math.min(this.bounds.minX, segBounds.minX); this.bounds.maxX = Math.max(this.bounds.maxX, segBounds.maxX); this.bounds.minY = Math.min(this.bounds.minY, segBounds.minY); this.bounds.maxY = Math.max(this.bounds.maxY, segBounds.maxY); }; var dumpSegmentsToConsole = function () { console.log("SEGMENTS:"); for (var i = 0; i < segments.length; i++) { console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]); } }; this.pointOnPath = function (location, absolute) { var seg = _findSegmentForLocation(location, absolute); return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || [0, 0]; }; this.gradientAtPoint = function (location, absolute) { var seg = _findSegmentForLocation(location, absolute); return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0; }; this.pointAlongPathFrom = function (location, distance, absolute) { var seg = _findSegmentForLocation(location, absolute); // TODO what happens if this crosses to the next segment? return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || [0, 0]; }; this.compute = function (params) { paintInfo = _prepareCompute.call(this, params); _clearSegments(); this._compute(paintInfo, params); this.x = paintInfo.points[0]; this.y = paintInfo.points[1]; this.w = paintInfo.points[2]; this.h = paintInfo.points[3]; this.segment = paintInfo.segment; _updateSegmentProportions(); }; return { addSegment: _addSegment, prepareCompute: _prepareCompute, sourceStub: sourceStub, targetStub: targetStub, maxStub: Math.max(sourceStub, targetStub), sourceGap: sourceGap, targetGap: targetGap, maxGap: Math.max(sourceGap, targetGap) }; }; _ju.extend(_jp.Connectors.AbstractConnector, AbstractComponent); // ********************************* END OF CONNECTOR TYPES ******************************************************************* // ********************************* ENDPOINT TYPES ******************************************************************* _jp.Endpoints.AbstractEndpoint = function (params) { AbstractComponent.apply(this, arguments); var compute = this.compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { var out = this._compute.apply(this, arguments); this.x = out[0]; this.y = out[1]; this.w = out[2]; this.h = out[3]; this.bounds.minX = this.x; this.bounds.minY = this.y; this.bounds.maxX = this.x + this.w; this.bounds.maxY = this.y + this.h; return out; }; return { compute: compute, cssClass: params.cssClass }; }; _ju.extend(_jp.Endpoints.AbstractEndpoint, AbstractComponent); /** * Class: Endpoints.Dot * A round endpoint, with default radius 10 pixels. */ /** * Function: Constructor * * Parameters: * * radius - radius of the endpoint. defaults to 10 pixels. */ _jp.Endpoints.Dot = function (params) { this.type = "Dot"; var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments); params = params || {}; this.radius = params.radius || 10; this.defaultOffset = 0.5 * this.radius; this.defaultInnerRadius = this.radius / 3; this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { this.radius = endpointStyle.radius || this.radius; var x = anchorPoint[0] - this.radius, y = anchorPoint[1] - this.radius, w = this.radius * 2, h = this.radius * 2; if (endpointStyle.stroke) { var lw = endpointStyle.strokeWidth || 1; x -= lw; y -= lw; w += (lw * 2); h += (lw * 2); } return [ x, y, w, h, this.radius ]; }; }; _ju.extend(_jp.Endpoints.Dot, _jp.Endpoints.AbstractEndpoint); _jp.Endpoints.Rectangle = function (params) { this.type = "Rectangle"; var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments); params = params || {}; this.width = params.width || 20; this.height = params.height || 20; this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { var width = endpointStyle.width || this.width, height = endpointStyle.height || this.height, x = anchorPoint[0] - (width / 2), y = anchorPoint[1] - (height / 2); return [ x, y, width, height]; }; }; _ju.extend(_jp.Endpoints.Rectangle, _jp.Endpoints.AbstractEndpoint); var DOMElementEndpoint = function (params) { _jp.jsPlumbUIComponent.apply(this, arguments); this._jsPlumb.displayElements = []; }; _ju.extend(DOMElementEndpoint, _jp.jsPlumbUIComponent, { getDisplayElements: function () { return this._jsPlumb.displayElements; }, appendDisplayElement: function (el) { this._jsPlumb.displayElements.push(el); } }); /** * Class: Endpoints.Image * Draws an image as the Endpoint. */ /** * Function: Constructor * * Parameters: * * src - location of the image to use. TODO: multiple references to self. not sure quite how to get rid of them entirely. perhaps self = null in the cleanup function will suffice TODO this class still might leak memory. */ _jp.Endpoints.Image = function (params) { this.type = "Image"; DOMElementEndpoint.apply(this, arguments); _jp.Endpoints.AbstractEndpoint.apply(this, arguments); var _onload = params.onload, src = params.src || params.url, clazz = params.cssClass ? " " + params.cssClass : ""; this._jsPlumb.img = new Image(); this._jsPlumb.ready = false; this._jsPlumb.initialized = false; this._jsPlumb.deleted = false; this._jsPlumb.widthToUse = params.width; this._jsPlumb.heightToUse = params.height; this._jsPlumb.endpoint = params.endpoint; this._jsPlumb.img.onload = function () { if (this._jsPlumb != null) { this._jsPlumb.ready = true; this._jsPlumb.widthToUse = this._jsPlumb.widthToUse || this._jsPlumb.img.width; this._jsPlumb.heightToUse = this._jsPlumb.heightToUse || this._jsPlumb.img.height; if (_onload) { _onload(this); } } }.bind(this); /* Function: setImage Sets the Image to use in this Endpoint. Parameters: img - may be a URL or an Image object onload - optional; a callback to execute once the image has loaded. */ this._jsPlumb.endpoint.setImage = function (_img, onload) { var s = _img.constructor === String ? _img : _img.src; _onload = onload; this._jsPlumb.img.src = s; if (this.canvas != null) { this.canvas.setAttribute("src", this._jsPlumb.img.src); } }.bind(this); this._jsPlumb.endpoint.setImage(src, _onload); this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { this.anchorPoint = anchorPoint; if (this._jsPlumb.ready) { return [anchorPoint[0] - this._jsPlumb.widthToUse / 2, anchorPoint[1] - this._jsPlumb.heightToUse / 2, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse]; } else { return [0, 0, 0, 0]; } }; this.canvas = _jp.createElement("img", { position:"absolute", margin:0, padding:0, outline:0 }, this._jsPlumb.instance.endpointClass + clazz); if (this._jsPlumb.widthToUse) { this.canvas.setAttribute("width", this._jsPlumb.widthToUse); } if (this._jsPlumb.heightToUse) { this.canvas.setAttribute("height", this._jsPlumb.heightToUse); } this._jsPlumb.instance.appendElement(this.canvas); this.actuallyPaint = function (d, style, anchor) { if (!this._jsPlumb.deleted) { if (!this._jsPlumb.initialized) { this.canvas.setAttribute("src", this._jsPlumb.img.src); this.appendDisplayElement(this.canvas); this._jsPlumb.initialized = true; } var x = this.anchorPoint[0] - (this._jsPlumb.widthToUse / 2), y = this.anchorPoint[1] - (this._jsPlumb.heightToUse / 2); _ju.sizeElement(this.canvas, x, y, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse); } }; this.paint = function (style, anchor) { if (this._jsPlumb != null) { // may have been deleted if (this._jsPlumb.ready) { this.actuallyPaint(style, anchor); } else { root.setTimeout(function () { this.paint(style, anchor); }.bind(this), 200); } } }; }; _ju.extend(_jp.Endpoints.Image, [ DOMElementEndpoint, _jp.Endpoints.AbstractEndpoint ], { cleanup: function (force) { if (force) { this._jsPlumb.deleted = true; if (this.canvas) { this.canvas.parentNode.removeChild(this.canvas); } this.canvas = null; } } }); /* * Class: Endpoints.Blank * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints. */ _jp.Endpoints.Blank = function (params) { var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments); this.type = "Blank"; DOMElementEndpoint.apply(this, arguments); this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { return [anchorPoint[0], anchorPoint[1], 10, 0]; }; var clazz = params.cssClass ? " " + params.cssClass : ""; this.canvas = _jp.createElement("div", { display: "block", width: "1px", height: "1px", background: "transparent", position: "absolute" }, this._jsPlumb.instance.endpointClass + clazz); this._jsPlumb.instance.appendElement(this.canvas); this.paint = function (style, anchor) { _ju.sizeElement(this.canvas, this.x, this.y, this.w, this.h); }; }; _ju.extend(_jp.Endpoints.Blank, [_jp.Endpoints.AbstractEndpoint, DOMElementEndpoint], { cleanup: function () { if (this.canvas && this.canvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas); } } }); /* * Class: Endpoints.Triangle * A triangular Endpoint. */ /* * Function: Constructor * * Parameters: * * width width of the triangle's base. defaults to 55 pixels. * height height of the triangle from base to apex. defaults to 55 pixels. */ _jp.Endpoints.Triangle = function (params) { this.type = "Triangle"; _jp.Endpoints.AbstractEndpoint.apply(this, arguments); var self = this; params = params || { }; params.width = params.width || 55; params.height = params.height || 55; this.width = params.width; this.height = params.height; this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) { var width = endpointStyle.width || self.width, height = endpointStyle.height || self.height, x = anchorPoint[0] - (width / 2), y = anchorPoint[1] - (height / 2); return [ x, y, width, height ]; }; }; // ********************************* END OF ENDPOINT TYPES ******************************************************************* // ********************************* OVERLAY DEFINITIONS *********************************************************************** var AbstractOverlay = _jp.Overlays.AbstractOverlay = function (params) { this.visible = true; this.isAppendedAtTopLevel = true; this.component = params.component; this.loc = params.location == null ? 0.5 : params.location; this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation; this.visible = params.visible !== false; }; AbstractOverlay.prototype = { cleanup: function (force) { if (force) { this.component = null; this.canvas = null; this.endpointLoc = null; } }, reattach:function(instance, component) { }, setVisible: function (val) { this.visible = val; this.component.repaint(); }, isVisible: function () { return this.visible; }, hide: function () { this.setVisible(false); }, show: function () { this.setVisible(true); }, incrementLocation: function (amount) { this.loc += amount; this.component.repaint(); }, setLocation: function (l) { this.loc = l; this.component.repaint(); }, getLocation: function () { return this.loc; }, updateFrom:function() { } }; /* * Class: Overlays.Arrow * * An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction * of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line * across the tail. */ /* * @constructor * * @param {Object} params Constructor params. * @param {Number} [params.length] Distance in pixels from head to tail baseline. default 20. * @param {Number} [params.width] Width in pixels of the tail baseline. default 20. * @param {String} [params.fill] Style to use when filling the arrow. defaults to "black". * @param {String} [params.stroke] Style to use when stroking the arrow. defaults to null, which means the arrow is not stroked. * @param {Number} [params.stroke-width] Line width to use when stroking the arrow. defaults to 1, but only used if stroke is not null. * @param {Number} [params.foldback] Distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623. * @param {Number} [params.location] Distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5. * @param {NUmber} [params.direction] Indicates the direction the arrow points in. valid values are -1 and 1; 1 is default. */ _jp.Overlays.Arrow = function (params) { this.type = "Arrow"; AbstractOverlay.apply(this, arguments); this.isAppendedAtTopLevel = false; params = params || {}; var self = this; this.length = params.length || 20; this.width = params.width || 20; this.id = params.id; var direction = (params.direction || 1) < 0 ? -1 : 1, paintStyle = params.paintStyle || { "stroke-width": 1 }, // how far along the arrow the lines folding back in come to. default is 62.3%. foldback = params.foldback || 0.623; this.computeMaxSize = function () { return self.width * 1.5; }; this.elementCreated = function(p, component) { this.path = p; if (params.events) { for (var i in params.events) { _jp.on(p, i, params.events[i]); } } }; this.draw = function (component, currentConnectionPaintStyle) { var hxy, mid, txy, tail, cxy; if (component.pointAlongPathFrom) { if (_ju.isString(this.loc) || this.loc > 1 || this.loc < 0) { var l = parseInt(this.loc, 10), fromLoc = this.loc < 0 ? 1 : 0; hxy = component.pointAlongPathFrom(fromLoc, l, false); mid = component.pointAlongPathFrom(fromLoc, l - (direction * this.length / 2), false); txy = _jg.pointOnLine(hxy, mid, this.length); } else if (this.loc === 1) { hxy = component.pointOnPath(this.loc); mid = component.pointAlongPathFrom(this.loc, -(this.length)); txy = _jg.pointOnLine(hxy, mid, this.length); if (direction === -1) { var _ = txy; txy = hxy; hxy = _; } } else if (this.loc === 0) { txy = component.pointOnPath(this.loc); mid = component.pointAlongPathFrom(this.loc, this.length); hxy = _jg.pointOnLine(txy, mid, this.length); if (direction === -1) { var __ = txy; txy = hxy; hxy = __; } } else { hxy = component.pointAlongPathFrom(this.loc, direction * this.length / 2); mid = component.pointOnPath(this.loc); txy = _jg.pointOnLine(hxy, mid, this.length); } tail = _jg.perpendicularLineTo(hxy, txy, this.width); cxy = _jg.pointOnLine(hxy, txy, foldback * this.length); var d = { hxy: hxy, tail: tail, cxy: cxy }, stroke = paintStyle.stroke || currentConnectionPaintStyle.stroke, fill = paintStyle.fill || currentConnectionPaintStyle.stroke, lineWidth = paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth; return { component: component, d: d, "stroke-width": lineWidth, stroke: stroke, fill: fill, minX: Math.min(hxy.x, tail[0].x, tail[1].x), maxX: Math.max(hxy.x, tail[0].x, tail[1].x), minY: Math.min(hxy.y, tail[0].y, tail[1].y), maxY: Math.max(hxy.y, tail[0].y, tail[1].y) }; } else { return {component: component, minX: 0, maxX: 0, minY: 0, maxY: 0}; } }; }; _ju.extend(_jp.Overlays.Arrow, AbstractOverlay, { updateFrom:function(d) { this.length = d.length || this.length; this.width = d.width|| this.width; this.direction = d.direction != null ? d.direction : this.direction; this.foldback = d.foldback|| this.foldback; }, cleanup:function() { if (this.path && this.canvas) { this.canvas.removeChild(this.path); } } }); /* * Class: Overlays.PlainArrow * * A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does * a 'call' to Arrow with foldback set appropriately. */ /* * Function: Constructor * See <Overlays.Arrow> for allowed parameters for this overlay. */ _jp.Overlays.PlainArrow = function (params) { params = params || {}; var p = _jp.extend(params, {foldback: 1}); _jp.Overlays.Arrow.call(this, p); this.type = "PlainArrow"; }; _ju.extend(_jp.Overlays.PlainArrow, _jp.Overlays.Arrow); /* * Class: Overlays.Diamond * * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just * happens that in this case, that point is greater than the length of the the arrow. * * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value * would be -l/4 in this case - move along one quarter of the total length. */ /* * Function: Constructor * See <Overlays.Arrow> for allowed parameters for this overlay. */ _jp.Overlays.Diamond = function (params) { params = params || {}; var l = params.length || 40, p = _jp.extend(params, {length: l / 2, foldback: 2}); _jp.Overlays.Arrow.call(this, p); this.type = "Diamond"; }; _ju.extend(_jp.Overlays.Diamond, _jp.Overlays.Arrow); var _getDimensions = function (component, forceRefresh) { if (component._jsPlumb.cachedDimensions == null || forceRefresh) { component._jsPlumb.cachedDimensions = component.getDimensions(); } return component._jsPlumb.cachedDimensions; }; // abstract superclass for overlays that add an element to the DOM. var AbstractDOMOverlay = function (params) { _jp.jsPlumbUIComponent.apply(this, arguments); AbstractOverlay.apply(this, arguments); // hand off fired events to associated component. var _f = this.fire; this.fire = function () { _f.apply(this, arguments); if (this.component) { this.component.fire.apply(this.component, arguments); } }; this.detached=false; this.id = params.id; this._jsPlumb.div = null; this._jsPlumb.initialised = false; this._jsPlumb.component = params.component; this._jsPlumb.cachedDimensions = null; this._jsPlumb.create = params.create; this._jsPlumb.initiallyInvisible = params.visible === false; this.getElement = function () { if (this._jsPlumb.div == null) { var div = this._jsPlumb.div = _jp.getElement(this._jsPlumb.create(this._jsPlumb.component)); div.style.position = "absolute"; jsPlumb.addClass(div, this._jsPlumb.instance.overlayClass + " " + (this.cssClass ? this.cssClass : params.cssClass ? params.cssClass : "")); this._jsPlumb.instance.appendElement(div); this._jsPlumb.instance.getId(div); this.canvas = div; // in IE the top left corner is what it placed at the desired location. This will not // be fixed. IE8 is not going to be supported for much longer. var ts = "translate(-50%, -50%)"; div.style.webkitTransform = ts; div.style.mozTransform = ts; div.style.msTransform = ts; div.style.oTransform = ts; div.style.transform = ts; // write the related component into the created element div._jsPlumb = this; if (params.visible === false) { div.style.display = "none"; } } return this._jsPlumb.div; }; this.draw = function (component, currentConnectionPaintStyle, absolutePosition) { var td = _getDimensions(this); if (td != null && td.length === 2) { var cxy = { x: 0, y: 0 }; // absolutePosition would have been set by a call to connection.setAbsoluteOverlayPosition. if (absolutePosition) { cxy = { x: absolutePosition[0], y: absolutePosition[1] }; } else if (component.pointOnPath) { var loc = this.loc, absolute = false; if (_ju.isString(this.loc) || this.loc < 0 || this.loc > 1) { loc = parseInt(this.loc, 10); absolute = true; } cxy = component.pointOnPath(loc, absolute); // a connection } else { var locToUse = this.loc.constructor === Array ? this.loc : this.endpointLoc; cxy = { x: locToUse[0] * component.w, y: locToUse[1] * component.h }; } var minx = cxy.x - (td[0] / 2), miny = cxy.y - (td[1] / 2); return { component: component, d: { minx: minx, miny: miny, td: td, cxy: cxy }, minX: minx, maxX: minx + td[0], minY: miny, maxY: miny + td[1] }; } else { return {minX: 0, maxX: 0, minY: 0, maxY: 0}; } }; }; _ju.extend(AbstractDOMOverlay, [_jp.jsPlumbUIComponent, AbstractOverlay], { getDimensions: function () { return [1,1]; }, setVisible: function (state) { if (this._jsPlumb.div) { this._jsPlumb.div.style.display = state ? "block" : "none"; // if initially invisible, dimensions are 0,0 and never get updated if (state && this._jsPlumb.initiallyInvisible) { _getDimensions(this, true); this.component.repaint(); this._jsPlumb.initiallyInvisible = false; } } }, /* * Function: clearCachedDimensions * Clears the cached dimensions for the label. As a performance enhancement, label dimensions are * cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but * there are other reasons why the text dimensions might change - if you make a change through CSS, for * example, you might change the font size. in that case you should explicitly call this method. */ clearCachedDimensions: function () { this._jsPlumb.cachedDimensions = null; }, cleanup: function (force) { if (force) { if (this._jsPlumb.div != null) { this._jsPlumb.div._jsPlumb = null; this._jsPlumb.instance.removeElement(this._jsPlumb.div); } } else { // if not a forced cleanup, just detach child from parent for now. if (this._jsPlumb && this._jsPlumb.div && this._jsPlumb.div.parentNode) { this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div); } this.detached = true; } }, reattach:function(instance, component) { if (this._jsPlumb.div != null) { instance.getContainer().appendChild(this._jsPlumb.div); } this.detached = false; }, computeMaxSize: function () { var td = _getDimensions(this); return Math.max(td[0], td[1]); }, paint: function (p, containerExtents) { if (!this._jsPlumb.initialised) { this.getElement(); p.component.appendDisplayElement(this._jsPlumb.div); this._jsPlumb.initialised = true; if (this.detached) { this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div); } } this._jsPlumb.div.style.left = (p.component.x + p.d.minx) + "px"; this._jsPlumb.div.style.top = (p.component.y + p.d.miny) + "px"; } }); /* * Class: Overlays.Custom * A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it. * The 'create' function is passed a Connection or Endpoint. */ /* * Function: Constructor * * Parameters: * create - function for jsPlumb to call that returns a DOM element. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5. * id - optional id to use for later retrieval of this overlay. * */ _jp.Overlays.Custom = function (params) { this.type = "Custom"; AbstractDOMOverlay.apply(this, arguments); }; _ju.extend(_jp.Overlays.Custom, AbstractDOMOverlay); _jp.Overlays.GuideLines = function () { var self = this; self.length = 50; self.strokeWidth = 5; this.type = "GuideLines"; AbstractOverlay.apply(this, arguments); _jp.jsPlumbUIComponent.apply(this, arguments); this.draw = function (connector, currentConnectionPaintStyle) { var head = connector.pointAlongPathFrom(self.loc, self.length / 2), mid = connector.pointOnPath(self.loc), tail = _jg.pointOnLine(head, mid, self.length), tailLine = _jg.perpendicularLineTo(head, tail, 40), headLine = _jg.perpendicularLineTo(tail, head, 20); return { connector: connector, head: head, tail: tail, headLine: headLine, tailLine: tailLine, minX: Math.min(head.x, tail.x, headLine[0].x, headLine[1].x), minY: Math.min(head.y, tail.y, headLine[0].y, headLine[1].y), maxX: Math.max(head.x, tail.x, headLine[0].x, headLine[1].x), maxY: Math.max(head.y, tail.y, headLine[0].y, headLine[1].y) }; }; // this.cleanup = function() { }; // nothing to clean up for GuideLines }; /* * Class: Overlays.Label */ /* * Function: Constructor * * Parameters: * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle. * label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your * label function returns null. empty strings _will_ be painted. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5. * id - optional id to use for later retrieval of this overlay. * * */ _jp.Overlays.Label = function (params) { this.labelStyle = params.labelStyle; var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null; this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null; var p = _jp.extend({ create: function () { return _jp.createElement("div"); }}, params); _jp.Overlays.Custom.call(this, p); this.type = "Label"; this.label = params.label || ""; this.labelText = null; if (this.labelStyle) { var el = this.getElement(); this.labelStyle.font = this.labelStyle.font || "12px sans-serif"; el.style.font = this.labelStyle.font; el.style.color = this.labelStyle.color || "black"; if (this.labelStyle.fill) { el.style.background = this.labelStyle.fill; } if (this.labelStyle.borderWidth > 0) { var dStyle = this.labelStyle.borderStyle ? this.labelStyle.borderStyle : "black"; el.style.border = this.labelStyle.borderWidth + "px solid " + dStyle; } if (this.labelStyle.padding) { el.style.padding = this.labelStyle.padding; } } }; _ju.extend(_jp.Overlays.Label, _jp.Overlays.Custom, { cleanup: function (force) { if (force) { this.div = null; this.label = null; this.labelText = null; this.cssClass = null; this.labelStyle = null; } }, getLabel: function () { return this.label; }, /* * Function: setLabel * sets the label's, um, label. you would think i'd call this function * 'setText', but you can pass either a Function or a String to this, so * it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep * that in mind if you need escaped HTML. */ setLabel: function (l) { this.label = l; this.labelText = null; this.clearCachedDimensions(); this.update(); this.component.repaint(); }, getDimensions: function () { this.update(); return AbstractDOMOverlay.prototype.getDimensions.apply(this, arguments); }, update: function () { if (typeof this.label === "function") { var lt = this.label(this); this.getElement().innerHTML = lt.replace(/\r\n/g, "<br/>"); } else { if (this.labelText == null) { this.labelText = this.label; this.getElement().innerHTML = this.labelText.replace(/\r\n/g, "<br/>"); } } }, updateFrom:function(d) { if(d.label != null){ this.setLabel(d.label); } } }); // ********************************* END OF OVERLAY DEFINITIONS *********************************************************************** }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the base class for library adapters. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { "use strict"; var root = this, _jp = root.jsPlumb; var _getEventManager = function(instance) { var e = instance._mottle; if (!e) { e = instance._mottle = new root.Mottle(); } return e; }; _jp.extend(root.jsPlumbInstance.prototype, { getEventManager:function() { return _getEventManager(this); }, on : function(el, event, callback) { // TODO: here we would like to map the tap event if we know its // an internal bind to a click. we have to know its internal because only // then can we be sure that the UP event wont be consumed (tap is a synthesized // event from a mousedown followed by a mouseup). //event = { "click":"tap", "dblclick":"dbltap"}[event] || event; this.getEventManager().on.apply(this, arguments); return this; }, off : function(el, event, callback) { this.getEventManager().off.apply(this, arguments); return this; } }); }).call(typeof window !== 'undefined' ? window : this); /* * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { "use strict"; var root = this, _ju = root.jsPlumbUtil, _jpi = root.jsPlumbInstance; var GROUP_COLLAPSED_CLASS = "jtk-group-collapsed"; var GROUP_EXPANDED_CLASS = "jtk-group-expanded"; var GROUP_CONTAINER_SELECTOR = "[jtk-group-content]"; var ELEMENT_DRAGGABLE_EVENT = "elementDraggable"; var STOP = "stop"; var REVERT = "revert"; var GROUP_MANAGER = "_groupManager"; var GROUP = "_jsPlumbGroup"; var GROUP_DRAG_SCOPE = "_jsPlumbGroupDrag"; var EVT_CHILD_ADDED = "group:addMember"; var EVT_CHILD_REMOVED = "group:removeMember"; var EVT_GROUP_ADDED = "group:add"; var EVT_GROUP_REMOVED = "group:remove"; var EVT_EXPAND = "group:expand"; var EVT_COLLAPSE = "group:collapse"; var EVT_GROUP_DRAG_STOP = "groupDragStop"; var EVT_CONNECTION_MOVED = "connectionMoved"; var EVT_INTERNAL_CONNECTION_DETACHED = "internal.connectionDetached"; var CMD_REMOVE_ALL = "removeAll"; var CMD_ORPHAN_ALL = "orphanAll"; var CMD_SHOW = "show"; var CMD_HIDE = "hide"; var GroupManager = function(_jsPlumb) { var _managedGroups = {}, _connectionSourceMap = {}, _connectionTargetMap = {}, self = this; _jsPlumb.bind("connection", function(p) { if (p.source[GROUP] != null && p.target[GROUP] != null && p.source[GROUP] === p.target[GROUP]) { _connectionSourceMap[p.connection.id] = p.source[GROUP]; _connectionTargetMap[p.connection.id] = p.source[GROUP]; } else { if (p.source[GROUP] != null) { _ju.suggest(p.source[GROUP].connections.source, p.connection); _connectionSourceMap[p.connection.id] = p.source[GROUP]; } if (p.target[GROUP] != null) { _ju.suggest(p.target[GROUP].connections.target, p.connection); _connectionTargetMap[p.connection.id] = p.target[GROUP]; } } }); function _cleanupDetachedConnection(conn) { delete conn.proxies; var group = _connectionSourceMap[conn.id], f; if (group != null) { f = function(c) { return c.id === conn.id; }; _ju.removeWithFunction(group.connections.source, f); _ju.removeWithFunction(group.connections.target, f); delete _connectionSourceMap[conn.id]; } group = _connectionTargetMap[conn.id]; if (group != null) { f = function(c) { return c.id === conn.id; }; _ju.removeWithFunction(group.connections.source, f); _ju.removeWithFunction(group.connections.target, f); delete _connectionTargetMap[conn.id]; } } _jsPlumb.bind(EVT_INTERNAL_CONNECTION_DETACHED, function(p) { _cleanupDetachedConnection(p.connection); }); _jsPlumb.bind(EVT_CONNECTION_MOVED, function(p) { var connMap = p.index === 0 ? _connectionSourceMap : _connectionTargetMap; var group = connMap[p.connection.id]; if (group) { var list = group.connections[p.index === 0 ? "source" : "target"]; var idx = list.indexOf(p.connection); if (idx !== -1) { list.splice(idx, 1); } } }); this.addGroup = function(group) { _jsPlumb.addClass(group.getEl(), GROUP_EXPANDED_CLASS); _managedGroups[group.id] = group; group.manager = this; _updateConnectionsForGroup(group); _jsPlumb.fire(EVT_GROUP_ADDED, { group:group }); }; this.addToGroup = function(group, el, doNotFireEvent) { group = this.getGroup(group); if (group) { var groupEl = group.getEl(); if (el._isJsPlumbGroup) { return; } var currentGroup = el._jsPlumbGroup; // if already a member of this group, do nothing if (currentGroup !== group) { var elpos = _jsPlumb.getOffset(el, true); var cpos = group.collapsed ? _jsPlumb.getOffset(groupEl, true) : _jsPlumb.getOffset(group.getDragArea(), true); // otherwise, transfer to this group. if (currentGroup != null) { currentGroup.remove(el, false, doNotFireEvent, false, group); self.updateConnectionsForGroup(currentGroup); } group.add(el, doNotFireEvent/*, currentGroup*/); var handleDroppedConnections = function (list, index) { var oidx = index === 0 ? 1 : 0; list.each(function (c) { c.setVisible(false); if (c.endpoints[oidx].element._jsPlumbGroup === group) { c.endpoints[oidx].setVisible(false); self.expandConnection(c, oidx, group); } else { c.endpoints[index].setVisible(false); self.collapseConnection(c, index, group); } }); }; if (group.collapsed) { handleDroppedConnections(_jsPlumb.select({source: el}), 0); handleDroppedConnections(_jsPlumb.select({target: el}), 1); } var elId = _jsPlumb.getId(el); _jsPlumb.dragManager.setParent(el, elId, groupEl, _jsPlumb.getId(groupEl), elpos); var newPosition = { left: elpos.left - cpos.left, top: elpos.top - cpos.top }; _jsPlumb.setPosition(el, newPosition); _jsPlumb.dragManager.revalidateParent(el, elId, elpos); self.updateConnectionsForGroup(group); _jsPlumb.revalidate(elId); if (!doNotFireEvent) { var p = {group: group, el: el}; if (currentGroup) { p.sourceGroup = currentGroup; } _jsPlumb.fire(EVT_CHILD_ADDED, p); } } } }; this.removeFromGroup = function(group, el, doNotFireEvent) { group = this.getGroup(group); if (group) { group.remove(el, null, doNotFireEvent); } }; this.getGroup = function(groupId) { var group = groupId; if (_ju.isString(groupId)) { group = _managedGroups[groupId]; if (group == null) { throw new TypeError("No such group [" + groupId + "]"); } } return group; }; this.getGroups = function() { var o = []; for (var g in _managedGroups) { o.push(_managedGroups[g]); } return o; }; this.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) { group = this.getGroup(group); this.expandGroup(group, true); // this reinstates any original connections and removes all proxies, but does not fire an event. var newPositions = group[deleteMembers ? CMD_REMOVE_ALL : CMD_ORPHAN_ALL](manipulateDOM, doNotFireEvent); _jsPlumb.remove(group.getEl()); delete _managedGroups[group.id]; delete _jsPlumb._groups[group.id]; _jsPlumb.fire(EVT_GROUP_REMOVED, { group:group }); return newPositions; // this will be null in the case or remove, but be a map of {id->[x,y]} in the case of orphan }; this.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) { for (var g in _managedGroups) { this.removeGroup(_managedGroups[g], deleteMembers, manipulateDOM, doNotFireEvent); } }; function _setVisible(group, state) { var m = group.getMembers(); for (var i = 0; i < m.length; i++) { _jsPlumb[state ? CMD_SHOW : CMD_HIDE](m[i], true); } } var _collapseConnection = this.collapseConnection = function(c, index, group) { var proxyEp, groupEl = group.getEl(), groupElId = _jsPlumb.getId(groupEl), originalElementId = c.endpoints[index].elementId; var otherEl = c.endpoints[index === 0 ? 1 : 0].element; if (otherEl[GROUP] && (!otherEl[GROUP].shouldProxy() && otherEl[GROUP].collapsed)) { return; } c.proxies = c.proxies || []; if(c.proxies[index]) { proxyEp = c.proxies[index].ep; }else { proxyEp = _jsPlumb.addEndpoint(groupEl, { endpoint:group.getEndpoint(c, index), anchor:group.getAnchor(c, index), parameters:{ isProxyEndpoint:true } }); } proxyEp.setDeleteOnEmpty(true); // for this index, stash proxy info: the new EP, the original EP. c.proxies[index] = { ep:proxyEp, originalEp: c.endpoints[index] }; // and advise the anchor manager if (index === 0) { // TODO why are there two differently named methods? Why is there not one method that says "some end of this // connection changed (you give the index), and here's the new element and element id." _jsPlumb.anchorManager.sourceChanged(originalElementId, groupElId, c, groupEl); } else { _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, originalElementId, groupElId, c); c.target = groupEl; c.targetId = groupElId; } // detach the original EP from the connection. c.proxies[index].originalEp.detachFromConnection(c, null, true); // set the proxy as the new ep proxyEp.connections = [ c ]; c.endpoints[index] = proxyEp; c.setVisible(true); }; this.collapseGroup = function(group) { group = this.getGroup(group); if (group == null || group.collapsed) { return; } var groupEl = group.getEl(); // todo remove old proxy endpoints first, just in case? //group.proxies.length = 0; // hide all connections _setVisible(group, false); if (group.shouldProxy()) { // collapses all connections in a group. var _collapseSet = function (conns, index) { for (var i = 0; i < conns.length; i++) { var c = conns[i]; _collapseConnection(c, index, group); } }; // setup proxies for sources and targets _collapseSet(group.connections.source, 0); _collapseSet(group.connections.target, 1); } group.collapsed = true; _jsPlumb.removeClass(groupEl, GROUP_EXPANDED_CLASS); _jsPlumb.addClass(groupEl, GROUP_COLLAPSED_CLASS); _jsPlumb.revalidate(groupEl); _jsPlumb.fire(EVT_COLLAPSE, { group:group }); }; var _expandConnection = this.expandConnection = function(c, index, group) { // if no proxies or none for this end of the connection, abort. if (c.proxies == null || c.proxies[index] == null) { return; } var groupElId = _jsPlumb.getId(group.getEl()), originalElement = c.proxies[index].originalEp.element, originalElementId = c.proxies[index].originalEp.elementId; c.endpoints[index] = c.proxies[index].originalEp; // and advise the anchor manager if (index === 0) { // TODO why are there two differently named methods? Why is there not one method that says "some end of this // connection changed (you give the index), and here's the new element and element id." _jsPlumb.anchorManager.sourceChanged(groupElId, originalElementId, c, originalElement); } else { _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, groupElId, originalElementId, c); c.target = originalElement; c.targetId = originalElementId; } // detach the proxy EP from the connection (which will cause it to be removed as we no longer need it) c.proxies[index].ep.detachFromConnection(c, null); c.proxies[index].originalEp.addConnection(c); // cleanup delete c.proxies[index]; }; this.expandGroup = function(group, doNotFireEvent) { group = this.getGroup(group); if (group == null || !group.collapsed) { return; } var groupEl = group.getEl(); _setVisible(group, true); if (group.shouldProxy()) { // collapses all connections in a group. var _expandSet = function (conns, index) { for (var i = 0; i < conns.length; i++) { var c = conns[i]; _expandConnection(c, index, group); } }; // setup proxies for sources and targets _expandSet(group.connections.source, 0); _expandSet(group.connections.target, 1); } group.collapsed = false; _jsPlumb.addClass(groupEl, GROUP_EXPANDED_CLASS); _jsPlumb.removeClass(groupEl, GROUP_COLLAPSED_CLASS); _jsPlumb.revalidate(groupEl); this.repaintGroup(group); if (!doNotFireEvent) { _jsPlumb.fire(EVT_EXPAND, { group: group}); } }; this.repaintGroup = function(group) { group = this.getGroup(group); var m = group.getMembers(); for (var i = 0; i < m.length; i++) { _jsPlumb.revalidate(m[i]); } }; // TODO refactor this with the code that responds to `connection` events. function _updateConnectionsForGroup(group) { var members = group.getMembers(); var c1 = _jsPlumb.getConnections({source:members, scope:"*"}, true); var c2 = _jsPlumb.getConnections({target:members, scope:"*"}, true); var processed = {}; group.connections.source.length = 0; group.connections.target.length = 0; var oneSet = function(c) { for (var i = 0; i < c.length; i++) { if (processed[c[i].id]) { continue; } processed[c[i].id] = true; if (c[i].source._jsPlumbGroup === group) { if (c[i].target._jsPlumbGroup !== group) { group.connections.source.push(c[i]); } _connectionSourceMap[c[i].id] = group; } else if (c[i].target._jsPlumbGroup === group) { group.connections.target.push(c[i]); _connectionTargetMap[c[i].id] = group; } } }; oneSet(c1); oneSet(c2); } this.updateConnectionsForGroup = _updateConnectionsForGroup; this.refreshAllGroups = function() { for (var g in _managedGroups) { _updateConnectionsForGroup(_managedGroups[g]); _jsPlumb.dragManager.updateOffsets(_jsPlumb.getId(_managedGroups[g].getEl())); } }; }; /** * * @param {jsPlumbInstance} _jsPlumb Associated jsPlumb instance. * @param {Object} params * @param {Element} params.el The DOM element representing the Group. * @param {String} [params.id] Optional ID for the Group. A UUID will be assigned as the Group's ID if you do not provide one. * @param {Boolean} [params.constrain=false] If true, child elements will not be able to be dragged outside of the Group container. * @param {Boolean} [params.revert=true] By default, child elements revert to the container if dragged outside. You can change this by setting `revert:false`. This behaviour is also overridden if you set `orphan` or `prune`. * @param {Boolean} [params.orphan=false] If true, child elements dropped outside of the Group container will be removed from the Group (but not from the DOM). * @param {Boolean} [params.prune=false] If true, child elements dropped outside of the Group container will be removed from the Group and also from the DOM. * @param {Boolean} [params.dropOverride=false] If true, a child element that has been dropped onto some other Group will not be subject to the controls imposed by `prune`, `revert` or `orphan`. * @constructor */ var Group = function(_jsPlumb, params) { var self = this; var el = params.el; this.getEl = function() { return el; }; this.id = params.id || _ju.uuid(); el._isJsPlumbGroup = true; var getDragArea = this.getDragArea = function() { var da = _jsPlumb.getSelector(el, GROUP_CONTAINER_SELECTOR); return da && da.length > 0 ? da[0] : el; }; var ghost = params.ghost === true; var constrain = ghost || (params.constrain === true); var revert = params.revert !== false; var orphan = params.orphan === true; var prune = params.prune === true; var dropOverride = params.dropOverride === true; var proxied = params.proxied !== false; var elements = []; this.connections = { source:[], target:[], internal:[] }; // this function, and getEndpoint below, are stubs for a future setup in which we can choose endpoint // and anchor based upon the connection and the index (source/target) of the endpoint to be proxied. this.getAnchor = function(conn, endpointIndex) { return params.anchor || "Continuous"; }; this.getEndpoint = function(conn, endpointIndex) { return params.endpoint || [ "Dot", { radius:10 }]; }; this.collapsed = false; if (params.draggable !== false) { var opts = { stop:function(params) { _jsPlumb.fire(EVT_GROUP_DRAG_STOP, jsPlumb.extend(params, {group:self})); }, scope:GROUP_DRAG_SCOPE }; if (params.dragOptions) { root.jsPlumb.extend(opts, params.dragOptions); } _jsPlumb.draggable(params.el, opts); } if (params.droppable !== false) { _jsPlumb.droppable(params.el, { drop:function(p) { var el = p.drag.el; if (el._isJsPlumbGroup) { return; } var currentGroup = el._jsPlumbGroup; if (currentGroup !== self) { if (currentGroup != null) { if (currentGroup.overrideDrop(el, self)) { return; } } _jsPlumb.getGroupManager().addToGroup(self, el, false); } } }); } var _each = function(_el, fn) { var els = _el.nodeType == null ? _el : [ _el ]; for (var i = 0; i < els.length; i++) { fn(els[i]); } }; this.overrideDrop = function(_el, targetGroup) { return dropOverride && (revert || prune || orphan); }; this.add = function(_el, doNotFireEvent/*, sourceGroup*/) { var dragArea = getDragArea(); _each(_el, function(__el) { if (__el._jsPlumbGroup != null) { if (__el._jsPlumbGroup === self) { return; } else { __el._jsPlumbGroup.remove(__el, true, doNotFireEvent, false); } } __el._jsPlumbGroup = self; elements.push(__el); // test if draggable and add handlers if so. if (_jsPlumb.isAlreadyDraggable(__el)) { _bindDragHandlers(__el); } if (__el.parentNode !== dragArea) { dragArea.appendChild(__el); } // if (!doNotFireEvent) { // var p = {group: self, el: __el}; // if (sourceGroup) { // p.sourceGroup = sourceGroup; // } // //_jsPlumb.fire(EVT_CHILD_ADDED, p); // } }); _jsPlumb.getGroupManager().updateConnectionsForGroup(self); }; this.remove = function(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections, targetGroup) { _each(el, function(__el) { delete __el._jsPlumbGroup; _ju.removeWithFunction(elements, function(e) { return e === __el; }); if (manipulateDOM) { try { self.getDragArea().removeChild(__el); } catch (e) { jsPlumbUtil.log("Could not remove element from Group " + e); } } _unbindDragHandlers(__el); if (!doNotFireEvent) { var p = {group: self, el: __el}; if (targetGroup) { p.targetGroup = targetGroup; } _jsPlumb.fire(EVT_CHILD_REMOVED, p); } }); if (!doNotUpdateConnections) { _jsPlumb.getGroupManager().updateConnectionsForGroup(self); } }; this.removeAll = function(manipulateDOM, doNotFireEvent) { for (var i = 0, l = elements.length; i < l; i++) { var el = elements[0]; self.remove(el, manipulateDOM, doNotFireEvent, true); _jsPlumb.remove(el, true); } elements.length = 0; _jsPlumb.getGroupManager().updateConnectionsForGroup(self); }; this.orphanAll = function() { var orphanedPositions = {}; for (var i = 0; i < elements.length; i++) { var newPosition = _orphan(elements[i]); orphanedPositions[newPosition[0]] = newPosition[1]; } elements.length = 0; return orphanedPositions; }; this.getMembers = function() { return elements; }; el[GROUP] = this; _jsPlumb.bind(ELEMENT_DRAGGABLE_EVENT, function(dragParams) { // if its for the current group, if (dragParams.el._jsPlumbGroup === this) { _bindDragHandlers(dragParams.el); } }.bind(this)); function _findParent(_el) { return _el.offsetParent; } function _isInsideParent(_el, pos) { var p = _findParent(_el), s = _jsPlumb.getSize(p), ss = _jsPlumb.getSize(_el), leftEdge = pos[0], rightEdge = leftEdge + ss[0], topEdge = pos[1], bottomEdge = topEdge + ss[1]; return rightEdge > 0 && leftEdge < s[0] && bottomEdge > 0 && topEdge < s[1]; } // // orphaning an element means taking it out of the group and adding it to the main jsplumb container. // we return the new calculated position from this method and the element's id. // function _orphan(_el) { var id = _jsPlumb.getId(_el); var pos = _jsPlumb.getOffset(_el); _el.parentNode.removeChild(_el); _jsPlumb.getContainer().appendChild(_el); _jsPlumb.setPosition(_el, pos); delete _el._jsPlumbGroup; _unbindDragHandlers(_el); _jsPlumb.dragManager.clearParent(_el, id); return [id, pos]; } // // remove an element from the group, then either prune it from the jsplumb instance, or just orphan it. // function _pruneOrOrphan(p) { var orphanedPosition = null; if (!_isInsideParent(p.el, p.pos)) { var group = p.el._jsPlumbGroup; if (prune) { _jsPlumb.remove(p.el); } else { orphanedPosition = _orphan(p.el); } group.remove(p.el); } return orphanedPosition; } // // redraws the element // function _revalidate(_el) { var id = _jsPlumb.getId(_el); _jsPlumb.revalidate(_el); _jsPlumb.dragManager.revalidateParent(_el, id); } // // unbind the group specific drag/revert handlers. // function _unbindDragHandlers(_el) { if (!_el._katavorioDrag) { return; } if (prune || orphan) { _el._katavorioDrag.off(STOP, _pruneOrOrphan); } if (!prune && !orphan && revert) { _el._katavorioDrag.off(REVERT, _revalidate); _el._katavorioDrag.setRevert(null); } } function _bindDragHandlers(_el) { if (!_el._katavorioDrag) { return; } if (prune || orphan) { _el._katavorioDrag.on(STOP, _pruneOrOrphan); } if (constrain) { _el._katavorioDrag.setConstrain(true); } if (ghost) { _el._katavorioDrag.setUseGhostProxy(true); } if (!prune && !orphan && revert) { _el._katavorioDrag.on(REVERT, _revalidate); _el._katavorioDrag.setRevert(function(__el, pos) { return !_isInsideParent(__el, pos); }); } } this.shouldProxy = function() { return proxied; }; _jsPlumb.getGroupManager().addGroup(this); }; /** * Adds a group to the jsPlumb instance. * @method addGroup * @param {Object} params * @return {Group} The newly created Group. */ _jpi.prototype.addGroup = function(params) { var j = this; j._groups = j._groups || {}; if (j._groups[params.id] != null) { throw new TypeError("cannot create Group [" + params.id + "]; a Group with that ID exists"); } if (params.el[GROUP] != null) { throw new TypeError("cannot create Group [" + params.id + "]; the given element is already a Group"); } var group = new Group(j, params); j._groups[group.id] = group; if (params.collapsed) { this.collapseGroup(group); } return group; }; /** * Add an element to a group. * @method addToGroup * @param {String} group Group, or ID of the group, to add the element to. * @param {Element} el Element to add to the group. */ _jpi.prototype.addToGroup = function(group, el, doNotFireEvent) { var _one = function(_el) { var id = this.getId(_el); this.manage(id, _el); this.getGroupManager().addToGroup(group, _el, doNotFireEvent); }.bind(this); if (Array.isArray(el)) { for (var i = 0; i < el.length; i++) { _one(el[i]); } } else { _one(el); } }; /** * Remove an element from a group. * @method removeFromGroup * @param {String} group Group, or ID of the group, to remove the element from. * @param {Element} el Element to add to the group. */ _jpi.prototype.removeFromGroup = function(group, el, doNotFireEvent) { this.getGroupManager().removeFromGroup(group, el, doNotFireEvent); }; /** * Remove a group, and optionally remove its members from the jsPlumb instance. * @method removeGroup * @param {String|Group} group Group to delete, or ID of Group to delete. * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will * just be 'orphaned' (returned to the main container). * @returns {Map[String, Position}} When deleteMembers is false, this method returns a map of {id->position} */ _jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) { return this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent); }; /** * Remove all groups, and optionally remove their members from the jsPlumb instance. * @method removeAllGroup * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will * just be 'orphaned' (returned to the main container). */ _jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) { this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent); }; /** * Get a Group * @method getGroup * @param {String} groupId ID of the group to get * @return {Group} Group with the given ID, null if not found. */ _jpi.prototype.getGroup = function(groupId) { return this.getGroupManager().getGroup(groupId); }; /** * Gets all the Groups managed by the jsPlumb instance. * @returns {Group[]} List of Groups. Empty if none. */ _jpi.prototype.getGroups = function() { return this.getGroupManager().getGroups(); }; /** * Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group * will vary from application to application. jsPlumb does these things: * * - Hides any connections that are internal to the group (connections between members, and connections from member of * the group to the group itself) * - Proxies all connections for which the source or target is a member of the group. * - Hides the proxied connections. * - Adds the jtk-group-expanded class to the group's element * - Removes the jtk-group-collapsed class from the group's element. * * @method expandGroup * @param {String|Group} group Group to expand, or ID of Group to expand. */ _jpi.prototype.expandGroup = function(group) { this.getGroupManager().expandGroup(group); }; /** * Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group * will vary from application to application. jsPlumb does these things: * * - Shows any connections that are internal to the group (connections between members, and connections from member of * the group to the group itself) * - Removes proxies for all connections for which the source or target is a member of the group. * - Shows the previously proxied connections. * - Adds the jtk-group-collapsed class to the group's element * - Removes the jtk-group-expanded class from the group's element. * * @method expandGroup * @param {String|Group} group Group to expand, or ID of Group to expand. */ _jpi.prototype.collapseGroup = function(groupId) { this.getGroupManager().collapseGroup(groupId); }; _jpi.prototype.repaintGroup = function(group) { this.getGroupManager().repaintGroup(group); }; /** * Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method. * * @method toggleGroup * @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse. */ _jpi.prototype.toggleGroup = function(group) { group = this.getGroupManager().getGroup(group); if (group != null) { this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group); } }; // // lazy init a group manager for the given jsplumb instance. // _jpi.prototype.getGroupManager = function() { var mgr = this[GROUP_MANAGER]; if (mgr == null) { mgr = this[GROUP_MANAGER] = new GroupManager(this); } return mgr; }; _jpi.prototype.removeGroupManager = function() { delete this[GROUP_MANAGER]; }; /** * Gets the Group that the given element belongs to, null if none. * @method getGroupFor * @param {String|Element} el Element, or element ID. * @returns {Group} A Group, if found, or null. */ _jpi.prototype.getGroupFor = function(el) { el = this.getElement(el); if (el) { return el[GROUP]; } }; }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; var STRAIGHT = "Straight"; var ARC = "Arc"; var Flowchart = function (params) { this.type = "Flowchart"; params = params || {}; params.stub = params.stub == null ? 30 : params.stub; var segments, _super = _jp.Connectors.AbstractConnector.apply(this, arguments), midpoint = params.midpoint == null ? 0.5 : params.midpoint, alwaysRespectStubs = params.alwaysRespectStubs === true, lastx = null, lasty = null, lastOrientation, cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0, // TODO now common between this and AbstractBezierEditor; refactor into superclass? loopbackRadius = params.loopbackRadius || 25, isLoopbackCurrently = false, sgn = function (n) { return n < 0 ? -1 : n === 0 ? 0 : 1; }, segmentDirections = function(segment) { return [ sgn( segment[2] - segment[0] ), sgn( segment[3] - segment[1] ) ]; }, /** * helper method to add a segment. */ addSegment = function (segments, x, y, paintInfo) { if (lastx === x && lasty === y) { return; } var lx = lastx == null ? paintInfo.sx : lastx, ly = lasty == null ? paintInfo.sy : lasty, o = lx === x ? "v" : "h"; lastx = x; lasty = y; segments.push([ lx, ly, x, y, o ]); }, segLength = function (s) { return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2)); }, _cloneArray = function (a) { var _a = []; _a.push.apply(_a, a); return _a; }, writeSegments = function (conn, segments, paintInfo) { var current = null, next, currentDirection, nextDirection; for (var i = 0; i < segments.length - 1; i++) { current = current || _cloneArray(segments[i]); next = _cloneArray(segments[i + 1]); currentDirection = segmentDirections(current); nextDirection = segmentDirections(next); if (cornerRadius > 0 && current[4] !== next[4]) { var minSegLength = Math.min(segLength(current), segLength(next)); var radiusToUse = Math.min(cornerRadius, minSegLength / 2); current[2] -= currentDirection[0] * radiusToUse; current[3] -= currentDirection[1] * radiusToUse; next[0] += nextDirection[0] * radiusToUse; next[1] += nextDirection[1] * radiusToUse; var ac = (currentDirection[1] === nextDirection[0] && nextDirection[0] === 1) || ((currentDirection[1] === nextDirection[0] && nextDirection[0] === 0) && currentDirection[0] !== nextDirection[1]) || (currentDirection[1] === nextDirection[0] && nextDirection[0] === -1), sgny = next[1] > current[3] ? 1 : -1, sgnx = next[0] > current[2] ? 1 : -1, sgnEqual = sgny === sgnx, cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2], cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1]; _super.addSegment(conn, STRAIGHT, { x1: current[0], y1: current[1], x2: current[2], y2: current[3] }); _super.addSegment(conn, ARC, { r: radiusToUse, x1: current[2], y1: current[3], x2: next[0], y2: next[1], cx: cx, cy: cy, ac: ac }); } else { // dx + dy are used to adjust for line width. var dx = (current[2] === current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2), dy = (current[3] === current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2); _super.addSegment(conn, STRAIGHT, { x1: current[0] - dx, y1: current[1] - dy, x2: current[2] + dx, y2: current[3] + dy }); } current = next; } if (next != null) { // last segment _super.addSegment(conn, STRAIGHT, { x1: next[0], y1: next[1], x2: next[2], y2: next[3] }); } }; this._compute = function (paintInfo, params) { segments = []; lastx = null; lasty = null; lastOrientation = null; var commonStubCalculator = function () { return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY]; }, stubCalculators = { perpendicular: commonStubCalculator, orthogonal: commonStubCalculator, opposite: function (axis) { var pi = paintInfo, idx = axis === "x" ? 0 : 1, areInProximity = { "x": function () { return ( (pi.so[idx] === 1 && ( ( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) || ( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) || ( (pi.so[idx] === -1 && ( ( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) || ( (pi.sx < pi.endStubX) && (pi.tx < pi.sx))))); }, "y": function () { return ( (pi.so[idx] === 1 && ( ( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) || ( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) || ( (pi.so[idx] === -1 && ( ( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) || ( (pi.sy < pi.endStubY) && (pi.ty < pi.sy))))); } }; if (!alwaysRespectStubs && areInProximity[axis]()) { return { "x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY], "y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2] }[axis]; } else { return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY]; } } }; // calculate Stubs. var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis), idx = paintInfo.sourceAxis === "x" ? 0 : 1, oidx = paintInfo.sourceAxis === "x" ? 1 : 0, ss = stubs[idx], oss = stubs[oidx], es = stubs[idx + 2], oes = stubs[oidx + 2]; // add the start stub segment. use stubs for loopback as it will look better, with the loop spaced // away from the element. addSegment(segments, stubs[0], stubs[1], paintInfo); // if its a loopback and we should treat it differently. // if (false && params.sourcePos[0] === params.targetPos[0] && params.sourcePos[1] === params.targetPos[1]) { // // // we use loopbackRadius here, as statemachine connectors do. // // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius, // // down by 2*radius, left by radius. // addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo); // addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo); // addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo); // addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo); // addSegment(segments, stubs[0], stubs[1], paintInfo); // // } // else { var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint), midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint); var orientations = {x: [0, 1], y: [1, 0]}, lineCalculators = { perpendicular: function (axis) { var pi = paintInfo, sis = { x: [ [[1, 2, 3, 4], null, [2, 1, 4, 3]], null, [[4, 3, 2, 1], null, [3, 4, 1, 2]] ], y: [ [[3, 2, 1, 4], null, [2, 3, 4, 1]], null, [[4, 1, 2, 3], null, [1, 4, 3, 2]] ] }, stubs = { x: [[pi.startStubX, pi.endStubX], null, [pi.endStubX, pi.startStubX]], y: [[pi.startStubY, pi.endStubY], null, [pi.endStubY, pi.startStubY]] }, midLines = { x: [[midx, pi.startStubY], [midx, pi.endStubY]], y: [[pi.startStubX, midy], [pi.endStubX, midy]] }, linesToEnd = { x: [[pi.endStubX, pi.startStubY]], y: [[pi.startStubX, pi.endStubY]] }, startToEnd = { x: [[pi.startStubX, pi.endStubY], [pi.endStubX, pi.endStubY]], y: [[pi.endStubX, pi.startStubY], [pi.endStubX, pi.endStubY]] }, startToMidToEnd = { x: [[pi.startStubX, midy], [pi.endStubX, midy], [pi.endStubX, pi.endStubY]], y: [[midx, pi.startStubY], [midx, pi.endStubY], [pi.endStubX, pi.endStubY]] }, otherStubs = { x: [pi.startStubY, pi.endStubY], y: [pi.startStubX, pi.endStubX] }, soIdx = orientations[axis][0], toIdx = orientations[axis][1], _so = pi.so[soIdx] + 1, _to = pi.to[toIdx] + 1, otherFlipped = (pi.to[toIdx] === -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] === 1 && (otherStubs[axis][1] > otherStubs[axis][0])), stub1 = stubs[axis][_so][0], stub2 = stubs[axis][_so][1], segmentIndexes = sis[axis][_so][_to]; if (pi.segment === segmentIndexes[3] || (pi.segment === segmentIndexes[2] && otherFlipped)) { return midLines[axis]; } else if (pi.segment === segmentIndexes[2] && stub2 < stub1) { return linesToEnd[axis]; } else if ((pi.segment === segmentIndexes[2] && stub2 >= stub1) || (pi.segment === segmentIndexes[1] && !otherFlipped)) { return startToMidToEnd[axis]; } else if (pi.segment === segmentIndexes[0] || (pi.segment === segmentIndexes[1] && otherFlipped)) { return startToEnd[axis]; } }, orthogonal: function (axis, startStub, otherStartStub, endStub, otherEndStub) { var pi = paintInfo, extent = { "x": pi.so[0] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub), "y": pi.so[1] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub) }[axis]; return { "x": [ [extent, otherStartStub], [extent, otherEndStub], [endStub, otherEndStub] ], "y": [ [otherStartStub, extent], [otherEndStub, extent], [otherEndStub, endStub] ] }[axis]; }, opposite: function (axis, ss, oss, es) { var pi = paintInfo, otherAxis = {"x": "y", "y": "x"}[axis], dim = {"x": "height", "y": "width"}[axis], comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"]; if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) { var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub; return { "x": [ [ss, _val], [es, _val] ], "y": [ [_val, ss], [_val, es] ] }[axis]; } else if (!comparator || (pi.so[idx] === 1 && ss > es) || (pi.so[idx] === -1 && ss < es)) { return { "x": [ [ss, midy], [es, midy] ], "y": [ [midx, ss], [midx, es] ] }[axis]; } else if ((pi.so[idx] === 1 && ss < es) || (pi.so[idx] === -1 && ss > es)) { return { "x": [ [midx, pi.sy], [midx, pi.ty] ], "y": [ [pi.sx, midy], [pi.tx, midy] ] }[axis]; } } }; // compute the rest of the line var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes); if (p) { for (var i = 0; i < p.length; i++) { addSegment(segments, p[i][0], p[i][1], paintInfo); } } // line to end stub addSegment(segments, stubs[2], stubs[3], paintInfo); //} // end stub to end (common) addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo); // write out the segments. writeSegments(this, segments, paintInfo); }; }; _jp.Connectors.Flowchart = Flowchart; _ju.extend(_jp.Connectors.Flowchart, _jp.Connectors.AbstractConnector); }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the code for the Bezier connector type. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; _jp.Connectors.AbstractBezierConnector = function(params) { params = params || {}; var showLoopback = params.showLoopback !== false, curviness = params.curviness || 10, margin = params.margin || 5, proximityLimit = params.proximityLimit || 80, clockwise = params.orientation && params.orientation === "clockwise", loopbackRadius = params.loopbackRadius || 25, isLoopbackCurrently = false, _super; this._compute = function (paintInfo, p) { var sp = p.sourcePos, tp = p.targetPos, _w = Math.abs(sp[0] - tp[0]), _h = Math.abs(sp[1] - tp[1]); if (!showLoopback || (p.sourceEndpoint.elementId !== p.targetEndpoint.elementId)) { isLoopbackCurrently = false; this._computeBezier(paintInfo, p, sp, tp, _w, _h); } else { isLoopbackCurrently = true; // a loopback connector. draw an arc from one anchor to the other. var x1 = p.sourcePos[0], y1 = p.sourcePos[1] - margin, cx = x1, cy = y1 - loopbackRadius, // canvas sizing stuff, to ensure the whole painted area is visible. _x = cx - loopbackRadius, _y = cy - loopbackRadius; _w = 2 * loopbackRadius; _h = 2 * loopbackRadius; paintInfo.points[0] = _x; paintInfo.points[1] = _y; paintInfo.points[2] = _w; paintInfo.points[3] = _h; // ADD AN ARC SEGMENT. _super.addSegment(this, "Arc", { loopback: true, x1: (x1 - _x) + 4, y1: y1 - _y, startAngle: 0, endAngle: 2 * Math.PI, r: loopbackRadius, ac: !clockwise, x2: (x1 - _x) - 4, y2: y1 - _y, cx: cx - _x, cy: cy - _y }); } }; _super = _jp.Connectors.AbstractConnector.apply(this, arguments); return _super; }; _ju.extend(_jp.Connectors.AbstractBezierConnector, _jp.Connectors.AbstractConnector); var Bezier = function (params) { params = params || {}; this.type = "Bezier"; var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments), majorAnchor = params.curviness || 150, minorAnchor = 10; this.getCurviness = function () { return majorAnchor; }; this._findControlPoint = function (point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, soo, too) { // determine if the two anchors are perpendicular to each other in their orientation. we swap the control // points around if so (code could be tightened up) var perpendicular = soo[0] !== too[0] || soo[1] === too[1], p = []; if (!perpendicular) { if (soo[0] === 0) { p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor); } else { p.push(point[0] - (majorAnchor * soo[0])); } if (soo[1] === 0) { p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor); } else { p.push(point[1] + (majorAnchor * too[1])); } } else { if (too[0] === 0) { p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor); } else { p.push(point[0] + (majorAnchor * too[0])); } if (too[1] === 0) { p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor); } else { p.push(point[1] + (majorAnchor * soo[1])); } } return p; }; this._computeBezier = function (paintInfo, p, sp, tp, _w, _h) { var _CP, _CP2, _sx = sp[0] < tp[0] ? _w : 0, _sy = sp[1] < tp[1] ? _h : 0, _tx = sp[0] < tp[0] ? 0 : _w, _ty = sp[1] < tp[1] ? 0 : _h; _CP = this._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint, paintInfo.so, paintInfo.to); _CP2 = this._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint, paintInfo.to, paintInfo.so); _super.addSegment(this, "Bezier", { x1: _sx, y1: _sy, x2: _tx, y2: _ty, cp1x: _CP[0], cp1y: _CP[1], cp2x: _CP2[0], cp2y: _CP2[1] }); }; }; _jp.Connectors.Bezier = Bezier; _ju.extend(Bezier, _jp.Connectors.AbstractBezierConnector); }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the state machine connectors, which extend AbstractBezierConnector. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; var _segment = function (x1, y1, x2, y2) { if (x1 <= x2 && y2 <= y1) { return 1; } else if (x1 <= x2 && y1 <= y2) { return 2; } else if (x2 <= x1 && y2 >= y1) { return 3; } return 4; }, // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the // center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left. // // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are: // // 0 - absolute x // 1 - absolute y // 2 - proportional x in element (0 is left edge, 1 is right edge) // 3 - proportional y in element (0 is top edge, 1 is bottom edge) // _findControlPoint = function (midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) { // TODO (maybe) // - if anchor pos is 0.5, make the control point take into account the relative position of the elements. if (distance <= proximityLimit) { return [midx, midy]; } if (segment === 1) { if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) { return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; } else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) { return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; } else { return [ midx + (-1 * dx) , midy + (-1 * dy) ]; } } else if (segment === 2) { if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) { return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; } else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) { return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; } else { return [ midx + dx, midy + (-1 * dy) ]; } } else if (segment === 3) { if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) { return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; } else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) { return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; } else { return [ midx + (-1 * dx) , midy + (-1 * dy) ]; } } else if (segment === 4) { if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) { return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ]; } else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) { return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ]; } else { return [ midx + dx , midy + (-1 * dy) ]; } } }; var StateMachine = function (params) { params = params || {}; this.type = "StateMachine"; var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments), curviness = params.curviness || 10, margin = params.margin || 5, proximityLimit = params.proximityLimit || 80, clockwise = params.orientation && params.orientation === "clockwise", _controlPoint; this._computeBezier = function(paintInfo, params, sp, tp, w, h) { var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w, _sy = params.sourcePos[1] < params.targetPos[1] ? 0 : h, _tx = params.sourcePos[0] < params.targetPos[0] ? w : 0, _ty = params.sourcePos[1] < params.targetPos[1] ? h : 0; // now adjust for the margin if (params.sourcePos[2] === 0) { _sx -= margin; } if (params.sourcePos[2] === 1) { _sx += margin; } if (params.sourcePos[3] === 0) { _sy -= margin; } if (params.sourcePos[3] === 1) { _sy += margin; } if (params.targetPos[2] === 0) { _tx -= margin; } if (params.targetPos[2] === 1) { _tx += margin; } if (params.targetPos[3] === 0) { _ty -= margin; } if (params.targetPos[3] === 1) { _ty += margin; } // // these connectors are quadratic bezier curves, having a single control point. if both anchors // are located at 0.5 on their respective faces, the control point is set to the midpoint and you // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned // at 'curviness' pixels away along the normal to the straight line connecting the two anchors. // // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node, // for example, we might increase the distance the control point is away from the midpoint in a bid to // steer it around that node. this will work within limits, but i think those limits would also be the likely // limits for, once again, aesthetic good sense in the layout of a chart using these connectors. // // the second possible change is actually two possible changes: firstly, it is possible we should gradually // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors // with respect to how far their anchor is from the center of its respective face. this could either look cool, // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time. // var _midx = (_sx + _tx) / 2, _midy = (_sy + _ty) / 2, segment = _segment(_sx, _sy, _tx, _ty), distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)), cp1x, cp2x, cp1y, cp2y; // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it // will work by extending the control point to force the curve to be, um, curvier. _controlPoint = _findControlPoint(_midx, _midy, segment, params.sourcePos, params.targetPos, curviness, curviness, distance, proximityLimit); cp1x = _controlPoint[0]; cp2x = _controlPoint[0]; cp1y = _controlPoint[1]; cp2y = _controlPoint[1]; _super.addSegment(this, "Bezier", { x1: _tx, y1: _ty, x2: _sx, y2: _sy, cp1x: cp1x, cp1y: cp1y, cp2x: cp2x, cp2y: cp2y }); }; }; _jp.Connectors.StateMachine = StateMachine; _ju.extend(StateMachine, _jp.Connectors.AbstractBezierConnector); }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; var STRAIGHT = "Straight"; var Straight = function (params) { this.type = STRAIGHT; var _super = _jp.Connectors.AbstractConnector.apply(this, arguments); this._compute = function (paintInfo, _) { _super.addSegment(this, STRAIGHT, {x1: paintInfo.sx, y1: paintInfo.sy, x2: paintInfo.startStubX, y2: paintInfo.startStubY}); _super.addSegment(this, STRAIGHT, {x1: paintInfo.startStubX, y1: paintInfo.startStubY, x2: paintInfo.endStubX, y2: paintInfo.endStubY}); _super.addSegment(this, STRAIGHT, {x1: paintInfo.endStubX, y1: paintInfo.endStubY, x2: paintInfo.tx, y2: paintInfo.ty}); }; }; _jp.Connectors.Straight = Straight; _ju.extend(Straight, _jp.Connectors.AbstractConnector); }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the SVG renderers. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { // ************************** SVG utility methods ******************************************** "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil; var svgAttributeMap = { "stroke-linejoin": "stroke-linejoin", "stroke-dashoffset": "stroke-dashoffset", "stroke-linecap": "stroke-linecap" }, STROKE_DASHARRAY = "stroke-dasharray", DASHSTYLE = "dashstyle", LINEAR_GRADIENT = "linearGradient", RADIAL_GRADIENT = "radialGradient", DEFS = "defs", FILL = "fill", STOP = "stop", STROKE = "stroke", STROKE_WIDTH = "stroke-width", STYLE = "style", NONE = "none", JSPLUMB_GRADIENT = "jsplumb_gradient_", LINE_WIDTH = "strokeWidth", ns = { svg: "http://www.w3.org/2000/svg" }, _attr = function (node, attributes) { for (var i in attributes) { node.setAttribute(i, "" + attributes[i]); } }, _node = function (name, attributes) { attributes = attributes || {}; attributes.version = "1.1"; attributes.xmlns = ns.svg; return _jp.createElementNS(ns.svg, name, null, null, attributes); }, _pos = function (d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; }, _clearGradient = function (parent) { var els = parent.querySelectorAll(" defs,linearGradient,radialGradient"); for (var i = 0; i < els.length; i++) { els[i].parentNode.removeChild(els[i]); } }, _updateGradient = function (parent, node, style, dimensions, uiComponent) { var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.instance.idstamp(); // first clear out any existing gradient _clearGradient(parent); // this checks for an 'offset' property in the gradient, and in the absence of it, assumes // we want a linear gradient. if it's there, we create a radial gradient. // it is possible that a more explicit means of defining the gradient type would be // better. relying on 'offset' means that we can never have a radial gradient that uses // some default offset, for instance. // issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would // not show gradients when the line was perfectly horizontal or vertical. var g; if (!style.gradient.offset) { g = _node(LINEAR_GRADIENT, {id: id, gradientUnits: "userSpaceOnUse"}); } else { g = _node(RADIAL_GRADIENT, { id: id }); } var defs = _node(DEFS); parent.appendChild(defs); defs.appendChild(g); // the svg radial gradient seems to treat stops in the reverse // order to how canvas does it. so we want to keep all the maths the same, but // iterate the actual style declarations in reverse order, if the x indexes are not in order. for (var i = 0; i < style.gradient.stops.length; i++) { var styleToUse = uiComponent.segment === 1 || uiComponent.segment === 2 ? i : style.gradient.stops.length - 1 - i, stopColor = style.gradient.stops[styleToUse][1], s = _node(STOP, {"offset": Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color": stopColor}); g.appendChild(s); } var applyGradientTo = style.stroke ? STROKE : FILL; node.setAttribute(applyGradientTo, "url(#" + id + ")"); }, _applyStyles = function (parent, node, style, dimensions, uiComponent) { node.setAttribute(FILL, style.fill ? style.fill : NONE); node.setAttribute(STROKE, style.stroke ? style.stroke : NONE); if (style.gradient) { _updateGradient(parent, node, style, dimensions, uiComponent); } else { // make sure we clear any existing gradient _clearGradient(parent); node.setAttribute(STYLE, ""); } if (style.strokeWidth) { node.setAttribute(STROKE_WIDTH, style.strokeWidth); } // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like // the syntax in VML but is actually kind of nasty: values are given in the pixel // coordinate space, whereas in VML they are multiples of the width of the stroked // line, which makes a lot more sense. for that reason, jsPlumb is supporting both // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from // VML, which will be the preferred method. the code below this converts a dashstyle // attribute given in terms of stroke width into a pixel representation, by using the // stroke's lineWidth. if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) { var sep = style[DASHSTYLE].indexOf(",") === -1 ? " " : ",", parts = style[DASHSTYLE].split(sep), styleToUse = ""; parts.forEach(function (p) { styleToUse += (Math.floor(p * style.strokeWidth) + sep); }); node.setAttribute(STROKE_DASHARRAY, styleToUse); } else if (style[STROKE_DASHARRAY]) { node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]); } // extra attributes such as join type, dash offset. for (var i in svgAttributeMap) { if (style[i]) { node.setAttribute(svgAttributeMap[i], style[i]); } } }, _appendAtIndex = function (svg, path, idx) { if (svg.childNodes.length > idx) { svg.insertBefore(path, svg.childNodes[idx]); } else { svg.appendChild(path); } }; /** utility methods for other objects to use. */ _ju.svg = { node: _node, attr: _attr, pos: _pos }; // ************************** / SVG utility methods ******************************************** /* * Base class for SVG components. */ var SvgComponent = function (params) { var pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {}; _jp.jsPlumbUIComponent.apply(this, params.originalArgs); this.canvas = null; this.path = null; this.svg = null; this.bgCanvas = null; var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""), svgParams = { "style": "", "width": 0, "height": 0, "pointer-events": pointerEventsSpec, "position": "absolute" }; this.svg = _node("svg", svgParams); if (params.useDivWrapper) { this.canvas = _jp.createElement("div", { position : "absolute" }); _ju.sizeElement(this.canvas, 0, 0, 1, 1); this.canvas.className = clazz; } else { _attr(this.svg, { "class": clazz }); this.canvas = this.svg; } params._jsPlumb.appendElement(this.canvas, params.originalArgs[0].parent); if (params.useDivWrapper) { this.canvas.appendChild(this.svg); } var displayElements = [ this.canvas ]; this.getDisplayElements = function () { return displayElements; }; this.appendDisplayElement = function (el) { displayElements.push(el); }; this.paint = function (style, anchor, extents) { if (style != null) { var xy = [ this.x, this.y ], wh = [ this.w, this.h ], p; if (extents != null) { if (extents.xmin < 0) { xy[0] += extents.xmin; } if (extents.ymin < 0) { xy[1] += extents.ymin; } wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0); wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0); } if (params.useDivWrapper) { _ju.sizeElement(this.canvas, xy[0], xy[1], wh[0], wh[1]); xy[0] = 0; xy[1] = 0; p = _pos([ 0, 0 ]); } else { p = _pos([ xy[0], xy[1] ]); } renderer.paint.apply(this, arguments); _attr(this.svg, { "style": p, "width": wh[0] || 0, "height": wh[1] || 0 }); } }; return { renderer: renderer }; }; _ju.extend(SvgComponent, _jp.jsPlumbUIComponent, { cleanup: function (force) { if (force || this.typeId == null) { if (this.canvas) { this.canvas._jsPlumb = null; } if (this.svg) { this.svg._jsPlumb = null; } if (this.bgCanvas) { this.bgCanvas._jsPlumb = null; } if (this.canvas && this.canvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas); } if (this.bgCanvas && this.bgCanvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas); } this.svg = null; this.canvas = null; this.path = null; this.group = null; } else { // if not a forced cleanup, just detach from DOM for now. if (this.canvas && this.canvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas); } if (this.bgCanvas && this.bgCanvas.parentNode) { this.bgCanvas.parentNode.removeChild(this.bgCanvas); } } }, reattach:function(instance) { var c = instance.getContainer(); if (this.canvas && this.canvas.parentNode == null) { c.appendChild(this.canvas); } if (this.bgCanvas && this.bgCanvas.parentNode == null) { c.appendChild(this.bgCanvas); } }, setVisible: function (v) { if (this.canvas) { this.canvas.style.display = v ? "block" : "none"; } } }); /* * Base class for SVG connectors. */ _jp.ConnectorRenderers.svg = function (params) { var self = this, _super = SvgComponent.apply(this, [ { cssClass: params._jsPlumb.connectorClass, originalArgs: arguments, pointerEventsSpec: "none", _jsPlumb: params._jsPlumb } ]); _super.renderer.paint = function (style, anchor, extents) { var segments = self.getSegments(), p = "", offset = [0, 0]; if (extents.xmin < 0) { offset[0] = -extents.xmin; } if (extents.ymin < 0) { offset[1] = -extents.ymin; } if (segments.length > 0) { p = self.getPathData(); var a = { d: p, transform: "translate(" + offset[0] + "," + offset[1] + ")", "pointer-events": params["pointer-events"] || "visibleStroke" }, outlineStyle = null, d = [self.x, self.y, self.w, self.h]; // outline style. actually means drawing an svg object underneath the main one. if (style.outlineStroke) { var outlineWidth = style.outlineWidth || 1, outlineStrokeWidth = style.strokeWidth + (2 * outlineWidth); outlineStyle = _jp.extend({}, style); delete outlineStyle.gradient; outlineStyle.stroke = style.outlineStroke; outlineStyle.strokeWidth = outlineStrokeWidth; if (self.bgPath == null) { self.bgPath = _node("path", a); _jp.addClass(self.bgPath, _jp.connectorOutlineClass); _appendAtIndex(self.svg, self.bgPath, 0); } else { _attr(self.bgPath, a); } _applyStyles(self.svg, self.bgPath, outlineStyle, d, self); } if (self.path == null) { self.path = _node("path", a); _appendAtIndex(self.svg, self.path, style.outlineStroke ? 1 : 0); } else { _attr(self.path, a); } _applyStyles(self.svg, self.path, style, d, self); } }; }; _ju.extend(_jp.ConnectorRenderers.svg, SvgComponent); // ******************************* svg segment renderer ***************************************************** // ******************************* /svg segments ***************************************************** /* * Base class for SVG endpoints. */ var SvgEndpoint = _jp.SvgEndpoint = function (params) { var _super = SvgComponent.apply(this, [ { cssClass: params._jsPlumb.endpointClass, originalArgs: arguments, pointerEventsSpec: "all", useDivWrapper: true, _jsPlumb: params._jsPlumb } ]); _super.renderer.paint = function (style) { var s = _jp.extend({}, style); if (s.outlineStroke) { s.stroke = s.outlineStroke; } if (this.node == null) { this.node = this.makeNode(s); this.svg.appendChild(this.node); } else if (this.updateNode != null) { this.updateNode(this.node); } _applyStyles(this.svg, this.node, s, [ this.x, this.y, this.w, this.h ], this); _pos(this.node, [ this.x, this.y ]); }.bind(this); }; _ju.extend(SvgEndpoint, SvgComponent); /* * SVG Dot Endpoint */ _jp.Endpoints.svg.Dot = function () { _jp.Endpoints.Dot.apply(this, arguments); SvgEndpoint.apply(this, arguments); this.makeNode = function (style) { return _node("circle", { "cx": this.w / 2, "cy": this.h / 2, "r": this.radius }); }; this.updateNode = function (node) { _attr(node, { "cx": this.w / 2, "cy": this.h / 2, "r": this.radius }); }; }; _ju.extend(_jp.Endpoints.svg.Dot, [_jp.Endpoints.Dot, SvgEndpoint]); /* * SVG Rectangle Endpoint */ _jp.Endpoints.svg.Rectangle = function () { _jp.Endpoints.Rectangle.apply(this, arguments); SvgEndpoint.apply(this, arguments); this.makeNode = function (style) { return _node("rect", { "width": this.w, "height": this.h }); }; this.updateNode = function (node) { _attr(node, { "width": this.w, "height": this.h }); }; }; _ju.extend(_jp.Endpoints.svg.Rectangle, [_jp.Endpoints.Rectangle, SvgEndpoint]); /* * SVG Image Endpoint is the default image endpoint. */ _jp.Endpoints.svg.Image = _jp.Endpoints.Image; /* * Blank endpoint in svg renderer is the default Blank endpoint. */ _jp.Endpoints.svg.Blank = _jp.Endpoints.Blank; /* * Label overlay in svg renderer is the default Label overlay. */ _jp.Overlays.svg.Label = _jp.Overlays.Label; /* * Custom overlay in svg renderer is the default Custom overlay. */ _jp.Overlays.svg.Custom = _jp.Overlays.Custom; var AbstractSvgArrowOverlay = function (superclass, originalArgs) { superclass.apply(this, originalArgs); _jp.jsPlumbUIComponent.apply(this, originalArgs); this.isAppendedAtTopLevel = false; var self = this; this.path = null; this.paint = function (params, containerExtents) { // only draws on connections, not endpoints. if (params.component.svg && containerExtents) { if (this.path == null) { this.path = _node("path", { "pointer-events": "all" }); params.component.svg.appendChild(this.path); if (this.elementCreated) { this.elementCreated(this.path, params.component); } this.canvas = params.component.svg; // for the sake of completeness; this behaves the same as other overlays } var clazz = originalArgs && (originalArgs.length === 1) ? (originalArgs[0].cssClass || "") : "", offset = [0, 0]; if (containerExtents.xmin < 0) { offset[0] = -containerExtents.xmin; } if (containerExtents.ymin < 0) { offset[1] = -containerExtents.ymin; } _attr(this.path, { "d": makePath(params.d), "class": clazz, stroke: params.stroke ? params.stroke : null, fill: params.fill ? params.fill : null, transform: "translate(" + offset[0] + "," + offset[1] + ")" }); } }; var makePath = function (d) { return (isNaN(d.cxy.x) || isNaN(d.cxy.y)) ? "" : "M" + d.hxy.x + "," + d.hxy.y + " L" + d.tail[0].x + "," + d.tail[0].y + " L" + d.cxy.x + "," + d.cxy.y + " L" + d.tail[1].x + "," + d.tail[1].y + " L" + d.hxy.x + "," + d.hxy.y; }; this.transfer = function(target) { if (target.canvas && this.path && this.path.parentNode) { this.path.parentNode.removeChild(this.path); target.canvas.appendChild(this.path); } }; }; _ju.extend(AbstractSvgArrowOverlay, [_jp.jsPlumbUIComponent, _jp.Overlays.AbstractOverlay], { cleanup: function (force) { if (this.path != null) { if (force) { this._jsPlumb.instance.removeElement(this.path); } else { if (this.path.parentNode) { this.path.parentNode.removeChild(this.path); } } } }, reattach:function(instance, component) { if (this.path && component.canvas) { component.canvas.appendChild(this.path); } }, setVisible: function (v) { if (this.path != null) { (this.path.style.display = (v ? "block" : "none")); } } }); _jp.Overlays.svg.Arrow = function () { AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Arrow, arguments]); }; _ju.extend(_jp.Overlays.svg.Arrow, [ _jp.Overlays.Arrow, AbstractSvgArrowOverlay ]); _jp.Overlays.svg.PlainArrow = function () { AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.PlainArrow, arguments]); }; _ju.extend(_jp.Overlays.svg.PlainArrow, [ _jp.Overlays.PlainArrow, AbstractSvgArrowOverlay ]); _jp.Overlays.svg.Diamond = function () { AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Diamond, arguments]); }; _ju.extend(_jp.Overlays.svg.Diamond, [ _jp.Overlays.Diamond, AbstractSvgArrowOverlay ]); // a test _jp.Overlays.svg.GuideLines = function () { var path = null, self = this, p1_1, p1_2; _jp.Overlays.GuideLines.apply(this, arguments); this.paint = function (params, containerExtents) { if (path == null) { path = _node("path"); params.connector.svg.appendChild(path); self.attachListeners(path, params.connector); self.attachListeners(path, self); p1_1 = _node("path"); params.connector.svg.appendChild(p1_1); self.attachListeners(p1_1, params.connector); self.attachListeners(p1_1, self); p1_2 = _node("path"); params.connector.svg.appendChild(p1_2); self.attachListeners(p1_2, params.connector); self.attachListeners(p1_2, self); } var offset = [0, 0]; if (containerExtents.xmin < 0) { offset[0] = -containerExtents.xmin; } if (containerExtents.ymin < 0) { offset[1] = -containerExtents.ymin; } _attr(path, { "d": makePath(params.head, params.tail), stroke: "red", fill: null, transform: "translate(" + offset[0] + "," + offset[1] + ")" }); _attr(p1_1, { "d": makePath(params.tailLine[0], params.tailLine[1]), stroke: "blue", fill: null, transform: "translate(" + offset[0] + "," + offset[1] + ")" }); _attr(p1_2, { "d": makePath(params.headLine[0], params.headLine[1]), stroke: "green", fill: null, transform: "translate(" + offset[0] + "," + offset[1] + ")" }); }; var makePath = function (d1, d2) { return "M " + d1.x + "," + d1.y + " L" + d2.x + "," + d2.y; }; }; _ju.extend(_jp.Overlays.svg.GuideLines, _jp.Overlays.GuideLines); }).call(typeof window !== 'undefined' ? window : this); /* * This file contains the 'vanilla' adapter - having no external dependencies other than bundled libs. * * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com) * * https://jsplumbtoolkit.com * https://github.com/jsplumb/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ; (function () { "use strict"; var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jk = root.Katavorio, _jg = root.Biltong; var _getDragManager = function (instance, category) { category = category || "main"; var key = "_katavorio_" + category; var k = instance[key], e = instance.getEventManager(); if (!k) { k = new _jk({ bind: e.on, unbind: e.off, getSize: _jp.getSize, getConstrainingRectangle:function(el) { return [ el.parentNode.scrollWidth, el.parentNode.scrollHeight ]; }, getPosition: function (el, relativeToRoot) { // if this is a nested draggable then compute the offset against its own offsetParent, otherwise // compute against the Container's origin. see also the getUIPosition method below. var o = instance.getOffset(el, relativeToRoot, el._katavorioDrag ? el.offsetParent : null); return [o.left, o.top]; }, setPosition: function (el, xy) { el.style.left = xy[0] + "px"; el.style.top = xy[1] + "px"; }, addClass: _jp.addClass, removeClass: _jp.removeClass, intersects: _jg.intersects, indexOf: function(l, i) { return l.indexOf(i); }, scope:instance.getDefaultScope(), css: { noSelect: instance.dragSelectClass, droppable: "jtk-droppable", draggable: "jtk-draggable", drag: "jtk-drag", selected: "jtk-drag-selected", active: "jtk-drag-active", hover: "jtk-drag-hover", ghostProxy:"jtk-ghost-proxy" } }); k.setZoom(instance.getZoom()); instance[key] = k; instance.bind("zoom", k.setZoom); } return k; }; var _animProps = function (o, p) { var _one = function (pName) { if (p[pName] != null) { if (_ju.isString(p[pName])) { var m = p[pName].match(/-=/) ? -1 : 1, v = p[pName].substring(2); return o[pName] + (m * v); } else { return p[pName]; } } else { return o[pName]; } }; return [ _one("left"), _one("top") ]; }; _jp.extend(root.jsPlumbInstance.prototype, { animationSupported:true, getElement: function (el) { if (el == null) { return null; } // here we pluck the first entry if el was a list of entries. // this is not my favourite thing to do, but previous versions of // jsplumb supported jquery selectors, and it is possible a selector // will be passed in here. el = typeof el === "string" ? el : el.length != null && el.enctype == null ? el[0] : el; return typeof el === "string" ? document.getElementById(el) : el; }, removeElement: function (element) { _getDragManager(this).elementRemoved(element); this.getEventManager().remove(element); }, // // this adapter supports a rudimentary animation function. no easing is supported. only // left/top properties are supported. property delta args are expected to be in the form // // +=x.xxxx // // or // // -=x.xxxx // doAnimate: function (el, properties, options) { options = options || {}; var o = this.getOffset(el), ap = _animProps(o, properties), ldist = ap[0] - o.left, tdist = ap[1] - o.top, d = options.duration || 250, step = 15, steps = d / step, linc = (step / d) * ldist, tinc = (step / d) * tdist, idx = 0, _int = setInterval(function () { _jp.setPosition(el, { left: o.left + (linc * (idx + 1)), top: o.top + (tinc * (idx + 1)) }); if (options.step != null) { options.step(idx, Math.ceil(steps)); } idx++; if (idx >= steps) { window.clearInterval(_int); if (options.complete != null) { options.complete(); } } }, step); }, // DRAG/DROP destroyDraggable: function (el, category) { _getDragManager(this, category).destroyDraggable(el); }, unbindDraggable: function (el, evt, fn, category) { _getDragManager(this, category).destroyDraggable(el, evt, fn); }, destroyDroppable: function (el, category) { _getDragManager(this, category).destroyDroppable(el); }, unbindDroppable: function (el, evt, fn, category) { _getDragManager(this, category).destroyDroppable(el, evt, fn); }, initDraggable: function (el, options, category) { _getDragManager(this, category).draggable(el, options); }, initDroppable: function (el, options, category) { _getDragManager(this, category).droppable(el, options); }, isAlreadyDraggable: function (el) { return el._katavorioDrag != null; }, isDragSupported: function (el, options) { return true; }, isDropSupported: function (el, options) { return true; }, isElementDraggable: function (el) { el = _jp.getElement(el); return el._katavorioDrag && el._katavorioDrag.isEnabled(); }, getDragObject: function (eventArgs) { return eventArgs[0].drag.getDragElement(); }, getDragScope: function (el) { return el._katavorioDrag && el._katavorioDrag.scopes.join(" ") || ""; }, getDropEvent: function (args) { return args[0].e; }, getUIPosition: function (eventArgs, zoom) { // here the position reported to us by Katavorio is relative to the element's offsetParent. For top // level nodes that is fine, but if we have a nested draggable then its offsetParent is actually // not going to be the jsplumb container; it's going to be some child of that element. In that case // we want to adjust the UI position to account for the offsetParent's position relative to the Container // origin. var el = eventArgs[0].el; if (el.offsetParent == null) { return null; } var finalPos = eventArgs[0].finalPos || eventArgs[0].pos; var p = { left:finalPos[0], top:finalPos[1] }; if (el._katavorioDrag && el.offsetParent !== this.getContainer()) { var oc = this.getOffset(el.offsetParent); p.left += oc.left; p.top += oc.top; } return p; }, setDragFilter: function (el, filter, _exclude) { if (el._katavorioDrag) { el._katavorioDrag.setFilter(filter, _exclude); } }, setElementDraggable: function (el, draggable) { el = _jp.getElement(el); if (el._katavorioDrag) { el._katavorioDrag.setEnabled(draggable); } }, setDragScope: function (el, scope) { if (el._katavorioDrag) { el._katavorioDrag.k.setDragScope(el, scope); } }, setDropScope:function(el, scope) { if (el._katavorioDrop && el._katavorioDrop.length > 0) { el._katavorioDrop[0].k.setDropScope(el, scope); } }, addToPosse:function(el, spec) { var specs = Array.prototype.slice.call(arguments, 1); var dm = _getDragManager(this); _jp.each(el, function(_el) { _el = [ _jp.getElement(_el) ]; _el.push.apply(_el, specs ); dm.addToPosse.apply(dm, _el); }); }, setPosse:function(el, spec) { var specs = Array.prototype.slice.call(arguments, 1); var dm = _getDragManager(this); _jp.each(el, function(_el) { _el = [ _jp.getElement(_el) ]; _el.push.apply(_el, specs ); dm.setPosse.apply(dm, _el); }); }, removeFromPosse:function(el, posseId) { var specs = Array.prototype.slice.call(arguments, 1); var dm = _getDragManager(this); _jp.each(el, function(_el) { _el = [ _jp.getElement(_el) ]; _el.push.apply(_el, specs ); dm.removeFromPosse.apply(dm, _el); }); }, removeFromAllPosses:function(el) { var dm = _getDragManager(this); _jp.each(el, function(_el) { dm.removeFromAllPosses(_jp.getElement(_el)); }); }, setPosseState:function(el, posseId, state) { var dm = _getDragManager(this); _jp.each(el, function(_el) { dm.setPosseState(_jp.getElement(_el), posseId, state); }); }, dragEvents: { 'start': 'start', 'stop': 'stop', 'drag': 'drag', 'step': 'step', 'over': 'over', 'out': 'out', 'drop': 'drop', 'complete': 'complete', 'beforeStart':'beforeStart' }, animEvents: { 'step': "step", 'complete': 'complete' }, stopDrag: function (el) { if (el._katavorioDrag) { el._katavorioDrag.abort(); } }, addToDragSelection: function (spec) { _getDragManager(this).select(spec); }, removeFromDragSelection: function (spec) { _getDragManager(this).deselect(spec); }, clearDragSelection: function () { _getDragManager(this).deselectAll(); }, trigger: function (el, event, originalEvent, payload) { this.getEventManager().trigger(el, event, originalEvent, payload); }, doReset:function() { // look for katavorio instances and reset each one if found. for (var key in this) { if (key.indexOf("_katavorio_") === 0) { this[key].reset(); } } } }); var ready = function (f) { var _do = function () { if (/complete|loaded|interactive/.test(document.readyState) && typeof(document.body) !== "undefined" && document.body != null) { f(); } else { setTimeout(_do, 9); } }; _do(); }; ready(_jp.init); }).call(typeof window !== 'undefined' ? window : this);
'use strict'; /** * @ngdoc overview * @name ngCookies */ angular.module('ngCookies', ['ng']). /** * @ngdoc object * @name ngCookies.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example <doc:example> <doc:source> <script> function ExampleController($cookies) { // Retrieving a cookie var favoriteCookie = $cookies.myFavorite; // Setting a cookie $cookies.myFavorite = 'oatmeal'; } </script> </doc:source> </doc:example> */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { if (angular.isDefined(lastCookies[name])) { cookies[name] = lastCookies[name]; } else { delete cookies[name]; } } else if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc object * @name ngCookies.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name ngCookies.$cookieStore#get * @methodOf ngCookies.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return angular.fromJson($cookies[key]); }, /** * @ngdoc method * @name ngCookies.$cookieStore#put * @methodOf ngCookies.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name ngCookies.$cookieStore#remove * @methodOf ngCookies.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]);
/* * The MIT License * * Copyright (c) 2013, Sebastian Sdorra * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; angular.module('sample.widgets.github', ['adf.provider', 'highcharts-ng']) .value('githubApiUrl', 'https://api.github.com/repos/') .config(function(dashboardProvider){ // template object for github widgets var widget = { templateUrl: 'scripts/widgets/github/github.html', reload: true, resolve: { commits: function(githubService, config){ if (config.path){ return githubService.get(config.path); } } }, edit: { templateUrl: 'scripts/widgets/github/edit.html' } }; // register github template by extending the template object dashboardProvider .widget('githubHistory', angular.extend({ title: 'Github History', description: 'Display the commit history of a GitHub project as chart', controller: 'githubHistoryCtrl' }, widget)) .widget('githubAuthor', angular.extend({ title: 'Github Author', description: 'Displays the commits per author as pie chart', controller: 'githubAuthorCtrl' }, widget)); }) .service('githubService', function($q, $http, githubApiUrl){ return { get: function(path){ var deferred = $q.defer(); var url = githubApiUrl + path + '/commits?callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data){ if (data && data.data){ deferred.resolve(data.data); } else { deferred.reject(); } }) .error(function(){ deferred.reject(); }); return deferred.promise; } }; }) .controller('githubHistoryCtrl', function($scope, config, commits){ function parseDate(input) { var parts = input.split('-'); return Date.UTC(parts[0], parts[1]-1, parts[2]); } var data = {}; angular.forEach(commits, function(commit){ var day = commit.commit.author.date; day = day.substring(0, day.indexOf('T')); if (data[day]){ data[day]++; } else { data[day] = 1; } }); var seriesData = []; angular.forEach(data, function(count, day){ seriesData.push([parseDate(day), count]); }); seriesData.sort(function(a, b){ return a[0] - b[0]; }); if ( commits ){ $scope.chartConfig = { chart: { type: 'spline' }, title: { text: 'Github commit history' }, xAxis: { type: 'datetime' }, yAxis: { title: { text: 'Commits' }, min: 0 }, series: [{ name: config.path, data: seriesData }] }; } }) .controller('githubAuthorCtrl', function($scope, config, commits){ var data = {}; angular.forEach(commits, function(commit){ var author = commit.commit.author.name; if (data[author]){ data[author]++; } else { data[author] = 1; } }); var seriesData = []; angular.forEach(data, function(count, author){ seriesData.push([author, count]); }); if (seriesData.length > 0){ seriesData.sort(function(a, b){ return b[1] - a[1]; }); var s = seriesData[0]; seriesData[0] = { name: s[0], y: s[1], sliced: true, selected: true }; } if ( commits ){ $scope.chartConfig = { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text: config.path }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, color: '#000000', connectorColor: '#000000', format: '<b>{point.name}</b>: {point.percentage:.1f} %' } } }, series: [{ type: 'pie', name: config.path, data: seriesData }] }; } });
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/AlphaPresentForms.js * * Copyright (c) 2012 Design Science, Inc. * * Part of the MathJax library. * See http://www.mathjax.org for details. * * Licensed under the Apache License, Version 2.0; * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold"],{64256:[691,0,610,15,666],64257:[691,0,556,14,536],64258:[691,0,556,15,535],64259:[691,0,833,15,813],64260:[691,0,833,15,812]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Bold/AlphaPresentForms.js");
'use strict'; var expect = require('chai').expect; var stub = require('../../helpers/stub').stub; var commandOptions = require('../../factories/command-options'); var InstallCommand = require('../../../lib/commands/install-addon'); var Task = require('../../../lib/models/task'); var Project = require('../../../lib/models/project'); var Promise = require('../../../lib/ext/promise'); var AddonInstall = require('../../../lib/tasks/addon-install'); describe('install:addon command', function() { var command, options, tasks, generateBlueprintInstance, npmInstance; beforeEach(function() { tasks = { AddonInstall: AddonInstall, NpmInstall: Task.extend({ init: function() { npmInstance = this; } }), GenerateFromBlueprint: Task.extend({ init: function() { generateBlueprintInstance = this; } }) }; options = commandOptions({ settings: {}, project: { name: function() { return 'some-random-name'; }, isEmberCLIProject: function() { return true; }, initializeAddons: function() { }, reloadAddons: function() { this.addons = [ { pkg: { name: 'ember-data', } }, { pkg: { name: 'ember-cli-cordova', 'ember-addon': { defaultBlueprint: 'cordova-starter-kit' } } }, { pkg: { name: 'ember-cli-qunit' } } ]; }, findAddonByName: Project.prototype.findAddonByName }, tasks: tasks }); stub(tasks.NpmInstall.prototype, 'run', Promise.resolve()); stub(tasks.GenerateFromBlueprint.prototype, 'run', Promise.resolve()); command = new InstallCommand(options); }); afterEach(function() { tasks.NpmInstall.prototype.run.restore(); tasks.GenerateFromBlueprint.prototype.run.restore(); }); it('initializes npm install and generate blueprint task with ui, project and analytics', function() { return command.validateAndRun(['ember-data']).then(function() { expect(npmInstance.ui, 'ui was set'); expect(npmInstance.project, 'project was set'); expect(npmInstance.analytics, 'analytics was set'); expect(generateBlueprintInstance.ui, 'ui was set'); expect(generateBlueprintInstance.project, 'project was set'); expect(generateBlueprintInstance.analytics, 'analytics was set'); }); }); describe('with args', function() { it('runs the npm install task with given name and save-dev true', function() { return command.validateAndRun(['ember-data']).then(function() { var npmRun = tasks.NpmInstall.prototype.run; expect(npmRun.called).to.equal(1, 'expected npm install run was called once'); expect(npmRun.calledWith[0][0]).to.deep.equal({ packages: ['ember-data'], 'save-dev': true, 'save-exact': true }, 'expected npm install called with given name and save-dev true'); }); }); it('runs the packae name blueprint task with given name and args', function() { return command.validateAndRun(['ember-data']).then(function() { var generateRun = tasks.GenerateFromBlueprint.prototype.run; expect(generateRun.calledWith[0][0].ignoreMissingMain, true); expect(generateRun.calledWith[0][0].args).to.deep.equal([ 'ember-data' ], 'expected generate blueprint called with correct args'); }); }); it('runs the defaultBlueprint task with given github/name and args', function() { return command.validateAndRun(['ember-cli-cordova', 'com.ember.test']).then(function() { var generateRun = tasks.GenerateFromBlueprint.prototype.run; expect(generateRun.calledWith[0][0].ignoreMissingMain, true); expect(generateRun.calledWith[0][0].args).to.deep.equal([ 'cordova-starter-kit', 'com.ember.test' ], 'expected generate blueprint called with correct args'); }); }); it('runs the package name blueprint task when given github/name and args', function() { return command.validateAndRun(['ember-cli/ember-cli-qunit']).then(function() { var generateRun = tasks.GenerateFromBlueprint.prototype.run; expect(generateRun.calledWith[0][0].ignoreMissingMain, true); expect(generateRun.calledWith[0][0].args).to.deep.equal([ 'ember-cli-qunit' ], 'expected generate blueprint called with correct args'); }); }); it('gives helpful message if it can\'t find the addon', function() { return command.validateAndRun(['unknown-addon']).then(function() { expect(false, 'should reject with error'); }).catch(function(err) { expect(err.message).to.equal( 'Install failed. Could not find addon with name: unknown-addon', 'expected error to have helpful message' ); }); }); }); });