Best JavaScript code snippet using jest
CollisionHelper.js
Source:CollisionHelper.js
...33 gravityFactor: 0,34 };3536 return function(oldPos, newPos, gravityFactor, ellipsoid, triangleIterator, stopOnFirstHit, horizontalOnly) {37 p.ellipsoidSpace.copy(ellipsoid);38 p.worldPosition.copy(oldPos);39 p.worldVelocity.subVectors(newPos, oldPos);4041 p.foundCollision = false;42 p.nearestDistance = 0;43 p.collisionRecursionDepth = 0;44 p.stopOnFirstHit = stopOnFirstHit;45 p.gravityFactor = gravityFactor;4647 var result = this.collisionSlide(p, triangleIterator);48 newPos.copy(result.pos);4950 return result;51 }52 }(),5354 collisionSlide: function(p, triangleIterator) {55 p.lspVelocity.copy(p.worldVelocity).divide(p.ellipsoidSpace);56 p.lspPosition.copy(p.worldPosition).divide(p.ellipsoidSpace);57 var oldY = p.lspPosition.y;5859 p.collisionRecursionDepth = 0;60 var finalPosition = this.collideWithWorld(p, triangleIterator);61 var climbing = (oldY < finalPosition.y);6263 if (p.gravityFactor !== 0 && !climbing && !p.horizontalOnly) {64 p.lspVelocity.copy(this.gravity);65 p.lspVelocity.y *= p.gravityFactor;66 p.lspVelocity.divide(p.ellipsoidSpace);67 p.lspPosition.copy(finalPosition);68 p.collisionRecursionDepth = 0;69 finalPosition = this.collideWithWorld(p, triangleIterator);70 }7172 finalPosition.multiply(p.ellipsoidSpace);7374 if (p.horizontalOnly) {75 finalPosition.y = p.originalHeight;76 }7778 var result = { 79 pos: finalPosition,80 climbing: climbing,81 foundCollision: p.foundCollision,82 gridObject: p.gridObject,83 normal: p.normal,84 };8586 return result;87 },8889 collideWithWorld: function() {90 var normal = new THREE.Vector3();91 var aux = new THREE.Vector3();92 var result = new THREE.Vector3();93 var destinationPoint = new THREE.Vector3();94 var newPosition = new THREE.Vector3();95 var slidePlaneOrigin = new THREE.Vector3();96 var slidePlaneNormal = new THREE.Vector3();97 var newDestinationPoint = new THREE.Vector3();98 var newVelocityVector = new THREE.Vector3();99 var v0 = new THREE.Vector3();100 var v1 = new THREE.Vector3();101 var v2 = new THREE.Vector3();102103 return function(p, triangleIterator) {104 var that = this;105106 var unitScale = this.unitsPerMeter / 100;107 var veryCloseDistance = 0.005 * unitScale;108109 if (p.collisionRecursionDepth > 5) {110 return p.lspPosition;111 }112113 p.lspNormalizedVelocity.copy(p.lspVelocity).normalize();114115 p.foundCollision = false;116 p.nearestDistance = 0;117118 triangleIterator(function(gridObject, t0, t1, t2, triangleOffset) {119 GAME.grid.totalSphereTriangleChecks++;120 121 v0.copy(t0).divide(p.ellipsoidSpace);122 v1.copy(t1).divide(p.ellipsoidSpace);123 v2.copy(t2).divide(p.ellipsoidSpace);124125 aux.subVectors(v2, v0);126 normal.copy(v1).sub(v0).cross(aux).normalize();127128 that.sphereCollidingWithTriangle(gridObject, p, v0, v1, v2, normal);129 });130131 if (!p.foundCollision) {132 result.copy(p.lspPosition).add(p.lspVelocity);133 return result;134 }135136 destinationPoint.copy(p.lspPosition).add(p.lspVelocity);137 newPosition.copy(p.lspPosition);138139 if (p.nearestDistance >= veryCloseDistance) {140 aux.copy(p.lspVelocity).normalize();141 aux.multiplyScalar(p.nearestDistance - veryCloseDistance);142 newPosition.copy(p.lspPosition).add(aux);143144 aux.normalize().multiplyScalar(veryCloseDistance);145 p.intersectionPoint.sub(aux);146 }147148 if (!p.stopOnFirstHit) {149 slidePlaneOrigin.copy(p.intersectionPoint);150 slidePlaneNormal.copy(newPosition).sub(p.intersectionPoint).normalize();151152 var x = slidePlaneOrigin.x;153 var y = slidePlaneOrigin.y;154 var z = slidePlaneOrigin.z;155156 var A = slidePlaneNormal.x;157 var B = slidePlaneNormal.y;158 var C = slidePlaneNormal.z;159 var D = -((A * x) + (B * y) + (C * z));160161 var planeConstant = D;162163 var signedDistFromDestPointToSlidingPlane = slidePlaneNormal.dot(destinationPoint) + planeConstant;164165 aux.copy(slidePlaneNormal).multiplyScalar(signedDistFromDestPointToSlidingPlane);166 newDestinationPoint.copy(destinationPoint).sub(aux);167 newVelocityVector.copy(newDestinationPoint).sub(p.intersectionPoint);168169 if (newVelocityVector.length() < veryCloseDistance) {170 return newPosition;171 }172173 p.collisionRecursionDepth++;174 p.lspPosition.copy(newPosition);175 p.lspVelocity.copy(newVelocityVector);176177 return this.collideWithWorld(p, triangleIterator);178 } else {179 p.lspPosition.copy(newPosition);180 return p.lspPosition;181 }182 }183 }(),184185 sphereCollidingWithTriangle: function() {186 var velocity = new THREE.Vector3();187 var position = new THREE.Vector3();188 var aux = new THREE.Vector3();189 var planeIntersectionPoint = new THREE.Vector3();190 var collisionPoint = new THREE.Vector3();191 var edge = new THREE.Vector3();192 var spherePositionToVertex = new THREE.Vector3();193194 return function(gridObject, p, v0, v1, v2, normal) {195 var facing = normal.dot(p.lspNormalizedVelocity); 196 if (facing <= 0) {197 velocity.copy(p.lspVelocity);198 position.copy(p.lspPosition);199200 var t0, t1;201 var sphereInPlane = false;202203 var A = normal.x;204 var B = normal.y;205 var C = normal.z;206 var D = -((A * v0.x) + (B * v0.y) + (C * v0.z));207208 var planeConstant = D;209210 var signedDistFromPositionToTriPlane = position.dot(normal) + planeConstant;211 var planeNormalDotVelocity = normal.dot(velocity);212213 if (planeNormalDotVelocity === 0) {214 if (Math.abs(signedDistFromPositionToTriPlane) >= 1) {215 return false;216 } else {217 sphereInPlane = true;218 }219 } else {220 t0 = (1 - signedDistFromPositionToTriPlane) / planeNormalDotVelocity;221 t1 = (-1 - signedDistFromPositionToTriPlane) / planeNormalDotVelocity;222223 if (t0 > t1) {224 var temp = t0;225 t0 = t1;226 t1 = temp;227 }228229 if (t0 > 1 || t1 < 0) {230 return false;231 }232233 if (t0 < 0) {234 t0 = 0;235 }236 if (t1 > 1) {237 t1 = 1;238 }239 }240241 var collidingWithTri = false;242 var t = 1;243244 if (!sphereInPlane) {245 aux.copy(velocity).multiplyScalar(t0);246 planeIntersectionPoint.copy(position).add(aux).sub(normal);247248 if (this.checkPointInTriangle(planeIntersectionPoint, v0, v1, v2)) {249 collidingWithTri = true;250 t = t0;251 collisionPoint.copy(planeIntersectionPoint);252 }253 }254255 if (!collidingWithTri) {256 var a, b, c;257 var velocityLengthSquared = velocity.lengthSq();258 a = velocityLengthSquared;259 var result = {};260261 aux.copy(position).sub(v0);262 b = 2 * velocity.dot(aux);263 aux.copy(v0).sub(position);264 c = aux.length();265 c = c * c - 1;266 if (this.getLowestRoot(a, b, c, t, result)) {267 t = result.root;268 collidingWithTri = true;269 collisionPoint.copy(v0);270 }271272 aux.copy(position).sub(v1);273 b = 2 * velocity.dot(aux);274 aux.copy(v1).sub(position);275 c = aux.length();276 c = c * c - 1;277 if (this.getLowestRoot(a, b, c, t, result)) {278 t = result.root;279 collidingWithTri = true;280 collisionPoint.copy(v1);281 }282283 aux.copy(position).sub(v2);284 b = 2 * velocity.dot(aux);285 aux.copy(v2).sub(position);286 c = aux.length();287 c = c * c - 1;288 if (this.getLowestRoot(a, b, c, t, result)) {289 t = result.root;290 collidingWithTri = true;291 collisionPoint.copy(v2);292 }293294 edge.copy(v1).sub(v0);295 spherePositionToVertex.copy(v0).sub(position);296 var edgeLengthSquared = edge.lengthSq();297 var edgeDotVelocity = edge.dot(velocity);298 var edgeDotSpherePositionToVertex = edge.dot(spherePositionToVertex);299 var spherePositionToVertexLengthSquared = spherePositionToVertex.lengthSq();300301 a = edgeLengthSquared * -velocityLengthSquared + (edgeDotVelocity * edgeDotVelocity);302 b = edgeLengthSquared * 2 * velocity.dot(spherePositionToVertex) - 2 * edgeDotVelocity * edgeDotSpherePositionToVertex;303 c = edgeLengthSquared * (1 - spherePositionToVertexLengthSquared) + 304 (edgeDotSpherePositionToVertex * edgeDotSpherePositionToVertex);305306 if (this.getLowestRoot(a, b, c, t, result)) {307 var f = (edgeDotVelocity * result.root - edgeDotSpherePositionToVertex) / edgeLengthSquared;308 if (f >= 0 && f <= 1) {309 t = result.root;310 collidingWithTri = true;311 edge.multiplyScalar(f);312 collisionPoint.copy(v0).add(edge);313 }314 }315316 edge.copy(v2).sub(v1);317 spherePositionToVertex.copy(v1).sub(position);318 edgeLengthSquared = edge.lengthSq();319 edgeDotVelocity = edge.dot(velocity);320 edgeDotSpherePositionToVertex = edge.dot(spherePositionToVertex);321 spherePositionToVertexLengthSquared = spherePositionToVertex.lengthSq();322323 a = edgeLengthSquared * -velocityLengthSquared + (edgeDotVelocity * edgeDotVelocity);324 b = edgeLengthSquared * 2 * velocity.dot(spherePositionToVertex) - 2 * edgeDotVelocity * edgeDotSpherePositionToVertex;325 c = edgeLengthSquared * (1 - spherePositionToVertexLengthSquared) + 326 (edgeDotSpherePositionToVertex * edgeDotSpherePositionToVertex);327328 if (this.getLowestRoot(a, b, c, t, result)) {329 var f = (edgeDotVelocity * result.root - edgeDotSpherePositionToVertex) / edgeLengthSquared;330 if (f >= 0 && f <= 1) {331 t = result.root;332 collidingWithTri = true;333 edge.multiplyScalar(f);334 collisionPoint.copy(v1).add(edge);335 }336 }337338 edge.copy(v0).sub(v2);339 spherePositionToVertex.copy(v2).sub(position);340 edgeLengthSquared = edge.lengthSq();341 edgeDotVelocity = edge.dot(velocity);342 edgeDotSpherePositionToVertex = edge.dot(spherePositionToVertex);343 spherePositionToVertexLengthSquared = spherePositionToVertex.lengthSq();344345 a = edgeLengthSquared * -velocityLengthSquared + (edgeDotVelocity * edgeDotVelocity);346 b = edgeLengthSquared * 2 * velocity.dot(spherePositionToVertex) - 2 * edgeDotVelocity * edgeDotSpherePositionToVertex;347 c = edgeLengthSquared * (1 - spherePositionToVertexLengthSquared) + 348 (edgeDotSpherePositionToVertex * edgeDotSpherePositionToVertex);349350 if (this.getLowestRoot(a, b, c, t, result)) {351 var f = (edgeDotVelocity * result.root - edgeDotSpherePositionToVertex) / edgeLengthSquared;352 if (f >= 0 && f <= 1) {353 t = result.root;354 collidingWithTri = true;355 edge.multiplyScalar(f);356 collisionPoint.copy(v2).add(edge);357 }358 }359 }360361 if (collidingWithTri) {362 var distToCollision = t * velocity.length();363 if (!p.foundCollision || distToCollision < p.nearestDistance) {364 p.nearestDistance = distToCollision;365 p.intersectionPoint.copy(collisionPoint);366 p.foundCollision = true;367 p.normal.copy(normal);368 p.gridObject = gridObject;369370 return true;371 }372 }373 }374375 return false;376 }377 }(),378379 checkPointInTriangle: function() {380 var cp1 = new THREE.Vector3();381 var cp2 = new THREE.Vector3();382 var aux = new THREE.Vector3();383 var aux2 = new THREE.Vector3();384385 return function(point, v1, v2, v3) {386 aux.copy(v3).sub(v2);387 aux2.copy(point).sub(v2);388 cp1.crossVectors(aux, aux2);389390 aux.copy(v3).sub(v2);391 aux2.copy(v1).sub(v2);392 cp2.crossVectors(aux, aux2);393394 if (cp1.dot(cp2) >= 0) {395 aux.copy(v3).sub(v1);396 aux2.copy(point).sub(v1);397 cp1.crossVectors(aux, aux2);398399 aux.copy(v3).sub(v1);400 aux2.copy(v2).sub(v1);401 cp2.crossVectors(aux, aux2);402403 if (cp1.dot(cp2) >= 0) {404 aux.copy(v2).sub(v1);405 aux2.copy(point).sub(v1);406 cp1.crossVectors(aux, aux2);407408 aux.copy(v2).sub(v1);409 aux2.copy(v3).sub(v1);410 cp2.crossVectors(aux, aux2);411412 if (cp1.dot(cp2) >= 0) {413 return true;414 }415 }416 }417 }418 }(),419420 getLowestRoot: function(a, b, c, maxR, result) {421 var determinant = b * b - 4 * a * c;422 if (determinant < 0) {423 return false;
...
Manager.js
Source:Manager.js
1define([2 "../_base/array", "../_base/declare", "../_base/lang", "../_base/window",3 "../dom-class", "../Evented", "../has", "../keys", "../on", "../topic", "../touch",4 "./common", "./autoscroll", "./Avatar"5], function(array, declare, lang, win, domClass, Evented, has, keys, on, topic, touch,6 dnd, autoscroll, Avatar){7// module:8// dojo/dnd/Manager9var Manager = declare("dojo.dnd.Manager", [Evented], {10 // summary:11 // the manager of DnD operations (usually a singleton)12 constructor: function(){13 this.avatar = null;14 this.source = null;15 this.nodes = [];16 this.copy = true;17 this.target = null;18 this.canDropFlag = false;19 this.events = [];20 },21 // avatar's offset from the mouse22 OFFSET_X: has("touch") ? 0 : 16,23 OFFSET_Y: has("touch") ? -64 : 16,24 // methods25 overSource: function(source){26 // summary:27 // called when a source detected a mouse-over condition28 // source: Object29 // the reporter30 if(this.avatar){31 this.target = (source && source.targetState != "Disabled") ? source : null;32 this.canDropFlag = Boolean(this.target);33 this.avatar.update();34 }35 topic.publish("/dnd/source/over", source);36 },37 outSource: function(source){38 // summary:39 // called when a source detected a mouse-out condition40 // source: Object41 // the reporter42 if(this.avatar){43 if(this.target == source){44 this.target = null;45 this.canDropFlag = false;46 this.avatar.update();47 topic.publish("/dnd/source/over", null);48 }49 }else{50 topic.publish("/dnd/source/over", null);51 }52 },53 startDrag: function(source, nodes, copy){54 // summary:55 // called to initiate the DnD operation56 // source: Object57 // the source which provides items58 // nodes: Array59 // the list of transferred items60 // copy: Boolean61 // copy items, if true, move items otherwise62 // Tell autoscroll that a drag is starting63 autoscroll.autoScrollStart(win.doc);64 this.source = source;65 this.nodes = nodes;66 this.copy = Boolean(copy); // normalizing to true boolean67 this.avatar = this.makeAvatar();68 win.body().appendChild(this.avatar.node);69 topic.publish("/dnd/start", source, nodes, this.copy);70 function stopEvent(e){71 e.preventDefault();72 e.stopPropagation();73 }74 this.events = [75 on(win.doc, touch.move, lang.hitch(this, "onMouseMove")),76 on(win.doc, touch.release, lang.hitch(this, "onMouseUp")),77 on(win.doc, "keydown", lang.hitch(this, "onKeyDown")),78 on(win.doc, "keyup", lang.hitch(this, "onKeyUp")),79 // cancel text selection and text dragging80 on(win.doc, "dragstart", stopEvent),81 on(win.body(), "selectstart", stopEvent)82 ];83 var c = "dojoDnd" + (copy ? "Copy" : "Move");84 domClass.add(win.body(), c);85 },86 canDrop: function(flag){87 // summary:88 // called to notify if the current target can accept items89 var canDropFlag = Boolean(this.target && flag);90 if(this.canDropFlag != canDropFlag){91 this.canDropFlag = canDropFlag;92 this.avatar.update();93 }94 },95 stopDrag: function(){96 // summary:97 // stop the DnD in progress98 domClass.remove(win.body(), ["dojoDndCopy", "dojoDndMove"]);99 array.forEach(this.events, function(handle){ handle.remove(); });100 this.events = [];101 this.avatar.destroy();102 this.avatar = null;103 this.source = this.target = null;104 this.nodes = [];105 },106 makeAvatar: function(){107 // summary:108 // makes the avatar; it is separate to be overwritten dynamically, if needed109 return new Avatar(this);110 },111 updateAvatar: function(){112 // summary:113 // updates the avatar; it is separate to be overwritten dynamically, if needed114 this.avatar.update();115 },116 // mouse event processors117 onMouseMove: function(e){118 // summary:119 // event processor for onmousemove120 // e: Event121 // mouse event122 var a = this.avatar;123 if(a){124 autoscroll.autoScrollNodes(e);125 //autoscroll.autoScroll(e);126 var s = a.node.style;127 s.left = (e.pageX + this.OFFSET_X) + "px";128 s.top = (e.pageY + this.OFFSET_Y) + "px";129 var copy = Boolean(this.source.copyState(dnd.getCopyKeyState(e)));130 if(this.copy != copy){131 this._setCopyStatus(copy);132 }133 }134 if(has("touch")){135 // Prevent page from scrolling so that user can drag instead.136 e.preventDefault();137 }138 },139 onMouseUp: function(e){140 // summary:141 // event processor for onmouseup142 // e: Event143 // mouse event144 if(this.avatar){145 if(this.target && this.canDropFlag){146 var copy = Boolean(this.source.copyState(dnd.getCopyKeyState(e)));147 topic.publish("/dnd/drop/before", this.source, this.nodes, copy, this.target, e);148 topic.publish("/dnd/drop", this.source, this.nodes, copy, this.target, e);149 }else{150 topic.publish("/dnd/cancel");151 }152 this.stopDrag();153 }154 },155 // keyboard event processors156 onKeyDown: function(e){157 // summary:158 // event processor for onkeydown:159 // watching for CTRL for copy/move status, watching for ESCAPE to cancel the drag160 // e: Event161 // keyboard event162 if(this.avatar){163 switch(e.keyCode){164 case keys.CTRL:165 var copy = Boolean(this.source.copyState(true));166 if(this.copy != copy){167 this._setCopyStatus(copy);168 }169 break;170 case keys.ESCAPE:171 topic.publish("/dnd/cancel");172 this.stopDrag();173 break;174 }175 }176 },177 onKeyUp: function(e){178 // summary:179 // event processor for onkeyup, watching for CTRL for copy/move status180 // e: Event181 // keyboard event182 if(this.avatar && e.keyCode == keys.CTRL){183 var copy = Boolean(this.source.copyState(false));184 if(this.copy != copy){185 this._setCopyStatus(copy);186 }187 }188 },189 // utilities190 _setCopyStatus: function(copy){191 // summary:192 // changes the copy status193 // copy: Boolean194 // the copy status195 this.copy = copy;196 this.source._markDndStatus(this.copy);197 this.updateAvatar();198 domClass.replace(win.body(),199 "dojoDnd" + (this.copy ? "Copy" : "Move"),200 "dojoDnd" + (this.copy ? "Move" : "Copy"));201 }202});203// dnd._manager:204// The manager singleton variable. Can be overwritten if needed.205dnd._manager = null;206Manager.manager = dnd.manager = function(){207 // summary:208 // Returns the current DnD manager. Creates one if it is not created yet.209 if(!dnd._manager){210 dnd._manager = new Manager();211 }212 return dnd._manager; // Object213};214// TODO: for 2.0, store _manager and manager in Manager only. Don't access dnd or dojo.dnd.215return Manager;...
copybutton.js
Source:copybutton.js
1// Localization support2const messages = {3 'en': {4 'copy': 'Copy',5 'copy_to_clipboard': 'Copy to clipboard',6 'copy_success': 'Copied!',7 'copy_failure': 'Failed to copy',8 },9 'es' : {10 'copy': 'Copiar',11 'copy_to_clipboard': 'Copiar al portapapeles',12 'copy_success': '¡Copiado!',13 'copy_failure': 'Error al copiar',14 },15 'de' : {16 'copy': 'Kopieren',17 'copy_to_clipboard': 'In die Zwischenablage kopieren',18 'copy_success': 'Kopiert!',19 'copy_failure': 'Fehler beim Kopieren',20 }21}22let locale = 'en'23if( document.documentElement.lang !== undefined24 && messages[document.documentElement.lang] !== undefined ) {25 locale = document.documentElement.lang26}27/**28 * Set up copy/paste for code blocks29 */30const runWhenDOMLoaded = cb => {31 if (document.readyState != 'loading') {32 cb()33 } else if (document.addEventListener) {34 document.addEventListener('DOMContentLoaded', cb)35 } else {36 document.attachEvent('onreadystatechange', function() {37 if (document.readyState == 'complete') cb()38 })39 }40}41const codeCellId = index => `codecell${index}`42// Clears selected text since ClipboardJS will select the text when copying43const clearSelection = () => {44 if (window.getSelection) {45 window.getSelection().removeAllRanges()46 } else if (document.selection) {47 document.selection.empty()48 }49}50// Changes tooltip text for two seconds, then changes it back51const temporarilyChangeTooltip = (el, newText) => {52 const oldText = el.getAttribute('data-tooltip')53 el.setAttribute('data-tooltip', newText)54 setTimeout(() => el.setAttribute('data-tooltip', oldText), 2000)55}56const addCopyButtonToCodeCells = () => {57 // If ClipboardJS hasn't loaded, wait a bit and try again. This58 // happens because we load ClipboardJS asynchronously.59 if (window.ClipboardJS === undefined) {60 setTimeout(addCopyButtonToCodeCells, 250)61 return62 }63 // Add copybuttons to all of our code cells64 const codeCells = document.querySelectorAll('div.highlight pre')65 codeCells.forEach((codeCell, index) => {66 const id = codeCellId(index)67 codeCell.setAttribute('id', id)68 const pre_bg = getComputedStyle(codeCell).backgroundColor;69 const clipboardButton = id =>70 `<a class="copybtn o-tooltip--left" style="background-color: ${pre_bg}" data-tooltip="${messages[locale]['copy']}" data-clipboard-target="#${id}">71 <img src="${DOCUMENTATION_OPTIONS.URL_ROOT}_static/copy-button.svg" alt="${messages[locale]['copy_to_clipboard']}">72 </a>`73 codeCell.insertAdjacentHTML('afterend', clipboardButton(id))74 })75function escapeRegExp(string) {76 return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string77}78// Callback when a copy button is clicked. Will be passed the node that was clicked79// should then grab the text and replace pieces of text that shouldn't be used in output80function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true) {81 var regexp;82 var match;83 // create regexp to capture prompt and remaining line84 if (isRegexp) {85 regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)')86 } else {87 regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)')88 }89 const outputLines = [];90 var promptFound = false;91 for (const line of textContent.split('\n')) {92 match = line.match(regexp)93 if (match) {94 promptFound = true95 if (removePrompts) {96 outputLines.push(match[2])97 } else {98 outputLines.push(line)99 }100 } else {101 if (!onlyCopyPromptLines) {102 outputLines.push(line)103 }104 }105 }106 // If no lines with the prompt were found then just use original lines107 if (promptFound) {108 textContent = outputLines.join('\n');109 }110 // Remove a trailing newline to avoid auto-running when pasting111 if (textContent.endsWith("\n")) {112 textContent = textContent.slice(0, -1)113 }114 return textContent115}116var copyTargetText = (trigger) => {117 var target = document.querySelector(trigger.attributes['data-clipboard-target'].value);118 return formatCopyText(target.innerText, '', false, true, true)119}120 // Initialize with a callback so we can modify the text before copy121 const clipboard = new ClipboardJS('.copybtn', {text: copyTargetText})122 // Update UI with error/success messages123 clipboard.on('success', event => {124 clearSelection()125 temporarilyChangeTooltip(event.trigger, messages[locale]['copy_success'])126 })127 clipboard.on('error', event => {128 temporarilyChangeTooltip(event.trigger, messages[locale]['copy_failure'])129 })130}...
bootstrap-table-copy-rows.js
Source:bootstrap-table-copy-rows.js
1/**2 * @author Homer Glascock <HopGlascock@gmail.com>3 * @version: v1.0.04 */5 !function ($) {6 "use strict";7 var calculateObjectValue = $.fn.bootstrapTable.utils.calculateObjectValue,8 sprintf = $.fn.bootstrapTable.utils.sprintf;9 var copytext = function (text) {10 var textField = document.createElement('textarea');11 $(textField).html(text);12 document.body.appendChild(textField);13 textField.select();14 try {15 document.execCommand('copy');16 }17 catch (e) {18 console.log("Oops, unable to copy");19 }20 $(textField).remove();21 };22 $.extend($.fn.bootstrapTable.defaults, {23 copyBtn: false,24 copyWHiddenBtn: false,25 copyDelemeter: ", "26 });27 $.fn.bootstrapTable.methods.push('copyColumnsToClipboard', 'copyColumnsToClipboardWithHidden');28 var BootstrapTable = $.fn.bootstrapTable.Constructor,29 _initToolbar = BootstrapTable.prototype.initToolbar;30 BootstrapTable.prototype.initToolbar = function () {31 _initToolbar.apply(this, Array.prototype.slice.apply(arguments));32 var that = this,33 $btnGroup = this.$toolbar.find('>.btn-group');34 if (this.options.clickToSelect || this.options.singleSelect) {35 if (this.options.copyBtn) {36 var copybtn = "<button class='btn btn-default' id='copyBtn'><span class='glyphicon glyphicon-copy icon-pencil'></span></button>";37 $btnGroup.append(copybtn);38 $btnGroup.find('#copyBtn').click(function () { that.copyColumnsToClipboard(); });39 }40 if (this.options.copyWHiddenBtn) {41 var copyhiddenbtn = "<button class='btn btn-default' id='copyWHiddenBtn'><span class='badge'><span class='glyphicon glyphicon-copy icon-pencil'></span></span></button>";42 $btnGroup.append(copyhiddenbtn);43 $btnGroup.find('#copyWHiddenBtn').click(function () { that.copyColumnsToClipboardWithHidden(); });44 }45 }46 };47 BootstrapTable.prototype.copyColumnsToClipboard = function () {48 var that = this,49 ret = "",50 delimet = this.options.copyDelemeter;51 $.each(that.getSelections(), function (index, row) {52 $.each(that.options.columns[0], function (indy, column) {53 if (column.field !== "state" && column.field !== "RowNumber" && column.visible) {54 if (row[column.field] !== null) {55 ret += calculateObjectValue(column, that.header.formatters[indy], [row[column.field], row, index], row[column.field]);56 }57 ret += delimet;58 }59 });60 ret += "\r\n";61 });62 copytext(ret);63 };64 BootstrapTable.prototype.copyColumnsToClipboardWithHidden = function () {65 var that = this,66 ret = "",67 delimet = this.options.copyDelemeter;68 $.each(that.getSelections(), function (index, row) {69 $.each(that.options.columns[0], function (indy, column) {70 if (column.field != "state" && column.field !== "RowNumber") {71 if (row[column.field] !== null) {72 ret += calculateObjectValue(column, that.header.formatters[indy], [row[column.field], row, index], row[column.field]);73 }74 ret += delimet;75 }76 });77 ret += "\r\n";78 });79 copytext(ret);80 };...
HtmlDragCopy.js
Source:HtmlDragCopy.js
1/*2 Copyright (c) 2004-2006, The Dojo Foundation3 All Rights Reserved.4 Licensed under the Academic Free License version 2.1 or above OR the5 modified BSD license. For more information on Dojo licensing, see:6 http://dojotoolkit.org/community/licensing.shtml7*/8dojo.provide("dojo.dnd.HtmlDragCopy");9dojo.require("dojo.dnd.*");10dojo.declare("dojo.dnd.HtmlDragCopySource", dojo.dnd.HtmlDragSource,11function(node, type, copyOnce){12 this.copyOnce = copyOnce;13 this.makeCopy = true;14},15{16 onDragStart: function(){17 var dragObj = new dojo.dnd.HtmlDragCopyObject(this.dragObject, this.type, this);18 if(this.dragClass) { dragObj.dragClass = this.dragClass; }19 if (this.constrainToContainer) {20 dragObj.constrainTo(this.constrainingContainer || this.domNode.parentNode);21 }22 return dragObj;23 },24 onSelected: function() {25 for (var i=0; i<this.dragObjects.length; i++) {26 dojo.dnd.dragManager.selectedSources.push(new dojo.dnd.HtmlDragCopySource(this.dragObjects[i]));27 }28 }29});30dojo.declare("dojo.dnd.HtmlDragCopyObject", dojo.dnd.HtmlDragObject,31function(dragObject, type, source){32 this.copySource = source;33},34{35 onDragStart: function(e) {36 dojo.dnd.HtmlDragCopyObject.superclass.onDragStart.apply(this, arguments);37 if(this.copySource.makeCopy) {38 this.sourceNode = this.domNode;39 this.domNode = this.domNode.cloneNode(true);40 }41 },42 onDragEnd: function(e){43 switch(e.dragStatus){44 case "dropFailure": // slide back to the start45 var startCoords = dojo.html.getAbsolutePosition(this.dragClone, true);46 // offset the end so the effect can be seen47 var endCoords = { left: this.dragStartPosition.x + 1,48 top: this.dragStartPosition.y + 1};49 // animate50 var anim = dojo.lfx.slideTo(this.dragClone, endCoords, 500, dojo.lfx.easeOut);51 var dragObject = this;52 dojo.event.connect(anim, "onEnd", function (e) {53 // pause for a second (not literally) and disappear54 dojo.lang.setTimeout(function() {55 dojo.html.removeNode(dragObject.dragClone);56 dragObject.dragClone = null;57 if(dragObject.copySource.makeCopy) {58 dojo.html.removeNode(dragObject.domNode);59 dragObject.domNode = dragObject.sourceNode;60 dragObject.sourceNode = null;61 }62 },63 200);64 });65 anim.play();66 dojo.event.topic.publish('dragEnd', { source: this } );67 return;68 }69 dojo.dnd.HtmlDragCopyObject.superclass.onDragEnd.apply(this, arguments);70 this.copySource.dragObject = this.domNode;71 if(this.copySource.copyOnce){72 this.copySource.makeCopy = false;73 }74 new dojo.dnd.HtmlDragCopySource(this.sourceNode, this.type, this.copySource.copyOnce);75 this.sourceNode = null;76 }...
index.js
Source:index.js
1// @flow2import React, { Component } from 'react';3import Clipboard from 'clipboard';4import { COLORS } from 'shared/constants/tetromino';5import Button from '../Button';6type Props = {7 disabled: boolean,8 copyText: string,9 defaultLabel: string,10 successLabel: string,11 errorLabel: string12};13type LocalState = {14 copyStatus: null | 'success' | 'error'15};16export default class CopyButton extends Component<Props, LocalState> {17 clipboard: ?typeof Clipboard;18 state = {19 copyStatus: null20 };21 componentWillUnmount() {22 if (this.clipboard) {23 this.clipboard.destroy();24 }25 }26 handleCopyBtnRef = (node: ?HTMLElement) => {27 if (node) {28 const clipboard = new Clipboard(node);29 clipboard.on('success', this.handleCopySuccess);30 clipboard.on('error', this.handleCopyError);31 this.clipboard = clipboard;32 }33 };34 handleCopySuccess = () => {35 this.setState({36 copyStatus: 'success'37 });38 };39 handleCopyError = () => {40 this.setState({41 copyStatus: 'error'42 });43 };44 render() {45 const {46 disabled,47 copyText,48 defaultLabel,49 successLabel,50 errorLabel51 } = this.props;52 const { copyStatus } = this.state;53 let bgColor;54 switch (copyStatus) {55 case 'success':56 bgColor = COLORS.S;57 break;58 case 'error':59 bgColor = COLORS.Z;60 break;61 default:62 bgColor = COLORS.J;63 }64 return !disabled ? (65 <div ref={this.handleCopyBtnRef} data-clipboard-text={copyText}>66 <Button bgColor={bgColor} color="#fff">67 {!copyStatus && defaultLabel}68 {copyStatus === 'success' && successLabel}69 {copyStatus === 'error' && errorLabel}70 </Button>71 </div>72 ) : (73 <div>74 <Button disabled bgColor={bgColor} color="#fff">75 {defaultLabel}76 </Button>77 </div>78 );79 }...
index.fixture.js
Source:index.fixture.js
1// @flow2import React from 'react';3import { StateMock } from '@react-mock/state';4import CopyButton from '.';5export default {6 default: (7 <CopyButton8 disabled={false}9 copyText="I made you copy me!"10 defaultLabel="Copy link"11 successLabel="Link copied!"12 errorLabel="Copy failed :("13 />14 ),15 disabled: (16 <CopyButton17 disabled={true}18 copyText="I made you copy me!"19 defaultLabel="Copy link"20 successLabel="Link copied!"21 errorLabel="Copy failed :("22 />23 ),24 'copy success': (25 <StateMock state={{ copyStatus: 'success' }}>26 <CopyButton27 disabled={false}28 copyText="I made you copy me!"29 defaultLabel="Copy link"30 successLabel="Link copied!"31 errorLabel="Copy failed :("32 />33 </StateMock>34 ),35 'copy error': (36 <StateMock state={{ copyStatus: 'error' }}>37 <CopyButton38 disabled={false}39 copyText="I made you copy me!"40 defaultLabel="Copy link"41 successLabel="Link copied!"42 errorLabel="Copy failed :("43 />44 </StateMock>45 )...
copy-clipboard.js
Source:copy-clipboard.js
1$(function () {2 $(".js-copy-icon").on("click", function () {3 if (copyText(String($(this).prev(".postbox-url__url").text()))) {4 $('head').append('<style>.postbox-url__description:after { content: "copied!!"; } </style>');5 }6 });7 $(".js-copy-icon").mouseover(function (e) {8 $('head').append('<style>.postbox-url__description:after { content: "click to copy"; } </style>');9 });10 $(".js-copy-icon").mouseout(function (e) {11 $('head').append('<style>.postbox-url__description:after { content: "click to copy"; } </style>');12 });13 function copyText(copyText) {14 const copyFrom = document.createElement("textarea");15 copyFrom.textContent = copyText;16 const bodyElm = document.getElementsByTagName("body")[0];17 bodyElm.appendChild(copyFrom);18 copyFrom.select();19 const retVal = document.execCommand('copy');20 bodyElm.removeChild(copyFrom);21 return retVal;22 }...
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!