How to use shared method in wpt

Best JavaScript code snippet using wpt

dragular.js

Source:dragular.js Github

copy

Full Screen

1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){2'use strict';3/**4 * dragular Directive by Luckylooke https://github.com/luckylooke/dragular5 * Angular version of dragula https://github.com/bevacqua/dragula6 */7 var dragularModule = require('./dragularModule');8dragularModule.directive('dragular', ["dragularService", function(dragularService) {9 return {10 restrict: 'A',11 link: function($scope, iElm, iAttrs) {12 var drake,13 options = $scope.$eval(iAttrs.dragular) || tryJson(iAttrs.dragular) || {};14 function tryJson(json) {15 try { // I dont like try catch solutions but I havent find sattisfying way of chcecking json validity.16 return JSON.parse(json);17 } catch (e) {18 return undefined;19 }20 }21 if(options && options.containersModel && typeof options.containersModel === 'string'){22 options.containersModel = $scope.$eval(options.containersModel);23 }24 if(options && options.dynamicModelAttribute){25 // watch for model changes26 $scope.$watch(function () {27 return $scope.$eval(iAttrs.dragularModel);28 }, function (newVal) {29 if(newVal){30 drake.containersModel = drake.sanitizeContainersModel($scope.$eval(newVal));31 }32 });33 }else if(iAttrs.dragularModel){34 // bind once and keep reference35 options.containersModel = $scope.$eval(iAttrs.dragularModel);36 }37 if(iAttrs.dragularNameSpace){38 options.nameSpace = iAttrs.dragularNameSpace.split(' ');39 }40 drake = dragularService(iElm[0], options);41 }42 };43}]);44},{"./dragularModule":2}],2:[function(require,module,exports){45/* global angular */46'use strict';47/**48 * Dragular 3.4.0 by Luckylooke https://github.com/luckylooke/dragular49 * Angular version of dragula https://github.com/bevacqua/dragula50 */51module.exports = angular.module('dragularModule', []);52({"dragularDirective":require("./dragularDirective.js"),"dragularService":require("./dragularService.js")});53},{"./dragularDirective.js":1,"./dragularService.js":3}],3:[function(require,module,exports){54(function (global){55/* global angular */56'use strict';57/**58 * dragular Service by Luckylooke https://github.com/luckylooke/dragular59 * Angular version of dragula https://github.com/bevacqua/dragula60 */61var dragularModule = require('./dragularModule'),62 shared = { // sahred object between all service instances63 classesCache: {}, // classes lookup cache64 containersCtx: {}, // containers model65 containers: {}, // containers66 mirror: null, // mirror image67 source: null, // source container68 item: null, // item being dragged69 copy: null, // copy flag70 sourceItem: null, // item originaly dragged if copy is enabled71 sourceModel: null, // source container model72 sourceFilteredModel: null, // source container filtered model if relevant73 target: null, // droppable container under drag item74 targetCtx: null, // target container context75 targetModel: null, // target container model76 lastDropTarget: null, // last container item was over77 offsetX: null, // reference x78 offsetY: null, // reference y79 moveX: null, // reference move x80 moveY: null, // reference move y81 offsetXr: null, // reference x right for boundingBox feature82 offsetYb: null, // reference y bottom for boundingBox feature83 clientX: null, // cache client x, init at grab, update at drag84 clientY: null, // cache client y, init at grab, update at drag85 mirrorWidth: null, // mirror width for boundingBox feature86 mirrorHeight: null, // mirror height for boundingBox feature87 initialSibling: null, // reference sibling when grabbed88 currentSibling: null, // reference sibling now89 initialIndex: null, // reference model index when grabbed90 currentIndex: null, // reference model index now91 tempModel: null, // if o.isContainer is used, model can be provided as well, it is temporary saved here during drags92 dragOverEvents: {}, // drag over events fired on element behind cursor93 lastElementBehindCursor: null, // last element behind cursor94 grabbed: null // holds mousedown context until first mousemove95 };96dragularModule.factory('dragularService', ["$rootScope", function dragularServiceFunction($rootScope) {97 // abbreviations98 var doc = document,99 docElm = doc.documentElement;100 // clean common/shared objects101 service.cleanEnviroment = function cleanEnviroment() {102 shared.classesCache = {};103 shared.containersCtx = {};104 shared.containers = {};105 shared.mirror = undefined;106 };107 service.shared = shared;108 return service;109 // service definition110 function service(arg0, arg1) {111 var initialContainers = arg0 || [],112 options = arg1 || {},113 o, // shorthand for options114 g = getBool, // shorthand for getBool115 // defaults116 defaultClasses = {117 mirror: 'gu-mirror',118 hide: 'gu-hide',119 unselectable: 'gu-unselectable',120 transit: 'gu-transit'121 },122 defaultEventNames = {123 // drag-over DOM events124 dragularenter: 'dragularenter',125 dragularleave: 'dragularleave',126 dragularrelease: 'dragularrelease',127 // $scope events128 dragularcloned: 'dragularcloned',129 dragulardrag: 'dragulardrag',130 dragularcancel: 'dragularcancel',131 dragulardrop: 'dragulardrop',132 dragularremove: 'dragularremove',133 dragulardragend: 'dragulardragend',134 dragularshadow: 'dragularshadow',135 dragularover: 'dragularover',136 dragularout: 'dragularout'137 },138 defaultOptions = { // options with defaults139 copyOptions: false, // copy options object when provided140 classes: defaultClasses, // classes used by dragular141 eventNames: defaultEventNames, // event names used by dragular142 containers: false, // initial containers provided via options object (are provided via parameter by default)143 containersModel: false, // if provided, model will be synced with DOM144 containersFilteredModel: false, // if provided, dragular will handle filtered model cases145 isContainer: never, // potential target can be forced to be container by custom logic146 isContainerModel: getEmptyObject, // if isContainer function is provided, you can provide also respective model147 moves: always, // can drag start?148 accepts: always, // can target accept dragged item? (target context used)149 canBeAccepted: always, // can be dragged item accepted by target? (source context used)150 copy: false, // dragged item will be copy of source? flag or function151 copySortSource: false, // enable sorting in source when copying item152 dontCopyModel: false, // dont make copy of model when coping item (#61)153 invalid: never, // target (in)validity function154 revertOnSpill: false, // item returns to original place155 removeOnSpill: false, // item will be removed if not placed into valid target156 lockX: false, // lock movement into x-axis157 lockY: false, // lock movement into y-axis158 boundingBox: false, // lock movement inside this element boundaries159 mirrorContainer: doc.body, // element for appending mirror160 ignoreInputTextSelection: true // text selection in inputs wont be considered as drag161 },162 drake = {163 containers: shared.containers,164 containersCtx: shared.containersCtx,165 sanitizeContainersModel: sanitizeContainersModel,166 isContainer: isContainer,167 start: manualStart,168 end: end,169 cancel: cancel,170 remove: remove,171 destroy: destroy,172 dragging: false173 };174 processServiceArguments(); // both arguments (containers and options) are optional, this function handle this175 extendOptions();176 processOptionsObject();177 registerEvents();178 return drake;179 // Function definitions: ==============================================================================================================180 // Initial functions: -----------------------------------------------------------------------------------------------------------------181 function sanitizeContainersModel(containersModel) {182 if (typeof(containersModel) === 'function') {183 return containersModel;184 }185 if (Array.isArray(containersModel)) {186 // |-------- is 2D array? -----------|187 return Array.isArray(containersModel[0]) ? containersModel : [containersModel];188 } else {189 return [];190 }191 }192 function processServiceArguments(){193 if (arguments.length === 1 && // if there is only one argument we need to distinguish if it is options object or container(s) reference194 !Array.isArray(arg0) && // array of containers elements195 !angular.isElement(arg0) && // one container element196 !arg0[0] && // array-like object with containers elements197 typeof arg0 !== 'string') { // selector198 // then arg0 is options object199 options = arg0 || {};200 initialContainers = []; // containers are not provided on init201 } else if (typeof arg0 === 'string') {202 initialContainers = document.querySelectorAll(arg0);203 }204 o = options.copyOptions ? angular.copy(options) : options;205 }206 function extendOptions(){207 var tmp = angular.extend({}, defaultOptions, o); // tmp for keeping defaults untouched208 angular.extend(o, tmp); // merge defaults back into options209 if(o.classes){210 tmp = angular.extend({}, defaultClasses, o.classes);211 angular.extend(o.classes, tmp);212 }213 if(o.eventNames){214 tmp = angular.extend({}, defaultEventNames, o.eventNames);215 angular.extend(o.eventNames, tmp);216 }217 }218 function processOptionsObject(){219 // bounding box must be pure DOM element, not jQuery wrapper or something else..220 if (!isElement(o.boundingBox)) {221 o.boundingBox = false;222 }223 // initial containers provided via options are higher priority then by parameter224 if(o.containers){225 initialContainers = o.containers;226 }227 // sanitize initialContainers228 initialContainers = makeArray(initialContainers);229 // sanitize o.containersModel230 o.containersModel = sanitizeContainersModel(o.containersModel);231 // sanitize o.containersFilteredModel232 if (Array.isArray(o.containersFilteredModel)) {233 // |-------- is 2D array? -----------|234 o.containersFilteredModel = Array.isArray(o.containersFilteredModel[0]) ? o.containersFilteredModel : [o.containersFilteredModel];235 } else {236 o.containersFilteredModel = [];237 }238 // feed containers groups and optionaly do same for models239 if (!o.nameSpace) {240 o.nameSpace = ['dragularCommon'];241 }242 if (!Array.isArray(o.nameSpace)) {243 o.nameSpace = [o.nameSpace];244 }245 o.nameSpace.forEach(function eachNameSpace(nameSpace) {246 if (!shared.containers[nameSpace]) {247 shared.containers[nameSpace] = [];248 shared.containersCtx[nameSpace] = [];249 }250 var len = initialContainers.length,251 shLen = shared.containers[nameSpace].length;252 for (var i = 0; i < len; i++) {253 shared.containers[nameSpace][i + shLen] = initialContainers[i];254 shared.containersCtx[nameSpace][i + shLen] = {255 o: o,256 m: getContainersModel()[i], // can be undefined257 fm: o.containersFilteredModel[i] // can be undefined258 };259 }260 });261 }262 function registerEvents(remove) {263 var op = remove ? 'off' : 'on';264 regEvent(docElm, op, 'mouseup', release);265 // regEvent(docElm, op, 'mousemove', startBecauseMouseMoved);266 initialContainers.forEach(function addMouseDown(container) {267 regEvent(container, 'on', 'mousedown', grab);268 });269 if(!remove){ // create dragular DOM events270 angular.forEach(['dragularenter', 'dragularleave', 'dragularrelease'], function prepareDragOverEvents(name) {271 var eventName = o.eventNames[name];272 if(!shared.dragOverEvents[eventName]){273 if (doc.createEvent) {274 shared.dragOverEvents[eventName] = doc.createEvent('HTMLEvents');275 shared.dragOverEvents[eventName].initEvent(eventName, true, true);276 } else {277 shared.dragOverEvents[eventName] = doc.createEventObject();278 shared.dragOverEvents[eventName].eventType = eventName;279 }280 }281 });282 }283 }284 // Event handlers functions (end of initial functions): -----------------------------------------------------------------------------------------------------------------285 function grab(e) {286 // filter some odd situations287 if (whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey) {288 return; // we only care about honest-to-god left clicks and touch events289 }290 // set itial values291 shared.moveX = e.clientX;292 shared.moveY = e.clientY;293 var context = canStart(e.target);294 if (!context || !context.item) {295 return;296 }297 shared.grabbed = context;298 eventualMovements();299 if (e.type === 'mousedown') {300 if (isInput(context.item)) { // see also: https://github.com/bevacqua/dragula/issues/208301 context.item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176302 } else {303 e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155304 }305 }306 }307 function release(e) {308 ungrab();309 if (!drake.dragging) {310 return;311 }312 shared.clientX = getCoord('clientX', e);313 shared.clientY = getCoord('clientY', e);314 var elementBehindCursor = getElementBehindPoint(shared.mirror, shared.clientX, shared.clientY),315 dropTarget = findDropTarget(elementBehindCursor, shared.clientX, shared.clientY);316 if (dropTarget && ((shared.copy && g(o.copySortSource)) || (!shared.copy || dropTarget !== shared.source))) {317 // found valid target and (is not copy case or target is not initial container)318 drop(shared.item, dropTarget);319 } else if (g(o.removeOnSpill)) {320 remove();321 } else {322 cancel();323 }324 // after release there is no container hovered325 shared.target = null;326 if (shared.lastElementBehindCursor) {327 fireEvent(shared.lastElementBehindCursor, shared.dragOverEvents.dragularrelease, elementBehindCursor);328 }329 if (o.scope) {330 o.scope.$emit(o.eventNames.dragularrelease, shared.item, shared.source);331 }332 }333 // Main logic functions (end of event handler functions): -----------------------------------------------------------------------------------------------------------------334 function isContainer(el) {335 if(!el){336 return false;337 }338 var i = o.nameSpace.length;339 while (i--) {340 if (shared.containers[o.nameSpace[i]].indexOf(el) !== -1) {341 return true;342 }343 }344 if (o.isContainer(el)) {345 shared.tempModel = o.isContainerModel(el);346 return true;347 } else {348 shared.tempModel = null;349 }350 return false;351 }352 function getContainersModel() {353 return (typeof(o.containersModel) === 'function') ? sanitizeContainersModel(o.containersModel(drake, shared)) : o.containersModel;354 }355 function removeContainers(all) {356 $rootScope.$applyAsync(function applyDestroyed() {357 var changes = Array.isArray(all) ? all : makeArray(all);358 changes.forEach(function forEachContainer(container) {359 angular.forEach(o.nameSpace, function forEachNs(nameSpace) {360 var index;361 index = shared.containers[nameSpace].indexOf(container);362 shared.containers[nameSpace].splice(index, 1);363 shared.containersCtx[nameSpace].splice(index, 1);364 });365 });366 });367 }368 function eventualMovements(remove) {369 var op = remove ? 'off' : 'on';370 regEvent(docElm, op, 'mousemove', startBecauseMouseMoved);371 }372 function movements(remove) {373 var op = remove ? 'off' : 'on';374 regEvent(docElm, op, 'selectstart', preventGrabbed); // IE8375 regEvent(docElm, op, 'click', preventGrabbed);376 regEvent(docElm, op, 'touchmove', preventGrabbed); // fixes touch devices scrolling while drag377 }378 function destroy() {379 registerEvents(true);380 removeContainers(initialContainers);381 release({});382 }383 function startBecauseMouseMoved(e) {384 if (!shared.grabbed || drake.dragging) {385 return;386 }387 if (whichMouseButton(e) === 0) {388 release({});389 return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope390 }391 // truthy check fixes dragula-#239, equality fixes dragula-#207392 if (e.clientX && e.clientX === shared.moveX && e.clientY && e.clientY === shared.moveY) {393 return;394 }395 if (g(o.ignoreInputTextSelection)) {396 var clientX = getCoord('clientX', e),397 clientY = getCoord('clientY', e),398 elementBehindCursor = doc.elementFromPoint(clientX, clientY);399 if (isInput(elementBehindCursor)) {400 return;401 }402 }403 var grabbed = shared.grabbed; // calling end() unsets shared.grabbed404 eventualMovements('remove'); // remove mousemove listener405 movements();406 end();407 start(grabbed);408 // automaticly detect direction of elements if not set in options409 if (!o.direction && getParent(shared.sourceItem)) {410 var parent = shared.sourceItem.parentNode,411 parentHeight = parent.offsetHeight,412 parentWidth = parent.offsetWidth,413 childHeight = shared.sourceItem.clientHeight,414 childWidth = shared.sourceItem.clientWidth;415 o.direction = parentHeight / childHeight < parentWidth / childWidth ? 'horizontal' : 'vertical';416 }417 // get initial coordinates, used to render shared.mirror for first time418 var offset = getOffset(shared.sourceItem);419 shared.offsetX = getCoord('pageX', e) - offset.left;420 shared.offsetY = getCoord('pageY', e) - offset.top;421 shared.clientX = getCoord('clientX', e);422 shared.clientY = getCoord('clientY', e);423 // limiting area of shared.mirror movement, get initial coordinates424 if (o.boundingBox) {425 shared.offsetXr = getCoord('pageX', e) - offset.right;426 shared.offsetYb = getCoord('pageY', e) - offset.bottom;427 }428 e.preventDefault();429 addClass(shared.item, o.classes.transit);430 renderMirrorImage();431 // initial position432 shared.mirror.style.left = shared.clientX - shared.offsetX + 'px';433 shared.mirror.style.top = shared.clientY - shared.offsetY + 'px';434 drag(e);435 }436 function canStart(item) {437 if (drake.dragging && shared.mirror) {438 console.log('usecase?');439 return; // already dragging440 }441 var handle = item;442 while (getParent(item) && !isContainer(getParent(item))) {443 // break loop if user tries to drag item which is considered invalid handle444 if (o.invalid(item, handle)) {445 return;446 }447 item = getParent(item); // drag target should be immediate child of container448 if (!item) {449 return;450 }451 }452 var source = getParent(item);453 if (!source ||454 o.invalid(item, handle) ||455 !o.moves(item, source, handle, nextEl(item))) {456 return;457 }458 return {459 item: item,460 source: source461 };462 }463 function manualStart(item) {464 var context = canStart(item);465 if (context) {466 start(context);467 }468 }469 function start(context) {470 shared.sourceItem = shared.item = context.item;471 shared.source = context.source;472 shared.initialSibling = shared.currentSibling = nextEl(context.item);473 if (g(o.copy, [context.item, context.source])) {474 shared.item = context.item.cloneNode(true);475 shared.copy = true;476 if (o.scope) {477 o.scope.$emit(o.eventNames.dragularcloned, shared.item, context.item);478 }479 } else {480 shared.copy = false;481 }482 // prepare models operations483 var containerIndex = initialContainers.indexOf(context.source);484 shared.sourceModel = getContainersModel()[containerIndex];485 shared.sourceFilteredModel = o.containersFilteredModel[containerIndex];486 shared.initialIndex = domIndexOf(context.item, context.source);487 drake.dragging = true;488 if (o.scope) {489 o.scope.$emit(o.eventNames.dragulardrag, shared.sourceItem, shared.source);490 }491 return true;492 }493 function end() {494 if (!drake.dragging || !shared.item) {495 return;496 }497 drop(shared.item, getParent(shared.item));498 }499 function ungrab() {500 shared.grabbed = false;501 eventualMovements('remove');502 movements('remove');503 }504 function drop(item, target) {505 if (shared.copy && g(o.copySortSource) && target === shared.source && getParent(item)) {506 item.parentNode.removeChild(shared.sourceItem);507 }508 if (shared.sourceModel && !isInitialPlacement(target)) {509 var dropIndex = domIndexOf(item, target);510 if(shared.targetCtx.fm){ // target has filtered model511 // convert index from index-in-filteredModel to index-in-model512 dropIndex = shared.targetCtx.m.indexOf(shared.targetCtx.fm[dropIndex]);513 }514 if(shared.sourceFilteredModel){ // target has filtered model515 // convert index from index-in-filteredModel to index-in-model516 shared.initialIndex = shared.sourceModel.indexOf(shared.sourceFilteredModel[shared.initialIndex]);517 }518 $rootScope.$applyAsync(function applyDrop() {519 if (target === shared.source) {520 shared.sourceModel.splice(dropIndex, 0, shared.sourceModel.splice(shared.initialIndex, 1)[0]);521 } else {522 shared.dropElmModel = shared.copy && !o.dontCopyModel ? angular.copy(shared.sourceModel[shared.initialIndex]) : shared.sourceModel[shared.initialIndex];523 if (!shared.tempModel) {524 shared.targetModel = shared.targetCtx.m;525 } else {526 shared.targetModel = shared.tempModel;527 }528 target.removeChild(item); // element must be removed for ngRepeat to apply correctly529 if (!shared.copy) {530 shared.sourceModel.splice(shared.initialIndex, 1);531 }532 shared.targetModel.splice(dropIndex, 0, shared.dropElmModel);533 }534 if (getParent(item)) {535 item.parentNode.removeChild(item);536 }537 emitDropEvent();538 cleanup();539 });540 } else {541 emitDropEvent();542 cleanup();543 }544 function emitDropEvent() {545 if (o.scope) {546 if (isInitialPlacement(target)) {547 o.scope.$emit(o.eventNames.dragularcancel, item, shared.source, shared.sourceModel, shared.initialIndex);548 } else {549 o.scope.$emit(o.eventNames.dragulardrop, item, target, shared.source, shared.sourceModel, shared.initialIndex, shared.targetModel, dropIndex);550 }551 }552 }553 }554 function remove() {555 if (!drake.dragging) {556 return;557 }558 var parent = getParent(shared.item);559 if (parent) {560 parent.removeChild(shared.item);561 }562 if (shared.sourceModel) {563 $rootScope.$applyAsync(function removeModel() {564 shared.sourceModel.splice(shared.initialIndex, 1);565 cleanup();566 });567 }568 if (o.scope) {569 o.scope.$emit(shared.copy ? o.eventNames.dragularcancel : o.eventNames.dragularremove, shared.item, parent, shared.sourceModel, shared.initialIndex);570 }571 if (!shared.sourceModel) {572 cleanup();573 }574 }575 function cancel(revert) {576 if (!drake.dragging) {577 return;578 }579 var reverts = arguments.length > 0 ? revert : g(o.revertOnSpill),580 parent = getParent(shared.item);581 var initial = isInitialPlacement(parent);582 if (!initial && !shared.copy && reverts) {583 shared.source.insertBefore(shared.item, shared.initialSibling);584 }585 if (shared.sourceModel && !shared.copy && !reverts) {586 drop(shared.item, parent);587 } else if (o.scope) {588 if (initial || reverts) {589 o.scope.$emit(o.eventNames.dragularcancel, shared.item, shared.source);590 }591 }592 if (!shared.sourceModel || shared.copy || reverts || initial) {593 cleanup();594 }595 }596 function cleanup() {597 ungrab();598 removeMirrorImage();599 if (shared.item) {600 rmClass(shared.item, o.classes.transit);601 }602 drake.dragging = false;603 if (g(o.removeOnSpill) === true) {604 spillOut();605 }606 if (o.scope) {607 if(shared.lastDropTarget){608 o.scope.$emit(o.eventNames.dragularout, shared.item, shared.lastDropTarget, shared.source);609 }610 o.scope.$emit(o.eventNames.dragulardragend, shared.item);611 }612 shared.source = shared.item = shared.sourceItem = shared.initialSibling = shared.currentSibling = shared.sourceModel = null;613 shared.initialIndex = shared.currentIndex = shared.lastDropTarget = shared.tempModel = shared.targetModel = null;614 shared.dropElmModel = shared.targetCtx = shared.copy = shared.moveX = shared.moveY = null;615 }616 // is item currently placed in original container and original position?617 function isInitialPlacement(target, s) { // watch performance - running each move several times!618 var sibling = s || (shared.mirror ? shared.currentSibling : nextEl(shared.item));619 return target === shared.source && sibling === shared.initialSibling;620 }621 // find valid drop container622 function findDropTarget(elementBehindCursor, clientX, clientY) { // watch performance - running each move!623 var target = elementBehindCursor;624 while (target && !accepted()) {625 target = getParent(target);626 }627 return target;628 function accepted() {629 var accepts = false;630 if (isContainer(target)) { // is droppable?631 var immediate = getImmediateChild(target, elementBehindCursor),632 reference = getReference(target, immediate, clientX, clientY),633 initial = isInitialPlacement(target, reference),634 i = o.nameSpace.length;635 while (i--) {636 if (shared.containers[o.nameSpace[i]].indexOf(target) !== -1) {637 shared.targetCtx = shared.containersCtx[o.nameSpace[i]][shared.containers[o.nameSpace[i]].indexOf(target)];638 break;639 }640 if (!shared.targetCtx) {641 shared.targetCtx = shared.containersCtx.dragularCommon[shared.containers.dragularCommon.indexOf(target)];642 }643 }644 accepts = initial ||645 (shared.targetCtx.o.accepts(shared.item, target, shared.source, reference, shared.sourceModel, shared.initialIndex) &&646 o.canBeAccepted(shared.item, target, shared.source, reference, shared.sourceModel, shared.initialIndex));647 if (shared.target !== target) { // used for scroll issue648 shared.target = target;649 }650 }651 return accepts;652 }653 }654 function drag(e) { // watch performance - running each move!655 if (!shared.mirror) {656 return;657 }658 // update coordinates659 shared.clientX = getCoord('clientX', e);660 shared.clientY = getCoord('clientY', e);661 // count mirror coordiates662 var x = shared.clientX - shared.offsetX,663 y = shared.clientY - shared.offsetY,664 pageX,665 pageY,666 offsetBox;667 // fill extra properties if boundingBox is used668 if (o.boundingBox) {669 pageX = getCoord('pageX', e);670 pageY = getCoord('pageY', e);671 offsetBox = getOffset(o.boundingBox);672 }673 if (!o.lockY) {674 if (!o.boundingBox || (pageX > offsetBox.left + shared.offsetX && pageX < offsetBox.right + shared.offsetXr)) {675 shared.mirror.style.left = x + 'px';676 } else if (o.boundingBox) { // check again in case user scrolled the view677 if (pageX < offsetBox.left + shared.offsetX) {678 shared.mirror.style.left = shared.clientX - (pageX - offsetBox.left) + 'px';679 } else {680 shared.mirror.style.left = shared.clientX - shared.mirrorWidth - (pageX - offsetBox.right) + 'px';681 }682 }683 }684 if (!o.lockX) {685 if (!o.boundingBox || (pageY > offsetBox.top + shared.offsetY && pageY < offsetBox.bottom + shared.offsetYb)) {686 shared.mirror.style.top = y + 'px';687 } else if (o.boundingBox) { // check again in case user scrolled the view688 if (pageY < offsetBox.top + shared.offsetY) {689 shared.mirror.style.top = shared.clientY - (pageY - offsetBox.top) + 'px';690 } else {691 shared.mirror.style.top = shared.clientY - shared.mirrorHeight - (pageY - offsetBox.bottom) + 'px';692 }693 }694 }695 var elementBehindCursor = getElementBehindPoint(shared.mirror, shared.clientX, shared.clientY),696 dropTarget = findDropTarget(elementBehindCursor, shared.clientX, shared.clientY),697 changed = dropTarget !== shared.lastDropTarget;698 if (elementBehindCursor !== shared.lastElementBehindCursor) {699 fireEvent(elementBehindCursor, shared.dragOverEvents.dragularenter, !!dropTarget);700 if (shared.lastElementBehindCursor) {701 fireEvent(shared.lastElementBehindCursor, shared.dragOverEvents.dragularleave, elementBehindCursor);702 }703 shared.lastElementBehindCursor = elementBehindCursor;704 }705 if (changed) {706 if (shared.lastDropTarget) {707 moved('out');708 }709 shared.lastDropTarget = dropTarget;710 moved('over');711 }712 // do not copy in same container713 if (dropTarget === shared.source && shared.copy && !g(o.copySortSource)) {714 if (getParent(shared.item)) {715 shared.item.parentNode.removeChild(shared.item);716 }717 return;718 }719 var reference,720 immediate = getImmediateChild(dropTarget, elementBehindCursor);721 if (immediate !== null) {722 reference = getReference(dropTarget, immediate, shared.clientX, shared.clientY);723 } else if (g(o.revertOnSpill) === true && !shared.copy) {724 // the case that mirror is not over valid target and reverting is on and copy is off725 reference = shared.initialSibling;726 dropTarget = shared.source;727 } else {728 // the case that mirror is not over valid target and removing is on or copy is on729 if (shared.copy && getParent(shared.item)) {730 // remove item or copy of item731 shared.item.parentNode.removeChild(shared.item);732 }733 return;734 }735 if (reference === null ||736 reference !== shared.item &&737 reference !== nextEl(shared.item) &&738 reference !== shared.currentSibling) {739 // moving item/copy to new container from previous one740 shared.currentSibling = reference;741 dropTarget.insertBefore(shared.item, reference); // if reference is null item is inserted at the end742 if (o.scope) {743 o.scope.$emit(o.eventNames.dragularshadow, shared.item, dropTarget);744 }745 }746 function moved(type) {747 if (o.scope) {748 o.scope.$emit(o.eventNames['dragular' + type], shared.item, shared.lastDropTarget, shared.source);749 }750 if (g(o.removeOnSpill) === true) {751 type === 'over' ? spillOver() : spillOut();752 }753 }754 }755 function spillOver() {756 rmClass(shared.item, o.classes.hide);757 }758 function spillOut() {759 if (drake.dragging) {760 addClass(shared.item, o.classes.hide);761 }762 }763 function scrollContainer(e) {764 if (shared.target) {765 var before = shared.target.scrollTop;766 shared.target.scrollTop += e.deltaY;767 // block scroll of the document when container can be scrolled768 if (before !== shared.target.scrollTop) {769 e.stopPropagation();770 e.preventDefault();771 }772 }773 }774 function renderMirrorImage() {775 if (shared.mirror) {776 return;777 }778 var rect = shared.sourceItem.getBoundingClientRect();779 shared.mirror = shared.sourceItem.cloneNode(true);780 shared.mirrorWidth = rect.width;781 shared.mirrorHeight = rect.height;782 shared.mirror.style.width = getRectWidth(rect) + 'px';783 shared.mirror.style.height = getRectHeight(rect) + 'px';784 rmClass(shared.mirror, o.classes.transit);785 addClass(shared.mirror, o.classes.mirror);786 o.mirrorContainer.appendChild(shared.mirror);787 regEvent(docElm, 'on', 'mousemove', drag);788 addClass(doc.body, o.classes.unselectable);789 regEvent(shared.mirror, 'on', 'wheel', scrollContainer);790 if (o.scope) {791 o.scope.$emit(o.eventNames.dragularcloned, shared.mirror, shared.sourceItem);792 }793 }794 function removeMirrorImage() {795 if (shared.mirror) {796 rmClass(doc.body, o.classes.unselectable);797 regEvent(docElm, 'off', 'mousemove', drag);798 regEvent(shared.mirror, 'off', 'wheel', scrollContainer);799 if(getParent(shared.mirror)){800 shared.mirror.parentNode.removeChild(shared.mirror);801 }802 shared.mirror = null;803 }804 }805 function getImmediateChild(dropTarget, target) { // watch performance - running each move several times!806 var immediate = target;807 while (immediate !== dropTarget && getParent(immediate) !== dropTarget) {808 immediate = getParent(immediate);809 }810 if (immediate === docElm) {811 return null;812 }813 return immediate;814 }815 function getReference(dropTarget, target, x, y) { // watch performance - running each move several times!816 var horizontal = o.direction === 'horizontal';817 return target !== dropTarget ? inside() : outside();818 function outside() { // slower, but able to figure out any position819 var len = dropTarget.children.length,820 i, el, rect;821 for (i = 0; i < len; i++) {822 el = dropTarget.children[i];823 rect = el.getBoundingClientRect();824 if (horizontal && rect.left > x) {825 return el;826 }827 if (!horizontal && rect.top > y) {828 return el;829 }830 }831 return null;832 }833 function inside() { // faster, but only available if dropped inside a child element834 var rect = target.getBoundingClientRect();835 if (horizontal) {836 return resolve(x > rect.left + getRectWidth(rect) / 2);837 }838 return resolve(y > rect.top + getRectHeight(rect) / 2);839 }840 function resolve(after) {841 return after ? nextEl(target) : target;842 }843 }844 function getElementBehindPoint(point, x, y) { // watch performance - running each move!845 var p = point || {},846 state = p.className,847 el;848 p.className += ' ' + o.classes.hide;849 el = doc.elementFromPoint(x, y);850 p.className = state;851 return el;852 }853 } // end of service854 /****************************************************************************************************************************/855 /****************************************************************************************************************************/856 /****************************************************************************************************************************/857 // HELPERS FUNCTIONS:858 function regEvent(el, op, type, fn) {859 var touch = {860 mouseup: 'touchend',861 mousedown: 'touchstart',862 mousemove: 'touchmove'863 },864 pointers = {865 mouseup: 'pointerup',866 mousedown: 'pointerdown',867 mousemove: 'pointermove'868 },869 microsoft = {870 mouseup: 'MSPointerUp',871 mousedown: 'MSPointerDown',872 mousemove: 'MSPointerMove'873 },874 $el = angular.element(el);875 if (global.navigator.pointerEnabled) {876 $el[op](pointers[type], fn);877 } else if (global.navigator.msPointerEnabled) {878 $el[op](microsoft[type], fn);879 } else if (touch[type]) {880 $el[op](touch[type], fn);881 }882 $el[op](type, fn);883 }884 function never() {885 return false;886 }887 function always() {888 return true;889 }890 // make array from array-like objects or from single element (based on bevacqua/atoa)891 function makeArray(all, startIndex) {892 if (Array.isArray(all)) {893 return all;894 }895 if (all.length) { // is array-like896 return Array.prototype.slice.call(all, startIndex); // convert to vanilla js array897 } else { // is one element898 return [all];899 }900 }901 function whichMouseButton (e) {902 if (e.touches !== void 0) { return e.touches.length; }903 if (e.buttons !== undefined) { return e.buttons; }904 if (e.which !== undefined) { return e.which; }905 var button = e.button;906 if (button !== undefined) { // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575907 return button & 1 ? 1 : button & 2 ? 3 : (button & 4 ? 2 : 0);908 }909 }910 function preventGrabbed(e) {911 if (shared.grabbed) {912 e.preventDefault();913 }914 }915 function getScroll(scrollProp, offsetProp) {916 if (typeof window[offsetProp] !== 'undefined') {917 return window[offsetProp];918 }919 if (docElm.clientHeight) {920 return docElm[scrollProp];921 }922 return doc.body[scrollProp];923 }924 function getOffset(el) { // watch performance - running each move!925 var rect = el.getBoundingClientRect(),926 scrollTop = getScroll('scrollTop', 'pageYOffset'),927 scrollLeft = getScroll('scrollLeft', 'pageXOffset');928 return {929 left: rect.left + scrollLeft,930 right: rect.right + scrollLeft,931 top: rect.top + scrollTop,932 bottom: rect.bottom + scrollTop933 };934 }935 function getRectWidth(rect) {936 return rect.width || (rect.right - rect.left);937 }938 function getRectHeight(rect) {939 return rect.height || (rect.bottom - rect.top);940 }941 function getEmptyObject() {942 return {};943 }944 function nextEl(el) {945 return el.nextElementSibling || manually();946 function manually() {947 var sibling = el;948 do {949 sibling = sibling.nextSibling;950 } while (sibling && sibling.nodeType !== 1);951 return sibling;952 }953 }954 //Cannot use angular.isElement because we need to check plain dom element, no jQlite wrapped955 function isElement(obj) {956 return (957 typeof HTMLElement === 'object' ? obj instanceof HTMLElement : //DOM2958 obj && typeof obj === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string'959 );960 }961 function lookupClass(className) {962 var cached = shared.classesCache[className];963 if (cached) {964 cached.lastIndex = 0;965 } else {966 shared.classesCache[className] = cached = new RegExp('(?:^|\\s)' + className + '(?:\\s|$)', 'g');967 }968 return cached;969 }970 function addClass(el, className) {971 var current = el.className;972 if (!current.length) {973 el.className = className;974 } else if (!lookupClass(className).test(current)) {975 el.className += ' ' + className;976 }977 }978 function rmClass(el, className) {979 el.className = el.className.replace(lookupClass(className), ' ').trim();980 }981 function getEventHost(e) {982 // on touchend event, we have to use `e.changedTouches`983 // see http://stackoverflow.com/questions/7192563/touchend-event-properties984 // see https://github.com/bevacqua/dragula/issues/34985 if (e.targetTouches && e.targetTouches.length) {986 return e.targetTouches[0];987 }988 if (e.changedTouches && e.changedTouches.length) {989 return e.changedTouches[0];990 }991 return e;992 }993 function getCoord(coord, e) { // watch performance - running each move several times!994 var host = getEventHost(e);995 var missMap = {996 pageX: 'clientX', // IE8997 pageY: 'clientY' // IE8998 };999 if (coord in missMap && !(coord in host) && missMap[coord] in host) {1000 coord = missMap[coord];1001 }1002 // Adding support for touch events, as they are not functional in the original1003 if (!host.type || host.type.indexOf('touch') < 0) {1004 return host[coord];1005 } else {1006 if (host.type.indexOf('end') === -1) {1007 // No clientX or clientY in a touch event1008 return host.originalEvent.touches[0][coord.replace('client', 'page')];1009 }1010 // Nothing should happen for touchend1011 return false;1012 }1013 }1014 function getParent (el) { // watch performance - running each move!1015 return el.parentNode === document ? null : el.parentNode;1016 }1017 function isInput (el) {1018 return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el);1019 }1020 function isEditable (el) {1021 if (!el) { return false; } // no parents were editable1022 if (el.contentEditable === 'false') { return false; } // stop the lookup1023 if (el.contentEditable === 'true') { return true; } // found a contentEditable element in the chain1024 return isEditable(getParent(el)); // contentEditable is set to 'inherit'1025 }1026 function domIndexOf(child, parent) {1027 return Array.prototype.indexOf.call(angular.element(parent).children(), child);1028 }1029 function fireEvent(target, e, extra) { // watch performance - running each move!1030 if (!target) {1031 return;1032 }1033 shared.extra = extra;1034 if (target.dispatchEvent) {1035 target.dispatchEvent(e);1036 } else {1037 target.fireEvent('on' + e.eventType, e);1038 }1039 }1040 1041 function getBool(prop, args, context){1042 if(angular.isFunction(prop)){1043 return !!prop.apply(context || this, args || shared);1044 }else{1045 return !!prop;1046 }1047 }1048}]);1049}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})...

Full Screen

Full Screen

dragularService.js

Source:dragularService.js Github

copy

Full Screen

1/* global angular */2'use strict';3/**4 * dragular Service by Luckylooke https://github.com/luckylooke/dragular5 * Angular version of dragula https://github.com/bevacqua/dragula6 */7var dragularModule = require('./dragularModule'),8 shared = { // sahred object between all service instances9 classesCache: {}, // classes lookup cache10 containersCtx: {}, // containers model11 containers: {}, // containers12 mirror: null, // mirror image13 source: null, // source container14 item: null, // item being dragged15 copy: null, // copy flag16 sourceItem: null, // item originaly dragged if copy is enabled17 sourceModel: null, // source container model18 sourceFilteredModel: null, // source container filtered model if relevant19 target: null, // droppable container under drag item20 targetCtx: null, // target container context21 targetModel: null, // target container model22 lastDropTarget: null, // last container item was over23 offsetX: null, // reference x24 offsetY: null, // reference y25 moveX: null, // reference move x26 moveY: null, // reference move y27 offsetXr: null, // reference x right for boundingBox feature28 offsetYb: null, // reference y bottom for boundingBox feature29 clientX: null, // cache client x, init at grab, update at drag30 clientY: null, // cache client y, init at grab, update at drag31 mirrorWidth: null, // mirror width for boundingBox feature32 mirrorHeight: null, // mirror height for boundingBox feature33 initialSibling: null, // reference sibling when grabbed34 currentSibling: null, // reference sibling now35 initialIndex: null, // reference model index when grabbed36 currentIndex: null, // reference model index now37 tempModel: null, // if o.isContainer is used, model can be provided as well, it is temporary saved here during drags38 dragOverEvents: {}, // drag over events fired on element behind cursor39 lastElementBehindCursor: null, // last element behind cursor40 grabbed: null // holds mousedown context until first mousemove41 };42dragularModule.factory('dragularService', function dragularServiceFunction($rootScope) {43 // abbreviations44 var doc = document,45 docElm = doc.documentElement;46 // clean common/shared objects47 service.cleanEnviroment = function cleanEnviroment() {48 shared.classesCache = {};49 shared.containersCtx = {};50 shared.containers = {};51 shared.mirror = undefined;52 };53 service.shared = shared;54 return service;55 // service definition56 function service(arg0, arg1) {57 var initialContainers = arg0 || [],58 options = arg1 || {},59 o, // shorthand for options60 g = getBool, // shorthand for getBool61 // defaults62 defaultClasses = {63 mirror: 'gu-mirror',64 hide: 'gu-hide',65 unselectable: 'gu-unselectable',66 transit: 'gu-transit'67 },68 defaultEventNames = {69 // drag-over DOM events70 dragularenter: 'dragularenter',71 dragularleave: 'dragularleave',72 dragularrelease: 'dragularrelease',73 // $scope events74 dragularcloned: 'dragularcloned',75 dragulardrag: 'dragulardrag',76 dragularcancel: 'dragularcancel',77 dragulardrop: 'dragulardrop',78 dragularremove: 'dragularremove',79 dragulardragend: 'dragulardragend',80 dragularshadow: 'dragularshadow',81 dragularover: 'dragularover',82 dragularout: 'dragularout'83 },84 defaultOptions = { // options with defaults85 copyOptions: false, // copy options object when provided86 classes: defaultClasses, // classes used by dragular87 eventNames: defaultEventNames, // event names used by dragular88 containers: false, // initial containers provided via options object (are provided via parameter by default)89 containersModel: false, // if provided, model will be synced with DOM90 containersFilteredModel: false, // if provided, dragular will handle filtered model cases91 isContainer: never, // potential target can be forced to be container by custom logic92 isContainerModel: getEmptyObject, // if isContainer function is provided, you can provide also respective model93 moves: always, // can drag start?94 accepts: always, // can target accept dragged item? (target context used)95 canBeAccepted: always, // can be dragged item accepted by target? (source context used)96 copy: false, // dragged item will be copy of source? flag or function97 copySortSource: false, // enable sorting in source when copying item98 dontCopyModel: false, // dont make copy of model when coping item (#61)99 invalid: never, // target (in)validity function100 revertOnSpill: false, // item returns to original place101 removeOnSpill: false, // item will be removed if not placed into valid target102 lockX: false, // lock movement into x-axis103 lockY: false, // lock movement into y-axis104 boundingBox: false, // lock movement inside this element boundaries105 mirrorContainer: doc.body, // element for appending mirror106 ignoreInputTextSelection: true // text selection in inputs wont be considered as drag107 },108 drake = {109 containers: shared.containers,110 containersCtx: shared.containersCtx,111 sanitizeContainersModel: sanitizeContainersModel,112 isContainer: isContainer,113 start: manualStart,114 end: end,115 cancel: cancel,116 remove: remove,117 destroy: destroy,118 dragging: false119 };120 processServiceArguments(); // both arguments (containers and options) are optional, this function handle this121 extendOptions();122 processOptionsObject();123 registerEvents();124 return drake;125 // Function definitions: ==============================================================================================================126 // Initial functions: -----------------------------------------------------------------------------------------------------------------127 function sanitizeContainersModel(containersModel) {128 if (typeof(containersModel) === 'function') {129 return containersModel;130 }131 if (Array.isArray(containersModel)) {132 // |-------- is 2D array? -----------|133 return Array.isArray(containersModel[0]) ? containersModel : [containersModel];134 } else {135 return [];136 }137 }138 function processServiceArguments(){139 if (arguments.length === 1 && // if there is only one argument we need to distinguish if it is options object or container(s) reference140 !Array.isArray(arg0) && // array of containers elements141 !angular.isElement(arg0) && // one container element142 !arg0[0] && // array-like object with containers elements143 typeof arg0 !== 'string') { // selector144 // then arg0 is options object145 options = arg0 || {};146 initialContainers = []; // containers are not provided on init147 } else if (typeof arg0 === 'string') {148 initialContainers = document.querySelectorAll(arg0);149 }150 o = options.copyOptions ? angular.copy(options) : options;151 }152 function extendOptions(){153 var tmp = angular.extend({}, defaultOptions, o); // tmp for keeping defaults untouched154 angular.extend(o, tmp); // merge defaults back into options155 if(o.classes){156 tmp = angular.extend({}, defaultClasses, o.classes);157 angular.extend(o.classes, tmp);158 }159 if(o.eventNames){160 tmp = angular.extend({}, defaultEventNames, o.eventNames);161 angular.extend(o.eventNames, tmp);162 }163 }164 function processOptionsObject(){165 // bounding box must be pure DOM element, not jQuery wrapper or something else..166 if (!isElement(o.boundingBox)) {167 o.boundingBox = false;168 }169 // initial containers provided via options are higher priority then by parameter170 if(o.containers){171 initialContainers = o.containers;172 }173 // sanitize initialContainers174 initialContainers = makeArray(initialContainers);175 // sanitize o.containersModel176 o.containersModel = sanitizeContainersModel(o.containersModel);177 // sanitize o.containersFilteredModel178 if (Array.isArray(o.containersFilteredModel)) {179 // |-------- is 2D array? -----------|180 o.containersFilteredModel = Array.isArray(o.containersFilteredModel[0]) ? o.containersFilteredModel : [o.containersFilteredModel];181 } else {182 o.containersFilteredModel = [];183 }184 // feed containers groups and optionaly do same for models185 if (!o.nameSpace) {186 o.nameSpace = ['dragularCommon'];187 }188 if (!Array.isArray(o.nameSpace)) {189 o.nameSpace = [o.nameSpace];190 }191 o.nameSpace.forEach(function eachNameSpace(nameSpace) {192 if (!shared.containers[nameSpace]) {193 shared.containers[nameSpace] = [];194 shared.containersCtx[nameSpace] = [];195 }196 var len = initialContainers.length,197 shLen = shared.containers[nameSpace].length;198 for (var i = 0; i < len; i++) {199 shared.containers[nameSpace][i + shLen] = initialContainers[i];200 shared.containersCtx[nameSpace][i + shLen] = {201 o: o,202 m: getContainersModel()[i], // can be undefined203 fm: o.containersFilteredModel[i] // can be undefined204 };205 }206 });207 }208 function registerEvents(remove) {209 var op = remove ? 'off' : 'on';210 regEvent(docElm, op, 'mouseup', release);211 // regEvent(docElm, op, 'mousemove', startBecauseMouseMoved);212 initialContainers.forEach(function addMouseDown(container) {213 regEvent(container, 'on', 'mousedown', grab);214 });215 if(!remove){ // create dragular DOM events216 angular.forEach(['dragularenter', 'dragularleave', 'dragularrelease'], function prepareDragOverEvents(name) {217 var eventName = o.eventNames[name];218 if(!shared.dragOverEvents[eventName]){219 if (doc.createEvent) {220 shared.dragOverEvents[eventName] = doc.createEvent('HTMLEvents');221 shared.dragOverEvents[eventName].initEvent(eventName, true, true);222 } else {223 shared.dragOverEvents[eventName] = doc.createEventObject();224 shared.dragOverEvents[eventName].eventType = eventName;225 }226 }227 });228 }229 }230 // Event handlers functions (end of initial functions): -----------------------------------------------------------------------------------------------------------------231 function grab(e) {232 // filter some odd situations233 if (whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey) {234 return; // we only care about honest-to-god left clicks and touch events235 }236 // set itial values237 shared.moveX = e.clientX;238 shared.moveY = e.clientY;239 var context = canStart(e.target);240 if (!context || !context.item) {241 return;242 }243 shared.grabbed = context;244 eventualMovements();245 if (e.type === 'mousedown') {246 if (isInput(context.item)) { // see also: https://github.com/bevacqua/dragula/issues/208247 context.item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176248 } else {249 e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155250 }251 }252 }253 function release(e) {254 ungrab();255 if (!drake.dragging) {256 return;257 }258 shared.clientX = getCoord('clientX', e);259 shared.clientY = getCoord('clientY', e);260 var elementBehindCursor = getElementBehindPoint(shared.mirror, shared.clientX, shared.clientY),261 dropTarget = findDropTarget(elementBehindCursor, shared.clientX, shared.clientY);262 if (dropTarget && ((shared.copy && g(o.copySortSource)) || (!shared.copy || dropTarget !== shared.source))) {263 // found valid target and (is not copy case or target is not initial container)264 drop(shared.item, dropTarget);265 } else if (g(o.removeOnSpill)) {266 remove();267 } else {268 cancel();269 }270 // after release there is no container hovered271 shared.target = null;272 if (shared.lastElementBehindCursor) {273 fireEvent(shared.lastElementBehindCursor, shared.dragOverEvents.dragularrelease, elementBehindCursor);274 }275 if (o.scope) {276 o.scope.$emit(o.eventNames.dragularrelease, shared.item, shared.source);277 }278 }279 // Main logic functions (end of event handler functions): -----------------------------------------------------------------------------------------------------------------280 function isContainer(el) {281 if(!el){282 return false;283 }284 var i = o.nameSpace.length;285 while (i--) {286 if (shared.containers[o.nameSpace[i]].indexOf(el) !== -1) {287 return true;288 }289 }290 if (o.isContainer(el)) {291 shared.tempModel = o.isContainerModel(el);292 return true;293 } else {294 shared.tempModel = null;295 }296 return false;297 }298 function getContainersModel() {299 return (typeof(o.containersModel) === 'function') ? sanitizeContainersModel(o.containersModel(drake, shared)) : o.containersModel;300 }301 function removeContainers(all) {302 $rootScope.$applyAsync(function applyDestroyed() {303 var changes = Array.isArray(all) ? all : makeArray(all);304 changes.forEach(function forEachContainer(container) {305 angular.forEach(o.nameSpace, function forEachNs(nameSpace) {306 var index;307 index = shared.containers[nameSpace].indexOf(container);308 shared.containers[nameSpace].splice(index, 1);309 shared.containersCtx[nameSpace].splice(index, 1);310 });311 });312 });313 }314 function eventualMovements(remove) {315 var op = remove ? 'off' : 'on';316 regEvent(docElm, op, 'mousemove', startBecauseMouseMoved);317 }318 function movements(remove) {319 var op = remove ? 'off' : 'on';320 regEvent(docElm, op, 'selectstart', preventGrabbed); // IE8321 regEvent(docElm, op, 'click', preventGrabbed);322 regEvent(docElm, op, 'touchmove', preventGrabbed); // fixes touch devices scrolling while drag323 }324 function destroy() {325 registerEvents(true);326 removeContainers(initialContainers);327 release({});328 }329 function startBecauseMouseMoved(e) {330 if (!shared.grabbed || drake.dragging) {331 return;332 }333 if (whichMouseButton(e) === 0) {334 release({});335 return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope336 }337 // truthy check fixes dragula-#239, equality fixes dragula-#207338 if (e.clientX && e.clientX === shared.moveX && e.clientY && e.clientY === shared.moveY) {339 return;340 }341 if (g(o.ignoreInputTextSelection)) {342 var clientX = getCoord('clientX', e),343 clientY = getCoord('clientY', e),344 elementBehindCursor = doc.elementFromPoint(clientX, clientY);345 if (isInput(elementBehindCursor)) {346 return;347 }348 }349 var grabbed = shared.grabbed; // calling end() unsets shared.grabbed350 eventualMovements('remove'); // remove mousemove listener351 movements();352 end();353 start(grabbed);354 // automaticly detect direction of elements if not set in options355 if (!o.direction && getParent(shared.sourceItem)) {356 var parent = shared.sourceItem.parentNode,357 parentHeight = parent.offsetHeight,358 parentWidth = parent.offsetWidth,359 childHeight = shared.sourceItem.clientHeight,360 childWidth = shared.sourceItem.clientWidth;361 o.direction = parentHeight / childHeight < parentWidth / childWidth ? 'horizontal' : 'vertical';362 }363 // get initial coordinates, used to render shared.mirror for first time364 var offset = getOffset(shared.sourceItem);365 shared.offsetX = getCoord('pageX', e) - offset.left;366 shared.offsetY = getCoord('pageY', e) - offset.top;367 shared.clientX = getCoord('clientX', e);368 shared.clientY = getCoord('clientY', e);369 // limiting area of shared.mirror movement, get initial coordinates370 if (o.boundingBox) {371 shared.offsetXr = getCoord('pageX', e) - offset.right;372 shared.offsetYb = getCoord('pageY', e) - offset.bottom;373 }374 e.preventDefault();375 addClass(shared.item, o.classes.transit);376 renderMirrorImage();377 // initial position378 shared.mirror.style.left = shared.clientX - shared.offsetX + 'px';379 shared.mirror.style.top = shared.clientY - shared.offsetY + 'px';380 drag(e);381 }382 function canStart(item) {383 if (drake.dragging && shared.mirror) {384 console.log('usecase?');385 return; // already dragging386 }387 var handle = item;388 while (getParent(item) && !isContainer(getParent(item))) {389 // break loop if user tries to drag item which is considered invalid handle390 if (o.invalid(item, handle)) {391 return;392 }393 item = getParent(item); // drag target should be immediate child of container394 if (!item) {395 return;396 }397 }398 var source = getParent(item);399 if (!source ||400 o.invalid(item, handle) ||401 !o.moves(item, source, handle, nextEl(item))) {402 return;403 }404 return {405 item: item,406 source: source407 };408 }409 function manualStart(item) {410 var context = canStart(item);411 if (context) {412 start(context);413 }414 }415 function start(context) {416 shared.sourceItem = shared.item = context.item;417 shared.source = context.source;418 shared.initialSibling = shared.currentSibling = nextEl(context.item);419 if (g(o.copy, [context.item, context.source])) {420 shared.item = context.item.cloneNode(true);421 shared.copy = true;422 if (o.scope) {423 o.scope.$emit(o.eventNames.dragularcloned, shared.item, context.item);424 }425 } else {426 shared.copy = false;427 }428 // prepare models operations429 var containerIndex = initialContainers.indexOf(context.source);430 shared.sourceModel = getContainersModel()[containerIndex];431 shared.sourceFilteredModel = o.containersFilteredModel[containerIndex];432 shared.initialIndex = domIndexOf(context.item, context.source);433 drake.dragging = true;434 if (o.scope) {435 o.scope.$emit(o.eventNames.dragulardrag, shared.sourceItem, shared.source);436 }437 return true;438 }439 function end() {440 if (!drake.dragging || !shared.item) {441 return;442 }443 drop(shared.item, getParent(shared.item));444 }445 function ungrab() {446 shared.grabbed = false;447 eventualMovements('remove');448 movements('remove');449 }450 function drop(item, target) {451 if (shared.copy && g(o.copySortSource) && target === shared.source && getParent(item)) {452 item.parentNode.removeChild(shared.sourceItem);453 }454 if (shared.sourceModel && !isInitialPlacement(target)) {455 var dropIndex = domIndexOf(item, target);456 if(shared.targetCtx.fm){ // target has filtered model457 // convert index from index-in-filteredModel to index-in-model458 dropIndex = shared.targetCtx.m.indexOf(shared.targetCtx.fm[dropIndex]);459 }460 if(shared.sourceFilteredModel){ // target has filtered model461 // convert index from index-in-filteredModel to index-in-model462 shared.initialIndex = shared.sourceModel.indexOf(shared.sourceFilteredModel[shared.initialIndex]);463 }464 $rootScope.$applyAsync(function applyDrop() {465 if (target === shared.source) {466 shared.sourceModel.splice(dropIndex, 0, shared.sourceModel.splice(shared.initialIndex, 1)[0]);467 } else {468 shared.dropElmModel = shared.copy && !o.dontCopyModel ? angular.copy(shared.sourceModel[shared.initialIndex]) : shared.sourceModel[shared.initialIndex];469 if (!shared.tempModel) {470 shared.targetModel = shared.targetCtx.m;471 } else {472 shared.targetModel = shared.tempModel;473 }474 target.removeChild(item); // element must be removed for ngRepeat to apply correctly475 if (!shared.copy) {476 shared.sourceModel.splice(shared.initialIndex, 1);477 }478 shared.targetModel.splice(dropIndex, 0, shared.dropElmModel);479 }480 if (getParent(item)) {481 item.parentNode.removeChild(item);482 }483 emitDropEvent();484 cleanup();485 });486 } else {487 emitDropEvent();488 cleanup();489 }490 function emitDropEvent() {491 if (o.scope) {492 if (isInitialPlacement(target)) {493 o.scope.$emit(o.eventNames.dragularcancel, item, shared.source, shared.sourceModel, shared.initialIndex);494 } else {495 o.scope.$emit(o.eventNames.dragulardrop, item, target, shared.source, shared.sourceModel, shared.initialIndex, shared.targetModel, dropIndex);496 }497 }498 }499 }500 function remove() {501 if (!drake.dragging) {502 return;503 }504 var parent = getParent(shared.item);505 if (parent) {506 parent.removeChild(shared.item);507 }508 if (shared.sourceModel) {509 $rootScope.$applyAsync(function removeModel() {510 shared.sourceModel.splice(shared.initialIndex, 1);511 cleanup();512 });513 }514 if (o.scope) {515 o.scope.$emit(shared.copy ? o.eventNames.dragularcancel : o.eventNames.dragularremove, shared.item, parent, shared.sourceModel, shared.initialIndex);516 }517 if (!shared.sourceModel) {518 cleanup();519 }520 }521 function cancel(revert) {522 if (!drake.dragging) {523 return;524 }525 var reverts = arguments.length > 0 ? revert : g(o.revertOnSpill),526 parent = getParent(shared.item);527 var initial = isInitialPlacement(parent);528 if (!initial && !shared.copy && reverts) {529 shared.source.insertBefore(shared.item, shared.initialSibling);530 }531 if (shared.sourceModel && !shared.copy && !reverts) {532 drop(shared.item, parent);533 } else if (o.scope) {534 if (initial || reverts) {535 o.scope.$emit(o.eventNames.dragularcancel, shared.item, shared.source);536 }537 }538 if (!shared.sourceModel || shared.copy || reverts || initial) {539 cleanup();540 }541 }542 function cleanup() {543 ungrab();544 removeMirrorImage();545 if (shared.item) {546 rmClass(shared.item, o.classes.transit);547 }548 drake.dragging = false;549 if (g(o.removeOnSpill) === true) {550 spillOut();551 }552 if (o.scope) {553 if(shared.lastDropTarget){554 o.scope.$emit(o.eventNames.dragularout, shared.item, shared.lastDropTarget, shared.source);555 }556 o.scope.$emit(o.eventNames.dragulardragend, shared.item);557 }558 shared.source = shared.item = shared.sourceItem = shared.initialSibling = shared.currentSibling = shared.sourceModel = null;559 shared.initialIndex = shared.currentIndex = shared.lastDropTarget = shared.tempModel = shared.targetModel = null;560 shared.dropElmModel = shared.targetCtx = shared.copy = shared.moveX = shared.moveY = null;561 }562 // is item currently placed in original container and original position?563 function isInitialPlacement(target, s) { // watch performance - running each move several times!564 var sibling = s || (shared.mirror ? shared.currentSibling : nextEl(shared.item));565 return target === shared.source && sibling === shared.initialSibling;566 }567 // find valid drop container568 function findDropTarget(elementBehindCursor, clientX, clientY) { // watch performance - running each move!569 var target = elementBehindCursor;570 while (target && !accepted()) {571 target = getParent(target);572 }573 return target;574 function accepted() {575 var accepts = false;576 if (isContainer(target)) { // is droppable?577 var immediate = getImmediateChild(target, elementBehindCursor),578 reference = getReference(target, immediate, clientX, clientY),579 initial = isInitialPlacement(target, reference),580 i = o.nameSpace.length;581 while (i--) {582 if (shared.containers[o.nameSpace[i]].indexOf(target) !== -1) {583 shared.targetCtx = shared.containersCtx[o.nameSpace[i]][shared.containers[o.nameSpace[i]].indexOf(target)];584 break;585 }586 if (!shared.targetCtx) {587 shared.targetCtx = shared.containersCtx.dragularCommon[shared.containers.dragularCommon.indexOf(target)];588 }589 }590 accepts = initial ||591 (shared.targetCtx.o.accepts(shared.item, target, shared.source, reference, shared.sourceModel, shared.initialIndex) &&592 o.canBeAccepted(shared.item, target, shared.source, reference, shared.sourceModel, shared.initialIndex));593 if (shared.target !== target) { // used for scroll issue594 shared.target = target;595 }596 }597 return accepts;598 }599 }600 function drag(e) { // watch performance - running each move!601 if (!shared.mirror) {602 return;603 }604 // update coordinates605 shared.clientX = getCoord('clientX', e);606 shared.clientY = getCoord('clientY', e);607 // count mirror coordiates608 var x = shared.clientX - shared.offsetX,609 y = shared.clientY - shared.offsetY,610 pageX,611 pageY,612 offsetBox;613 // fill extra properties if boundingBox is used614 if (o.boundingBox) {615 pageX = getCoord('pageX', e);616 pageY = getCoord('pageY', e);617 offsetBox = getOffset(o.boundingBox);618 }619 if (!o.lockY) {620 if (!o.boundingBox || (pageX > offsetBox.left + shared.offsetX && pageX < offsetBox.right + shared.offsetXr)) {621 shared.mirror.style.left = x + 'px';622 } else if (o.boundingBox) { // check again in case user scrolled the view623 if (pageX < offsetBox.left + shared.offsetX) {624 shared.mirror.style.left = shared.clientX - (pageX - offsetBox.left) + 'px';625 } else {626 shared.mirror.style.left = shared.clientX - shared.mirrorWidth - (pageX - offsetBox.right) + 'px';627 }628 }629 }630 if (!o.lockX) {631 if (!o.boundingBox || (pageY > offsetBox.top + shared.offsetY && pageY < offsetBox.bottom + shared.offsetYb)) {632 shared.mirror.style.top = y + 'px';633 } else if (o.boundingBox) { // check again in case user scrolled the view634 if (pageY < offsetBox.top + shared.offsetY) {635 shared.mirror.style.top = shared.clientY - (pageY - offsetBox.top) + 'px';636 } else {637 shared.mirror.style.top = shared.clientY - shared.mirrorHeight - (pageY - offsetBox.bottom) + 'px';638 }639 }640 }641 var elementBehindCursor = getElementBehindPoint(shared.mirror, shared.clientX, shared.clientY),642 dropTarget = findDropTarget(elementBehindCursor, shared.clientX, shared.clientY),643 changed = dropTarget !== shared.lastDropTarget;644 if (elementBehindCursor !== shared.lastElementBehindCursor) {645 fireEvent(elementBehindCursor, shared.dragOverEvents.dragularenter, !!dropTarget);646 if (shared.lastElementBehindCursor) {647 fireEvent(shared.lastElementBehindCursor, shared.dragOverEvents.dragularleave, elementBehindCursor);648 }649 shared.lastElementBehindCursor = elementBehindCursor;650 }651 if (changed) {652 if (shared.lastDropTarget) {653 moved('out');654 }655 shared.lastDropTarget = dropTarget;656 moved('over');657 }658 // do not copy in same container659 if (dropTarget === shared.source && shared.copy && !g(o.copySortSource)) {660 if (getParent(shared.item)) {661 shared.item.parentNode.removeChild(shared.item);662 }663 return;664 }665 var reference,666 immediate = getImmediateChild(dropTarget, elementBehindCursor);667 if (immediate !== null) {668 reference = getReference(dropTarget, immediate, shared.clientX, shared.clientY);669 } else if (g(o.revertOnSpill) === true && !shared.copy) {670 // the case that mirror is not over valid target and reverting is on and copy is off671 reference = shared.initialSibling;672 dropTarget = shared.source;673 } else {674 // the case that mirror is not over valid target and removing is on or copy is on675 if (shared.copy && getParent(shared.item)) {676 // remove item or copy of item677 shared.item.parentNode.removeChild(shared.item);678 }679 return;680 }681 if (reference === null ||682 reference !== shared.item &&683 reference !== nextEl(shared.item) &&684 reference !== shared.currentSibling) {685 // moving item/copy to new container from previous one686 shared.currentSibling = reference;687 dropTarget.insertBefore(shared.item, reference); // if reference is null item is inserted at the end688 if (o.scope) {689 o.scope.$emit(o.eventNames.dragularshadow, shared.item, dropTarget);690 }691 }692 function moved(type) {693 if (o.scope) {694 o.scope.$emit(o.eventNames['dragular' + type], shared.item, shared.lastDropTarget, shared.source);695 }696 if (g(o.removeOnSpill) === true) {697 type === 'over' ? spillOver() : spillOut();698 }699 }700 }701 function spillOver() {702 rmClass(shared.item, o.classes.hide);703 }704 function spillOut() {705 if (drake.dragging) {706 addClass(shared.item, o.classes.hide);707 }708 }709 function scrollContainer(e) {710 if (shared.target) {711 var before = shared.target.scrollTop;712 shared.target.scrollTop += e.deltaY;713 // block scroll of the document when container can be scrolled714 if (before !== shared.target.scrollTop) {715 e.stopPropagation();716 e.preventDefault();717 }718 }719 }720 function renderMirrorImage() {721 if (shared.mirror) {722 return;723 }724 var rect = shared.sourceItem.getBoundingClientRect();725 shared.mirror = shared.sourceItem.cloneNode(true);726 shared.mirrorWidth = rect.width;727 shared.mirrorHeight = rect.height;728 shared.mirror.style.width = getRectWidth(rect) + 'px';729 shared.mirror.style.height = getRectHeight(rect) + 'px';730 rmClass(shared.mirror, o.classes.transit);731 addClass(shared.mirror, o.classes.mirror);732 o.mirrorContainer.appendChild(shared.mirror);733 regEvent(docElm, 'on', 'mousemove', drag);734 addClass(doc.body, o.classes.unselectable);735 regEvent(shared.mirror, 'on', 'wheel', scrollContainer);736 if (o.scope) {737 o.scope.$emit(o.eventNames.dragularcloned, shared.mirror, shared.sourceItem);738 }739 }740 function removeMirrorImage() {741 if (shared.mirror) {742 rmClass(doc.body, o.classes.unselectable);743 regEvent(docElm, 'off', 'mousemove', drag);744 regEvent(shared.mirror, 'off', 'wheel', scrollContainer);745 if(getParent(shared.mirror)){746 shared.mirror.parentNode.removeChild(shared.mirror);747 }748 shared.mirror = null;749 }750 }751 function getImmediateChild(dropTarget, target) { // watch performance - running each move several times!752 var immediate = target;753 while (immediate !== dropTarget && getParent(immediate) !== dropTarget) {754 immediate = getParent(immediate);755 }756 if (immediate === docElm) {757 return null;758 }759 return immediate;760 }761 function getReference(dropTarget, target, x, y) { // watch performance - running each move several times!762 var horizontal = o.direction === 'horizontal';763 return target !== dropTarget ? inside() : outside();764 function outside() { // slower, but able to figure out any position765 var len = dropTarget.children.length,766 i, el, rect;767 for (i = 0; i < len; i++) {768 el = dropTarget.children[i];769 rect = el.getBoundingClientRect();770 if (horizontal && rect.left > x) {771 return el;772 }773 if (!horizontal && rect.top > y) {774 return el;775 }776 }777 return null;778 }779 function inside() { // faster, but only available if dropped inside a child element780 var rect = target.getBoundingClientRect();781 if (horizontal) {782 return resolve(x > rect.left + getRectWidth(rect) / 2);783 }784 return resolve(y > rect.top + getRectHeight(rect) / 2);785 }786 function resolve(after) {787 return after ? nextEl(target) : target;788 }789 }790 function getElementBehindPoint(point, x, y) { // watch performance - running each move!791 var p = point || {},792 state = p.className,793 el;794 p.className += ' ' + o.classes.hide;795 el = doc.elementFromPoint(x, y);796 p.className = state;797 return el;798 }799 } // end of service800 /****************************************************************************************************************************/801 /****************************************************************************************************************************/802 /****************************************************************************************************************************/803 // HELPERS FUNCTIONS:804 function regEvent(el, op, type, fn) {805 var touch = {806 mouseup: 'touchend',807 mousedown: 'touchstart',808 mousemove: 'touchmove'809 },810 pointers = {811 mouseup: 'pointerup',812 mousedown: 'pointerdown',813 mousemove: 'pointermove'814 },815 microsoft = {816 mouseup: 'MSPointerUp',817 mousedown: 'MSPointerDown',818 mousemove: 'MSPointerMove'819 },820 $el = angular.element(el);821 if (global.navigator.pointerEnabled) {822 $el[op](pointers[type], fn);823 } else if (global.navigator.msPointerEnabled) {824 $el[op](microsoft[type], fn);825 } else if (touch[type]) {826 $el[op](touch[type], fn);827 }828 $el[op](type, fn);829 }830 function never() {831 return false;832 }833 function always() {834 return true;835 }836 // make array from array-like objects or from single element (based on bevacqua/atoa)837 function makeArray(all, startIndex) {838 if (Array.isArray(all)) {839 return all;840 }841 if (all.length) { // is array-like842 return Array.prototype.slice.call(all, startIndex); // convert to vanilla js array843 } else { // is one element844 return [all];845 }846 }847 function whichMouseButton (e) {848 if (e.touches !== void 0) { return e.touches.length; }849 if (e.buttons !== undefined) { return e.buttons; }850 if (e.which !== undefined) { return e.which; }851 var button = e.button;852 if (button !== undefined) { // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575853 return button & 1 ? 1 : button & 2 ? 3 : (button & 4 ? 2 : 0);854 }855 }856 function preventGrabbed(e) {857 if (shared.grabbed) {858 e.preventDefault();859 }860 }861 function getScroll(scrollProp, offsetProp) {862 if (typeof window[offsetProp] !== 'undefined') {863 return window[offsetProp];864 }865 if (docElm.clientHeight) {866 return docElm[scrollProp];867 }868 return doc.body[scrollProp];869 }870 function getOffset(el) { // watch performance - running each move!871 var rect = el.getBoundingClientRect(),872 scrollTop = getScroll('scrollTop', 'pageYOffset'),873 scrollLeft = getScroll('scrollLeft', 'pageXOffset');874 return {875 left: rect.left + scrollLeft,876 right: rect.right + scrollLeft,877 top: rect.top + scrollTop,878 bottom: rect.bottom + scrollTop879 };880 }881 function getRectWidth(rect) {882 return rect.width || (rect.right - rect.left);883 }884 function getRectHeight(rect) {885 return rect.height || (rect.bottom - rect.top);886 }887 function getEmptyObject() {888 return {};889 }890 function nextEl(el) {891 return el.nextElementSibling || manually();892 function manually() {893 var sibling = el;894 do {895 sibling = sibling.nextSibling;896 } while (sibling && sibling.nodeType !== 1);897 return sibling;898 }899 }900 //Cannot use angular.isElement because we need to check plain dom element, no jQlite wrapped901 function isElement(obj) {902 return (903 typeof HTMLElement === 'object' ? obj instanceof HTMLElement : //DOM2904 obj && typeof obj === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string'905 );906 }907 function lookupClass(className) {908 var cached = shared.classesCache[className];909 if (cached) {910 cached.lastIndex = 0;911 } else {912 shared.classesCache[className] = cached = new RegExp('(?:^|\\s)' + className + '(?:\\s|$)', 'g');913 }914 return cached;915 }916 function addClass(el, className) {917 var current = el.className;918 if (!current.length) {919 el.className = className;920 } else if (!lookupClass(className).test(current)) {921 el.className += ' ' + className;922 }923 }924 function rmClass(el, className) {925 el.className = el.className.replace(lookupClass(className), ' ').trim();926 }927 function getEventHost(e) {928 // on touchend event, we have to use `e.changedTouches`929 // see http://stackoverflow.com/questions/7192563/touchend-event-properties930 // see https://github.com/bevacqua/dragula/issues/34931 if (e.targetTouches && e.targetTouches.length) {932 return e.targetTouches[0];933 }934 if (e.changedTouches && e.changedTouches.length) {935 return e.changedTouches[0];936 }937 return e;938 }939 function getCoord(coord, e) { // watch performance - running each move several times!940 var host = getEventHost(e);941 var missMap = {942 pageX: 'clientX', // IE8943 pageY: 'clientY' // IE8944 };945 if (coord in missMap && !(coord in host) && missMap[coord] in host) {946 coord = missMap[coord];947 }948 // Adding support for touch events, as they are not functional in the original949 if (!host.type || host.type.indexOf('touch') < 0) {950 return host[coord];951 } else {952 if (host.type.indexOf('end') === -1) {953 // No clientX or clientY in a touch event954 return host.originalEvent.touches[0][coord.replace('client', 'page')];955 }956 // Nothing should happen for touchend957 return false;958 }959 }960 function getParent (el) { // watch performance - running each move!961 return el.parentNode === document ? null : el.parentNode;962 }963 function isInput (el) {964 return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el);965 }966 function isEditable (el) {967 if (!el) { return false; } // no parents were editable968 if (el.contentEditable === 'false') { return false; } // stop the lookup969 if (el.contentEditable === 'true') { return true; } // found a contentEditable element in the chain970 return isEditable(getParent(el)); // contentEditable is set to 'inherit'971 }972 function domIndexOf(child, parent) {973 return Array.prototype.indexOf.call(angular.element(parent).children(), child);974 }975 function fireEvent(target, e, extra) { // watch performance - running each move!976 if (!target) {977 return;978 }979 shared.extra = extra;980 if (target.dispatchEvent) {981 target.dispatchEvent(e);982 } else {983 target.fireEvent('on' + e.eventType, e);984 }985 }986 987 function getBool(prop, args, context){988 if(angular.isFunction(prop)){989 return !!prop.apply(context || this, args || shared);990 }else{991 return !!prop;992 }993 }...

Full Screen

Full Screen

DocumentSharedForm.js

Source:DocumentSharedForm.js Github

copy

Full Screen

1/**2 * 文档共享表单3 * 4 */5var DocumentSharedForm = function(docId) {6 this.docId = docId;7};8/**9 * 显示视图10 * 11 * @return {}12 */13DocumentSharedForm.prototype.getView = function() {14 var docId = this.docId;15 var formPanel = new Ext.FormPanel({16 id : 'documentSharedForm',17 bodyStyle : 'padding:4px 10px 4px 10px',18 items : [{19 xtype : 'hidden',20 name : 'docId',21 id:'docId',22 value : this.docId23 }, {24 xtype : 'fieldset',25 border : false,26 layout : 'column',27 items : [{28 xtype : 'label',29 text : '共享人员',30 width : 10031 }, {32 xtype : 'hidden',33 name : 'sharedUserIds',34 id : 'sharedUserIds'35 }, {36 xtype : 'textarea',37 name : 'sharedUserNames',38 id : 'sharedUserNames',39 width : 30040 }, {41 xtype : 'button',42 text : '选择',43 iconCls:'btn-select',44 width : 80,45 handler : function() {46 //显示选择器,并且设置用户47 UserSelector.getView(48 function(uIds, fnames) {49 var sharedUserIds = Ext50 .getCmp('sharedUserIds');51 var sharedUserNames = Ext52 .getCmp('sharedUserNames');53 if (sharedUserIds.getValue() == '') {//若原没有值,则直接设置54 sharedUserIds.setValue(','+uIds+',');55 sharedUserNames.setValue(fnames);56 return;57 }else{58 //去掉重复的人员59 var vIds = sharedUserIds.getValue()60 .split(',');61 var fnms = sharedUserNames.getValue()62 .split(',');63 sharedUserIds64 .setValue(uniqueArray(vIds65 .concat(uIds66 .split(',')))+',');67 sharedUserNames68 .setValue(uniqueArray(fnms69 .concat(fnames70 .split(','))));71 72 }73 }).show();74 }75 }, {76 xtype : 'button',77 iconCls:'btn-clear',78 text : '清空',79 handler:function(){80 var sharedUserIds = Ext.getCmp('sharedUserIds');81 var sharedUserNames = Ext.getCmp('sharedUserNames');82 83 sharedUserIds.setValue('');84 sharedUserNames.setValue('');85 },86 width : 8087 }]88 }, {89 xtype : 'fieldset',90 border : false,91 layout : 'column',92 items : [{93 xtype : 'label',94 text : '共享部门',95 width : 10096 }, {97 name : 'sharedDepIds',98 id : 'sharedDepIds',99 xtype : 'hidden'100 }, {101 name : 'sharedDepNames',102 id : 'sharedDepNames',103 xtype : 'textarea',104 width : 300105 }, {106 xtype : 'button',107 text : '选择',108 iconCls:'btn-select',109 width : 80,110 handler : function() {111 DepSelector.getView(function(ids, names) {112 var sharedDepIds = Ext.getCmp('sharedDepIds');113 var sharedDepNames = Ext.getCmp('sharedDepNames');114 if (sharedDepIds.getValue() == '') {//若原没有值,则直接设置115 sharedDepIds.setValue(','+ids+',');116 sharedDepNames.setValue(names);117 return;118 }119 //去掉重复的部门120 var vIds = sharedDepIds.getValue().split(',');121 var fnms = sharedDepNames.getValue().split(',');122 sharedDepIds.setValue(uniqueArray(vIds123 .concat(ids.split(',')))+',');124 sharedDepNames.setValue(uniqueArray(fnms125 .concat(names.split(','))));126 }).show();127 }128 }, {129 xtype : 'button',130 text : '清空',131 iconCls:'btn-clear',132 handler:function(){133 var sharedDepIds = Ext.getCmp('sharedDepIds');134 var sharedDepNames = Ext.getCmp('sharedDepNames');135 136 sharedDepIds.setValue('');137 sharedDepNames.setValue('');138 },139 width : 80140 }]141 }, {142 xtype : 'fieldset',143 border : false,144 layout : 'column',145 items : [{146 xtype : 'label',147 text : '共享角色',148 width : 100149 }, {150 xtype : 'hidden',151 id : 'sharedRoleIds',152 name : 'sharedRoleIds'153 }, {154 name : 'sharedRoleNames',155 id : 'sharedRoleNames',156 xtype : 'textarea',157 width : 300158 }, {159 xtype : 'button',160 text : '选择',161 iconCls:'btn-select',162 width : 80,163 handler : function() {164 RoleSelector.getView(function(ids, names) {165 var sharedRoleIds = Ext.getCmp('sharedRoleIds');166 var sharedRoleNames = Ext.getCmp('sharedRoleNames');167 if (sharedRoleIds.getValue() == '') {//若原没有值,则直接设置168 sharedRoleIds.setValue(','+ids+',');169 sharedRoleNames.setValue(names);170 return;171 }172 //去掉重复的部门173 var vIds = sharedRoleIds.getValue().split(',');174 var fnms = sharedRoleNames.getValue().split(',');175 sharedRoleIds.setValue(uniqueArray(vIds.concat(ids.split(',')))+',');176 sharedRoleNames.setValue(uniqueArray(fnms.concat(names.split(','))));177 }).show();178 }179 }, {180 xtype : 'button',181 text : '清空',182 iconCls:'btn-clear',183 handler:function(){184 var sharedRoleIds = Ext.getCmp('sharedRoleIds');185 var sharedRoleNames = Ext.getCmp('sharedRoleNames');186 187 sharedRoleIds.setValue('');188 sharedRoleNames.setValue('');189 },190 width : 80191 }]192 }]193 });194 195 var window = new Ext.Window({196 title : '文档授权信息',197 width : 620,198 iconCls:'menu-mail_folder',199 height : 380,200 modal : true,201 layout : 'anchor',202 plain : true,203 bodyStyle : 'padding:5px;',204 scope : this,205 buttonAlign : 'center',206 items : formPanel,207 buttons : [{208 xtype : 'button',209 text : '共享',210 iconCls:'btn-ok',211 handler : function() {212 formPanel.getForm().submit({213 url:__ctxPath+'/document/shareDocument.do',214 method:'post',215 waitMsg:'正在提交...',216 success:function(fp,action){217 window.close();218 }219 }220 );221 }222 },{223 xtype:'button',224 iconCls:'btn-cancel',225 text:'关闭',226 handler:function(){227 window.close();228 }229 }]230 });231 return window;...

Full Screen

Full Screen

webpack.config.js

Source:webpack.config.js Github

copy

Full Screen

1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */4/* eslint-env node */5/* eslint max-len: [0] */6"use strict";7const path = require("path");8const { NormalModuleReplacementPlugin } = require("webpack");9const { toolboxConfig } = require("./node_modules/devtools-launchpad/index");10const { getConfig } = require("./bin/configure");11let webpackConfig = {12 entry: {13 netmonitor: [path.join(__dirname, "index.js")]14 },15 module: {16 loaders: [17 {18 test: /\.(png|svg)$/,19 loader: "file-loader?name=[path][name].[ext]",20 },21 ]22 },23 output: {24 path: path.join(__dirname, "assets/build"),25 filename: "[name].js",26 publicPath: "/assets/build",27 libraryTarget: "umd",28 },29 // Fallback compatibility for npm link30 resolve: {31 fallback: path.join(__dirname, "node_modules"),32 alias: {33 "react": path.join(__dirname, "node_modules/react"),34 "devtools/client/framework/devtools": path.join(__dirname, "../../client/shims/devtools"),35 "devtools/client/framework/menu": "devtools-modules/src/menu",36 "devtools/client/framework/menu-item": path.join(__dirname, "../../client/framework/menu-item"),37 "devtools/client/locales": path.join(__dirname, "../../client/locales/en-US"),38 "devtools/client/netmonitor/src/utils/menu": "devtools-contextmenu",39 "devtools/client/shared/components/autocomplete-popup": path.join(__dirname, "../../client/shared/components/autocomplete-popup"),40 "devtools/client/shared/components/reps/reps": path.join(__dirname, "../../client/shared/components/reps/reps"),41 "devtools/client/shared/components/search-box": path.join(__dirname, "../../client/shared/components/search-box"),42 "devtools/client/shared/components/splitter/draggable": path.join(__dirname, "../../client/shared/components/splitter/draggable"),43 "devtools/client/shared/components/splitter/split-box": path.join(__dirname, "../../client/shared/components/splitter/split-box"),44 "devtools/client/shared/components/stack-trace": path.join(__dirname, "../../client/shared/components/stack-trace"),45 "devtools/client/shared/components/tabs/tabbar": path.join(__dirname, "../../client/shared/components/tabs/tabbar"),46 "devtools/client/shared/components/tabs/tabs": path.join(__dirname, "../../client/shared/components/tabs/tabs"),47 "devtools/client/shared/components/tree/tree-view": path.join(__dirname, "../../client/shared/components/tree/tree-view"),48 "devtools/client/shared/components/tree/tree-row": path.join(__dirname, "../../client/shared/components/tree/tree-row"),49 "devtools/client/shared/curl": path.join(__dirname, "../../client/shared/curl"),50 "devtools/client/shared/file-saver": path.join(__dirname, "../../client/shared/file-saver"),51 "devtools/client/shared/keycodes": path.join(__dirname, "../../client/shared/keycodes"),52 "devtools/client/shared/key-shortcuts": path.join(__dirname, "../../client/shared/key-shortcuts"),53 "devtools/client/shared/prefs": path.join(__dirname, "../../client/shared/prefs"),54 "devtools/client/shared/scroll": path.join(__dirname, "../../client/shared/scroll"),55 "devtools/client/shared/source-utils": path.join(__dirname, "../../client/shared/source-utils"),56 "devtools/client/shared/vendor/immutable": "immutable",57 "devtools/client/shared/vendor/react": "react",58 "devtools/client/shared/vendor/react-dom": "react-dom",59 "devtools/client/shared/vendor/react-redux": "react-redux",60 "devtools/client/shared/vendor/redux": "redux",61 "devtools/client/shared/vendor/reselect": "reselect",62 "devtools/client/shared/vendor/jszip": "jszip",63 "devtools/client/shared/widgets/tooltip/HTMLTooltip": path.join(__dirname, "../../client/shared/widgets/tooltip/HTMLTooltip"),64 "devtools/client/shared/widgets/tooltip/ImageTooltipHelper": path.join(__dirname, "../../client/shared/widgets/tooltip/ImageTooltipHelper"),65 "devtools/client/shared/widgets/tooltip/TooltipToggle": path.join(__dirname, "../../client/shared/widgets/tooltip/TooltipToggle"),66 "devtools/client/shared/widgets/Chart": path.join(__dirname, "../../client/shared/widgets/Chart"),67 "devtools/client/sourceeditor/editor": "devtools-source-editor/src/source-editor",68 "devtools/shared/async-utils": path.join(__dirname, "../../shared/async-utils"),69 "devtools/shared/defer": path.join(__dirname, "../../shared/defer"),70 "devtools/shared/event-emitter": "devtools-modules/src/utils/event-emitter",71 "devtools/shared/fronts/timeline": path.join(__dirname, "../../shared/shims/fronts/timeline"),72 "devtools/shared/l10n": path.join(__dirname, "../../shared/l10n"),73 "devtools/shared/locales": path.join(__dirname, "../../shared/locales/en-US"),74 "devtools/shared/platform/clipboard": path.join(__dirname, "../../shared/platform/content/clipboard"),75 "devtools/shared/plural-form": path.join(__dirname, "../../shared/plural-form"),76 "devtools/shared/task": path.join(__dirname, "../../shared/task"),77 "toolkit/locales": path.join(__dirname, "../../../toolkit/locales/en-US"),78 "Services": "devtools-modules/src/Services",79 },80 },81};82const mappings = [83 [84 /chrome:\/\/devtools\/skin/,85 (result) => {86 result.request = result.request87 .replace("./chrome://devtools/skin", path.join(__dirname, "../themes"));88 }89 ],90 [91 /chrome:\/\/devtools\/content/,92 (result) => {93 result.request = result.request94 .replace("./chrome://devtools/content", path.join(__dirname, ".."));95 }96 ],97 [98 /resource:\/\/devtools/,99 (result) => {100 result.request = result.request101 .replace("./resource://devtools/client", path.join(__dirname, ".."));102 }103 ],104];105webpackConfig.plugins = mappings.map(([regex, res]) =>106 new NormalModuleReplacementPlugin(regex, res));107// Exclude to transpile all scripts in devtools/ but not for this folder108const basePath = path.join(__dirname, "../../").replace(/\\/g, "\\\\");109const baseName = path.basename(__dirname);110webpackConfig.babelExcludes = new RegExp(`^${basePath}(.(?!${baseName}))*$`);111let config = toolboxConfig(webpackConfig, getConfig());112// Remove loaders from devtools-launchpad's webpack.config.js113// * For svg-inline loader:114// Netmonitor uses file loader to bundle image assets instead of svg-inline loader115// * For raw loader:116// devtools/shared/l10n has preloaded raw loader in require.context117config.module.loaders = config.module.loaders118 .filter((loader) => !["svg-inline", "raw"].includes(loader.loader));...

Full Screen

Full Screen

sharedDeviceAccess.service.js

Source:sharedDeviceAccess.service.js Github

copy

Full Screen

1import httpStatus from 'http-status';2import { pick } from 'lodash';3import SharedDeviceAccess from '../models/sharedDeviceAccess.model';4import AppError from '../utils/AppError';5import { getQueryOptions } from '../utils/service.util';6const checkDuplicateSharedDeviceAccessService = async (deviceId, email, excludeDeviceId) => {7 const sharedDeviceAccess = await SharedDeviceAccess.findOne({ deviceId, email, _id: { $ne: excludeDeviceId } });8 if (sharedDeviceAccess) {9 throw new AppError(httpStatus.BAD_REQUEST, 'User already have access to device');10 }11};12const checkAccessIfExists = async (deviceId, email) => {13 const sharedDeviceAccess = await SharedDeviceAccess.findOne({ deviceId, email });14 if (!sharedDeviceAccess) {15 throw new AppError(httpStatus.FORBIDDEN, "User doesn't have access to the device");16 }17 return sharedDeviceAccess;18};19const createSharedDeviceAccessService = async sharedDeviceAccessBody => {20 await checkDuplicateSharedDeviceAccessService(sharedDeviceAccessBody.deviceId, sharedDeviceAccessBody.email);21 return SharedDeviceAccess.create(sharedDeviceAccessBody);22};23const getSharedDeviceAccessByIdService = async id => {24 const sharedDeviceAccess = await SharedDeviceAccess.findById(id);25 if (!sharedDeviceAccess) {26 throw new AppError(httpStatus.NOT_FOUND, 'No shared device access found with this id');27 }28 return sharedDeviceAccess;29};30const getSharedDeviceAccessesService = async query => {31 const filter = pick(query, ['id', 'deviceId', 'email', 'sharedBy', 'isDisabled']);32 const options = getQueryOptions(query);33 return SharedDeviceAccess.find(filter, null, options);34};35const deleteSharedDeviceAccessByDeviceIdService = async deviceId => {36 const sharedDeviceAccesses = await SharedDeviceAccess.find({ deviceId });37 return Promise.all(sharedDeviceAccesses.map(sharedDeviceAccess => sharedDeviceAccess.remove()));38};39const updateSharedDeviceAccessService = async (id, updateBody) => {40 const sharedDeviceAccess = await getSharedDeviceAccessByIdService(id);41 if (updateBody.deviceId || updateBody.email) {42 await checkDuplicateSharedDeviceAccessService(updateBody.deviceId, updateBody.email, id);43 }44 Object.assign(sharedDeviceAccess, updateBody);45 await sharedDeviceAccess.save();46 return sharedDeviceAccess;47};48const updateSharedDeviceAccessEmailService = async (oldEmail, newEmail) => {49 const sharedDeviceAccesses = await SharedDeviceAccess.find({ email: oldEmail });50 return Promise.all(51 sharedDeviceAccesses.map(async sharedDeviceAccess => {52 Object.assign(sharedDeviceAccess, { email: newEmail });53 await sharedDeviceAccess.save();54 return sharedDeviceAccess;55 })56 );57};58const deleteSharedDeviceAccessService = async id => {59 const sharedDeviceAccess = await getSharedDeviceAccessByIdService(id);60 await sharedDeviceAccess.remove();61 return sharedDeviceAccess;62};63const checkAndDeleteAccessIfExists = async (deviceId, email) => {64 const sharedDeviceAccesses = await SharedDeviceAccess.find({ deviceId, email });65 return Promise.all(sharedDeviceAccesses.map(sharedDeviceAccess => sharedDeviceAccess.remove()));66};67const deleteSharedDeviceAccessByUserEmailService = async email => {68 const sharedDeviceAccesses = await SharedDeviceAccess.find({ email });69 return Promise.all(sharedDeviceAccesses.map(sharedDeviceAccess => sharedDeviceAccess.remove()));70};71const getSharedDeviceAccessByDeviceIdService = deviceId => {72 return SharedDeviceAccess.find({ deviceId, isDisabled: false });73};74const getSharedDeviceAccessByEmailService = email => {75 return SharedDeviceAccess.find({ email, isDisabled: false });76};77module.exports = {78 checkDuplicateSharedDeviceAccessService,79 createSharedDeviceAccessService,80 getSharedDeviceAccessByIdService,81 getSharedDeviceAccessesService,82 updateSharedDeviceAccessService,83 updateSharedDeviceAccessEmailService,84 deleteSharedDeviceAccessByDeviceIdService,85 deleteSharedDeviceAccessService,86 deleteSharedDeviceAccessByUserEmailService,87 checkAndDeleteAccessIfExists,88 getSharedDeviceAccessByDeviceIdService,89 getSharedDeviceAccessByEmailService,90 checkAccessIfExists,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/*2 * Licensed to Elasticsearch B.V. under one or more contributor3 * license agreements. See the NOTICE file distributed with4 * this work for additional information regarding copyright5 * ownership. Elasticsearch B.V. licenses this file to you under6 * the Apache License, Version 2.0 (the "License"); you may7 * not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing,13 * software distributed under the License is distributed on an14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 * KIND, either express or implied. See the License for the16 * specific language governing permissions and limitations17 * under the License.18 */19const Path = require('path');20exports.distDir = Path.resolve(__dirname, 'target');21exports.jsDepFilenames = ['kbn-ui-shared-deps.@elastic.js'];22exports.jsFilename = 'kbn-ui-shared-deps.js';23exports.baseCssDistFilename = 'kbn-ui-shared-deps.css';24exports.lightCssDistFilename = 'kbn-ui-shared-deps.v7.light.css';25exports.lightV8CssDistFilename = 'kbn-ui-shared-deps.v8.light.css';26exports.darkCssDistFilename = 'kbn-ui-shared-deps.v7.dark.css';27exports.darkV8CssDistFilename = 'kbn-ui-shared-deps.v8.dark.css';28exports.externals = {29 // stateful deps30 angular: '__kbnSharedDeps__.Angular',31 '@kbn/i18n': '__kbnSharedDeps__.KbnI18n',32 '@kbn/i18n/angular': '__kbnSharedDeps__.KbnI18nAngular',33 '@kbn/i18n/react': '__kbnSharedDeps__.KbnI18nReact',34 jquery: '__kbnSharedDeps__.Jquery',35 moment: '__kbnSharedDeps__.Moment',36 'moment-timezone': '__kbnSharedDeps__.MomentTimezone',37 react: '__kbnSharedDeps__.React',38 'react-dom': '__kbnSharedDeps__.ReactDom',39 'react-dom/server': '__kbnSharedDeps__.ReactDomServer',40 'react-intl': '__kbnSharedDeps__.ReactIntl',41 'react-router': '__kbnSharedDeps__.ReactRouter',42 'react-router-dom': '__kbnSharedDeps__.ReactRouterDom',43 '@kbn/monaco': '__kbnSharedDeps__.KbnMonaco',44 // this is how plugins/consumers from npm load monaco45 'monaco-editor/esm/vs/editor/editor.api': '__kbnSharedDeps__.MonacoBarePluginApi',46 /**47 * big deps which are locked to a single version48 */49 rxjs: '__kbnSharedDeps__.Rxjs',50 'rxjs/operators': '__kbnSharedDeps__.RxjsOperators',51 numeral: '__kbnSharedDeps__.ElasticNumeral',52 '@elastic/numeral': '__kbnSharedDeps__.ElasticNumeral',53 '@elastic/charts': '__kbnSharedDeps__.ElasticCharts',54 '@elastic/eui': '__kbnSharedDeps__.ElasticEui',55 '@elastic/eui/lib/services': '__kbnSharedDeps__.ElasticEuiLibServices',56 '@elastic/eui/lib/services/format': '__kbnSharedDeps__.ElasticEuiLibServicesFormat',57 '@elastic/eui/dist/eui_charts_theme': '__kbnSharedDeps__.ElasticEuiChartsTheme',58 '@elastic/eui/dist/eui_theme_light.json': '__kbnSharedDeps__.ElasticEuiLightTheme',59 '@elastic/eui/dist/eui_theme_dark.json': '__kbnSharedDeps__.ElasticEuiDarkTheme',60 /**61 * massive deps that we should really get rid of or reduce in size substantially62 */63 elasticsearch: '__kbnSharedDeps__.ElasticsearchBrowser',64 'elasticsearch-browser': '__kbnSharedDeps__.ElasticsearchBrowser',65 'elasticsearch-browser/elasticsearch': '__kbnSharedDeps__.ElasticsearchBrowser',66};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wpt = new wptools();3var options = {4};5var page = wpt.page('Barack Obama', options);6page.get(function(err, info) {7 console.log(info);8});9### wptools.page(title, options)10### page.get(callback)11### page.getRevisions(callback)12### page.getImages(callback)13### page.getLinks(callback)14### page.getCategories(callback)15### page.getCoordinates(callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var options = {3};4wpt.runTest(url, options, function (err, data) {5 if (err) {6 console.log(err);7 }8 else {9 console.log(data);10 }11});12var request = require('request');13var exports = module.exports = {};14exports.runTest = function (url, options, callback) {15 var apiKey = 'API_KEY';16 var parameters = 'url=' + url + '&k=' + apiKey;17 for (var key in options) {18 if (options[key] !== '') {19 parameters = parameters + '&' + key + '=' + options[key];20 }21 }22 var fullUrl = apiUrl + parameters;23 request(fullUrl, function (error, response, body) {24 if (!error && response.statusCode == 200) {25 callback(null, body);26 }27 else {28 callback(error, null);29 }30 });31};

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = require('wpt');3var options = {4};5wpt.runTest(url, options, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data.data.runs[1].firstView.SpeedIndex);10 }11});12var wpt = require('wpt');13var options = {14};15wpt.runTest(url, options, function(err, data) {16 if (err) {17 console.log(err);18 } else {19 console.log(data.data.runs[1].firstView.SpeedIndex);20 }21});22var wpt = require('wpt');23var options = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2wpt.testUrl(testUrl, function(err, data) {3 if (err) {4 console.log(err);5 }6 else {7 console.log(data);8 }9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2wpt.getTestResults(12345, function(err, data) {3});4var wpt = require('wpt');5wpt.getTestResults(12345, function(err, data) {6});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2 console.log(data);3});4exports.runTest = function(url, callback) {5 var data = {6 };7 callback(data);8};

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt');2wpt.test('test', 'test', 'test', 'test', function(data) {3 console.log(data);4});5var wpt = require('webpagetest');6var wpt = new WebPageTest('www.webpagetest.org', 'A.9a3aefc3f3e0e8a1f1eaae6b0cf0a0d8');7exports.test = function(url, location, runs, connectivity, callback) {8 wpt.runTest(url, {9 }, function(err, data) {10 if (err) return console.log(err);11 callback(data);12 });13};

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt');2wpt.test('test', 'test', 'test', 'test', function(data) {3 console.log(data);4});5var wpt = require('webpagetest');6var wpt = new WebPageTest('www.webpagetest.org', 'A.9a3aefc3f3e0e8a1f1eaae6b0cf0a0d8');7exports.test = function(url, location, runs, connectivity, callback) {8 wpt.runTest(url, {9 }, function(err, data) {10 if (err) return console.log(err);11 callback(data);12 });13};

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('./wpt.js');2wpt.getTestStatus(12345678, function(status) {3 console.log(status);4});5## getTestStatus(testId, callback)6## getTestResults(testId, callback)7## getTestResultsByLocation(testId, location, callback)8## getTestResultsByLabel(testId, label, callback)9## getTestResultsByRun(testId, run, callback)10## getTestResultsByStep(testId, step, callback)11## getTestResultsByCached(testId, cached, callback)12## getTestResultsByConnectivity(testId, connectivity, callback)13## getTestResultsByLocationAndRun(testId, location, run, callback)14## getTestResultsByLocationAndStep(testId, location, step, callback)15## getTestResultsByLocationAndCached(testId, location, cached, callback)16## getTestResultsByLocationAndConnectivity(testId, location, connectivity, callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2 console.log(data);3});4exports.runTest = function(url, callback) {5 var data = {6 };7 callback(data);8};

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('./wpt.js');2wpt.getTestStatus(12345678, function(status) {3 console.log(status);4});5## getTestStatus(testId, callback)6## getTestResults(testId, callback)7## getTestResultsByLocation(testId, location, callback)8## getTestResultsByLabel(testId, label, callback)9## getTestResultsByRun(testId, run, callback)10## getTestResultsByStep(testId, step, callback)11## getTestResultsByCached(testId, cached, callback)12## getTestResultsByConnectivity(testId, connectivity, callback)13## getTestResultsByLocationAndRun(testId, location, run, callback)14## getTestResultsByLocationAndStep(testId, location, step, callback)15## getTestResultsByLocationAndCached(testId, location, cached, callback)16## getTestResultsByLocationAndConnectivity(testId, location, connectivity, callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('./wpt.js');2import { test } from 'wpt.js';3export { test };4import { test } from './wpt.js';5const wpt = require('wpt.js');6module.exports = wpt;7const wpt = require('./wpt.js');8define(['wpt.js'], function(wpt) {9 return wpt;10});11require(['./wpt.js'], function(wpt) {12});13(function(root, factory) {14 if (typeof define === 'function' && define.amd) {15 define(['wpt.js'], factory);16 } else if (typeof module === 'object' && module.exports) {17 module.exports = factory(require('wpt.js'));18 } else {19 root.returnExports = factory(root.wpt);20 }21})(this, function(wpt) {22 return wpt;23});24require(['./wpt.js'], function(wpt) {25});26System.register(['wpt.js'], function(_export) {27 return {28 function(_wptJs) {29 _export('default', _wptJs);30 }31 execute: function() {}32 };33});34System.import

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 wpt 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