How to use config method in stryker-parent

Best JavaScript code snippet using stryker-parent

ResponderEventPlugin-test.internal.js

Source:ResponderEventPlugin-test.internal.js Github

copy

Full Screen

1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @emails react-core8 */9'use strict';10const {HostComponent} = require('shared/ReactWorkTags');11let EventPluginHub;12let EventPluginUtils;13let ResponderEventPlugin;14const touch = function(nodeHandle, i) {15 return {target: nodeHandle, identifier: i};16};17function injectComponentTree(ComponentTree) {18 EventPluginUtils.setComponentTree(19 ComponentTree.getFiberCurrentPropsFromNode,20 ComponentTree.getInstanceFromNode,21 ComponentTree.getNodeFromInstance,22 );23}24/**25 * @param {NodeHandle} nodeHandle @see NodeHandle. Handle of target.26 * @param {Array<Touch>} touches All active touches.27 * @param {Array<Touch>} changedTouches Only the touches that have changed.28 * @return {TouchEvent} Model of a touch event that is compliant with responder29 * system plugin.30 */31const touchEvent = function(nodeHandle, touches, changedTouches) {32 return {33 target: nodeHandle,34 changedTouches: changedTouches,35 touches: touches,36 };37};38const subsequence = function(arr, indices) {39 const ret = [];40 for (let i = 0; i < indices.length; i++) {41 const index = indices[i];42 ret.push(arr[index]);43 }44 return ret;45};46const antiSubsequence = function(arr, indices) {47 const ret = [];48 for (let i = 0; i < arr.length; i++) {49 if (indices.indexOf(i) === -1) {50 ret.push(arr[i]);51 }52 }53 return ret;54};55/**56 * Helper for creating touch test config data.57 * @param allTouchHandles58 */59const _touchConfig = function(60 topType,61 targetNodeHandle,62 allTouchHandles,63 changedIndices,64 eventTarget,65) {66 const allTouchObjects = allTouchHandles.map(touch);67 const changedTouchObjects = subsequence(allTouchObjects, changedIndices);68 const activeTouchObjects =69 topType === 'topTouchStart'70 ? allTouchObjects71 : topType === 'topTouchMove'72 ? allTouchObjects73 : topType === 'topTouchEnd'74 ? antiSubsequence(allTouchObjects, changedIndices)75 : topType === 'topTouchCancel'76 ? antiSubsequence(allTouchObjects, changedIndices)77 : null;78 return {79 nativeEvent: touchEvent(80 targetNodeHandle,81 activeTouchObjects,82 changedTouchObjects,83 ),84 topLevelType: topType,85 targetInst: getInstanceFromNode(targetNodeHandle),86 };87};88/**89 * Creates test data for touch events using environment agnostic "node90 * handles".91 *92 * @param {NodeHandle} nodeHandle Environment agnostic handle to DOM node.93 * @param {Array<NodeHandle>} allTouchHandles Encoding of all "touches" in the94 * form of a mapping from integer (touch `identifier`) to touch target. This is95 * encoded in array form. Because of this, it is possible for two separate96 * touches (meaning two separate indices) to have the same touch target ID -97 * this corresponds to real world cases where two separate unique touches have98 * the same target. These touches don't just represent all active touches,99 * rather it also includes any touches that are not active, but are in the100 * process of being removed.101 * @param {Array<NodeHandle>} changedIndices Indices of `allTouchHandles` that102 * have changed.103 * @return {object} Config data used by test cases for extracting responder104 * events.105 */106const startConfig = function(nodeHandle, allTouchHandles, changedIndices) {107 return _touchConfig(108 'topTouchStart',109 nodeHandle,110 allTouchHandles,111 changedIndices,112 nodeHandle,113 );114};115/**116 * @see `startConfig`117 */118const moveConfig = function(nodeHandle, allTouchHandles, changedIndices) {119 return _touchConfig(120 'topTouchMove',121 nodeHandle,122 allTouchHandles,123 changedIndices,124 nodeHandle,125 );126};127/**128 * @see `startConfig`129 */130const endConfig = function(nodeHandle, allTouchHandles, changedIndices) {131 return _touchConfig(132 'topTouchEnd',133 nodeHandle,134 allTouchHandles,135 changedIndices,136 nodeHandle,137 );138};139/**140 * Test config for events that aren't negotiation related, but rather result of141 * a negotiation.142 *143 * Returns object of the form:144 *145 * {146 * responderReject: {147 * // Whatever "readableIDToID" was passed in.148 * grandParent: {order: NA, assertEvent: null, returnVal: blah},149 * ...150 * child: {order: NA, assertEvent: null, returnVal: blah},151 * }152 * responderGrant: {153 * grandParent: {order: NA, assertEvent: null, returnVal: blah},154 * ...155 * child: {order: NA, assertEvent: null, returnVal: blah}156 * }157 * ...158 * }159 *160 * After this is created, a test case would configure specific event orderings161 * and optional assertions. Anything left with an `order` of `NA` will be162 * required to never be invoked (the test runner will make sure it throws if163 * ever invoked).164 *165 */166const NA = -1;167const oneEventLoopTestConfig = function(readableIDToID) {168 const ret = {169 // Negotiation170 scrollShouldSetResponder: {bubbled: {}, captured: {}},171 startShouldSetResponder: {bubbled: {}, captured: {}},172 moveShouldSetResponder: {bubbled: {}, captured: {}},173 responderTerminationRequest: {},174 // Non-negotiation175 responderReject: {}, // These do not bubble capture.176 responderGrant: {},177 responderStart: {},178 responderMove: {},179 responderTerminate: {},180 responderEnd: {},181 responderRelease: {},182 };183 for (const eventName in ret) {184 for (const readableNodeName in readableIDToID) {185 if (ret[eventName].bubbled) {186 // Two phase187 ret[eventName].bubbled[readableNodeName] = {188 order: NA,189 assertEvent: null,190 returnVal: undefined,191 };192 ret[eventName].captured[readableNodeName] = {193 order: NA,194 assertEvent: null,195 returnVal: undefined,196 };197 } else {198 ret[eventName][readableNodeName] = {199 order: NA,200 assertEvent: null,201 returnVal: undefined,202 };203 }204 }205 }206 return ret;207};208/**209 * @param {object} eventTestConfig210 * @param {object} readableIDToID211 */212const registerTestHandlers = function(eventTestConfig, readableIDToID) {213 const runs = {dispatchCount: 0};214 const neverFire = function(readableID, registrationName) {215 runs.dispatchCount++;216 expect('').toBe(217 'Event type: ' +218 registrationName +219 '\nShould never occur on:' +220 readableID +221 '\nFor event test config:\n' +222 JSON.stringify(eventTestConfig) +223 '\n',224 );225 };226 const registerOneEventType = function(registrationName, eventTypeTestConfig) {227 for (const readableID in eventTypeTestConfig) {228 const nodeConfig = eventTypeTestConfig[readableID];229 const id = readableIDToID[readableID];230 const handler =231 nodeConfig.order === NA232 ? neverFire.bind(null, readableID, registrationName)233 : // We partially apply readableID and nodeConfig, as they change in the234 // parent closure across iterations.235 function(rID, config, e) {236 expect(237 rID +238 '->' +239 registrationName +240 ' index:' +241 runs.dispatchCount++,242 ).toBe(rID + '->' + registrationName + ' index:' + config.order);243 if (config.assertEvent) {244 config.assertEvent(e);245 }246 return config.returnVal;247 }.bind(null, readableID, nodeConfig);248 putListener(getInstanceFromNode(id), registrationName, handler);249 }250 };251 for (const eventName in eventTestConfig) {252 const oneEventTypeTestConfig = eventTestConfig[eventName];253 const hasTwoPhase = !!oneEventTypeTestConfig.bubbled;254 if (hasTwoPhase) {255 registerOneEventType(256 ResponderEventPlugin.eventTypes[eventName].phasedRegistrationNames257 .bubbled,258 oneEventTypeTestConfig.bubbled,259 );260 registerOneEventType(261 ResponderEventPlugin.eventTypes[eventName].phasedRegistrationNames262 .captured,263 oneEventTypeTestConfig.captured,264 );265 } else {266 registerOneEventType(267 ResponderEventPlugin.eventTypes[eventName].registrationName,268 oneEventTypeTestConfig,269 );270 }271 }272 return runs;273};274const run = function(config, hierarchyConfig, nativeEventConfig) {275 let max = NA;276 const searchForMax = function(nodeConfig) {277 for (const readableID in nodeConfig) {278 const order = nodeConfig[readableID].order;279 max = order > max ? order : max;280 }281 };282 for (const eventName in config) {283 const eventConfig = config[eventName];284 if (eventConfig.bubbled) {285 searchForMax(eventConfig.bubbled);286 searchForMax(eventConfig.captured);287 } else {288 searchForMax(eventConfig);289 }290 }291 // Register the handlers292 const runData = registerTestHandlers(config, hierarchyConfig);293 // Trigger the event294 const extractedEvents = ResponderEventPlugin.extractEvents(295 nativeEventConfig.topLevelType,296 nativeEventConfig.targetInst,297 nativeEventConfig.nativeEvent,298 nativeEventConfig.target,299 );300 // At this point the negotiation events have been dispatched as part of the301 // extraction process, but not the side effectful events. Below, we dispatch302 // side effectful events.303 EventPluginHub.runEventsInBatch(extractedEvents);304 // Ensure that every event that declared an `order`, was actually dispatched.305 expect('number of events dispatched:' + runData.dispatchCount).toBe(306 'number of events dispatched:' + (max + 1),307 ); // +1 for extra ++308};309const GRANDPARENT_HOST_NODE = {};310const PARENT_HOST_NODE = {};311const CHILD_HOST_NODE = {};312const CHILD_HOST_NODE2 = {};313// These intentionally look like Fibers. ReactTreeTraversal depends on their field names.314// TODO: we could test this with regular DOM nodes (and real fibers) instead.315const GRANDPARENT_INST = {316 return: null,317 tag: HostComponent,318 stateNode: GRANDPARENT_HOST_NODE,319 memoizedProps: {},320};321const PARENT_INST = {322 return: GRANDPARENT_INST,323 tag: HostComponent,324 stateNode: PARENT_HOST_NODE,325 memoizedProps: {},326};327const CHILD_INST = {328 return: PARENT_INST,329 tag: HostComponent,330 stateNode: CHILD_HOST_NODE,331 memoizedProps: {},332};333const CHILD_INST2 = {334 return: PARENT_INST,335 tag: HostComponent,336 stateNode: CHILD_HOST_NODE2,337 memoizedProps: {},338};339GRANDPARENT_HOST_NODE.testInstance = GRANDPARENT_INST;340PARENT_HOST_NODE.testInstance = PARENT_INST;341CHILD_HOST_NODE.testInstance = CHILD_INST;342CHILD_HOST_NODE2.testInstance = CHILD_INST2;343const three = {344 grandParent: GRANDPARENT_HOST_NODE,345 parent: PARENT_HOST_NODE,346 child: CHILD_HOST_NODE,347};348const siblings = {349 parent: PARENT_HOST_NODE,350 childOne: CHILD_HOST_NODE,351 childTwo: CHILD_HOST_NODE2,352};353function getInstanceFromNode(node) {354 return node.testInstance;355}356function getNodeFromInstance(inst) {357 return inst.stateNode;358}359function getFiberCurrentPropsFromNode(node) {360 return node.testInstance.memoizedProps;361}362function putListener(instance, registrationName, handler) {363 instance.memoizedProps[registrationName] = handler;364}365function deleteAllListeners(instance) {366 instance.memoizedProps = {};367}368describe('ResponderEventPlugin', () => {369 beforeEach(() => {370 jest.resetModules();371 const ReactDOMUnstableNativeDependencies = require('react-dom/unstable-native-dependencies');372 EventPluginHub = require('events/EventPluginHub');373 EventPluginUtils = require('events/EventPluginUtils');374 ResponderEventPlugin =375 ReactDOMUnstableNativeDependencies.ResponderEventPlugin;376 deleteAllListeners(GRANDPARENT_INST);377 deleteAllListeners(PARENT_INST);378 deleteAllListeners(CHILD_INST);379 deleteAllListeners(CHILD_INST2);380 injectComponentTree({381 getInstanceFromNode,382 getNodeFromInstance,383 getFiberCurrentPropsFromNode,384 });385 });386 it('should do nothing when no one wants to respond', () => {387 let config = oneEventLoopTestConfig(three);388 config.startShouldSetResponder.captured.grandParent = {389 order: 0,390 returnVal: false,391 };392 config.startShouldSetResponder.captured.parent = {393 order: 1,394 returnVal: false,395 };396 config.startShouldSetResponder.captured.child = {397 order: 2,398 returnVal: false,399 };400 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false};401 config.startShouldSetResponder.bubbled.parent = {402 order: 4,403 returnVal: false,404 };405 config.startShouldSetResponder.bubbled.grandParent = {406 order: 5,407 returnVal: false,408 };409 run(config, three, startConfig(three.child, [three.child], [0]));410 expect(ResponderEventPlugin._getResponder()).toBe(null);411 // Now no handlers should be called on `touchEnd`.412 config = oneEventLoopTestConfig(three);413 run(config, three, endConfig(three.child, [three.child], [0]));414 expect(ResponderEventPlugin._getResponder()).toBe(null);415 });416 /**417 * Simple Start Granting418 * --------------------419 */420 it('should grant responder grandParent while capturing', () => {421 let config = oneEventLoopTestConfig(three);422 config.startShouldSetResponder.captured.grandParent = {423 order: 0,424 returnVal: true,425 };426 config.responderGrant.grandParent = {order: 1};427 config.responderStart.grandParent = {order: 2};428 run(config, three, startConfig(three.child, [three.child], [0]));429 expect(ResponderEventPlugin._getResponder()).toBe(430 getInstanceFromNode(three.grandParent),431 );432 config = oneEventLoopTestConfig(three);433 config.responderEnd.grandParent = {order: 0};434 config.responderRelease.grandParent = {order: 1};435 run(config, three, endConfig(three.child, [three.child], [0]));436 expect(ResponderEventPlugin._getResponder()).toBe(null);437 });438 it('should grant responder parent while capturing', () => {439 let config = oneEventLoopTestConfig(three);440 config.startShouldSetResponder.captured.grandParent = {441 order: 0,442 returnVal: false,443 };444 config.startShouldSetResponder.captured.parent = {445 order: 1,446 returnVal: true,447 };448 config.responderGrant.parent = {order: 2};449 config.responderStart.parent = {order: 3};450 run(config, three, startConfig(three.child, [three.child], [0]));451 expect(ResponderEventPlugin._getResponder()).toBe(452 getInstanceFromNode(three.parent),453 );454 config = oneEventLoopTestConfig(three);455 config.responderEnd.parent = {order: 0};456 config.responderRelease.parent = {order: 1};457 run(config, three, endConfig(three.child, [three.child], [0]));458 expect(ResponderEventPlugin._getResponder()).toBe(null);459 });460 it('should grant responder child while capturing', () => {461 let config = oneEventLoopTestConfig(three);462 config.startShouldSetResponder.captured.grandParent = {463 order: 0,464 returnVal: false,465 };466 config.startShouldSetResponder.captured.parent = {467 order: 1,468 returnVal: false,469 };470 config.startShouldSetResponder.captured.child = {order: 2, returnVal: true};471 config.responderGrant.child = {order: 3};472 config.responderStart.child = {order: 4};473 run(config, three, startConfig(three.child, [three.child], [0]));474 expect(ResponderEventPlugin._getResponder()).toBe(475 getInstanceFromNode(three.child),476 );477 config = oneEventLoopTestConfig(three);478 config.responderEnd.child = {order: 0};479 config.responderRelease.child = {order: 1};480 run(config, three, endConfig(three.child, [three.child], [0]));481 expect(ResponderEventPlugin._getResponder()).toBe(null);482 });483 it('should grant responder child while bubbling', () => {484 let config = oneEventLoopTestConfig(three);485 config.startShouldSetResponder.captured.grandParent = {486 order: 0,487 returnVal: false,488 };489 config.startShouldSetResponder.captured.parent = {490 order: 1,491 returnVal: false,492 };493 config.startShouldSetResponder.captured.child = {494 order: 2,495 returnVal: false,496 };497 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};498 config.responderGrant.child = {order: 4};499 config.responderStart.child = {order: 5};500 run(config, three, startConfig(three.child, [three.child], [0]));501 expect(ResponderEventPlugin._getResponder()).toBe(502 getInstanceFromNode(three.child),503 );504 config = oneEventLoopTestConfig(three);505 config.responderEnd.child = {order: 0};506 config.responderRelease.child = {order: 1};507 run(config, three, endConfig(three.child, [three.child], [0]));508 expect(ResponderEventPlugin._getResponder()).toBe(null);509 });510 it('should grant responder parent while bubbling', () => {511 let config = oneEventLoopTestConfig(three);512 config.startShouldSetResponder.captured.grandParent = {513 order: 0,514 returnVal: false,515 };516 config.startShouldSetResponder.captured.parent = {517 order: 1,518 returnVal: false,519 };520 config.startShouldSetResponder.captured.child = {521 order: 2,522 returnVal: false,523 };524 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false};525 config.startShouldSetResponder.bubbled.parent = {order: 4, returnVal: true};526 config.responderGrant.parent = {order: 5};527 config.responderStart.parent = {order: 6};528 run(config, three, startConfig(three.child, [three.child], [0]));529 expect(ResponderEventPlugin._getResponder()).toBe(530 getInstanceFromNode(three.parent),531 );532 config = oneEventLoopTestConfig(three);533 config.responderEnd.parent = {order: 0};534 config.responderRelease.parent = {order: 1};535 run(config, three, endConfig(three.child, [three.child], [0]));536 expect(ResponderEventPlugin._getResponder()).toBe(null);537 });538 it('should grant responder grandParent while bubbling', () => {539 let config = oneEventLoopTestConfig(three);540 config.startShouldSetResponder.captured.grandParent = {541 order: 0,542 returnVal: false,543 };544 config.startShouldSetResponder.captured.parent = {545 order: 1,546 returnVal: false,547 };548 config.startShouldSetResponder.captured.child = {549 order: 2,550 returnVal: false,551 };552 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false};553 config.startShouldSetResponder.bubbled.parent = {554 order: 4,555 returnVal: false,556 };557 config.startShouldSetResponder.bubbled.grandParent = {558 order: 5,559 returnVal: true,560 };561 config.responderGrant.grandParent = {order: 6};562 config.responderStart.grandParent = {order: 7};563 run(config, three, startConfig(three.child, [three.child], [0]));564 expect(ResponderEventPlugin._getResponder()).toBe(565 getInstanceFromNode(three.grandParent),566 );567 config = oneEventLoopTestConfig(three);568 config.responderEnd.grandParent = {order: 0};569 config.responderRelease.grandParent = {order: 1};570 run(config, three, endConfig(three.child, [three.child], [0]));571 expect(ResponderEventPlugin._getResponder()).toBe(null);572 });573 /**574 * Simple Move Granting575 * --------------------576 */577 it('should grant responder grandParent while capturing move', () => {578 let config = oneEventLoopTestConfig(three);579 config.startShouldSetResponder.captured.grandParent = {order: 0};580 config.startShouldSetResponder.captured.parent = {order: 1};581 config.startShouldSetResponder.captured.child = {order: 2};582 config.startShouldSetResponder.bubbled.child = {order: 3};583 config.startShouldSetResponder.bubbled.parent = {order: 4};584 config.startShouldSetResponder.bubbled.grandParent = {order: 5};585 run(config, three, startConfig(three.child, [three.child], [0]));586 config = oneEventLoopTestConfig(three);587 config.moveShouldSetResponder.captured.grandParent = {588 order: 0,589 returnVal: true,590 };591 config.responderGrant.grandParent = {order: 1};592 config.responderMove.grandParent = {order: 2};593 run(config, three, moveConfig(three.child, [three.child], [0]));594 expect(ResponderEventPlugin._getResponder()).toBe(595 getInstanceFromNode(three.grandParent),596 );597 config = oneEventLoopTestConfig(three);598 config.responderEnd.grandParent = {order: 0};599 config.responderRelease.grandParent = {order: 1};600 run(config, three, endConfig(three.child, [three.child], [0]));601 expect(ResponderEventPlugin._getResponder()).toBe(null);602 });603 it('should grant responder parent while capturing move', () => {604 let config = oneEventLoopTestConfig(three);605 config.startShouldSetResponder.captured.grandParent = {order: 0};606 config.startShouldSetResponder.captured.parent = {order: 1};607 config.startShouldSetResponder.captured.child = {order: 2};608 config.startShouldSetResponder.bubbled.child = {order: 3};609 config.startShouldSetResponder.bubbled.parent = {order: 4};610 config.startShouldSetResponder.bubbled.grandParent = {order: 5};611 run(config, three, startConfig(three.child, [three.child], [0]));612 config = oneEventLoopTestConfig(three);613 config.moveShouldSetResponder.captured.grandParent = {614 order: 0,615 returnVal: false,616 };617 config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: true};618 config.responderGrant.parent = {order: 2};619 config.responderMove.parent = {order: 3};620 run(config, three, moveConfig(three.child, [three.child], [0]));621 expect(ResponderEventPlugin._getResponder()).toBe(622 getInstanceFromNode(three.parent),623 );624 config = oneEventLoopTestConfig(three);625 config.responderEnd.parent = {order: 0};626 config.responderRelease.parent = {order: 1};627 run(config, three, endConfig(three.child, [three.child], [0]));628 expect(ResponderEventPlugin._getResponder()).toBe(null);629 });630 it('should grant responder child while capturing move', () => {631 let config = oneEventLoopTestConfig(three);632 config.startShouldSetResponder.captured.grandParent = {order: 0};633 config.startShouldSetResponder.captured.parent = {order: 1};634 config.startShouldSetResponder.captured.child = {order: 2};635 config.startShouldSetResponder.bubbled.child = {order: 3};636 config.startShouldSetResponder.bubbled.parent = {order: 4};637 config.startShouldSetResponder.bubbled.grandParent = {order: 5};638 run(config, three, startConfig(three.child, [three.child], [0]));639 config = oneEventLoopTestConfig(three);640 config.moveShouldSetResponder.captured.grandParent = {641 order: 0,642 returnVal: false,643 };644 config.moveShouldSetResponder.captured.parent = {645 order: 1,646 returnVal: false,647 };648 config.moveShouldSetResponder.captured.child = {order: 2, returnVal: true};649 config.responderGrant.child = {order: 3};650 config.responderMove.child = {order: 4};651 run(config, three, moveConfig(three.child, [three.child], [0]));652 expect(ResponderEventPlugin._getResponder()).toBe(653 getInstanceFromNode(three.child),654 );655 config = oneEventLoopTestConfig(three);656 config.responderEnd.child = {order: 0};657 config.responderRelease.child = {order: 1};658 run(config, three, endConfig(three.child, [three.child], [0]));659 expect(ResponderEventPlugin._getResponder()).toBe(null);660 });661 it('should grant responder child while bubbling move', () => {662 let config = oneEventLoopTestConfig(three);663 config.startShouldSetResponder.captured.grandParent = {order: 0};664 config.startShouldSetResponder.captured.parent = {order: 1};665 config.startShouldSetResponder.captured.child = {order: 2};666 config.startShouldSetResponder.bubbled.child = {order: 3};667 config.startShouldSetResponder.bubbled.parent = {order: 4};668 config.startShouldSetResponder.bubbled.grandParent = {order: 5};669 run(config, three, startConfig(three.child, [three.child], [0]));670 config = oneEventLoopTestConfig(three);671 config.moveShouldSetResponder.captured.grandParent = {672 order: 0,673 returnVal: false,674 };675 config.moveShouldSetResponder.captured.parent = {676 order: 1,677 returnVal: false,678 };679 config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false};680 config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: true};681 config.responderGrant.child = {order: 4};682 config.responderMove.child = {order: 5};683 run(config, three, moveConfig(three.child, [three.child], [0]));684 expect(ResponderEventPlugin._getResponder()).toBe(685 getInstanceFromNode(three.child),686 );687 config = oneEventLoopTestConfig(three);688 config.responderEnd.child = {order: 0};689 config.responderRelease.child = {order: 1};690 run(config, three, endConfig(three.child, [three.child], [0]));691 expect(ResponderEventPlugin._getResponder()).toBe(null);692 });693 it('should grant responder parent while bubbling move', () => {694 let config = oneEventLoopTestConfig(three);695 config.startShouldSetResponder.captured.grandParent = {order: 0};696 config.startShouldSetResponder.captured.parent = {order: 1};697 config.startShouldSetResponder.captured.child = {order: 2};698 config.startShouldSetResponder.bubbled.child = {order: 3};699 config.startShouldSetResponder.bubbled.parent = {order: 4};700 config.startShouldSetResponder.bubbled.grandParent = {order: 5};701 run(config, three, startConfig(three.child, [three.child], [0]));702 config = oneEventLoopTestConfig(three);703 config.moveShouldSetResponder.captured.grandParent = {704 order: 0,705 returnVal: false,706 };707 config.moveShouldSetResponder.captured.parent = {708 order: 1,709 returnVal: false,710 };711 config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false};712 config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: false};713 config.moveShouldSetResponder.bubbled.parent = {order: 4, returnVal: true};714 config.responderGrant.parent = {order: 5};715 config.responderMove.parent = {order: 6};716 run(config, three, moveConfig(three.child, [three.child], [0]));717 expect(ResponderEventPlugin._getResponder()).toBe(718 getInstanceFromNode(three.parent),719 );720 config = oneEventLoopTestConfig(three);721 config.responderEnd.parent = {order: 0};722 config.responderRelease.parent = {order: 1};723 run(config, three, endConfig(three.child, [three.child], [0]));724 expect(ResponderEventPlugin._getResponder()).toBe(null);725 });726 it('should grant responder grandParent while bubbling move', () => {727 let config = oneEventLoopTestConfig(three);728 config.startShouldSetResponder.captured.grandParent = {order: 0};729 config.startShouldSetResponder.captured.parent = {order: 1};730 config.startShouldSetResponder.captured.child = {order: 2};731 config.startShouldSetResponder.bubbled.child = {order: 3};732 config.startShouldSetResponder.bubbled.parent = {order: 4};733 config.startShouldSetResponder.bubbled.grandParent = {order: 5};734 run(config, three, startConfig(three.child, [three.child], [0]));735 config = oneEventLoopTestConfig(three);736 config.moveShouldSetResponder.captured.grandParent = {737 order: 0,738 returnVal: false,739 };740 config.moveShouldSetResponder.captured.parent = {741 order: 1,742 returnVal: false,743 };744 config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false};745 config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: false};746 config.moveShouldSetResponder.bubbled.parent = {order: 4, returnVal: false};747 config.moveShouldSetResponder.bubbled.grandParent = {748 order: 5,749 returnVal: true,750 };751 config.responderGrant.grandParent = {order: 6};752 config.responderMove.grandParent = {order: 7};753 run(config, three, moveConfig(three.child, [three.child], [0]));754 expect(ResponderEventPlugin._getResponder()).toBe(755 getInstanceFromNode(three.grandParent),756 );757 config = oneEventLoopTestConfig(three);758 config.responderEnd.grandParent = {order: 0};759 config.responderRelease.grandParent = {order: 1};760 run(config, three, endConfig(three.child, [three.child], [0]));761 expect(ResponderEventPlugin._getResponder()).toBe(null);762 });763 /**764 * Common ancestor tests765 * ---------------------766 */767 it('should bubble negotiation to first common ancestor of responder', () => {768 let config = oneEventLoopTestConfig(three);769 config.startShouldSetResponder.captured.grandParent = {770 order: 0,771 returnVal: false,772 };773 config.startShouldSetResponder.captured.parent = {774 order: 1,775 returnVal: true,776 };777 config.responderGrant.parent = {order: 2};778 config.responderStart.parent = {order: 3};779 run(config, three, startConfig(three.child, [three.child], [0]));780 expect(ResponderEventPlugin._getResponder()).toBe(781 getInstanceFromNode(three.parent),782 );783 // While `parent` is still responder, we create new handlers that verify784 // the ordering of propagation, restarting the count at `0`.785 config = oneEventLoopTestConfig(three);786 config.startShouldSetResponder.captured.grandParent = {787 order: 0,788 returnVal: false,789 };790 config.startShouldSetResponder.bubbled.grandParent = {791 order: 1,792 returnVal: false,793 };794 config.responderStart.parent = {order: 2};795 run(config, three, startConfig(three.child, [three.child], [0]));796 expect(ResponderEventPlugin._getResponder()).toBe(797 getInstanceFromNode(three.parent),798 );799 config = oneEventLoopTestConfig(three);800 config.responderEnd.parent = {order: 0};801 config.responderRelease.parent = {order: 1};802 run(config, three, endConfig(three.child, [three.child], [0]));803 expect(ResponderEventPlugin._getResponder()).toBe(null);804 });805 it('should bubble negotiation to first common ancestor of responder then transfer', () => {806 let config = oneEventLoopTestConfig(three);807 config.startShouldSetResponder.captured.grandParent = {808 order: 0,809 returnVal: false,810 };811 config.startShouldSetResponder.captured.parent = {812 order: 1,813 returnVal: true,814 };815 config.responderGrant.parent = {order: 2};816 config.responderStart.parent = {order: 3};817 run(config, three, startConfig(three.child, [three.child], [0]));818 expect(ResponderEventPlugin._getResponder()).toBe(819 getInstanceFromNode(three.parent),820 );821 config = oneEventLoopTestConfig(three);822 // Parent is responder, and responder is transferred by a second touch start823 config.startShouldSetResponder.captured.grandParent = {824 order: 0,825 returnVal: true,826 };827 config.responderGrant.grandParent = {order: 1};828 config.responderTerminationRequest.parent = {order: 2, returnVal: true};829 config.responderTerminate.parent = {order: 3};830 config.responderStart.grandParent = {order: 4};831 run(832 config,833 three,834 startConfig(three.child, [three.child, three.child], [1]),835 );836 expect(ResponderEventPlugin._getResponder()).toBe(837 getInstanceFromNode(three.grandParent),838 );839 config = oneEventLoopTestConfig(three);840 config.responderEnd.grandParent = {order: 0};841 // one remains\ /one ended \842 run(config, three, endConfig(three.child, [three.child, three.child], [1]));843 expect(ResponderEventPlugin._getResponder()).toBe(844 getInstanceFromNode(three.grandParent),845 );846 config = oneEventLoopTestConfig(three);847 config.responderEnd.grandParent = {order: 0};848 config.responderRelease.grandParent = {order: 1};849 run(config, three, endConfig(three.child, [three.child], [0]));850 expect(ResponderEventPlugin._getResponder()).toBe(null);851 });852 /**853 * If nothing is responder, then the negotiation should propagate directly to854 * the deepest target in the second touch.855 */856 it('should negotiate with deepest target on second touch if nothing is responder', () => {857 // Initially nothing wants to become the responder858 let config = oneEventLoopTestConfig(three);859 config.startShouldSetResponder.captured.grandParent = {860 order: 0,861 returnVal: false,862 };863 config.startShouldSetResponder.captured.parent = {864 order: 1,865 returnVal: false,866 };867 config.startShouldSetResponder.bubbled.parent = {868 order: 2,869 returnVal: false,870 };871 config.startShouldSetResponder.bubbled.grandParent = {872 order: 3,873 returnVal: false,874 };875 run(config, three, startConfig(three.parent, [three.parent], [0]));876 expect(ResponderEventPlugin._getResponder()).toBe(null);877 config = oneEventLoopTestConfig(three);878 // Now child wants to become responder. Negotiation should bubble as deep879 // as the target is because we don't find first common ancestor (with880 // current responder) because there is no current responder.881 // (Even if this is the second active touch).882 config.startShouldSetResponder.captured.grandParent = {883 order: 0,884 returnVal: false,885 };886 config.startShouldSetResponder.captured.parent = {887 order: 1,888 returnVal: false,889 };890 config.startShouldSetResponder.captured.child = {891 order: 2,892 returnVal: false,893 };894 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};895 config.responderGrant.child = {order: 4};896 config.responderStart.child = {order: 5};897 // / Two active touches \ /one of them new\898 run(899 config,900 three,901 startConfig(three.child, [three.parent, three.child], [1]),902 );903 expect(ResponderEventPlugin._getResponder()).toBe(904 getInstanceFromNode(three.child),905 );906 // Now we remove the original first touch, keeping the second touch that907 // started within the current responder (child). Nothing changes because908 // there's still touches that started inside of the current responder.909 config = oneEventLoopTestConfig(three);910 config.responderEnd.child = {order: 0};911 // / one ended\ /one remains \912 run(913 config,914 three,915 endConfig(three.child, [three.parent, three.child], [0]),916 );917 expect(ResponderEventPlugin._getResponder()).toBe(918 getInstanceFromNode(three.child),919 );920 // Okay, now let's add back that first touch (nothing should change) and921 // then we'll try peeling back the touches in the opposite order to make922 // sure that first removing the second touch instantly causes responder to923 // be released.924 config = oneEventLoopTestConfig(three);925 config.startShouldSetResponder.captured.grandParent = {926 order: 0,927 returnVal: false,928 };929 config.startShouldSetResponder.captured.parent = {930 order: 1,931 returnVal: false,932 };933 config.startShouldSetResponder.bubbled.parent = {934 order: 2,935 returnVal: false,936 };937 config.startShouldSetResponder.bubbled.grandParent = {938 order: 3,939 returnVal: false,940 };941 // Interesting: child still gets moves even though touch target is parent!942 // Current responder gets a `responderStart` for any touch while responder.943 config.responderStart.child = {order: 4};944 // / Two active touches \ /one of them new\945 run(946 config,947 three,948 startConfig(three.parent, [three.child, three.parent], [1]),949 );950 expect(ResponderEventPlugin._getResponder()).toBe(951 getInstanceFromNode(three.child),952 );953 // Now, move that new touch that had no effect, and did not start within954 // the current responder.955 config = oneEventLoopTestConfig(three);956 config.moveShouldSetResponder.captured.grandParent = {957 order: 0,958 returnVal: false,959 };960 config.moveShouldSetResponder.captured.parent = {961 order: 1,962 returnVal: false,963 };964 config.moveShouldSetResponder.bubbled.parent = {order: 2, returnVal: false};965 config.moveShouldSetResponder.bubbled.grandParent = {966 order: 3,967 returnVal: false,968 };969 // Interesting: child still gets moves even though touch target is parent!970 // Current responder gets a `responderMove` for any touch while responder.971 config.responderMove.child = {order: 4};972 // / Two active touches \ /one of them moved\973 run(974 config,975 three,976 moveConfig(three.parent, [three.child, three.parent], [1]),977 );978 expect(ResponderEventPlugin._getResponder()).toBe(979 getInstanceFromNode(three.child),980 );981 config = oneEventLoopTestConfig(three);982 config.responderEnd.child = {order: 0};983 config.responderRelease.child = {order: 1};984 // /child end \ /parent remain\985 run(986 config,987 three,988 endConfig(three.child, [three.child, three.parent], [0]),989 );990 expect(ResponderEventPlugin._getResponder()).toBe(null);991 });992 /**993 * If nothing is responder, then the negotiation should propagate directly to994 * the deepest target in the second touch.995 */996 it('should negotiate until first common ancestor when there are siblings', () => {997 // Initially nothing wants to become the responder998 let config = oneEventLoopTestConfig(siblings);999 config.startShouldSetResponder.captured.parent = {1000 order: 0,1001 returnVal: false,1002 };1003 config.startShouldSetResponder.captured.childOne = {1004 order: 1,1005 returnVal: false,1006 };1007 config.startShouldSetResponder.bubbled.childOne = {1008 order: 2,1009 returnVal: true,1010 };1011 config.responderGrant.childOne = {order: 3};1012 config.responderStart.childOne = {order: 4};1013 run(1014 config,1015 siblings,1016 startConfig(siblings.childOne, [siblings.childOne], [0]),1017 );1018 expect(ResponderEventPlugin._getResponder()).toBe(1019 getInstanceFromNode(siblings.childOne),1020 );1021 // If the touch target is the sibling item, the negotiation should only1022 // propagate to first common ancestor of current responder and sibling (so1023 // the parent).1024 config = oneEventLoopTestConfig(siblings);1025 config.startShouldSetResponder.captured.parent = {1026 order: 0,1027 returnVal: false,1028 };1029 config.startShouldSetResponder.bubbled.parent = {1030 order: 1,1031 returnVal: false,1032 };1033 config.responderStart.childOne = {order: 2};1034 const touchConfig = startConfig(1035 siblings.childTwo,1036 [siblings.childOne, siblings.childTwo],1037 [1],1038 );1039 run(config, siblings, touchConfig);1040 expect(ResponderEventPlugin._getResponder()).toBe(1041 getInstanceFromNode(siblings.childOne),1042 );1043 // move childOne1044 config = oneEventLoopTestConfig(siblings);1045 config.moveShouldSetResponder.captured.parent = {1046 order: 0,1047 returnVal: false,1048 };1049 config.moveShouldSetResponder.bubbled.parent = {order: 1, returnVal: false};1050 config.responderMove.childOne = {order: 2};1051 run(1052 config,1053 siblings,1054 moveConfig(1055 siblings.childOne,1056 [siblings.childOne, siblings.childTwo],1057 [0],1058 ),1059 );1060 expect(ResponderEventPlugin._getResponder()).toBe(1061 getInstanceFromNode(siblings.childOne),1062 );1063 // move childTwo: Only negotiates to `parent`.1064 config = oneEventLoopTestConfig(siblings);1065 config.moveShouldSetResponder.captured.parent = {1066 order: 0,1067 returnVal: false,1068 };1069 config.moveShouldSetResponder.bubbled.parent = {order: 1, returnVal: false};1070 config.responderMove.childOne = {order: 2};1071 run(1072 config,1073 siblings,1074 moveConfig(1075 siblings.childTwo,1076 [siblings.childOne, siblings.childTwo],1077 [1],1078 ),1079 );1080 expect(ResponderEventPlugin._getResponder()).toBe(1081 getInstanceFromNode(siblings.childOne),1082 );1083 });1084 it('should notify of being rejected. responderStart/Move happens on current responder', () => {1085 // Initially nothing wants to become the responder1086 let config = oneEventLoopTestConfig(three);1087 config.startShouldSetResponder.captured.grandParent = {1088 order: 0,1089 returnVal: false,1090 };1091 config.startShouldSetResponder.captured.parent = {1092 order: 1,1093 returnVal: false,1094 };1095 config.startShouldSetResponder.captured.child = {1096 order: 2,1097 returnVal: false,1098 };1099 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};1100 config.responderGrant.child = {order: 4};1101 config.responderStart.child = {order: 5};1102 run(config, three, startConfig(three.child, [three.child], [0]));1103 expect(ResponderEventPlugin._getResponder()).toBe(1104 getInstanceFromNode(three.child),1105 );1106 // Suppose parent wants to become responder on move, and is rejected1107 config = oneEventLoopTestConfig(three);1108 config.moveShouldSetResponder.captured.grandParent = {1109 order: 0,1110 returnVal: false,1111 };1112 config.moveShouldSetResponder.captured.parent = {1113 order: 1,1114 returnVal: false,1115 };1116 config.moveShouldSetResponder.bubbled.parent = {order: 2, returnVal: true};1117 config.responderGrant.parent = {order: 3};1118 config.responderTerminationRequest.child = {order: 4, returnVal: false};1119 config.responderReject.parent = {order: 5};1120 // The start/move should occur on the original responder if new one is rejected1121 config.responderMove.child = {order: 6};1122 let touchConfig = moveConfig(three.child, [three.child], [0]);1123 run(config, three, touchConfig);1124 expect(ResponderEventPlugin._getResponder()).toBe(1125 getInstanceFromNode(three.child),1126 );1127 config = oneEventLoopTestConfig(three);1128 config.startShouldSetResponder.captured.grandParent = {1129 order: 0,1130 returnVal: false,1131 };1132 config.startShouldSetResponder.captured.parent = {1133 order: 1,1134 returnVal: false,1135 };1136 config.startShouldSetResponder.bubbled.parent = {order: 2, returnVal: true};1137 config.responderGrant.parent = {order: 3};1138 config.responderTerminationRequest.child = {order: 4, returnVal: false};1139 config.responderReject.parent = {order: 5};1140 // The start/move should occur on the original responder if new one is rejected1141 config.responderStart.child = {order: 6};1142 touchConfig = startConfig(three.child, [three.child, three.child], [1]);1143 run(config, three, touchConfig);1144 expect(ResponderEventPlugin._getResponder()).toBe(1145 getInstanceFromNode(three.child),1146 );1147 });1148 it('should negotiate scroll', () => {1149 // Initially nothing wants to become the responder1150 let config = oneEventLoopTestConfig(three);1151 config.startShouldSetResponder.captured.grandParent = {1152 order: 0,1153 returnVal: false,1154 };1155 config.startShouldSetResponder.captured.parent = {1156 order: 1,1157 returnVal: false,1158 };1159 config.startShouldSetResponder.captured.child = {1160 order: 2,1161 returnVal: false,1162 };1163 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};1164 config.responderGrant.child = {order: 4};1165 config.responderStart.child = {order: 5};1166 run(config, three, startConfig(three.child, [three.child], [0]));1167 expect(ResponderEventPlugin._getResponder()).toBe(1168 getInstanceFromNode(three.child),1169 );1170 // If the touch target is the sibling item, the negotiation should only1171 // propagate to first common ancestor of current responder and sibling (so1172 // the parent).1173 config = oneEventLoopTestConfig(three);1174 config.scrollShouldSetResponder.captured.grandParent = {1175 order: 0,1176 returnVal: false,1177 };1178 config.scrollShouldSetResponder.captured.parent = {1179 order: 1,1180 returnVal: false,1181 };1182 config.scrollShouldSetResponder.bubbled.parent = {1183 order: 2,1184 returnVal: true,1185 };1186 config.responderGrant.parent = {order: 3};1187 config.responderTerminationRequest.child = {order: 4, returnVal: false};1188 config.responderReject.parent = {order: 5};1189 run(config, three, {1190 topLevelType: 'topScroll',1191 targetInst: getInstanceFromNode(three.parent),1192 nativeEvent: {},1193 });1194 expect(ResponderEventPlugin._getResponder()).toBe(1195 getInstanceFromNode(three.child),1196 );1197 // Now lets let the scroll take control this time.1198 config = oneEventLoopTestConfig(three);1199 config.scrollShouldSetResponder.captured.grandParent = {1200 order: 0,1201 returnVal: false,1202 };1203 config.scrollShouldSetResponder.captured.parent = {1204 order: 1,1205 returnVal: false,1206 };1207 config.scrollShouldSetResponder.bubbled.parent = {1208 order: 2,1209 returnVal: true,1210 };1211 config.responderGrant.parent = {order: 3};1212 config.responderTerminationRequest.child = {order: 4, returnVal: true};1213 config.responderTerminate.child = {order: 5};1214 run(config, three, {1215 topLevelType: 'topScroll',1216 targetInst: getInstanceFromNode(three.parent),1217 nativeEvent: {},1218 });1219 expect(ResponderEventPlugin._getResponder()).toBe(1220 getInstanceFromNode(three.parent),1221 );1222 });1223 it('should cancel correctly', () => {1224 // Initially our child becomes responder1225 let config = oneEventLoopTestConfig(three);1226 config.startShouldSetResponder.captured.grandParent = {1227 order: 0,1228 returnVal: false,1229 };1230 config.startShouldSetResponder.captured.parent = {1231 order: 1,1232 returnVal: false,1233 };1234 config.startShouldSetResponder.captured.child = {1235 order: 2,1236 returnVal: false,1237 };1238 config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};1239 config.responderGrant.child = {order: 4};1240 config.responderStart.child = {order: 5};1241 run(config, three, startConfig(three.child, [three.child], [0]));1242 expect(ResponderEventPlugin._getResponder()).toBe(1243 getInstanceFromNode(three.child),1244 );1245 config = oneEventLoopTestConfig(three);1246 config.responderEnd.child = {order: 0};1247 config.responderTerminate.child = {order: 1};1248 const nativeEvent = _touchConfig(1249 'topTouchCancel',1250 three.child,1251 [three.child],1252 [0],1253 );1254 run(config, three, nativeEvent);1255 expect(ResponderEventPlugin._getResponder()).toBe(null);1256 });1257 it('should determine the first common ancestor correctly', () => {1258 // This test was moved here from the ReactTreeTraversal test since only the1259 // ResponderEventPlugin uses `getLowestCommonAncestor`1260 const React = require('react');1261 const ReactTestUtils = require('react-dom/test-utils');1262 const ReactTreeTraversal = require('shared/ReactTreeTraversal');1263 const ReactDOMComponentTree = require('../../react-dom/src/client/ReactDOMComponentTree');1264 class ChildComponent extends React.Component {1265 render() {1266 return (1267 <div ref="DIV" id={this.props.id + '__DIV'}>1268 <div ref="DIV_1" id={this.props.id + '__DIV_1'} />1269 <div ref="DIV_2" id={this.props.id + '__DIV_2'} />1270 </div>1271 );1272 }1273 }1274 class ParentComponent extends React.Component {1275 render() {1276 return (1277 <div ref="P" id="P">1278 <div ref="P_P1" id="P_P1">1279 <ChildComponent ref="P_P1_C1" id="P_P1_C1" />1280 <ChildComponent ref="P_P1_C2" id="P_P1_C2" />1281 </div>1282 <div ref="P_OneOff" id="P_OneOff" />1283 </div>1284 );1285 }1286 }1287 const parent = ReactTestUtils.renderIntoDocument(<ParentComponent />);1288 const ancestors = [1289 // Common ancestor with self is self.1290 {1291 one: parent.refs.P_P1_C1.refs.DIV_1,1292 two: parent.refs.P_P1_C1.refs.DIV_1,1293 com: parent.refs.P_P1_C1.refs.DIV_1,1294 },1295 // Common ancestor with self is self - even if topmost DOM.1296 {one: parent.refs.P, two: parent.refs.P, com: parent.refs.P},1297 // Siblings1298 {1299 one: parent.refs.P_P1_C1.refs.DIV_1,1300 two: parent.refs.P_P1_C1.refs.DIV_2,1301 com: parent.refs.P_P1_C1.refs.DIV,1302 },1303 // Common ancestor with parent is the parent.1304 {1305 one: parent.refs.P_P1_C1.refs.DIV_1,1306 two: parent.refs.P_P1_C1.refs.DIV,1307 com: parent.refs.P_P1_C1.refs.DIV,1308 },1309 // Common ancestor with grandparent is the grandparent.1310 {1311 one: parent.refs.P_P1_C1.refs.DIV_1,1312 two: parent.refs.P_P1,1313 com: parent.refs.P_P1,1314 },1315 // Grandparent across subcomponent boundaries.1316 {1317 one: parent.refs.P_P1_C1.refs.DIV_1,1318 two: parent.refs.P_P1_C2.refs.DIV_1,1319 com: parent.refs.P_P1,1320 },1321 // Something deep with something one-off.1322 {1323 one: parent.refs.P_P1_C1.refs.DIV_1,1324 two: parent.refs.P_OneOff,1325 com: parent.refs.P,1326 },1327 ];1328 let i;1329 for (i = 0; i < ancestors.length; i++) {1330 const plan = ancestors[i];1331 const firstCommon = ReactTreeTraversal.getLowestCommonAncestor(1332 ReactDOMComponentTree.getInstanceFromNode(plan.one),1333 ReactDOMComponentTree.getInstanceFromNode(plan.two),1334 );1335 expect(firstCommon).toBe(1336 ReactDOMComponentTree.getInstanceFromNode(plan.com),1337 );1338 }1339 });...

Full Screen

Full Screen

SimpleChart.js

Source:SimpleChart.js Github

copy

Full Screen

1//Author: Monie Corleone2//Purpose: To draw line chart in canvas element3//The MIT License (MIT)4//Copyright (c) <2015> <Monie Corleone>5; (function ($, window, document, undefined) {6 var pluginName = "SimpleChart";7 var defaults = {8 ChartType: "Line", //Area, Scattered, Bar, Hybrid, Pie, Stacked, Stacked Hybrid9 xPadding: 60,10 yPadding: 50,11 topmargin: 25,12 rightmargin: 20,13 data: null,14 toolwidth: 300,15 toolheight: 300,16 axiscolor: "#333",17 font: "italic 10pt sans-serif",18 headerfontsize: "14px",19 axisfontsize: "12px",20 piefontsize: "13px",21 pielabelcolor: "#fff",22 pielabelpercentcolor: "#000",23 textAlign: "center",24 textcolor: "#E6E6E6",25 showlegends: true,26 showpielables: false,27 legendposition: 'bottom',28 legendsize: '100',29 xaxislabel: null,30 yaxislabel: null,31 title: null,32 LegendTitle: "Legend",33 pieborderColor: "#fff",34 pieborderWidth: 235 };36 function Plugin(element, options) {37 this.element = element;38 this.options = $.extend({}, defaults, options);39 this.init();40 }41 Plugin.prototype = {42 init: function () {43 var that = this,44 config = that.options;45 var graph = $(that.element).addClass("SimpleChart").addClass(config.ChartType).append("<canvas class='SimpleChartcanvas'></canvas>").find('canvas').css({46 float: (config.legendposition == 'right' || config.legendposition == 'left') ? 'left' : '',47 'margin-top': config.topmargin,48 'margin-right': config.rightmargin49 });50 var ctx = graph[0].getContext("2d");51 graph[0].width = $(that.element).width() - (config.showlegends ? ((config.legendposition == 'right' || config.legendposition == 'left') ? parseInt(config.legendsize) + parseInt(config.xPadding) : 0) : 0) - config.rightmargin;52 graph[0].height = $(that.element).height() - (config.showlegends ? ((config.legendposition == 'bottom' || config.legendposition == 'top') ? config.legendsize : 0) : 0) - config.topmargin;53 var c = graph[0].getContext('2d');54 switch (config.ChartType) {55 case "Line":56 that.drawAxis(c, graph);57 that.drawLineAreaScatteredHybridCharts(c, graph);58 break;59 case "Area":60 that.drawAxis(c, graph);61 that.drawLineAreaScatteredHybridCharts(c, graph);62 break;63 case "Scattered":64 that.drawAxis(c, graph);65 that.drawLineAreaScatteredHybridCharts(c, graph);66 break;67 case "Hybrid":68 that.drawAxis(c, graph);69 that.drawLineAreaScatteredHybridCharts(c, graph);70 that.drawBar(c, graph);71 that.drawHybrid(c, graph);72 break;73 case "Bar":74 that.drawAxis(c, graph);75 that.drawBar(c, graph);76 break;77 case "Pie":78 that.drawPie(c, graph);79 break;80 case "Stacked":81 that.drawAxis(c, graph);82 that.drawStacked(c, graph);83 break;84 case "StackedHybrid":85 that.drawAxis(c, graph);86 that.drawStacked(c, graph);87 that.drawLineAreaScatteredHybridCharts(c, graph);88 break;89 }90 //show legend91 if (config.showlegends) {92 that.drawLegends(graph);93 }94 },95 reload: function () {96 $(this.element).empty();97 this.init();98 },99 destroy: function () {100 $(this.element).empty();101 },102 FindYMax: function () {103 config = this.options;104 var max = 0;105 for (var i = 0; i < config.data.length; i++) {106 for (var j = 0; j < config.data[i].values.length; j++) {107 if (config.data[i].values[j].Y > max) {108 max = config.data[i].values[j].Y;109 }110 }111 }112 max += 10 - max % 10;113 return max;114 },115 pixelX: function (val, i) {116 config = this.options;117 var graph = $(this.element).find('.SimpleChartcanvas');118 return ((graph.width() - config.xPadding) / config.data[i].values.length) * val + (config.xPadding * 1.5);119 },120 pixelY: function (val) {121 config = this.options;122 var graph = $(this.element).find('.SimpleChartcanvas');123 return graph.height() - (((graph.height() - config.yPadding) / this.FindYMax()) * val) - config.yPadding;124 },125 getRandomColor: function () {126 var letters = '0123456789ABCDEF'.split('');127 var color = '#';128 for (var i = 0; i < 6; i++) {129 color += letters[Math.floor(Math.random() * 16)];130 }131 return color;132 },133 drawAxis: function (c, graph) {134 var that = this, xelementarray = new Array(),135 config = this.options;136 c.lineWidth = 2;137 c.strokeStyle = config.axiscolor;138 c.font = config.font;139 c.textAlign = config.textAlign;140 c.beginPath();141 c.moveTo(config.xPadding, 0);142 c.lineTo(config.xPadding, graph.height() - config.yPadding);143 c.lineTo(graph.width(), graph.height() - config.yPadding);144 c.stroke();145 c.fillStyle = config.textcolor;146 for (var i = 0; i < config.data.length; i++) {147 for (var j = 0; j < config.data[i].values.length; j++) {148 if (xelementarray.indexOf(config.data[i].values[j].X) < 0) {149 xelementarray.push(config.data[i].values[j].X);150 c.fillText(config.data[i].values[j].X, that.pixelX(j, i), graph.height() - config.yPadding + 20);151 }152 }153 }154 c.save();155 var fontArgs = c.font.split(' ');156 c.font = config.axisfontsize + ' ' + fontArgs[fontArgs.length - 1];157 if (config.xaxislabel) {158 c.fillText(config.xaxislabel, graph.width() / 2, graph.height());159 }160 if (config.yaxislabel) {161 c.save();162 c.translate(0, graph.height() / 2);163 c.rotate(-Math.PI / 2);164 c.fillText(config.yaxislabel, 0, 15);165 c.restore();166 }167 if (config.title) {168 $("<div class='simple-chart-Header' />").appendTo($(that.element)).html(config.title).css({169 left: graph.width() / 2 - ($(that.element).find('.simple-chart-Header').width() / 2),170 top: 5171 });172 }173 c.restore();174 c.textAlign = "right"175 c.textBaseline = "middle";176 var maxY = that.FindYMax();177 var incrementvalue = "";178 for (var i = 0 ; i < Math.ceil(maxY).toString().length - 1; i++) {179 incrementvalue += "0";180 }181 incrementvalue = "1" + incrementvalue;182 incrementvalue = Math.ceil(maxY / parseInt(incrementvalue)) * Math.pow(10, (Math.ceil(maxY / 10).toString().length - 1));183 for (var i = 0; i < that.FindYMax() ; i += parseInt(incrementvalue)) {184 c.fillStyle = config.textcolor;185 c.fillText(i, config.xPadding - 10, that.pixelY(i));186 c.fillStyle = config.axiscolor;187 c.beginPath();188 c.arc(config.xPadding, that.pixelY(i), 6, 0, Math.PI * 2, true);189 c.fill();190 }191 },192 drawPie: function (c, graph) {193 var that = this,194 config = this.options;195 c.clearRect(0, 0, graph.width(), graph.height());196 var totalVal = 0, lastend = 0;197 for (var j = 0; j < config.data[0].values.length; j++) {198 totalVal += (typeof config.data[0].values[j].Y == 'number') ? config.data[0].values[j].Y : 0;199 }200 for (var i = 0; i < config.data[0].values.length; i++) {201 c.fillStyle = config.data[0].linecolor == "Random" ? config.data[0].values[i].color = randomcolor = that.getRandomColor() : config.data[0].linecolor;202 c.beginPath();203 var centerx = graph.width() / 2.2;204 var centery = graph.height() / 2.2;205 c.moveTo(centerx, centery);206 c.arc(centerx, centery, (config.legendposition == 'right' || config.legendposition == 'left') ? centerx : centery, lastend, lastend +207 (Math.PI * 2 * (config.data[0].values[i].Y / totalVal)), false);208 c.lineTo(centerx, centery);209 c.fill();210 c.fillStyle = config.pielabelcolor;211 c.lineWidth = config.pieborderWidth;212 c.strokeStyle = config.pieborderColor;213 c.stroke();214 if (config.showpielables) {215 c.save();216 c.translate(centerx, centery);217 c.rotate(lastend - 0.20 +218 (Math.PI * 2 * (config.data[0].values[i].Y / totalVal)));219 var dx = Math.floor(centerx * 0.5) + 40;220 var dy = Math.floor(centery * 0.05);221 c.textAlign = "right";222 var fontArgs = c.font.split(' ');223 c.font = config.piefontsize + ' ' + fontArgs[fontArgs.length - 1];224 c.fillText(config.data[0].values[i].X, dx, dy);225 c.restore();226 c.save();227 c.fillStyle = config.pielabelpercentcolor;228 c.translate(centerx, centery);229 c.rotate(lastend - 0.15 +230 (Math.PI * 2 * (config.data[0].values[i].Y / totalVal)));231 var dx = Math.floor(centerx * 0.5) + 90;232 var dy = Math.floor(centery * 0.05);233 c.textAlign = "right";234 var fontArgs = c.font.split(' ');235 c.font = config.piefontsize + ' ' + fontArgs[fontArgs.length - 1];236 c.fillText(Math.round((config.data[0].values[i].Y / totalVal) * 100) + "%", dx, dy);237 c.restore();238 }239 lastend += Math.PI * 2 * (config.data[0].values[i].Y / totalVal);240 }241 var canvasOffset = $(graph).offset();242 var offsetX = canvasOffset.left;243 var offsetY = canvasOffset.top;244 },245 drawBar: function (c, graph) {246 var that = this,247 config = this.options;248 for (var i = 0; i < config.data[0].values.length; i++) {249 var randomcolor;250 c.strokeStyle = config.data[0].linecolor == "Random" ? config.data[0].values[i].color = randomcolor = that.getRandomColor() : config.data[0].linecolor;251 c.fillStyle = config.data[0].linecolor == "Random" ? randomcolor : config.data[0].linecolor;252 c.beginPath();253 c.rect(that.pixelX(i, 0) - config.yPadding / 4, that.pixelY(config.data[0].values[i].Y), config.yPadding / 2, graph.height() - that.pixelY(config.data[0].values[i].Y) - config.xPadding + 8);254 c.closePath();255 c.stroke();256 c.fill();257 c.textAlign = "left";258 c.fillStyle = "#000";259 c.fillText(config.data[0].values[i].Y, that.pixelX(i, 0) - config.yPadding / 4, that.pixelY(config.data[0].values[i].Y) + 7, 200);260 }261 },262 drawStacked: function (c, graph) {263 var that = this,264 config = this.options;265 for (var i = 0; i < config.data.length; i++) {266 for (var j = 0; j < config.data[i].values.length; j++) {267 var randomcolor;268 c.strokeStyle = config.data[i].linecolor == "Random" ? config.data[i].values[j].color = randomcolor = that.getRandomColor() : config.data[i].linecolor;269 c.fillStyle = config.data[i].linecolor == "Random" ? randomcolor : config.data[i].linecolor;270 c.beginPath();271 c.rect(that.pixelX(j, 0) - config.yPadding / 4, that.pixelY(config.data[i].values[j].Y), config.yPadding / 2, graph.height() - that.pixelY(config.data[i].values[j].Y) - config.xPadding + 8);272 c.closePath();273 c.stroke();274 c.fill();275 c.textAlign = "left";276 c.fillStyle = "#000";277 c.fillText(config.data[i].values[j].Y, that.pixelX(j, 0) - config.yPadding / 4, that.pixelY(config.data[i].values[j].Y) + 7, 200);278 }279 }280 },281 drawHybrid: function (c, graph) {282 var that = this,283 config = this.options;284 var randomcolor;285 c.strokeStyle = config.data[0].linecolor == "Random" ? randomcolor = that.getRandomColor() : config.data[0].linecolor;286 c.beginPath();287 c.moveTo(that.pixelX(0, 0), that.pixelY(config.data[0].values[0].Y));288 for (var j = 1; j < config.data[0].values.length; j++) {289 c.lineTo(that.pixelX(j, 0), that.pixelY(config.data[0].values[j].Y));290 }291 c.stroke();292 c.fillStyle = config.data[0].linecolor == "Random" ? randomcolor : config.data[0].linecolor;293 for (var j = 0; j < config.data[0].values.length; j++) {294 c.beginPath();295 c.arc(that.pixelX(j, 0), that.pixelY(config.data[0].values[j].Y), 4, 0, Math.PI * 2, true);296 c.fill();297 }298 },299 drawLineAreaScatteredHybridCharts: function (c, graph) {300 var that = this,301 config = this.options;302 var tipCanvas = $(that.element).append("<canvas id='tip'></canvas><div class='down-triangle'></div>").find("#tip").attr('width', config.toolwidth).attr('height', config.toolheight);303 var tipCtx = tipCanvas[0].getContext("2d");304 var highlighter = $(that.element).append("<canvas id='highlighter'></canvas>").find('#highlighter').attr('width', "18").attr('height', "18");305 var higlightctx = highlighter[0].getContext("2d");306 var tipbaloontip = $(that.element).find('.down-triangle');307 var canvasOffset = $(graph).offset();308 var offsetX = canvasOffset.left;309 var offsetY = canvasOffset.top;310 $(graph[0]).on("mousemove", function (e) {311 drawToolTiponHover(e);312 });313 for (var i = 0; i < config.data.length; i++) {314 c.strokeStyle = config.data[i].linecolor == "Random" ? config.data[i].Randomlinecolor = that.getRandomColor() : config.data[i].linecolor;315 c.beginPath();316 c.moveTo(that.pixelX(0, i), that.pixelY(config.data[i].values[0].Y));317 if (config.ChartType !== "Scattered" && config.ChartType !== "Hybrid") {318 for (var j = 1; j < config.data[i].values.length; j++) {319 c.lineTo(that.pixelX(j, i), that.pixelY(config.data[i].values[j].Y));320 }321 c.stroke();322 }323 c.fillStyle = config.data[i].linecolor == "Random" ? config.data[i].Randomlinecolor : config.data[i].linecolor;324 if (config.ChartType == "Area") {325 c.lineTo(that.pixelX(config.data[i].values.length - 1, i), that.pixelY(0));326 c.lineTo(that.pixelX(0, 0), that.pixelY(0));327 c.stroke();328 c.fill();329 }330 if (config.ChartType == "Line" || config.ChartType == "Scattered" || config.ChartType == "StackedHybrid") {331 for (var j = 0; j < config.data[i].values.length; j++) {332 c.beginPath();333 c.arc(that.pixelX(j, i), that.pixelY(config.data[i].values[j].Y), 4, 0, Math.PI * 2, true);334 c.fill();335 }336 }337 }338 var linepoints = [];339 for (var i = 0; i < config.data.length; i++) {340 for (var j = 0; j < config.data[i].values.length; j++) {341 linepoints.push({342 x: that.pixelX(j, i),343 y: that.pixelY(config.data[i].values[j].Y),344 r: 4,345 rXr: 16,346 tip: config.data[i].values[j].Y,347 color: config.data[i].linecolor == "Random" ? config.data[i].Randomlinecolor : config.data[i].linecolor348 });349 }350 }351 function drawToolTiponHover(e) {352 mouseX = parseInt(e.pageX - offsetX);353 mouseY = parseInt(e.pageY - offsetY);354 var hit = false;355 for (var i = 0; i < linepoints.length; i++) {356 var dot = linepoints[i];357 var dx = mouseX - dot.x;358 var dy = mouseY - dot.y;359 if (dx * dx + dy * dy < dot.rXr) {360 tipCanvas[0].style.left = (dot.x - (tipCanvas[0].width / 2)) - 3 + "px";361 tipCanvas[0].style.top = (dot.y - 21 - tipCanvas[0].height) + config.topmargin + "px";362 tipCtx.clearRect(0, 0, tipCanvas[0].width, tipCanvas[0].height);363 tipCtx.fillText(dot.tip, 5, 15);364 tipbaloontip[0].style.left = (dot.x) - 7 + "px";365 tipbaloontip[0].style.top = (dot.y + config.topmargin) - 19 + "px";366 if (config.ChartType == "Line" || config.ChartType == "Scattered" || config.ChartType == "Hybrid" || config.ChartType == "StackedHybrid") {367 highlighter[0].style.left = (dot.x) - 9 + "px";368 highlighter[0].style.top = (dot.y + config.topmargin) - 9 + "px";369 }370 higlightctx.clearRect(0, 0, highlighter.width(), highlighter.height());371 higlightctx.strokeStyle = dot.color;372 higlightctx.beginPath();373 higlightctx.arc(9, 9, 7, 0, 2 * Math.PI);374 higlightctx.lineWidth = 2;375 higlightctx.stroke();376 hit = true;377 }378 }379 if (!hit) {380 tipCanvas[0].style.left = "-400px";381 highlighter[0].style.left = "-400px";382 tipbaloontip[0].style.left = "-400px";383 }384 }385 },386 drawLegends: function (graph) {387 var that = this,388 config = this.options;389 if (config.ChartType == "Line" || config.ChartType == "Area" || config.ChartType == "Scattered" || config.ChartType == "Stacked" || config.ChartType == "StackedHybrid") {390 var _legends = $("<div class='simple-chart-legends' />", { id: "legendsdiv" }).css({391 width: (config.legendposition == 'right' || config.legendposition == 'left') ? (config.legendsize - 5) : graph.width(),392 height: (config.legendposition == 'top' || config.legendposition == 'bottom') ? (config.legendsize - 5) : graph.height(),393 float: (config.legendposition == 'right' || config.legendposition == 'left') ? 'left' : ''394 }).appendTo($(that.element));395 var _ul = $(_legends).append("<span>" + config.LegendTitle + "</span>").append("<ul />").find("ul")396 for (var i = 0; i < config.data.length; i++) {397 $("<li />", { class: "legendsli" }).append("<span />").find('span').addClass("legendindicator").append('<span class="line" style="background: ' + (config.data[i].linecolor == "Random" ? config.data[i].Randomlinecolor : config.data[i].linecolor) + '"></span><span class="circle" style="background: ' + (config.data[i].linecolor == "Random" ? config.data[i].Randomlinecolor : config.data[i].linecolor) + '"></span>').parent().append("<span>" + config.data[i].title + "</span>").appendTo(_ul);398 }399 if (config.legendposition == 'top' || config.legendposition == 'left') {400 $(_legends).insertBefore($(that.element).find('.SimpleChartcanvas'));401 }402 if (config.legendposition == 'right' || config.legendposition == 'left') {403 $(_legends).addClass('vertical')404 }405 else {406 $(_legends).addClass('horizontal');407 }408 }409 if (config.ChartType == "Bar" || config.ChartType == "Hybrid" || config.ChartType == "Pie") {410 var _legends = $("<div class='simple-chart-legends' />", { id: "legendsdiv" }).css({411 width: (config.legendposition == 'right' || config.legendposition == 'left') ? (config.legendsize - 5) : graph.width(),412 height: (config.legendposition == 'top' || config.legendposition == 'bottom') ? (config.legendsize - 5) : graph.height(),413 float: (config.legendposition == 'right' || config.legendposition == 'left') ? 'left' : ''414 }).appendTo($(that.element));415 var _ul = $(_legends).append("<span>" + config.LegendTitle + "</span>").append("<ul />").find("ul")416 for (var i = 0; i < config.data[0].values.length; i++) {417 $("<li />", { class: "legendsli" }).append("<span />").find('span').addClass("legendindicator").append('<span class="line" style="background: ' + (config.data[0].linecolor == "Random" ? config.data[0].values[i].color : config.data[0].linecolor) + '"></span><span class="circle" style="background: ' + (config.data[0].linecolor == "Random" ? config.data[0].values[i].color : config.data[0].linecolor) + '"></span>').parent().append("<span>" + config.data[0].values[i].X + "</span><span class='legendvalue'>" + (config.ChartType == 'Pie' ? config.data[0].values[i].Y : '') + "</span>").appendTo(_ul);418 }419 if (config.legendposition == 'top' || config.legendposition == 'left') {420 $(_legends).insertBefore($(that.element).find('.SimpleChartcanvas'));421 }422 if (config.legendposition == 'right' || config.legendposition == 'left') {423 $(_legends).addClass('vertical')424 }425 else {426 $(_legends).addClass('horizontal');427 }428 }429 }430 }431 $.fn[pluginName] = function (options) {432 if (typeof options === "string") {433 var args = Array.prototype.slice.call(arguments, 1);434 this.each(function () {435 var plugin = $.data(this, 'plugin_' + pluginName);436 if (plugin[options]) {437 plugin[options].apply(plugin, args);438 } else {439 plugin['options'][options] = args[0];440 }441 });442 } else {443 return this.each(function () {444 if (!$.data(this, 'plugin_' + pluginName)) {445 $.data(this, 'plugin_' + pluginName, new Plugin(this, options));446 }447 });448 }449 }...

Full Screen

Full Screen

UI.js

Source:UI.js Github

copy

Full Screen

1/** global: Craft */2/** global: Garnish */3Craft.ui =4 {5 createTextInput: function(config) {6 var $input = $('<input/>', {7 attr: {8 'class': 'text',9 type: (config.type || 'text'),10 id: config.id,11 size: config.size,12 name: config.name,13 value: config.value,14 maxlength: config.maxlength,15 autofocus: this.getAutofocusValue(config.autofocus),16 autocomplete: (typeof config.autocomplete === 'undefined' || !config.autocomplete ? 'off' : null),17 disabled: this.getDisabledValue(config.disabled),18 readonly: config.readonly,19 title: config.title,20 placeholder: config.placeholder21 }22 });23 if (config.class) {24 $input.addClass(config.class);25 }26 if (config.placeholder) {27 $input.addClass('nicetext');28 }29 if (config.type === 'password') {30 $input.addClass('password');31 }32 if (config.disabled) {33 $input.addClass('disabled');34 }35 if (!config.size) {36 $input.addClass('fullwidth');37 }38 if (config.showCharsLeft && config.maxlength) {39 $input40 .attr('data-show-chars-left')41 .css('padding-' + (Craft.orientation === 'ltr' ? 'right' : 'left'), (7.2 * config.maxlength.toString().length + 14) + 'px');42 }43 if (config.placeholder || config.showCharsLeft) {44 new Garnish.NiceText($input);45 }46 if (config.type === 'password') {47 return $('<div class="passwordwrapper"/>').append($input);48 }49 else {50 return $input;51 }52 },53 createTextField: function(config) {54 return this.createField(this.createTextInput(config), config);55 },56 createTextarea: function(config) {57 var $textarea = $('<textarea/>', {58 'class': 'text',59 'rows': config.rows || 2,60 'cols': config.cols || 50,61 'id': config.id,62 'name': config.name,63 'maxlength': config.maxlength,64 'autofocus': config.autofocus && !Garnish.isMobileBrowser(true),65 'disabled': !!config.disabled,66 'placeholder': config.placeholder,67 'html': config.value68 });69 if (config.showCharsLeft) {70 $textarea.attr('data-show-chars-left', '');71 }72 if (config.class) {73 $textarea.addClass(config.class);74 }75 if (!config.size) {76 $textarea.addClass('fullwidth');77 }78 return $textarea;79 },80 createTextareaField: function(config) {81 return this.createField(this.createTextarea(config), config);82 },83 createSelect: function(config) {84 var $container = $('<div/>', {85 'class': 'select'86 });87 if (config.class) {88 $container.addClass(config.class);89 }90 var $select = $('<select/>', {91 'id': config.id,92 'name': config.name,93 'autofocus': config.autofocus && Garnish.isMobileBrowser(true),94 'disabled': config.disabled,95 'data-target-prefix': config.targetPrefix96 }).appendTo($container);97 var $optgroup = null;98 for (var key in config.options) {99 if (!config.options.hasOwnProperty(key)) {100 continue;101 }102 var option = config.options[key];103 // Starting a new <optgroup>?104 if (typeof option.optgroup !== 'undefined') {105 $optgroup = $('<optgroup/>', {106 'label': option.label107 }).appendTo($select);108 } else {109 var optionLabel = (typeof option.label !== 'undefined' ? option.label : option),110 optionValue = (typeof option.value !== 'undefined' ? option.value : key),111 optionDisabled = (typeof option.disabled !== 'undefined' ? option.disabled : false);112 $('<option/>', {113 'value': optionValue,114 'selected': (optionValue == config.value),115 'disabled': optionDisabled,116 'html': optionLabel117 }).appendTo($optgroup || $select);118 }119 }120 if (config.toggle) {121 $select.addClass('fieldtoggle');122 new Craft.FieldToggle($select);123 }124 return $container;125 },126 createSelectField: function(config) {127 return this.createField(this.createSelect(config), config);128 },129 createCheckbox: function(config) {130 var id = (config.id || 'checkbox' + Math.floor(Math.random() * 1000000000));131 var $input = $('<input/>', {132 type: 'checkbox',133 value: (typeof config.value !== 'undefined' ? config.value : '1'),134 id: id,135 'class': 'checkbox',136 name: config.name,137 checked: (config.checked ? 'checked' : null),138 autofocus: this.getAutofocusValue(config.autofocus),139 disabled: this.getDisabledValue(config.disabled),140 'data-target': config.toggle,141 'data-reverse-target': config.reverseToggle142 });143 if (config.class) {144 $input.addClass(config.class);145 }146 if (config.toggle || config.reverseToggle) {147 $input.addClass('fieldtoggle');148 new Craft.FieldToggle($input);149 }150 var $label = $('<label/>', {151 'for': id,152 html: config.label153 });154 // Should we include a hidden input first?155 if (config.name && (config.name.length < 3 || config.name.substr(-2) !== '[]')) {156 return $([157 $('<input/>', {158 type: 'hidden',159 name: config.name,160 value: ''161 })[0],162 $input[0],163 $label[0]164 ]);165 }166 else {167 return $([168 $input[0],169 $label[0]170 ]);171 }172 },173 createCheckboxField: function(config) {174 var $field = $('<div class="field checkboxfield"/>', {175 id: (config.id ? config.id + '-field' : null)176 });177 if (config.first) {178 $field.addClass('first');179 }180 if (config.instructions) {181 $field.addClass('has-instructions');182 }183 this.createCheckbox(config).appendTo($field);184 if (config.instructions) {185 $('<div class="instructions"/>').text(config.instructions).appendTo($field);186 }187 return $field;188 },189 createCheckboxSelect: function(config) {190 var $container = $('<div class="checkbox-select"/>');191 if (config.class) {192 $container.addClass(config.class);193 }194 var allValue, allChecked;195 if (config.showAllOption) {196 allValue = (config.allValue || '*');197 allChecked = (config.values == allValue);198 // Create the "All" checkbox199 $('<div/>').appendTo($container).append(200 this.createCheckbox({201 id: config.id,202 'class': 'all',203 label: '<b>' + (config.allLabel || Craft.t('app', 'All')) + '</b>',204 name: config.name,205 value: allValue,206 checked: allChecked,207 autofocus: config.autofocus208 })209 );210 } else {211 allChecked = false;212 }213 // Create the actual options214 for (var i = 0; i < config.options.length; i++) {215 var option = config.options[i];216 if (option.value == allValue) {217 continue;218 }219 $('<div/>').appendTo($container).append(220 this.createCheckbox({221 label: option.label,222 name: (config.name ? config.name + '[]' : null),223 value: option.value,224 checked: (allChecked || Craft.inArray(option.value, config.values)),225 disabled: allChecked226 })227 );228 }229 new Garnish.CheckboxSelect($container);230 return $container;231 },232 createCheckboxSelectField: function(config) {233 return this.createField(this.createCheckboxSelect(config), config);234 },235 createLightswitch: function(config) {236 var value = config.value || '1';237 var $container = $('<div/>', {238 'class': 'lightswitch',239 tabindex: '0',240 'data-value': value,241 id: config.id,242 'aria-labelledby': config.labelId,243 'data-target': config.toggle,244 'data-reverse-target': config.reverseToggle245 });246 if (config.on) {247 $container.addClass('on');248 }249 if (config.small) {250 $container.addClass('small');251 }252 if (config.disabled) {253 $container.addClass('disabled');254 }255 $(256 '<div class="lightswitch-container">' +257 '<div class="label on"></div>' +258 '<div class="handle"></div>' +259 '<div class="label off"></div>' +260 '</div>'261 ).appendTo($container);262 if (config.name) {263 $('<input/>', {264 type: 'hidden',265 name: config.name,266 value: (config.on ? value : ''),267 disabled: config.disabled268 }).appendTo($container);269 }270 if (config.toggle || config.reverseToggle) {271 $container.addClass('fieldtoggle');272 new Craft.FieldToggle($container);273 }274 return $container.lightswitch();275 },276 createLightswitchField: function(config) {277 return this.createField(this.createLightswitch(config), config);278 },279 createColorInput: function(config) {280 var id = (config.id || 'color' + Math.floor(Math.random() * 1000000000));281 var containerId = config.containerId || id + '-container';282 var name = config.name || null;283 var value = config.value || null;284 var small = config.small || false;285 var autofocus = config.autofocus && Garnish.isMobileBrowser(true);286 var disabled = config.disabled || false;287 var $container = $('<div/>', {288 id: containerId,289 'class': 'flex color-container'290 });291 var $colorPreviewContainer = $('<div/>', {292 'class': 'color static' + (small ? ' small' : '')293 }).appendTo($container);294 var $colorPreview = $('<div/>', {295 'class': 'color-preview',296 style: config.value ? {backgroundColor: config.value} : null297 }).appendTo($colorPreviewContainer);298 var $input = this.createTextInput({299 id: id,300 name: name,301 value: value,302 size: 10,303 'class': 'color-input',304 autofocus: autofocus,305 disabled: disabled306 }).appendTo($container);307 new Craft.ColorInput($container);308 return $container;309 },310 createColorField: function(config) {311 return this.createField(this.createColorInput(config), config);312 },313 createDateInput: function(config) {314 var id = (config.id || 'date' + Math.floor(Math.random() * 1000000000))+'-date';315 var name = config.name || null;316 var inputName = name ? name+'[date]' : null;317 var value = config.value && typeof config.value.getMonth === 'function' ? config.value : null;318 var formattedValue = value ? Craft.formatDate(value) : null;319 var autofocus = config.autofocus && Garnish.isMobileBrowser(true);320 var disabled = config.disabled || false;321 var $container = $('<div/>', {322 'class': 'datewrapper'323 });324 var $input = this.createTextInput({325 id: id,326 name: inputName,327 value: formattedValue,328 placeholder: ' ',329 autocomplete: false,330 autofocus: autofocus,331 disabled: disabled332 }).appendTo($container);333 $('<div data-icon="date"></div>').appendTo($container);334 if (name) {335 $('<input/>', {336 type: 'hidden',337 name: name+'[timezone]',338 val: Craft.timezone339 }).appendTo($container);340 }341 $input.datepicker($.extend({342 defaultDate: value || new Date()343 }, Craft.datepickerOptions));344 return $container;345 },346 createDateField: function(config) {347 return this.createField(this.createDateInput(config), config);348 },349 createTimeInput: function(config) {350 var id = (config.id || 'time' + Math.floor(Math.random() * 1000000000))+'-time';351 var name = config.name || null;352 var inputName = name ? name+'[time]' : null;353 var value = config.value && typeof config.value.getMonth === 'function' ? config.value : null;354 var autofocus = config.autofocus && Garnish.isMobileBrowser(true);355 var disabled = config.disabled || false;356 var $container = $('<div/>', {357 'class': 'timewrapper'358 });359 var $input = this.createTextInput({360 id: id,361 name: inputName,362 placeholder: ' ',363 autocomplete: false,364 autofocus: autofocus,365 disabled: disabled366 }).appendTo($container);367 $('<div data-icon="time"></div>').appendTo($container);368 if (name) {369 $('<input/>', {370 type: 'hidden',371 name: name+'[timezone]',372 val: Craft.timezone373 }).appendTo($container);374 }375 $input.timepicker(Craft.timepickerOptions);376 if (value) {377 $input.timepicker('setTime', value.getHours()*3600 + value.getMinutes()*60 + value.getSeconds());378 }379 return $container;380 },381 createTimeField: function(config) {382 return this.createField(this.createTimeInput(config), config);383 },384 createField: function(input, config) {385 var label = (config.label && config.label !== '__blank__' ? config.label : null),386 siteId = (Craft.isMultiSite && config.siteId ? config.siteId : null);387 var $field = $('<div/>', {388 'class': 'field',389 'id': config.fieldId || (config.id ? config.id + '-field' : null)390 });391 if (config.first) {392 $field.addClass('first');393 }394 if (label || config.instructions) {395 var $heading = $('<div class="heading"/>').appendTo($field);396 if (label) {397 var $label = $('<label/>', {398 'id': config.labelId || (config.id ? config.id + '-label' : null),399 'class': (config.required ? 'required' : null),400 'for': config.id,401 text: label402 }).appendTo($heading);403 if (siteId) {404 for (var i = 0; i < Craft.sites.length; i++) {405 if (Craft.sites[i].id == siteId) {406 $('<span class="site"/>').text(Craft.sites[i].name).appendTo($label);407 break;408 }409 }410 }411 }412 if (config.instructions) {413 $('<div class="instructions"/>').text(config.instructions).appendTo($heading);414 }415 }416 $('<div class="input"/>').append(input).appendTo($field);417 if (config.warning) {418 $('<p class="warning"/>').text(config.warning).appendTo($field);419 }420 if (config.errors) {421 this.addErrorsToField($field, config.errors);422 }423 return $field;424 },425 createErrorList: function(errors) {426 var $list = $('<ul class="errors"/>');427 if (errors) {428 this.addErrorsToList($list, errors);429 }430 return $list;431 },432 addErrorsToList: function($list, errors) {433 for (var i = 0; i < errors.length; i++) {434 $('<li/>').text(errors[i]).appendTo($list);435 }436 },437 addErrorsToField: function($field, errors) {438 if (!errors) {439 return;440 }441 $field.addClass('has-errors');442 $field.children('.input').addClass('errors');443 var $errors = $field.children('ul.errors');444 if (!$errors.length) {445 $errors = this.createErrorList().appendTo($field);446 }447 this.addErrorsToList($errors, errors);448 },449 clearErrorsFromField: function($field) {450 $field.removeClass('has-errors');451 $field.children('.input').removeClass('errors');452 $field.children('ul.errors').remove();453 },454 getAutofocusValue: function(autofocus) {455 return (autofocus && !Garnish.isMobileBrowser(true) ? 'autofocus' : null);456 },457 getDisabledValue: function(disabled) {458 return (disabled ? 'disabled' : null);459 }...

Full Screen

Full Screen

config-min.js

Source:config-min.js Github

copy

Full Screen

1if(!ORYX){var ORYX={}2}if(!ORYX.CONFIG){ORYX.CONFIG={}3}ORYX.CONFIG.WEB_URL="org.jbpm.designer.jBPMDesigner";4ORYX.CONFIG.MENU_INDEX={File:1,Edit:2,Undo:3,localstorage:4,"Z-Order":5,Alignment:6,Grouping:7,lockunlockgroup:8,Docker:9,colorpickergroup:"AAA",editprocessforms:"BBB",sharegroup:"CCC",importgroup:"DDD",validationandsimulation:"EEE",servicerepogroup:"FFF",paintgroup:"GGG",fullscreengroup:"HHH",Help:"ZZZZZZ"};5ORYX.CONFIG.UUID_URL=function(b,a){if(b===undefined){b=ORYX.UUID6}if(a===undefined){a=ORYX.PROFILE7}if(ORYX.PATH===undefined){ORYX.PATH="designer/"8}return ORYX.PATH+"uuidRepository?uuid="+Base64.encode(encodeURI(b))+"&profile="+a+"&pp="+ORYX.PREPROCESSING+"&ts="+new Date().getTime()9};10ORYX.FULL_PERSPECTIVE="http://b3mn.org/stencilset/bpmn2.0#";11ORYX.SIMPLE_PERSPECTIVE="http://b3mn.org/stencilset/bpmn2.0simple#";12ORYX.RULEFLOW_PERSPECTIVE="http://b3mn.org/stencilset/bpmn2.0ruleflow#";13ORYX.CURRENT_PERSPECTIVE;14ORYX.CALCULATE_CURRENT_PERSPECTIVE=function(){if(!ORYX.CURRENT_PERSPECTIVE){var a=document.cookie.split(";");15for(var b=0;16b<a.length&&!ORYX.CURRENT_PERSPECTIVE;17b++){var d=a[b];18while(d.charAt(0)==" "){d=d.substring(1,d.length)19}if(d.indexOf("designerperspective=")==0){ORYX.CURRENT_PERSPECTIVE=d.substring("designerperspective=".length,d.length)20}}if(!ORYX.CURRENT_PERSPECTIVE){ORYX.CURRENT_PERSPECTIVE=ORYX.FULL_PERSPECTIVE21}}return ORYX.CURRENT_PERSPECTIVE22};23ORYX.CONFIG.TRANSFORMER_URL=function(b,a){if(b===undefined){b=ORYX.UUID24}if(a===undefined){a=ORYX.PROFILE25}return ORYX.PATH+"transformer?uuid="+window.btoa(encodeURI(b))+"&profile="+a26};27ORYX.CONFIG.TASKFORMS_URL=function(b,a){if(b===undefined){b=ORYX.UUID28}if(a===undefined){a=ORYX.PROFILE29}return ORYX.PATH+"taskforms?uuid="+window.btoa(encodeURI(b))+"&profile="+a30};31ORYX.CONFIG.UUID_AUTOSAVE_INTERVAL=120000;32ORYX.CONFIG.UUID_AUTOSAVE_DEFAULT=false;33ORYX.CONFIG.VERSION_URL=ORYX.CONFIG.ROOT_PATH+"VERSION";34ORYX.CONFIG.LICENSE_URL=ORYX.CONFIG.ROOT_PATH+"LICENSE";35ORYX.CONFIG.SERVER_HANDLER_ROOT="";36ORYX.CONFIG.STENCILSET_HANDLER=ORYX.CONFIG.SERVER_HANDLER_ROOT+"";37ORYX.CONFIG.MODE_READONLY="readonly";38ORYX.CONFIG.MODE_FULLSCREEN="fullscreen";39ORYX.CONFIG.SHOW_GRIDLINE=true;40ORYX.CONFIG.DISABLE_GRADIENT=false;41ORYX.CONFIG.PLUGINS_ENABLED=true;42ORYX.CONFIG.PLUGINS_CONFIG=ORYX.CONFIG.ROOT_PATH+"plugins";43ORYX.CONFIG.PROFILE_PATH=ORYX.CONFIG.ROOT_PATH+"profiles/";44ORYX.CONFIG.PLUGINS_FOLDER="Plugins/";45ORYX.CONFIG.PDF_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"pdf";46ORYX.CONFIG.PNML_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"pnml";47ORYX.CONFIG.SIMPLE_PNML_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"simplepnmlexporter";48ORYX.CONFIG.DESYNCHRONIZABILITY_URL=ORYX.CONFIG.ROOT_PATH+"desynchronizability";49ORYX.CONFIG.IBPMN2BPMN_URL=ORYX.CONFIG.ROOT_PATH+"ibpmn2bpmn";50ORYX.CONFIG.BPMN2YAWL_URL=ORYX.CONFIG.ROOT_PATH+"bpmn2yawl";51ORYX.CONFIG.QUERYEVAL_URL=ORYX.CONFIG.ROOT_PATH+"query";52ORYX.CONFIG.SYNTAXCHECKER_URL=ORYX.CONFIG.ROOT_PATH+"syntaxchecker";53ORYX.CONFIG.VALIDATOR_URL=ORYX.CONFIG.ROOT_PATH+"validator";54ORYX.CONFIG.AUTO_LAYOUTER_URL=ORYX.CONFIG.ROOT_PATH+"layouter";55ORYX.CONFIG.SS_EXTENSIONS_FOLDER=ORYX.CONFIG.ROOT_PATH+"stencilsets/extensions/";56ORYX.CONFIG.SS_EXTENSIONS_CONFIG=ORYX.CONFIG.ROOT_PATH+"stencilsets/extensions/extensions.json";57ORYX.CONFIG.ORYX_NEW_URL="/new";58ORYX.CONFIG.STEP_THROUGH=ORYX.CONFIG.ROOT_PATH+"stepthrough";59ORYX.CONFIG.STEP_THROUGH_CHECKER=ORYX.CONFIG.ROOT_PATH+"stepthroughchecker";60ORYX.CONFIG.XFORMS_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"xformsexport";61ORYX.CONFIG.XFORMS_EXPORT_ORBEON_URL=ORYX.CONFIG.ROOT_PATH+"xformsexport-orbeon";62ORYX.CONFIG.XFORMS_IMPORT_URL=ORYX.CONFIG.ROOT_PATH+"xformsimport";63ORYX.CONFIG.BPEL_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"bpelexporter";64ORYX.CONFIG.BPEL4CHOR_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"bpel4chorexporter";65ORYX.CONFIG.BPEL4CHOR2BPEL_EXPORT_URL=ORYX.CONFIG.ROOT_PATH+"bpel4chor2bpelexporter";66ORYX.CONFIG.TREEGRAPH_SUPPORT=ORYX.CONFIG.ROOT_PATH+"treegraphsupport";67ORYX.CONFIG.XPDL4CHOR2BPEL4CHOR_TRANSFORMATION_URL=ORYX.CONFIG.ROOT_PATH+"xpdl4chor2bpel4chor";68ORYX.CONFIG.RESOURCE_LIST=ORYX.CONFIG.ROOT_PATH+"resourceList";69ORYX.CONFIG.BPMN_LAYOUTER=ORYX.CONFIG.ROOT_PATH+"bpmnlayouter";70ORYX.CONFIG.EPC_LAYOUTER=ORYX.CONFIG.ROOT_PATH+"epclayouter";71ORYX.CONFIG.BPMN2MIGRATION=ORYX.CONFIG.ROOT_PATH+"bpmn2migration";72ORYX.CONFIG.BPMN20_SCHEMA_VALIDATION_ON=true;73ORYX.CONFIG.JPDLIMPORTURL=ORYX.CONFIG.ROOT_PATH+"jpdlimporter";74ORYX.CONFIG.JPDLEXPORTURL=ORYX.CONFIG.ROOT_PATH+"jpdlexporter";75ORYX.CONFIG.CPNTOOLSEXPORTER=ORYX.CONFIG.ROOT_PATH+"cpntoolsexporter";76ORYX.CONFIG.CPNTOOLSIMPORTER=ORYX.CONFIG.ROOT_PATH+"cpntoolsimporter";77ORYX.CONFIG.BPMN2XPDLPATH=ORYX.CONFIG.ROOT_PATH+"bpmn2xpdl";78ORYX.CONFIG.TBPMIMPORT=ORYX.CONFIG.ROOT_PATH+"tbpmimport";79ORYX.CONFIG.NAMESPACE_ORYX="http://www.b3mn.org/oryx";80ORYX.CONFIG.NAMESPACE_SVG="http://www.w3.org/2000/svg";81ORYX.CONFIG.CANVAS_WIDTH=3000;82ORYX.CONFIG.CANVAS_HEIGHT=2000;83ORYX.CONFIG.CANVAS_RESIZE_INTERVAL=300;84ORYX.CONFIG.SELECTED_AREA_PADDING=4;85ORYX.CONFIG.CANVAS_BACKGROUND_COLOR="none";86ORYX.CONFIG.GRID_DISTANCE=30;87ORYX.CONFIG.GRID_ENABLED=true;88ORYX.CONFIG.ZOOM_OFFSET=0.1;89ORYX.CONFIG.DEFAULT_SHAPE_MARGIN=60;90ORYX.CONFIG.SCALERS_SIZE=7;91ORYX.CONFIG.MINIMUM_SIZE=20;92ORYX.CONFIG.MAXIMUM_SIZE=30000;93ORYX.CONFIG.OFFSET_MAGNET=15;94ORYX.CONFIG.OFFSET_EDGE_LABEL_TOP=14;95ORYX.CONFIG.OFFSET_EDGE_LABEL_BOTTOM=12;96ORYX.CONFIG.OFFSET_EDGE_BOUNDS=5;97ORYX.CONFIG.COPY_MOVE_OFFSET=30;98ORYX.CONFIG.SHOW_GRIDLINE=true;99ORYX.CONFIG.BORDER_OFFSET=14;100ORYX.CONFIG.MAX_NUM_SHAPES_NO_GROUP=5;101ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER=30;102ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET=45;103ORYX.CONFIG.SHAPEMENU_RIGHT="Oryx_Right";104ORYX.CONFIG.SHAPEMENU_BOTTOM="Oryx_Bottom";105ORYX.CONFIG.SHAPEMENU_LEFT="Oryx_Left";106ORYX.CONFIG.SHAPEMENU_TOP="Oryx_Top";107ORYX.CONFIG.MORPHITEM_DISABLED="Oryx_MorphItem_disabled";108ORYX.CONFIG.TYPE_STRING="string";109ORYX.CONFIG.TYPE_BOOLEAN="boolean";110ORYX.CONFIG.TYPE_INTEGER="integer";111ORYX.CONFIG.TYPE_FLOAT="float";112ORYX.CONFIG.TYPE_COLOR="color";113ORYX.CONFIG.TYPE_DATE="date";114ORYX.CONFIG.TYPE_CHOICE="choice";115ORYX.CONFIG.TYPE_DYNAMICCHOICE="dynamicchoice";116ORYX.CONFIG.TYPE_DYNAMICDATAINPUT="dynamicdatainput";117ORYX.CONFIG.TYPE_DYNAMICDATAOUTPUT="dynamicdatoutput";118ORYX.CONFIG.TYPE_DYNAMICGATEWAYCONNECTIONS="dynamicgatewayconnections";119ORYX.CONFIG.TYPE_URL="url";120ORYX.CONFIG.TYPE_DIAGRAM_LINK="diagramlink";121ORYX.CONFIG.TYPE_COMPLEX="complex";122ORYX.CONFIG.TYPE_TEXT="text";123ORYX.CONFIG.TYPE_ENCODED_TEXT="encodedtext";124ORYX.CONFIG.TYPE_VARDEF="vardef";125ORYX.CONFIG.TYPE_EXPRESSION="expression";126ORYX.CONFIG.TYPE_TEXT_EXPRESSION="textexpression";127ORYX.CONFIG.TYPE_DOCS_EXPRESSION="docsexpression";128ORYX.CONFIG.TYPE_ACTION="action";129ORYX.CONFIG.TYPE_GLOBAL="global";130ORYX.CONFIG.TYPE_IMPORT="import";131ORYX.CONFIG.TYPE_DATAINPUT="datainput";132ORYX.CONFIG.TYPE_DATAOUTPUT="dataoutput";133ORYX.CONFIG.TYPE_DATAINPUT_SINGLE="datainputsingle";134ORYX.CONFIG.TYPE_DATAOUTPUT_SINGLE="dataoutputsingle";135ORYX.CONFIG.TYPE_DATAASSIGNMENT="dataassignment";136ORYX.CONFIG.TYPE_VISUALDATAASSIGNMENTS="visualdataassignment";137ORYX.CONFIG.TYPE_CALLEDELEMENT="calledelement";138ORYX.CONFIG.TYPE_CUSTOM="custom";139ORYX.CONFIG.TYPE_REASSIGNMENT="reassignment";140ORYX.CONFIG.TYPE_NOTIFICATIONS="notifications";141ORYX.CONFIG.TYPE_DTYPE_VARDEF="vardef";142ORYX.CONFIG.TYPE_DTYPE_DINPUT="dinput";143ORYX.CONFIG.TYPE_DTYPE_DOUTPUT="doutput";144ORYX.CONFIG.TYPE_DTYPE_GLOBAL="global";145ORYX.CONFIG.TYPE_RULEFLOW_GROUP="ruleflowgroup";146ORYX.CONFIG.TYPE_CASE_ROLES="caseroles";147ORYX.CONFIG.LABEL_LINE_DISTANCE=2;148ORYX.CONFIG.LABEL_DEFAULT_LINE_HEIGHT=12;149ORYX.CONFIG.ENABLE_MORPHMENU_BY_HOVER=true;150ORYX.CONFIG.EDITOR_ALIGN_BOTTOM=1;151ORYX.CONFIG.EDITOR_ALIGN_MIDDLE=2;152ORYX.CONFIG.EDITOR_ALIGN_TOP=4;153ORYX.CONFIG.EDITOR_ALIGN_LEFT=8;154ORYX.CONFIG.EDITOR_ALIGN_CENTER=16;155ORYX.CONFIG.EDITOR_ALIGN_RIGHT=32;156ORYX.CONFIG.EDITOR_ALIGN_SIZE=48;157ORYX.CONFIG.EVENT_MOUSEDOWN="mousedown";158ORYX.CONFIG.EVENT_MOUSEUP="mouseup";159ORYX.CONFIG.EVENT_MOUSEOVER="mouseover";160ORYX.CONFIG.EVENT_MOUSEOUT="mouseout";161ORYX.CONFIG.EVENT_MOUSEMOVE="mousemove";162ORYX.CONFIG.EVENT_DBLCLICK="dblclick";163ORYX.CONFIG.EVENT_CLICK="click";164ORYX.CONFIG.EVENT_KEYDOWN="keydown";165ORYX.CONFIG.EVENT_KEYUP="keyup";166ORYX.CONFIG.EVENT_LOADED="editorloaded";167ORYX.CONFIG.EVENT_EXECUTE_COMMANDS="executeCommands";168ORYX.CONFIG.EVENT_STENCIL_SET_LOADED="stencilSetLoaded";169ORYX.CONFIG.EVENT_STENCIL_SET_RELOAD="stencilSetReLoad";170ORYX.CONFIG.EVENT_SELECTION_CHANGED="selectionchanged";171ORYX.CONFIG.EVENT_SHAPEADDED="shapeadded";172ORYX.CONFIG.EVENT_PROPERTY_CHANGED="propertyChanged";173ORYX.CONFIG.EVENT_DRAGDROP_START="dragdrop.start";174ORYX.CONFIG.EVENT_SHAPE_MENU_CLOSE="shape.menu.close";175ORYX.CONFIG.EVENT_DRAGDROP_END="dragdrop.end";176ORYX.CONFIG.EVENT_RESIZE_START="resize.start";177ORYX.CONFIG.EVENT_RESIZE_END="resize.end";178ORYX.CONFIG.EVENT_DRAGDOCKER_DOCKED="dragDocker.docked";179ORYX.CONFIG.EVENT_DRAGDOCKER_MOVE_FINISHED="dragDocker.move.finished";180ORYX.CONFIG.EVENT_DOCKER_EVENT="docker.event";181ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW="highlight.showHighlight";182ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE="highlight.hideHighlight";183ORYX.CONFIG.EVENT_LOADING_ENABLE="loading.enable";184ORYX.CONFIG.EVENT_LOADING_DISABLE="loading.disable";185ORYX.CONFIG.EVENT_LOADING_STATUS="loading.status";186ORYX.CONFIG.EVENT_OVERLAY_SHOW="overlay.show";187ORYX.CONFIG.EVENT_OVERLAY_HIDE="overlay.hide";188ORYX.CONFIG.EVENT_DICTIONARY_ADD="dictionary.add";189ORYX.CONFIG.EVENT_TASKFORM_EDIT="taskform.edit";190ORYX.CONFIG.EVENT_TASKFORM_GENERATE="taskform.generate";191ORYX.CONFIG.EVENT_TASKFORM_GENERATE_ALL="taskform.generate.all";192ORYX.CONFIG.EVENT_ARRANGEMENT_TOP="arrangement.setToTop";193ORYX.CONFIG.EVENT_ARRANGEMENT_BACK="arrangement.setToBack";194ORYX.CONFIG.EVENT_ARRANGEMENT_FORWARD="arrangement.setForward";195ORYX.CONFIG.EVENT_ARRANGEMENT_BACKWARD="arrangement.setBackward";196ORYX.CONFIG.EVENT_PROPWINDOW_PROP_CHANGED="propertyWindow.propertyChanged";197ORYX.CONFIG.EVENT_KEYBIND_MOVE_FINISHED="keybind.move.finished";198ORYX.CONFIG.EVENT_LAYOUT_ROWS="layout.rows";199ORYX.CONFIG.EVENT_LAYOUT_BPEL="layout.BPEL";200ORYX.CONFIG.EVENT_LAYOUT_BPEL_VERTICAL="layout.BPEL.vertical";201ORYX.CONFIG.EVENT_LAYOUT_BPEL_HORIZONTAL="layout.BPEL.horizontal";202ORYX.CONFIG.EVENT_LAYOUT_BPEL_SINGLECHILD="layout.BPEL.singlechild";203ORYX.CONFIG.EVENT_LAYOUT_BPEL_AUTORESIZE="layout.BPEL.autoresize";204ORYX.CONFIG.EVENT_AUTOLAYOUT_LAYOUT="autolayout.layout";205ORYX.CONFIG.EVENT_UNDO_EXECUTE="undo.execute";206ORYX.CONFIG.EVENT_UNDO_ROLLBACK="undo.rollback";207ORYX.CONFIG.EVENT_BUTTON_UPDATE="toolbar.button.update";208ORYX.CONFIG.EVENT_LAYOUT="layout.dolayout";209ORYX.CONFIG.EVENT_COLOR_CHANGE="color.change";210ORYX.CONFIG.EVENT_DOCKERDRAG="dragTheDocker";211ORYX.CONFIG.EVENT_SHOW_PROPERTYWINDOW="propertywindow.show";212ORYX.CONFIG.EVENT_DRAG_TRACKER_DRAG="dragTracker.drag";213ORYX.CONFIG.EVENT_DRAG_TRACKER_RESIZE="dragTracker.resize";214ORYX.CONFIG.EVENT_DROP_SHAPE="drop.shape";215ORYX.CONFIG.EVENT_SHAPE_DELETED="shape.deleted";216ORYX.CONFIG.EVENT_SHAPE_CREATED="shape.created";217ORYX.CONFIG.EVENT_SHAPE_ADDED="shape.added";218ORYX.CONFIG.EVENT_FACADE_SELECTION_DELETION_REQUEST="facade_selection.deletion.request";219ORYX.CONFIG.EVENT_NODEXML_SHOW="nodexml.show";220ORYX.CONFIG.EVENT_DATAIOEDITOR_SHOW="dataioeditor.show";221ORYX.CONFIG.EVENT_VOICE_COMMAND="voice.command";222ORYX.CONFIG.EVENT_SIMULATION_SHOW_RESULTS="simulation.showresults";223ORYX.CONFIG.EVENT_SIMULATION_DISPLAY_GRAPH="simulation.displaygraph";224ORYX.CONFIG.EVENT_SIMULATION_BUILD_PATH_SVG="simulation.buildpathsvg";225ORYX.CONFIG.EVENT_SIMULATION_CLEAR_PATH_SVG="simulation.clearpathsvg";226ORYX.CONFIG.EVENT_SIMULATION_PATH_SVG_GENERATED="simulation.pathsvggenerated";227ORYX.CONFIG.EVENT_SIMULATION_ANNOTATE_PROCESS="simulation.annotateprocess";228ORYX.CONFIG.EVENT_SIMULATION_SHOW_ANNOTATED_PROCESS="simulation.showannotatedprocess";229ORYX.CONFIG.EVENT_NOTIFICATION_SHOW="notification.show";230ORYX.CONFIG.EVENT_DEF_DELETED="notification.def.deleted";231ORYX.CONFIG.EVENT_UPDATE_TASK_TYPE="updatetaskevent";232ORYX.CONFIG.EVENT_PASTE_NOTEMPTY_END="paste.notempty.end";233ORYX.CONFIG.EVENT_PASTE_END="paste.end";234ORYX.CONFIG.EVENT_DOCELEMENT_TO_MODEL="docelementtomodelevent";235ORYX.CONFIG.EVENT_INSTALL_WORKITEM="workitem.install";236ORYX.CONFIG.EVENT_EDIT_PROPS="props.edit";237ORYX.CONFIG.EVENT_PAINT_NEWSHAPE="paint.newshape";238ORYX.CONFIG.EVENT_PAINT_REMOVESHAPE="paint.removeshape";239ORYX.CONFIG.EVENT_CANVAS_RESIZED="canvas.resized";240ORYX.CONFIG.EVENT_CANVAS_RESIZE_SHAPES_MOVED="canvas.resizeshapemoved";241ORYX.CONFIG.EVENT_CANVAS_ZOOMED="canvas.zoomed";242ORYX.CONFIG.EVENT_MODE_CHANGED="mode.changed";243ORYX.CONFIG.EVENT_PAINT_CANVAS_TOGGLED="canvas.toggled";244ORYX.CONFIG.EVENT_DO_SAVE="designereventdosave";245ORYX.CONFIG.EVENT_DO_UPDATE="designereventdoupdate";246ORYX.CONFIG.EVENT_DO_CHECKSAVE="designereventdochecksave";247ORYX.CONFIG.EVENT_CANCEL_SAVE="designereventcancelsave";248ORYX.CONFIG.EVENT_DO_RELOAD="designereventreloads";249ORYX.CONFIG.EVENT_UPDATE_LOCK="designerupdatelock";250ORYX.CONFIG.EVENT_OPEN_XML_EDITOR="designeropeninxmleditor";251ORYX.CONFIG.VOICE_COMMAND_GENERATE_FORMS="voice.command.generate.forms";252ORYX.CONFIG.VOICE_COMMAND_VALIDATE="voice.command.validate";253ORYX.CONFIG.VOICE_COMMAND_GENERATE_IMAGE="voice.command.generate.image";254ORYX.CONFIG.VOICE_COMMAND_VIEW_SOURCE="voice.command.view.source";255ORYX.CONFIG.VOICE_COMMAND_ADD_TASK="voice.command.add.task";256ORYX.CONFIG.VOICE_COMMAND_ADD_GATEWAY="voice.command.add.gateway";257ORYX.CONFIG.VOICE_COMMAND_ADD_START_EVENT="voice.command.add.start.event";258ORYX.CONFIG.VOICE_COMMAND_ADD_END_EVENT="voice.command.add.end.event";259ORYX.CONFIG.VOICE_COMMAND_TASK_TYPE_USER="voice.command.task.type.user";260ORYX.CONFIG.VOICE_COMMAND_TASK_TYPE_SCRIPT="voice.command.task.type.script";261ORYX.CONFIG.VOICE_COMMAND_GATEWAY_TYPE_PARALLEL="voice.command.gateway.type.parallel";262ORYX.CONFIG.VOICE_ENTRY_GENERATE_FORMS="create forms";263ORYX.CONFIG.VOICE_ENTRY_VALIDATE="validate";264ORYX.CONFIG.VOICE_ENTRY_GENERATE_IMAGE="create image";265ORYX.CONFIG.VOICE_ENTRY_VIEW_SOURCE="show bpmn";266ORYX.CONFIG.VOICE_ENTRY_ADD_TASK="task,test,text,that,map,10,chat,pet";267ORYX.CONFIG.VOICE_ENTRY_ADD_GATEWAY="gateway";268ORYX.CONFIG.VOICE_ENTRY_ADD_START_EVENT="start,bart,dark";269ORYX.CONFIG.VOICE_ENTRY_ADD_END_EVENT="end,and";270ORYX.CONFIG.VOICE_ENTRY_TASK_TYPE_USER="user,used";271ORYX.CONFIG.VOICE_ENTRY_TASK_TYPE_SCRIPT="script,strip,red";272ORYX.CONFIG.VOICE_ENTRY_GATEWAY_TYPE_PARALLEL="parallel";273ORYX.CONFIG.CREATE_PATTERN="create.pattern";274ORYX.CONFIG.SELECTION_HIGHLIGHT_SIZE=5;275ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR="#4444FF";276ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR2="#9999FF";277ORYX.CONFIG.SELECTION_HIGHLIGHT_STYLE_CORNER="corner";278ORYX.CONFIG.SELECTION_HIGHLIGHT_STYLE_RECTANGLE="rectangle";279ORYX.CONFIG.SELECTION_VALID_COLOR="#00FF00";280ORYX.CONFIG.SELECTION_INVALID_COLOR="#FF0000";281ORYX.CONFIG.DOCKER_DOCKED_COLOR="#00FF00";282ORYX.CONFIG.DOCKER_UNDOCKED_COLOR="#FF0000";283ORYX.CONFIG.DOCKER_SNAP_OFFSET=10;284ORYX.CONFIG.EDIT_OFFSET_PASTE=10;285ORYX.CONFIG.KEY_CODE_X=88;286ORYX.CONFIG.KEY_CODE_C=67;287ORYX.CONFIG.KEY_CODE_V=86;288ORYX.CONFIG.KEY_CODE_P=80;289ORYX.CONFIG.KEY_CODE_M=77;290ORYX.CONFIG.KEY_CODE_D=68;291ORYX.CONFIG.KEY_CODE_DELETE=46;292ORYX.CONFIG.KEY_CODE_META=224;293ORYX.CONFIG.KEY_CODE_BACKSPACE=8;294ORYX.CONFIG.KEY_CODE_LEFT=37;295ORYX.CONFIG.KEY_CODE_RIGHT=39;296ORYX.CONFIG.KEY_CODE_UP=38;297ORYX.CONFIG.KEY_CODE_DOWN=40;298ORYX.CONFIG.KEY_Code_enter=12;299ORYX.CONFIG.KEY_Code_left=37;300ORYX.CONFIG.KEY_Code_right=39;301ORYX.CONFIG.KEY_Code_top=38;302ORYX.CONFIG.KEY_Code_bottom=40;303ORYX.CONFIG.META_KEY_META_CTRL="metactrl";304ORYX.CONFIG.META_KEY_ALT="alt";305ORYX.CONFIG.META_KEY_SHIFT="shift";306ORYX.CONFIG.KEY_ACTION_DOWN="down";307ORYX.CONFIG.KEY_ACTION_UP="up";308ORYX.CONFIG.PANEL_RIGHT_COLLAPSED=true;309ORYX.CONFIG.PANEL_LEFT_COLLAPSED=true;310ORYX.CONFIG.PANEL_RIGHT_COLLAPSED_SWITCH=ORYX.CONFIG.PANEL_RIGHT_COLLAPSED;311ORYX.CONFIG.PANEL_LEFT_COLLAPSED_SWITCH=ORYX.CONFIG.PANEL_LEFT_COLLAPSED;312ORYX.CONFIG.STENCIL_MAX_ORDER=999;313ORYX.CONFIG.STENCIL_GROUP_ORDER=function(){var a={"http://b3mn.org/stencilset/bpmn2.0#":{Tasks:1,"Start Events":3,"Catching Intermediate Events":5,"Throwing Intermediate Events":6,"End Events":4,Gateways:7,Subprocesses:2,"Service Tasks":8,"Connecting Objects":9,"Data Objects":10,Swimlanes:11,Artifacts:12,"Workflow Patterns":13}};314return a315};316var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(c){var a="";317var k,h,f,j,g,e,d;318var b=0;319c=Base64._utf8_encode(c);320while(b<c.length){k=c.charCodeAt(b++);321h=c.charCodeAt(b++);322f=c.charCodeAt(b++);323j=k>>2;324g=((k&3)<<4)|(h>>4);325e=((h&15)<<2)|(f>>6);326d=f&63;327if(isNaN(h)){e=d=64328}else{if(isNaN(f)){d=64329}}a=a+this._keyStr.charAt(j)+this._keyStr.charAt(g)+this._keyStr.charAt(e)+this._keyStr.charAt(d)330}return a331},decode:function(c){var a="";332var k,h,f;333var j,g,e,d;334var b=0;335c=c.replace(/[^A-Za-z0-9\+\/\=]/g,"");336while(b<c.length){j=this._keyStr.indexOf(c.charAt(b++));337g=this._keyStr.indexOf(c.charAt(b++));338e=this._keyStr.indexOf(c.charAt(b++));339d=this._keyStr.indexOf(c.charAt(b++));340k=(j<<2)|(g>>4);341h=((g&15)<<4)|(e>>2);342f=((e&3)<<6)|d;343a=a+String.fromCharCode(k);344if(e!=64){a=a+String.fromCharCode(h)345}if(d!=64){a=a+String.fromCharCode(f)346}}a=Base64._utf8_decode(a);347return a348},_utf8_encode:function(b){b=b.replace(/\r\n/g,"\n");349var a="";350for(var e=0;351e<b.length;352e++){var d=b.charCodeAt(e);353if(d<128){a+=String.fromCharCode(d)354}else{if((d>127)&&(d<2048)){a+=String.fromCharCode((d>>6)|192);355a+=String.fromCharCode((d&63)|128)356}else{a+=String.fromCharCode((d>>12)|224);357a+=String.fromCharCode(((d>>6)&63)|128);358a+=String.fromCharCode((d&63)|128)359}}}return a360},_utf8_decode:function(a){var b="";361var d=0;362var e=c1=c2=0;363while(d<a.length){e=a.charCodeAt(d);364if(e<128){b+=String.fromCharCode(e);365d++366}else{if((e>191)&&(e<224)){c2=a.charCodeAt(d+1);367b+=String.fromCharCode(((e&31)<<6)|(c2&63));368d+=2369}else{c2=a.charCodeAt(d+1);370c3=a.charCodeAt(d+2);371b+=String.fromCharCode(((e&15)<<12)|((c2&63)<<6)|(c3&63));372d+=3373}}}return b...

Full Screen

Full Screen

laypage.js

Source:laypage.js Github

copy

Full Screen

1/**2 3 @Name : laypage 分页组件4 @License:MIT5 6 */7layui.define(function(exports){8 "use strict";9 10 var doc = document11 ,id = 'getElementById'12 ,tag = 'getElementsByTagName'13 14 //字符常量15 ,MOD_NAME = 'laypage', DISABLED = 'layui-disabled'16 17 //构造器18 ,Class = function(options){19 var that = this;20 that.config = options || {};21 that.config.index = ++laypage.index;22 that.render(true);23 };24 //判断传入的容器类型25 Class.prototype.type = function(){26 var config = this.config;27 if(typeof config.elem === 'object'){28 return config.elem.length === undefined ? 2 : 3;29 }30 };31 //分页视图32 Class.prototype.view = function(){33 var that = this34 ,config = that.config35 ,groups = config.groups = 'groups' in config ? (config.groups|0) : 5; //连续页码个数36 37 //排版38 config.layout = typeof config.layout === 'object' 39 ? config.layout 40 : ['prev', 'page', 'next'];41 42 config.count = config.count|0; //数据总数43 config.curr = (config.curr|0) || 1; //当前页44 //每页条数的选择项45 config.limits = typeof config.limits === 'object'46 ? config.limits47 : [10, 20, 30, 40, 50];48 config.limit = (config.limit|0) || 10; //默认条数49 50 //总页数51 config.pages = Math.ceil(config.count/config.limit) || 1;52 53 //当前页不能超过总页数54 if(config.curr > config.pages){55 config.curr = config.pages;56 }57 58 //连续分页个数不能低于0且不能大于总页数59 if(groups < 0){60 groups = 1;61 } else if (groups > config.pages){62 groups = config.pages;63 }64 65 config.prev = 'prev' in config ? config.prev : '&#x4E0A;&#x4E00;&#x9875;'; //上一页文本66 config.next = 'next' in config ? config.next : '&#x4E0B;&#x4E00;&#x9875;'; //下一页文本67 68 //计算当前组69 var index = config.pages > groups 70 ? Math.ceil( (config.curr + (groups > 1 ? 1 : 0)) / (groups > 0 ? groups : 1) )71 : 172 73 //视图片段74 ,views = {75 //上一页76 prev: function(){77 return config.prev 78 ? '<a href="javascript:;" class="layui-laypage-prev'+ (config.curr == 1 ? (' ' + DISABLED) : '') +'" data-page="'+ (config.curr - 1) +'">'+ config.prev +'</a>'79 : '';80 }()81 82 //页码83 ,page: function(){84 var pager = [];85 86 //数据量为0时,不输出页码87 if(config.count < 1){88 return '';89 }90 91 //首页92 if(index > 1 && config.first !== false && groups !== 0){93 pager.push('<a href="javascript:;" class="layui-laypage-first" data-page="1" title="&#x9996;&#x9875;">'+ (config.first || 1) +'</a>');94 }95 //计算当前页码组的起始页96 var halve = Math.floor((groups-1)/2) //页码数等分97 ,start = index > 1 ? config.curr - halve : 198 ,end = index > 1 ? (function(){99 var max = config.curr + (groups - halve - 1);100 return max > config.pages ? config.pages : max;101 }()) : groups;102 103 //防止最后一组出现“不规定”的连续页码数104 if(end - start < groups - 1){105 start = end - groups + 1;106 }107 //输出左分割符108 if(config.first !== false && start > 2){109 pager.push('<span class="layui-laypage-spr">&#x2026;</span>')110 }111 112 //输出连续页码113 for(; start <= end; start++){114 if(start === config.curr){115 //当前页116 pager.push('<span class="layui-laypage-curr"><em class="layui-laypage-em" '+ (/^#/.test(config.theme) ? 'style="background-color:'+ config.theme +';"' : '') +'></em><em>'+ start +'</em></span>');117 } else {118 pager.push('<a href="javascript:;" data-page="'+ start +'">'+ start +'</a>');119 }120 }121 122 //输出输出右分隔符 & 末页123 if(config.pages > groups && config.pages > end && config.last !== false){124 if(end + 1 < config.pages){125 pager.push('<span class="layui-laypage-spr">&#x2026;</span>');126 }127 if(groups !== 0){128 pager.push('<a href="javascript:;" class="layui-laypage-last" title="&#x5C3E;&#x9875;" data-page="'+ config.pages +'">'+ (config.last || config.pages) +'</a>');129 }130 }131 return pager.join('');132 }()133 134 //下一页135 ,next: function(){136 return config.next 137 ? '<a href="javascript:;" class="layui-laypage-next'+ (config.curr == config.pages ? (' ' + DISABLED) : '') +'" data-page="'+ (config.curr + 1) +'">'+ config.next +'</a>'138 : '';139 }()140 141 //数据总数142 ,count: '<span class="layui-laypage-count">共 '+ config.count +' 条</span>'143 144 //每页条数145 ,limit: function(){146 var options = ['<span class="layui-laypage-limits"><select lay-ignore>'];147 layui.each(config.limits, function(index, item){148 options.push(149 '<option value="'+ item +'"'150 +(item === config.limit ? 'selected' : '') 151 +'>'+ item +' 条/页</option>'152 );153 });154 return options.join('') +'</select></span>';155 }()156 157 //刷新当前页158 ,refresh: ['<a href="javascript:;" data-page="'+ config.curr +'" class="layui-laypage-refresh">'159 ,'<i class="layui-icon layui-icon-refresh"></i>'160 ,'</a>'].join('')161 //跳页区域162 ,skip: function(){163 return ['<span class="layui-laypage-skip">&#x5230;&#x7B2C;'164 ,'<input type="text" min="1" value="'+ config.curr +'" class="layui-input">'165 ,'&#x9875;<button type="button" class="layui-laypage-btn">&#x786e;&#x5b9a;</button>'166 ,'</span>'].join('');167 }()168 };169 return ['<div class="layui-box layui-laypage layui-laypage-'+ (config.theme ? (170 /^#/.test(config.theme) ? 'molv' : config.theme171 ) : 'default') +'" id="layui-laypage-'+ config.index +'">'172 ,function(){173 var plate = [];174 layui.each(config.layout, function(index, item){175 if(views[item]){176 plate.push(views[item])177 }178 });179 return plate.join('');180 }()181 ,'</div>'].join('');182 };183 //跳页的回调184 Class.prototype.jump = function(elem, isskip){185 if(!elem) return;186 var that = this187 ,config = that.config188 ,childs = elem.children189 ,btn = elem[tag]('button')[0]190 ,input = elem[tag]('input')[0]191 ,select = elem[tag]('select')[0]192 ,skip = function(){193 var curr = input.value.replace(/\s|\D/g, '')|0;194 if(curr){195 config.curr = curr;196 that.render();197 }198 };199 200 if(isskip) return skip();201 202 //页码203 for(var i = 0, len = childs.length; i < len; i++){204 if(childs[i].nodeName.toLowerCase() === 'a'){205 laypage.on(childs[i], 'click', function(){206 var curr = this.getAttribute('data-page')|0;207 if(curr < 1 || curr > config.pages) return;208 config.curr = curr;209 that.render();210 });211 }212 }213 214 //条数215 if(select){216 laypage.on(select, 'change', function(){217 var value = this.value;218 if(config.curr*value > config.count){219 config.curr = Math.ceil(config.count/value);220 }221 config.limit = value;222 that.render();223 });224 }225 226 //确定227 if(btn){228 laypage.on(btn, 'click', function(){229 skip();230 });231 }232 };233 234 //输入页数字控制235 Class.prototype.skip = function(elem){236 if(!elem) return;237 var that = this, input = elem[tag]('input')[0];238 if(!input) return;239 laypage.on(input, 'keyup', function(e){240 var value = this.value241 ,keyCode = e.keyCode;242 if(/^(37|38|39|40)$/.test(keyCode)) return;243 if(/\D/.test(value)){244 this.value = value.replace(/\D/, '');245 }246 if(keyCode === 13){247 that.jump(elem, true)248 }249 });250 };251 //渲染分页252 Class.prototype.render = function(load){253 var that = this254 ,config = that.config255 ,type = that.type()256 ,view = that.view();257 258 if(type === 2){259 config.elem && (config.elem.innerHTML = view);260 } else if(type === 3){261 config.elem.html(view);262 } else {263 if(doc[id](config.elem)){264 doc[id](config.elem).innerHTML = view;265 }266 }267 config.jump && config.jump(config, load);268 269 var elem = doc[id]('layui-laypage-' + config.index);270 that.jump(elem);271 272 if(config.hash && !load){273 location.hash = '!'+ config.hash +'='+ config.curr;274 }275 276 that.skip(elem);277 };278 279 //外部接口280 var laypage = {281 //分页渲染282 render: function(options){283 var o = new Class(options);284 return o.index;285 }286 ,index: layui.laypage ? (layui.laypage.index + 10000) : 0287 ,on: function(elem, even, fn){288 elem.attachEvent ? elem.attachEvent('on'+ even, function(e){ //for ie289 e.target = e.srcElement;290 fn.call(elem, e);291 }) : elem.addEventListener(even, fn, false);292 return this;293 }294 }295 exports(MOD_NAME, laypage);...

Full Screen

Full Screen

api.js

Source:api.js Github

copy

Full Screen

1'use strict';2var async = require('async');3var validator = require('validator');4var nconf = require('nconf');5var meta = require('../meta');6var user = require('../user');7var posts = require('../posts');8var topics = require('../topics');9var categories = require('../categories');10var privileges = require('../privileges');11var plugins = require('../plugins');12var translator = require('../translator');13var apiController = module.exports;14apiController.loadConfig = function (req, callback) {15 var config = {};16 config.relative_path = nconf.get('relative_path');17 config.upload_url = nconf.get('upload_url');18 config.siteTitle = validator.escape(String(meta.config.title || meta.config.browserTitle || 'NodeBB'));19 config.browserTitle = validator.escape(String(meta.config.browserTitle || meta.config.title || 'NodeBB'));20 config.titleLayout = (meta.config.titleLayout || '{pageTitle} | {browserTitle}').replace(/{/g, '&#123;').replace(/}/g, '&#125;');21 config.showSiteTitle = parseInt(meta.config.showSiteTitle, 10) === 1;22 config.minimumTitleLength = meta.config.minimumTitleLength;23 config.maximumTitleLength = meta.config.maximumTitleLength;24 config.minimumPostLength = meta.config.minimumPostLength;25 config.maximumPostLength = meta.config.maximumPostLength;26 config.minimumTagsPerTopic = parseInt(meta.config.minimumTagsPerTopic || 0, 10);27 config.maximumTagsPerTopic = parseInt(meta.config.maximumTagsPerTopic || 5, 10);28 config.minimumTagLength = meta.config.minimumTagLength || 3;29 config.maximumTagLength = meta.config.maximumTagLength || 15;30 config.useOutgoingLinksPage = parseInt(meta.config.useOutgoingLinksPage, 10) === 1;31 config.allowGuestHandles = parseInt(meta.config.allowGuestHandles, 10) === 1;32 config.allowFileUploads = parseInt(meta.config.allowFileUploads, 10) === 1;33 config.allowTopicsThumbnail = parseInt(meta.config.allowTopicsThumbnail, 10) === 1;34 config.usePagination = parseInt(meta.config.usePagination, 10) === 1;35 config.disableChat = parseInt(meta.config.disableChat, 10) === 1;36 config.disableChatMessageEditing = parseInt(meta.config.disableChatMessageEditing, 10) === 1;37 config.maximumChatMessageLength = parseInt(meta.config.maximumChatMessageLength, 10) || 1000;38 config.socketioTransports = nconf.get('socket.io:transports') || ['polling', 'websocket'];39 config.websocketAddress = nconf.get('socket.io:address') || '';40 config.maxReconnectionAttempts = meta.config.maxReconnectionAttempts || 5;41 config.reconnectionDelay = meta.config.reconnectionDelay || 1500;42 config.topicsPerPage = meta.config.topicsPerPage || 20;43 config.postsPerPage = meta.config.postsPerPage || 20;44 config.maximumFileSize = meta.config.maximumFileSize;45 config['theme:id'] = meta.config['theme:id'];46 config['theme:src'] = meta.config['theme:src'];47 config.defaultLang = meta.config.defaultLang || 'en-GB';48 config.userLang = req.query.lang ? validator.escape(String(req.query.lang)) : config.defaultLang;49 config.loggedIn = !!req.user;50 config.uid = req.uid;51 config['cache-buster'] = meta.config['cache-buster'] || '';52 config.requireEmailConfirmation = parseInt(meta.config.requireEmailConfirmation, 10) === 1;53 config.topicPostSort = meta.config.topicPostSort || 'oldest_to_newest';54 config.categoryTopicSort = meta.config.categoryTopicSort || 'newest_to_oldest';55 config.csrf_token = req.csrfToken && req.csrfToken();56 config.searchEnabled = plugins.hasListeners('filter:search.query');57 config.bootswatchSkin = meta.config.bootswatchSkin || 'noskin';58 config.defaultBootswatchSkin = meta.config.bootswatchSkin || 'noskin';59 config.enablePostHistory = parseInt(meta.config.enablePostHistory || 1, 10) === 1;60 config.notificationAlertTimeout = parseInt(meta.config.notificationAlertTimeout, 10) || 5000;61 if (config.useOutgoingLinksPage) {62 config.outgoingLinksWhitelist = meta.config['outgoingLinks:whitelist'];63 }64 var timeagoCutoff = meta.config.timeagoCutoff === undefined ? 30 : meta.config.timeagoCutoff;65 config.timeagoCutoff = timeagoCutoff !== '' ? Math.max(0, parseInt(timeagoCutoff, 10)) : timeagoCutoff;66 config.cookies = {67 enabled: parseInt(meta.config.cookieConsentEnabled, 10) === 1,68 message: translator.escape(validator.escape(meta.config.cookieConsentMessage || '[[global:cookies.message]]')).replace(/\\/g, '\\\\'),69 dismiss: translator.escape(validator.escape(meta.config.cookieConsentDismiss || '[[global:cookies.accept]]')).replace(/\\/g, '\\\\'),70 link: translator.escape(validator.escape(meta.config.cookieConsentLink || '[[global:cookies.learn_more]]')).replace(/\\/g, '\\\\'),71 };72 async.waterfall([73 function (next) {74 if (!req.loggedIn) {75 return next(null, config);76 }77 user.getSettings(req.uid, next);78 },79 function (settings, next) {80 config.usePagination = settings.usePagination;81 config.topicsPerPage = settings.topicsPerPage;82 config.postsPerPage = settings.postsPerPage;83 config.userLang = (req.query.lang ? validator.escape(String(req.query.lang)) : null) || settings.userLang || config.defaultLang;84 config.acpLang = (req.query.lang ? validator.escape(String(req.query.lang)) : null) || settings.acpLang;85 config.openOutgoingLinksInNewTab = settings.openOutgoingLinksInNewTab;86 config.topicPostSort = settings.topicPostSort || config.topicPostSort;87 config.categoryTopicSort = settings.categoryTopicSort || config.categoryTopicSort;88 config.topicSearchEnabled = settings.topicSearchEnabled || false;89 config.delayImageLoading = settings.delayImageLoading !== undefined ? settings.delayImageLoading : true;90 config.bootswatchSkin = (parseInt(meta.config.disableCustomUserSkins, 10) !== 1 && settings.bootswatchSkin && settings.bootswatchSkin !== 'default') ? settings.bootswatchSkin : config.bootswatchSkin;91 plugins.fireHook('filter:config.get', config, next);92 },93 ], callback);94};95apiController.getConfig = function (req, res, next) {96 async.waterfall([97 function (next) {98 apiController.loadConfig(req, next);99 },100 function (config, next) {101 if (res.locals.isAPI) {102 res.json(config);103 } else {104 next(null, config);105 }106 },107 ], next);108};109apiController.getPostData = function (pid, uid, callback) {110 async.parallel({111 privileges: function (next) {112 privileges.posts.get([pid], uid, next);113 },114 post: function (next) {115 posts.getPostData(pid, next);116 },117 }, function (err, results) {118 if (err || !results.post) {119 return callback(err);120 }121 var post = results.post;122 var privileges = results.privileges[0];123 if (!privileges.read || !privileges['topics:read']) {124 return callback();125 }126 post.ip = privileges.isAdminOrMod ? post.ip : undefined;127 var selfPost = uid && uid === parseInt(post.uid, 10);128 if (post.deleted && !(privileges.isAdminOrMod || selfPost)) {129 post.content = '[[topic:post_is_deleted]]';130 }131 callback(null, post);132 });133};134apiController.getTopicData = function (tid, uid, callback) {135 async.parallel({136 privileges: function (next) {137 privileges.topics.get(tid, uid, next);138 },139 topic: function (next) {140 topics.getTopicData(tid, next);141 },142 }, function (err, results) {143 if (err || !results.topic) {144 return callback(err);145 }146 if (!results.privileges.read || !results.privileges['topics:read'] || (parseInt(results.topic.deleted, 10) && !results.privileges.view_deleted)) {147 return callback();148 }149 callback(null, results.topic);150 });151};152apiController.getCategoryData = function (cid, uid, callback) {153 async.parallel({154 privileges: function (next) {155 privileges.categories.get(cid, uid, next);156 },157 category: function (next) {158 categories.getCategoryData(cid, next);159 },160 }, function (err, results) {161 if (err || !results.category) {162 return callback(err);163 }164 if (!results.privileges.read) {165 return callback();166 }167 callback(null, results.category);168 });169};170apiController.getObject = function (req, res, next) {171 var methods = {172 post: apiController.getPostData,173 topic: apiController.getTopicData,174 category: apiController.getCategoryData,175 };176 var method = methods[req.params.type];177 if (!method) {178 return next();179 }180 method(req.params.id, req.uid, function (err, result) {181 if (err || !result) {182 return next(err);183 }184 res.json(result);185 });186};187apiController.getModerators = function (req, res, next) {188 categories.getModerators(req.params.cid, function (err, moderators) {189 if (err) {190 return next(err);191 }192 res.json({ moderators: moderators });193 });...

Full Screen

Full Screen

config.js

Source:config.js Github

copy

Full Screen

1$(document).ready(function(){2 loadLogo(pgNm);3});4let config = {};5/******* Images *******/6// Variable Setup7config.logo = {};8config.logo.main = {};9config.logo.regulator = {};10config.logo.manufacturer = {};11config.logo.dealership = {};12config.logo.lease_company = {};13config.logo.leasee = {};14config.logo.scrap_merchant = {};15// Logo size16config.logo.width = '4em';17config.logo.height = '1.6em';18//Main Logo19config.logo.main.src = 'Icons/IBM_logo.svg';20// Regulator Logo21config.logo.regulator.src = 'Icons/Regulator/IBM_logo.svg';22// Manufacturer Logo23config.logo.manufacturer.src = 'Icons/Manufacturer/IBM_logo.svg';24// Dealership Logo25config.logo.dealership.src = 'Icons/Dealership/IBM_logo.svg';26// Lease Company Logo27config.logo.lease_company.src = 'Icons/Lease_Company/IBM_logo.svg';28// Leasee Logo29config.logo.leasee.src = 'Icons/Leasee/IBM_logo.svg';30// Scrap Merchant Logo31config.logo.scrap_merchant.src = 'Icons/Scrap_Merchant/IBM_logo.svg';32/******* Participants *******/33//This is where we define the details of the users for each company (name and password)34// Variable Setup35config.participants = {};36config.participants.users = {};37config.participants.users.regulators = [];38config.participants.users.manufacturers = [];39config.participants.users.dealerships = [];40config.participants.users.lease_companies = [];41config.participants.users.leasees = [];42config.participants.users.scrap_merchants = [];43config.participants.regulator = {};44config.participants.manufacturer = {};45config.participants.dealership = {};46config.participants.lease_company = {};47config.participants.leasee = {};48config.participants.scrap_merchant = {};49// Regulators50config.participants.users.regulators[0]= {};51config.participants.users.regulators[0].company = 'DVLA';52config.participants.users.regulators[0].type = 'Regulator';53config.participants.users.regulators[0].user = 'Ronald';54// Manufacturers55config.participants.users.manufacturers[0] = {};56config.participants.users.manufacturers[0].company = 'Alfa Romeo';57config.participants.users.manufacturers[0].type = 'Manufacturer';58config.participants.users.manufacturers[0].user = 'Martin';59config.participants.users.manufacturers[1] = {};60config.participants.users.manufacturers[1].company = 'Toyota';61config.participants.users.manufacturers[1].type = 'Manufacturer';62config.participants.users.manufacturers[1].user = 'Maria';63config.participants.users.manufacturers[2] = {};64config.participants.users.manufacturers[2].company = 'Jaguar Land Rover';65config.participants.users.manufacturers[2].type = 'Manufacturer';66config.participants.users.manufacturers[2].user = 'Mandy';67// Dealerships68config.participants.users.dealerships[0] = {};69config.participants.users.dealerships[0].company = 'Beechvale Group';70config.participants.users.dealerships[0].type = 'Dealership';71config.participants.users.dealerships[0].user = 'Deborah';72config.participants.users.dealerships[1] = {};73config.participants.users.dealerships[1].company = 'Milescape';74config.participants.users.dealerships[1].type = 'Dealership';75config.participants.users.dealerships[1].user = 'Dennis';76config.participants.users.dealerships[2] = {};77config.participants.users.dealerships[2].company = 'Viewers Alfa Romeo';78config.participants.users.dealerships[2].type = 'Dealership';79config.participants.users.dealerships[2].user = 'Delia';80// Lease Companies81config.participants.users.lease_companies[0] = {};82config.participants.users.lease_companies[0].company = 'LeaseCan';83config.participants.users.lease_companies[0].type = 'Lease Company';84config.participants.users.lease_companies[0].user = 'Lesley';85config.participants.users.lease_companies[1] = {};86config.participants.users.lease_companies[1].company = 'Every Car Leasing';87config.participants.users.lease_companies[1].type = 'Lease Company';88config.participants.users.lease_companies[1].user = 'Larry';89config.participants.users.lease_companies[2] = {};90config.participants.users.lease_companies[2].company = 'Regionwide Vehicle Contracts';91config.participants.users.lease_companies[2].type = 'Lease Company';92config.participants.users.lease_companies[2].user = 'Luke';93// Leasees94config.participants.users.leasees[0] = {};95config.participants.users.leasees[0].company = 'Joe Payne';96config.participants.users.leasees[0].type = 'Leasee';97config.participants.users.leasees[0].user = 'Joe';98config.participants.users.leasees[1] = {};99config.participants.users.leasees[1].company = 'Andrew Hurt';100config.participants.users.leasees[1].type = 'Leasee';101config.participants.users.leasees[1].user = 'Andrew';102config.participants.users.leasees[2] = {};103config.participants.users.leasees[2].company = 'Anthony O\'Dowd';104config.participants.users.leasees[2].type = 'Leasee';105config.participants.users.leasees[2].user = 'Anthony';106// Scrap Merchants107config.participants.users.scrap_merchants[0] = {};108config.participants.users.scrap_merchants[0].company = 'Cray Bros (London) Ltd';109config.participants.users.scrap_merchants[0].type = 'Scrap Merchant';110config.participants.users.scrap_merchants[0].user = 'Sandy';111config.participants.users.scrap_merchants[1] = {};112config.participants.users.scrap_merchants[1].company = 'Aston Scrap Centre';113config.participants.users.scrap_merchants[1].type = 'Scrap Merchant';114config.participants.users.scrap_merchants[1].user = 'Scott';115config.participants.users.scrap_merchants[2] = {};116config.participants.users.scrap_merchants[2].company = 'ScrapIt! UK';117config.participants.users.scrap_merchants[2].type = 'Scrap Merchant';118config.participants.users.scrap_merchants[2].user = 'Sid';119/******* Used Particpants *******/120//This is where we select which participants will be used for the pages121// Regulator122config.participants.regulator = config.participants.users.regulators[0];123// Manufacturer124config.participants.manufacturer = config.participants.users.manufacturers[0];125// Dealership126config.participants.dealership = config.participants.users.dealerships[0];127// Lease Company128config.participants.lease_company = config.participants.users.lease_companies[0];129// Leasee130config.participants.leasee = config.participants.users.leasees[0];131// Scrap Merchant132config.participants.scrap_merchant = config.participants.users.scrap_merchants[0];133function loadLogo(pageType)134{135 $('#logo').attr('src', config.logo[pageType.toLowerCase()].src);136 $('#logo').css('width', config.logo.width);137 $('#logo').css('height', config.logo.height);138}139function loadParticipant(pageType)140{141 $('#username').html(config.participants[pageType].user);142 $('#company').html(config.participants[pageType].company);...

Full Screen

Full Screen

index.test.js

Source:index.test.js Github

copy

Full Screen

1const path = require('path');2const originalCwd = process.cwd();3const schema = {4 'some.key': 'someValue',5 'some.other.key': 'someOtherValue',6 'some.function': jest.fn((config) => config.get('some.other.key')),7};8beforeEach(() => {9 process.chdir(originalCwd);10 global.slateUserConfig = null;11 global.slateConfigPath = null;12 jest.resetModules();13});14describe('when the file first is executed it', () => {15 test('looks for slate.config.js in process.cwd and assigns its contents to a global variable global.slateUserConfig', () => {16 process.chdir(path.resolve(__dirname, './fixtures'));17 const userConfig = require('./fixtures/slate.config');18 require('../index');19 expect(global.slateUserConfig).toBeDefined();20 expect(global.slateUserConfig).toMatchObject(userConfig);21 });22 test('looks for a slate.config.js file if global.slateConfigPath is defined', () => {23 global.slateConfigPath = path.resolve(24 __dirname,25 'fixtures/slate.config.js',26 );27 const userConfig = require('./fixtures/slate.config');28 require('../index');29 expect(global.slateUserConfig).toBeDefined();30 expect(global.slateUserConfig).toMatchObject(userConfig);31 });32 test('if slate.config.js does not exist at process.cwd or the value specified by global.slateConfigPath, an empty object is returned', () => {33 require('../index');34 expect(global.slateUserConfig).toBeDefined();35 expect(global.slateUserConfig).toMatchObject({});36 });37 test('throws error if there is an error in the slate.config.js file', () => {38 global.slateConfigPath = path.resolve(39 __dirname,40 'fixtures/slateWithError.config.js',41 );42 expect(() => {43 require('../index');44 }).toThrowError(ReferenceError);45 });46});47describe('SlateConfig()', () => {48 test('requires a first argument which is assigned to this.schema', () => {49 const SlateConfig = require('../index');50 const config = new SlateConfig(schema);51 expect(config.schema).toMatchObject(schema);52 expect(() => new SlateConfig()).toThrowError();53 });54 test('SlateConfig.prototype.userConfig is a shortcut to global.slateUserConfig', () => {55 process.chdir(path.resolve(__dirname, './fixtures'));56 const SlateConfig = require('../index');57 const config = new SlateConfig(schema);58 expect(config.userConfig).toMatchObject(global.slateUserConfig);59 });60 test('does not modify the original schema object', () => {61 const SlateConfig = require('../index');62 const config = new SlateConfig(schema);63 config.get('some.function');64 expect(config.schema).not.toBe(schema);65 });66});67describe('SlateConfig.get()', () => {68 test('fetches the value of the provided key', () => {69 const SlateConfig = require('../index');70 const config = new SlateConfig(schema);71 expect(config.get('some.other.key')).toBe(schema['some.other.key']);72 });73 test('if the value is a function and not specified in this.userConfig, the function is executed with the config instance as the only argument', () => {74 const SlateConfig = require('../index');75 const config = new SlateConfig(schema);76 const value = config.get('some.function');77 expect(schema['some.function']).toBeCalledWith(config);78 expect(value).toBe(schema['some.other.key']);79 });80 test('if the value is specified in this.userConfig and is a function, it is executed with the config instance and the computed default value as arguments', () => {81 const userConfigValue = 'someNewValue';82 const userConfigFunction = jest.fn(() => userConfigValue);83 const SlateConfig = require('../index');84 const config = new SlateConfig(schema);85 const defaultValue = config.get('some.function');86 global.slateUserConfig = {87 'some.function': userConfigFunction,88 };89 const value = config.get('some.function');90 expect(global.slateUserConfig['some.function']).toBeCalledWith(91 config,92 defaultValue,93 );94 expect(value).toBe(userConfigValue);95 });96});97describe('SlateConfig.set()', () => {98 test('sets the value of a config for a given key', () => {99 const SlateConfig = require('../index');100 const config = new SlateConfig(schema);101 config.set('some.new.key', 'someNewValue');102 expect(config.schema['some.new.key']).toBe('someNewValue');103 });104 test('throws an error if key has already been set, unless override boolean has been explicitely set', () => {105 const SlateConfig = require('../index');106 const config = new SlateConfig(schema);107 expect(() => config.set('some.key', 'someOtherValue')).toThrowError();108 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = function(config) {2 config.set({3 mochaOptions: {4 }5 });6};7const stryker = require('stryker');8const strykerConfig = require('./test.js');9const strykerCli = new stryker.CliRunner();10strykerCli.run(strykerConfig);

Full Screen

Using AI Code Generation

copy

Full Screen

1var config = require("stryker-parent").config;2config.set({ testRunner: "karma" });3var karmaConfig = require("stryker-karma-runner").config;4karmaConfig.set({ browsers: ["Chrome"] });5module.exports = function(config) {6 config.set({7 });8};

Full Screen

Using AI Code Generation

copy

Full Screen

1var config = require('stryker-parent').config;2config.set({3});4var config = require('stryker-parent').config;5config.set({6});7var config = require('stryker-parent').config;8config.set({9});10var config = require('stryker-parent').config;11config.set({12});13var config = require('stryker-parent').config;14config.set({15});16var config = require('stryker-parent').config;17config.set({18});19var config = require('stryker-parent').config;20config.set({21});22var config = require('stryker-parent').config;23config.set({24});25var config = require('stryker-parent').config;26config.set({27});28var config = require('stryker-parent').config;29config.set({30});31var config = require('stryker-parent').config;32config.set({33});34var config = require('stryker-parent').config;35config.set({36});37var config = require('stryker-parent').config;38config.set({39});40var config = require('

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful