Best JavaScript code snippet using puppeteer
dndListSpec.js
Source:dndListSpec.js
1describe('dndList', function() {2 it('hides the placeholder element', function() {3 var element = compileAndLink('<dnd-list><img class="dndPlaceholder"></dnd-list>');4 expect(element.children().length).toBe(0);5 });6 it('disallows dropping if dnd-disable-if is true', function() {7 var source = compileAndLink('<div dnd-draggable="{}"></div>');8 var element = compileAndLink('<div dnd-list="[]" dnd-disable-if="disabled"></div>');9 element.scope().disabled = true;10 forAllHandlers(Dragstart.on(source).dragenter(element), element, verifyDropCancelled);11 });12 it('allows drop if dnd-disable-if is false', function() {13 var source = compileAndLink('<div dnd-draggable="{}"></div>');14 var element = compileAndLink('<div dnd-list="[]" dnd-disable-if="disabled"></div>');15 forAllHandlers(Dragstart.on(source).dragenter(element), element, verifyDropAccepted);16 });17 it('disallows dropping from external sources', function() {18 var element = compileAndLink('<div dnd-list="[]"></div>');19 var dragenter = Dragenter.validExternalOn(element);20 forAllHandlers(dragenter, element, verifyDropCancelled);21 });22 it('allows dropping from external sources if dnd-external-sources is set', function() {23 var element = compileAndLink('<div dnd-list="[]" dnd-external-sources="true"></div>');24 var dragenter = Dragenter.validExternalOn(element);25 forAllHandlers(dragenter, element, verifyDropAccepted);26 });27 it('disallows drop without valid mime types', function() {28 var element = compileAndLink('<div dnd-list="[]" dnd-external-sources="true"></div>');29 var dragenter = Dragenter.externalOn(element, {'text/plain': '{}'});30 forAllHandlers(dragenter, element, verifyDropCancelled);31 });32 // Old Internet Explorer versions don't have dataTransfer.types.33 it('allows drop if dataTransfer.types is undefined', function() {34 var element = compileAndLink('<div dnd-list="[]" dnd-external-sources="true"></div>');35 var data = angular.toJson({item: {}, type: 'mytype'});36 var dragenter = Dragenter.externalOn(element, {'Text': data}, {undefinedTypes: true});37 forAllHandlers(dragenter, element, verifyDropAccepted);38 });39 it('allows drop if dataTransfer.types contains "Text"', function() {40 var element = compileAndLink('<div dnd-list="[]" dnd-external-sources="true"></div>');41 var data = angular.toJson({item: {}, type: 'mytype'});42 var dragenter = Dragenter.externalOn(element, {'Text': data});43 forAllHandlers(dragenter, element, verifyDropAccepted);44 });45 it('allows drop if dataTransfer.types contains "application/json"', function() {46 var element = compileAndLink('<div dnd-list="[]" dnd-external-sources="true"></div>');47 var data = angular.toJson({item: {}, type: 'mytype'});48 var dragenter = Dragenter.externalOn(element, {'x-pdf': '{}', 'application/json': data});49 forAllHandlers(dragenter, element, verifyDropAccepted);50 });51 it('disallows dropping untyped elements if dnd-allowed-types is set', function() {52 var source = compileAndLink('<div dnd-draggable="{}"></div>');53 var element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'mytype\']"></div>');54 forAllHandlers(Dragstart.on(source).dragenter(element), element, verifyDropCancelled);55 });56 it('allows dropping typed elements if dnd-allowed-types is not set', function() {57 var source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'sometype\'"></div>');58 var element = compileAndLink('<div dnd-list="[]"></div>');59 forAllHandlers(Dragstart.on(source).dragenter(element), element, verifyDropAccepted);60 });61 it('disallows dropping elements of the wrong type', function() {62 var source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'othertype\'"></div>');63 var element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'mytype\']"></div>');64 forAllHandlers(Dragstart.on(source).dragenter(element), element, verifyDropCancelled);65 });66 it('allows dropping elements of the correct type', function() {67 var source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'mytype\'"></div>');68 var element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'MyType\']"></div>');69 forAllHandlers(Dragstart.on(source).dragenter(element), element, verifyDropAccepted);70 });71 it('disallows dropping elements of the wrong type (test for Edge)', function() {72 var source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'othertype\'"></div>');73 var element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'mytype\']"></div>');74 var dragstart = Dragstart.on(source, {allowedMimeTypes: ['text/plain', 'application/json']});75 forAllHandlers(dragstart.dragenter(element), element, verifyDropCancelled);76 });77 it('allows dropping elements of the correct type (test for Edge)', function() {78 var source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'mytype\'"></div>');79 var element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'mytype\']"></div>');80 var dragstart = Dragstart.on(source, {allowedMimeTypes: ['text/plain', 'application/json']});81 forAllHandlers(dragstart.dragenter(element), element, verifyDropAccepted);82 });83 it('allows dropping external elements if correct type is encoded inside', function() {84 var element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'myType\']" ' +85 'dnd-external-sources="true"></div>');86 var data = angular.toJson({item: {}, type: 'mytype'});87 var dragenter = Dragenter.externalOn(element, {'application/json': data});88 forAllHandlers(dragenter, element, verifyDropAccepted);89 });90 describe('dragover handler', function() {91 var source, element;92 beforeEach(function() {93 source = compileAndLink('<div dnd-draggable="{}"></div>');94 element = compileAndLink('<div dnd-list="list"></div>');95 element.scope().list = [];96 });97 it('adds dndDragover CSS class', function() {98 Dragstart.on(source).dragover(element);99 expect(element.hasClass('dndDragover')).toBe(true);100 });101 it('adds placeholder element', function() {102 Dragstart.on(source).dragover(element);103 expect(element.children().length).toBe(1);104 expect(element.children()[0].tagName).toBe('LI');105 });106 it('reuses custom placeholder element if it exists', function() {107 element = compileAndLink('<dnd-list><img class="dndPlaceholder"></dnd-list>');108 Dragstart.on(source).dragover(element);109 expect(element.children().length).toBe(1);110 expect(element.children()[0].tagName).toBe('IMG');111 });112 it('invokes dnd-dragover callback', function() {113 element = createListWithItemsAndCallbacks();114 Dragstart.on(source).dragover(element);115 expect(element.scope().dragover.event).toEqual(jasmine.any(DragEventMock));116 expect(element.scope().dragover.index).toBe(3);117 expect(element.scope().dragover.external).toBe(false);118 expect(element.scope().dragover.type).toBeUndefined();119 expect(element.scope().dragover.item).toBeUndefined();120 });121 it('invokes dnd-dragover with correct type', function() {122 source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'mytype\'"></div>');123 element = createListWithItemsAndCallbacks();124 Dragstart.on(source).dragover(element);125 expect(element.scope().dragover.type).toBe('mytype');126 expect(element.scope().dragover.external).toBe(false);127 });128 it('invokes dnd-dragover with correct type (test for IE)', function() {129 source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'mytype\'"></div>');130 element = createListWithItemsAndCallbacks();131 Dragstart.on(source, {allowedMimeTypes: ['Text']}).dragover(element);132 expect(element.scope().dragover.type).toBe('mytype');133 expect(element.scope().dragover.external).toBe(false);134 });135 it('invokes dnd-dragover with correct type for external drops', function() {136 element = createListWithItemsAndCallbacks();137 Dragenter.externalOn(element, {'application/x-dnd-mytype': {}}).dragover(element);138 expect(element.scope().dragover.type).toBe('mytype');139 expect(element.scope().dragover.external).toBe(true);140 });141 it('invokes dnd-dragover with null type for external drops from IE', function() {142 element = createListWithItemsAndCallbacks();143 Dragenter.externalOn(element, {'Text': 'unaccessible'}).dragover(element);144 expect(element.scope().dragover.type).toBeNull();145 expect(element.scope().dragover.external).toBe(true);146 });147 it('invokes dnd-dragover with undefined callback', function() {148 element = createListWithItemsAndCallbacks();149 Dragstart.on(source).dragover(element);150 expect(element.scope().dragover.callback).toBeUndefined();151 });152 it('invokes dnd-dragover with callback set on dragstart', function() {153 source = compileAndLink('<div dnd-draggable="{}" dnd-callback="a*b"></div>');154 source.scope().a = 2;155 element = compileAndLink('<ul dnd-list="[]" dnd-dragover="result = callback({b: 3});"></ul>');156 Dragstart.on(source).dragover(element);157 expect(element.scope().result).toBe(6)158 });159 it('dnd-dragover callback can cancel the drop', function() {160 element = compileAndLink('<div dnd-list="list" dnd-dragover="false"></div>');161 verifyDropCancelled(Dragstart.on(source).dragover(element), element);162 });163 it('allows all external drops with Text mime type', function() {164 element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'myType\']" ' +165 'dnd-external-sources="true"></div>');166 var dragenter = Dragenter.externalOn(element, {'Text': 'unaccessible'});167 verifyDropAccepted(dragenter.dragover(element), element);168 });169 describe('placeholder positioning (vertical)', positioningTests(false, false));170 describe('placeholder positioning (horizontal)', positioningTests(true, false));171 function positioningTests(horizontal) {172 return function() {173 var clientYField = 'client' + (horizontal ? 'X' : 'Y');174 var heightField = horizontal ? 'width' : 'height';175 var topField = horizontal ? 'left' : 'top';176 beforeEach(function() {177 element = createListWithItemsAndCallbacks(horizontal);178 angular.element(document.body).append(element);179 if (horizontal) {180 element.children().css('float','left');181 }182 });183 afterEach(function() {184 element.remove();185 });186 it('adds actual placeholder element', function() {187 var options = {target: element.children()[0]};188 options[clientYField] = 1;189 Dragstart.on(source).dragover(element, options);190 expect(element.scope().dragover.index).toBe(0);191 expect(angular.element(element.children()[0]).hasClass('dndPlaceholder')).toBe(true);192 });193 it('inserts before element if mouse is in first half', function() {194 var options = {target: element.children()[1]};195 var rect = options.target.getBoundingClientRect();196 options[clientYField] = rect[topField] + rect[heightField] / 2 - 1;197 Dragstart.on(source).dragover(element, options);198 expect(element.scope().dragover.index).toBe(1);199 });200 it('inserts after element if mouse is in second half', function() {201 var options = {target: element.children()[1]};202 var rect = options.target.getBoundingClientRect();203 options[clientYField] = rect[topField] + rect[heightField] / 2 + 1;204 Dragstart.on(source).dragover(element, options);205 expect(element.scope().dragover.index).toBe(2);206 });207 };208 }209 });210 describe('drop handler', function() {211 var source, element;212 beforeEach(function() {213 source = compileAndLink('<div dnd-draggable="{example: \'data\'}"></div>');214 element = createListWithItemsAndCallbacks();215 });216 it('inserts into the list and removes dndDragover class', function() {217 var dragover = Dragstart.on(source).dragover(element, {target: element.children()[0]});218 expect(element.hasClass("dndDragover")).toBe(true);219 dragover.drop(element);220 expect(element.scope().list).toEqual([1, {example: 'data'}, 2, 3]);221 expect(element.hasClass("dndDragover")).toBe(false);222 expect(element.children().length).toBe(3);223 });224 it('inserts in correct position', function() {225 Dragstart.on(source).dragover(element, {target: element.children()[1]}).drop(element);226 expect(element.scope().list).toEqual([1, 2, {example: 'data'}, 3]);227 expect(element.scope().inserted.index).toBe(2);228 });229 it('invokes the dnd-inserted callback', function() {230 Dragstart.on(source).dragover(element).drop(element);231 expect(element.scope().inserted.event).toEqual(jasmine.any(DragEventMock));232 expect(element.scope().inserted.index).toBe(3);233 expect(element.scope().inserted.external).toBe(false);234 expect(element.scope().inserted.type).toBeUndefined();235 expect(element.scope().inserted.item).toBe(element.scope().list[3]);236 });237 it('dnd-drop can transform the object', function() {238 var testObject = {transformed: true};239 element.scope().dropHandler = function(params) {240 expect(params.event).toEqual(jasmine.any(DragEventMock));241 expect(params.index).toBe(3);242 expect(params.external).toBe(false);243 expect(params.type).toBeUndefined();244 expect(params.item).toEqual({example: 'data'});245 return testObject;246 };247 Dragstart.on(source).dragover(element).drop(element);248 expect(element.scope().list[3]).toBe(testObject);249 });250 it('dnd-drop can cancel the drop', function() {251 element.scope().dropHandler = function() { return false; };252 var drop = Dragstart.on(source).dragover(element).drop(element);253 expect(element.scope().list).toEqual([1, 2, 3]);254 expect(element.scope().inserted).toBeUndefined();255 verifyDropCancelled(drop, element, true, 3);256 });257 it('dnd-drop can take care of inserting the element', function() {258 element.scope().dropHandler = function() { return true; };259 verifyDropAccepted(Dragstart.on(source).dragover(element).drop(element), element);260 expect(element.scope().list).toEqual([1, 2, 3]);261 });262 it('invokes dnd-drop with undefined callback', function() {263 element = createListWithItemsAndCallbacks();264 Dragstart.on(source).dragover(element).drop(element);265 expect(element.scope().drop.callback).toBeUndefined();266 });267 it('invokes dnd-drop with callback set on dragstart', function() {268 source = compileAndLink('<div dnd-draggable="{}" dnd-callback="a*b"></div>');269 source.scope().a = 2;270 element = compileAndLink('<ul dnd-list="list" dnd-drop="callback({b: 3});"></ul>');271 element.scope().list = [];272 Dragstart.on(source).dragover(element).drop(element);273 expect(element.scope().list).toEqual([6])274 });275 it('invokes callbacks with correct type', function() {276 source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'mytype\'"></div>');277 Dragstart.on(source).dragover(element).drop(element);278 expect(element.scope().drop.type).toBe('mytype');279 expect(element.scope().drop.external).toBe(false);280 expect(element.scope().inserted.type).toBe('mytype');281 expect(element.scope().inserted.external).toBe(false);282 });283 it('invokes callbacks with correct type for Edge', function() {284 source = compileAndLink('<div dnd-draggable="{}" dnd-type="\'mytype\'"></div>');285 Dragstart.on(source, {allowedMimeTypes: ['application/json']}).dragover(element).drop(element);286 expect(element.scope().drop.type).toBe('mytype');287 expect(element.scope().drop.external).toBe(false);288 expect(element.scope().inserted.type).toBe('mytype');289 expect(element.scope().inserted.external).toBe(false);290 });291 it('invokes callbacks with correct type for external elements', function() {292 var dragenter = Dragenter.externalOn(element, {'application/x-dnd-mytype': '{}'});293 verifyDropAccepted(dragenter.dragover(element).drop(element), element);294 expect(element.scope().drop.type).toBe('mytype');295 expect(element.scope().drop.external).toBe(true);296 expect(element.scope().inserted.type).toBe('mytype');297 expect(element.scope().inserted.external).toBe(true);298 });299 it('invokes callbacks with correct type for external elements (test for Edge)', function() {300 var data = angular.toJson({item: [1, 2, 3], type: 'mytype'});301 var dragenter = Dragenter.externalOn(element, {'application/json': data});302 verifyDropAccepted(dragenter.dragover(element).drop(element), element);303 expect(element.scope().drop.type).toBe('mytype');304 expect(element.scope().drop.external).toBe(true);305 expect(element.scope().inserted.type).toBe('mytype');306 expect(element.scope().inserted.external).toBe(true);307 expect(element.scope().inserted.item).toEqual([1, 2, 3]);308 });309 it('disallows drops with wrong type encoded inside (test for Edge)', function() {310 element = compileAndLink('<div dnd-list="[]" dnd-allowed-types="[\'myType\']" ' +311 'dnd-external-sources="true"></div>');312 var data = angular.toJson({item: [], type: 'othertype'});313 var dragenter = Dragenter.externalOn(element, {'application/json': data});314 verifyDropCancelled(dragenter.dragover(element).drop(element), element, true);315 });316 it('cancels drop when JSON is invalid', function() {317 var dragenter = Dragenter.externalOn(element, {'application/x-dnd': 'Lorem ipsum'});318 verifyDropCancelled(dragenter.dragover(element).drop(element), element, true, 3);319 });320 });321 describe('dragleave handler', function() {322 var element, dragover;323 beforeEach(function() {324 element = createListWithItemsAndCallbacks();325 angular.element(document.body).append(element);326 dragover = Dragstart.on(compileAndLink('<div dnd-draggable="{}"></div>')).dragover(element);327 expect(element.hasClass('dndDragover')).toBe(true);328 expect(element.children().length).toBe(4);329 });330 afterEach(function() {331 element.remove();332 });333 it('removes the placeholder and dndDragover class', function() {334 var rect = element[0].getBoundingClientRect();335 dragover.dragleave(element, {clientX: rect.left - 2, clientY: rect.top - 2});336 expect(element.hasClass('dndDragover')).toBe(false);337 expect(element.children().length).toBe(3);338 });339 it('removes the placeholder and dndDragover if child placeholder is already set', function() {340 var rect = element[0].getBoundingClientRect();341 dragover.dragleave(element, {clientX: rect.left + 2, clientY: rect.top + 2, phShown: true});342 expect(element.hasClass('dndDragover')).toBe(false);343 expect(element.children().length).toBe(3);344 });345 it('sets _dndPhShown if mouse is still inside', function() {346 var rect = element[0].getBoundingClientRect();347 var result = dragover.dragleave(element, {clientX: rect.left + 2, clientY: rect.top + 2});348 expect(element.hasClass('dndDragover')).toBe(true);349 expect(element.children().length).toBe(4);350 expect(result.dndPhShownSet).toBe(true);351 });352 });353 describe('dropEffect', function() {354 // This matrix shows the expected drop effect, given two effectAllowed values.355 var ALL = [ 'all', 'move', 'copy', 'link', 'copyLink', 'copyMove', 'linkMove'];356 var EXPECTED_MATRIX = {357 move: ['move', 'move', 'none', 'none', 'none', 'move', 'move'],358 copy: ['copy', 'none', 'copy', 'none', 'copy', 'copy', 'none'],359 link: ['link', 'none', 'none', 'link', 'link', 'none', 'link'],360 copyLink: ['copy', 'none', 'copy', 'link', 'copy', 'copy', 'link'],361 copyMove: ['move', 'move', 'copy', 'none', 'copy', 'move', 'move'],362 linkMove: ['move', 'move', 'none', 'link', 'link', 'move', 'move'],363 all: ['move', 'move', 'copy', 'link', 'copy', 'move', 'move'],364 '': ['move', 'move', 'copy', 'link', 'copy', 'move', 'move'],365 };366 angular.forEach(ALL, function(sourceEffectAllowed, index) {367 angular.forEach(EXPECTED_MATRIX, function(expected, targetEffectAllowed) {368 expected = expected[index];369 it('is ' + expected + ' for effect-allowed ' + sourceEffectAllowed370 + ' and ' + targetEffectAllowed, function() {371 var src = compileAndLink('<div dnd-draggable="{}" dnd-dragend="result = dropEffect" '372 + 'dnd-effect-allowed="' + sourceEffectAllowed + '"></div>');373 var target = createListWithItemsAndCallbacks(false, targetEffectAllowed);374 expect(Dragstart.on(src).effectAllowed).toBe(sourceEffectAllowed);375 if (expected != 'none') {376 // Verify dragover.377 expect(Dragstart.on(src).dragover(target).dropEffect).toBe(expected);378 expect(target.scope().dragover.dropEffect).toBe(expected);379 // Verify drop.380 expect(Dragstart.on(src).dragover(target).drop(target).dropEffect).toBe(expected);381 expect(target.scope().drop.dropEffect).toBe(expected);382 // Verify dragend.383 Dragstart.on(src).dragover(target).drop(target).dragend(src);384 expect(src.scope().result).toBe(expected);385 } else {386 verifyDropCancelled(Dragstart.on(src).dragover(target), target, false, 3);387 verifyDropCancelled(Dragstart.on(src).dragover(target).drop(target), target, true, 3);388 Dragstart.on(src).dragend(src);389 expect(src.scope().result).toBe('none');390 }391 });392 });393 });394 // In Safari dataTransfer.effectAllowed is always 'all', ignoring the value set in dragstart.395 it('is determined from internal state in Safari', function() {396 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="link"></div>');397 var target = createListWithItemsAndCallbacks(false, 'copyLink');398 var options = {effectAllowed: 'all'};399 Dragstart.on(src).dragover(target, options).drop(target, options);400 expect(target.scope().dragover.dropEffect).toBe('link');401 expect(target.scope().drop.dropEffect).toBe('link');402 });403 // On MacOS, modifiers automatically limit the effectAllowed passed to dragover and drop.404 it('is limited by modifier keys on MacOS', function() {405 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="all"></div>');406 var target = createListWithItemsAndCallbacks();407 Dragstart.on(src).dragover(target, {effectAllowed: 'copyLink'}).drop(target);408 expect(target.scope().dragover.dropEffect).toBe('copy');409 expect(target.scope().drop.dropEffect).toBe('copy');410 });411 it('is copy if Ctrl key is pressed', function() {412 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="all"></div>');413 var target = createListWithItemsAndCallbacks();414 Dragstart.on(src).dragover(target, {ctrlKey: true}).drop(target);415 expect(target.scope().dragover.dropEffect).toBe('copy');416 expect(target.scope().drop.dropEffect).toBe('copy');417 });418 it('is link if Alt key is pressed', function() {419 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="all"></div>');420 var target = createListWithItemsAndCallbacks();421 Dragstart.on(src).dragover(target, {altKey: true}).drop(target);422 expect(target.scope().dragover.dropEffect).toBe('link');423 expect(target.scope().drop.dropEffect).toBe('link');424 });425 it('ignores Ctrl key if copy is not possible', function() {426 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="linkMove"></div>');427 var target = createListWithItemsAndCallbacks();428 Dragstart.on(src).dragover(target, {ctrlKey: true}).drop(target);429 expect(target.scope().dragover.dropEffect).toBe('move');430 expect(target.scope().drop.dropEffect).toBe('move');431 });432 it('respects effectAllowed from external drops', function() {433 var target = createListWithItemsAndCallbacks();434 Dragenter.validExternalOn(target, {effectAllowed: 'copyLink'}).dragover(target).drop(target);435 expect(target.scope().dragover.dropEffect).toBe('copy');436 expect(target.scope().drop.dropEffect).toBe('copy');437 });438 it('respects effectAllowed from external drops in IE', function() {439 var target = createListWithItemsAndCallbacks();440 Dragenter.externalOn(target, {'Text': '{}'}, {effectAllowed: 'copyLink'})441 .dragover(target).drop(target);442 expect(target.scope().dragover.dropEffect).toBe('move');443 expect(target.scope().drop.dropEffect).toBe('move');444 });445 it('ignores effectAllowed from internal drops in IE', function() {446 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="copyLink"></div>');447 var target = createListWithItemsAndCallbacks();448 Dragstart.on(src, {allowedMimeTypes: ['Text']}).dragover(target, {altKey: true});449 expect(target.scope().dragover.dropEffect).toBe('link');450 });451 it('does not set dropEffect in IE', function() {452 var src = compileAndLink('<div dnd-draggable="{}" dnd-effect-allowed="copyLink"></div>');453 var target = createListWithItemsAndCallbacks();454 var dragover = Dragstart.on(src, {allowedMimeTypes: ['Text']}).dragover(target);455 expect(dragover.dropEffect).toBeUndefined();456 });457 });458 function verifyDropAccepted(result) {459 expect(result.defaultPrevented).toBe(true);460 if (result.type == 'dragenter') {461 expect(result.returnValue).toBeUndefined();462 expect(result.propagationStopped).toBe(false);463 } else {464 expect(result.returnValue).toBe(false);465 expect(result.propagationStopped).toBe(true);466 }467 }468 function verifyDropCancelled(result, element, opt_defaultPrevented, opt_children) {469 expect(result.returnValue).toBe(true);470 expect(result.propagationStopped).toBe(false);471 expect(result.defaultPrevented).toBe(opt_defaultPrevented || false);472 expect(result.dropEffect).toBeUndefined();473 expect(element.hasClass("dndDragover")).toBe(false);474 expect(element.children().length).toBe(opt_children || 0);475 }476 function forAllHandlers(dragenter, element, verify) {477 verify(dragenter, element);478 var dragover = dragenter.dragover(element);479 verify(dragover, element);480 var dragover2 = dragover.dragover(element);481 verify(dragover2, element);482 var drop = dragover2.drop(element);483 verify(drop, element);484 }485 function createListWithItemsAndCallbacks(horizontal, effectAllowed) {486 var params = '{event: event, dropEffect: dropEffect, index: index, '487 + 'item: item, external: external, type: type, callback: callback}';488 var element = compileAndLink('<ul dnd-list="list" dnd-external-sources="true" ' +489 'dnd-horizontal-list="' + (horizontal || 'false') + '" ' +490 (effectAllowed ? 'dnd-effect-allowed="' + effectAllowed + '" ' : '') +491 'dnd-dragover="dragover = ' + params + '" ' +492 'dnd-drop="dropHandler(' + params + ')" ' +493 'dnd-inserted="inserted = ' + params + '">' +494 '<li>A</li><li>B</li><li>C</li></ul>');495 element.scope().dropHandler = function(params) {496 element.scope().drop = params;497 return params.item;498 };499 element.scope().list = [1, 2, 3];500 return element;501 }...
Chessboard.jsx
Source:Chessboard.jsx
1import styled from "styled-components";2import React from "react";3import bb from "./Assets/bb.png";4import bk from "./Assets/bk.png";5import bn from "./Assets/bn.png";6import bp from "./Assets/bp.png";7import bq from "./Assets/bq.png";8import br from "./Assets/br.png";9import wb from "./Assets/wb.png";10import wk from "./Assets/wk.png";11import wn from "./Assets/wn.png";12import wp from "./Assets/wp.png";13import wq from "./Assets/wq.png";14import wr from "./Assets/wr.png";15const Chessboard = () => {16 const chessboard = [];17 let alpha = ["a", "b", "c", "d", "e", "f", "g", "h"];18 for (let i = 8; i > 0; i--) {19 for (let j = 0; j < 8; j++) {20 chessboard.push((alpha[j] + i).toString());21 }22 }23 let n = 1;24 // Squares Drag and Drop25 let start_p;26 const drop = (e) => {27 e.preventDefault();28 const pieceId = e.dataTransfer.getData("pieceId");29 const piece = document.getElementById(pieceId);30 piece.style.display = "block";31 console.log(e);32 if (e.target.children.length !== 0) {33 if (start_p.id === e.target.id) {34 return;35 }36 let p = document.getElementById(e.target.id).parentElement;37 p.removeChild(p.children[0]);38 p.appendChild(piece);39 } else {40 e.target.appendChild(piece);41 }42 };43 const dragOver = (e) => {44 e.preventDefault();45 };46 // Pieces Drag and Drop47 const dragStart = (e) => {48 const target = e.target;49 console.log(e);50 e.dataTransfer.setData("pieceId", target.id);51 start_p = document.getElementById(e.target.id).parentElement;52 setTimeout(() => {53 target.style.display = "none";54 }, 0);55 };56 return (57 <div>58 <Board>59 {chessboard.map((x) => {60 if (n % 9 === 0) {61 n++;62 }63 if (n % 2 === 0) {64 n++;65 switch (x) {66 case "b8":67 return (68 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>69 <Pieces70 src={bn}71 id="nb8"72 draggable="true"73 onDrop={drop}74 onDragOver={dragOver}75 onDragStart={dragStart}76 ></Pieces>77 </DarkSquare>78 );79 case "d8":80 return (81 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>82 <Pieces83 src={bq}84 id="qd8"85 draggable="true"86 onDragStart={dragStart}87 onDrop={drop}88 onDragOver={dragOver}89 ></Pieces>90 </DarkSquare>91 );92 case "f8":93 return (94 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>95 <Pieces96 src={bb}97 id="bf8"98 draggable="true"99 onDragStart={dragStart}100 onDrop={drop}101 onDragOver={dragOver}102 ></Pieces>103 </DarkSquare>104 );105 case "h8":106 return (107 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>108 <Pieces109 src={br}110 id="rh8"111 draggable="true"112 onDragStart={dragStart}113 onDrop={drop}114 onDragOver={dragOver}115 ></Pieces>116 </DarkSquare>117 );118 case "a7":119 return (120 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>121 <Pieces122 src={bp}123 id="pa7"124 draggable="true"125 onDragStart={dragStart}126 onDrop={drop}127 onDragOver={dragOver}128 ></Pieces>129 </DarkSquare>130 );131 case "c7":132 return (133 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>134 <Pieces135 src={bp}136 id="pc7"137 draggable="true"138 onDragStart={dragStart}139 onDrop={drop}140 onDragOver={dragOver}141 ></Pieces>142 </DarkSquare>143 );144 case "e7":145 return (146 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>147 <Pieces148 src={bp}149 id="pe7"150 draggable="true"151 onDragStart={dragStart}152 onDrop={drop}153 onDragOver={dragOver}154 ></Pieces>155 </DarkSquare>156 );157 case "g7":158 return (159 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>160 <Pieces161 src={bp}162 id="pg7"163 draggable="true"164 onDragStart={dragStart}165 onDrop={drop}166 onDragOver={dragOver}167 ></Pieces>168 </DarkSquare>169 );170 case "a1":171 return (172 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>173 <Pieces174 src={wr}175 id="ra1"176 draggable="true"177 onDragStart={dragStart}178 onDrop={drop}179 onDragOver={dragOver}180 ></Pieces>181 </DarkSquare>182 );183 case "c1":184 return (185 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>186 <Pieces187 src={wb}188 id="bc1"189 draggable="true"190 onDragStart={dragStart}191 onDrop={drop}192 onDragOver={dragOver}193 ></Pieces>194 </DarkSquare>195 );196 case "e1":197 return (198 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>199 <Pieces200 src={wk}201 id="ke1"202 draggable="true"203 onDragStart={dragStart}204 onDrop={drop}205 onDragOver={dragOver}206 ></Pieces>207 </DarkSquare>208 );209 case "g1":210 return (211 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>212 <Pieces213 src={wn}214 id="ng1"215 draggable="true"216 onDragStart={dragStart}217 onDrop={drop}218 onDragOver={dragOver}219 ></Pieces>220 </DarkSquare>221 );222 case "b2":223 return (224 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>225 <Pieces226 src={wp}227 id="pb2"228 draggable="true"229 onDragStart={dragStart}230 onDrop={drop}231 onDragOver={dragOver}232 ></Pieces>233 </DarkSquare>234 );235 case "d2":236 return (237 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>238 <Pieces239 src={wp}240 id="pd2"241 draggable="true"242 onDragStart={dragStart}243 onDrop={drop}244 onDragOver={dragOver}245 ></Pieces>246 </DarkSquare>247 );248 case "f2":249 return (250 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>251 <Pieces252 src={wp}253 id="pf2"254 draggable="true"255 onDragStart={dragStart}256 onDrop={drop}257 onDragOver={dragOver}258 ></Pieces>259 </DarkSquare>260 );261 case "h2":262 return (263 <DarkSquare onDrop={drop} onDragOver={dragOver} id={x}>264 <Pieces265 src={wp}266 id="ph2"267 draggable="true"268 onDragStart={dragStart}269 onDrop={drop}270 onDragOver={dragOver}271 ></Pieces>272 </DarkSquare>273 );274 default:275 return (276 <DarkSquare277 onDrop={drop}278 onDragOver={dragOver}279 id={x}280 ></DarkSquare>281 );282 }283 } else {284 n++;285 switch (x) {286 case "a8":287 return (288 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>289 <Pieces290 src={br}291 id="ra8"292 draggable="true"293 onDragStart={dragStart}294 onDrop={drop}295 onDragOver={dragOver}296 ></Pieces>297 </LightSquare>298 );299 case "c8":300 return (301 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>302 <Pieces303 src={bb}304 id="bc8"305 draggable="true"306 onDragStart={dragStart}307 onDrop={drop}308 onDragOver={dragOver}309 ></Pieces>310 </LightSquare>311 );312 case "e8":313 return (314 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>315 <Pieces316 src={bk}317 id="ke8"318 draggable="true"319 onDragStart={dragStart}320 onDrop={drop}321 onDragOver={dragOver}322 ></Pieces>323 </LightSquare>324 );325 case "g8":326 return (327 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>328 <Pieces329 src={bn}330 id="ng8"331 draggable="true"332 onDragStart={dragStart}333 onDrop={drop}334 onDragOver={dragOver}335 ></Pieces>336 </LightSquare>337 );338 case "b7":339 return (340 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>341 <Pieces342 src={bp}343 id="pb7"344 draggable="true"345 onDragStart={dragStart}346 onDrop={drop}347 onDragOver={dragOver}348 ></Pieces>349 </LightSquare>350 );351 case "d7":352 return (353 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>354 <Pieces355 src={bp}356 id="pd7"357 draggable="true"358 onDragStart={dragStart}359 onDrop={drop}360 onDragOver={dragOver}361 ></Pieces>362 </LightSquare>363 );364 case "f7":365 return (366 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>367 <Pieces368 src={bp}369 id="pf7"370 draggable="true"371 onDragStart={dragStart}372 onDrop={drop}373 onDragOver={dragOver}374 ></Pieces>375 </LightSquare>376 );377 case "h7":378 return (379 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>380 <Pieces381 src={bp}382 id="ph7"383 draggable="true"384 onDragStart={dragStart}385 onDrop={drop}386 onDragOver={dragOver}387 ></Pieces>388 </LightSquare>389 );390 case "b1":391 return (392 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>393 <Pieces394 src={wn}395 id="nb1"396 draggable="true"397 onDragStart={dragStart}398 onDrop={drop}399 onDragOver={dragOver}400 ></Pieces>401 </LightSquare>402 );403 case "d1":404 return (405 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>406 <Pieces407 src={wq}408 id="qd1"409 draggable="true"410 onDragStart={dragStart}411 onDrop={drop}412 onDragOver={dragOver}413 ></Pieces>414 </LightSquare>415 );416 case "f1":417 return (418 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>419 <Pieces420 src={wb}421 id="bf1"422 draggable="true"423 onDragStart={dragStart}424 onDrop={drop}425 onDragOver={dragOver}426 ></Pieces>427 </LightSquare>428 );429 case "h1":430 return (431 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>432 <Pieces433 src={wr}434 id="rh1"435 draggable="true"436 onDragStart={dragStart}437 onDrop={drop}438 onDragOver={dragOver}439 ></Pieces>440 </LightSquare>441 );442 case "a2":443 return (444 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>445 <Pieces446 src={wp}447 id="pa2"448 draggable="true"449 onDragStart={dragStart}450 onDrop={drop}451 onDragOver={dragOver}452 ></Pieces>453 </LightSquare>454 );455 case "c2":456 return (457 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>458 <Pieces459 src={wp}460 id="pc2"461 draggable="true"462 onDragStart={dragStart}463 onDrop={drop}464 onDragOver={dragOver}465 ></Pieces>466 </LightSquare>467 );468 case "e2":469 return (470 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>471 <Pieces472 src={wp}473 id="pe2"474 draggable="true"475 onDragStart={dragStart}476 onDrop={drop}477 onDragOver={dragOver}478 ></Pieces>479 </LightSquare>480 );481 case "g2":482 return (483 <LightSquare onDrop={drop} onDragOver={dragOver} id={x}>484 <Pieces485 src={wp}486 id="pg2"487 draggable="true"488 onDragStart={dragStart}489 onDrop={drop}490 onDragOver={dragOver}491 ></Pieces>492 </LightSquare>493 );494 default:495 return (496 <LightSquare497 onDrop={drop}498 onDragOver={dragOver}499 id={x}500 ></LightSquare>501 );502 }503 }504 })}505 </Board>506 </div>507 );508};509export default Chessboard;510const Board = styled.div`511 padding: 30px;512 display: grid;513 grid-template-columns: repeat(8, 90px);514 justify-content: center;515 align-items: center;516`;517const LightSquare = styled.button`518 height: 90px;519 width: 90px;520 background-color: #eeeed2;521 outline: none;522 border: none;523 padding: 0px;524 margin: 0px;525 :focus {526 background-color: #f6f669;527 }528`;529const DarkSquare = styled.button`530 height: 90px;531 width: 90px;532 background-color: #85aa53;533 outline: none;534 border: none;535 padding: 0px;536 margin: 0px;537 :focus {538 background-color: #baca2b;539 }540`;541const Pieces = styled.img`542 height: 100%;543 width: 100%;...
adding-files.test.js
Source:adding-files.test.js
1import { expect } from '@esm-bundle/chai';2import { change, click, fixtureSync, makeSoloTouchEvent } from '@vaadin/testing-helpers';3import sinon from 'sinon';4import '../vaadin-upload.js';5import { createFile, createFiles, touchDevice, xhrCreator } from './common.js';6describe('file list', () => {7 let upload, file, files;8 const testFileSize = 512;9 beforeEach(() => {10 upload = fixtureSync(`<vaadin-upload></vaadin-upload>`);11 upload.target = 'http://foo.com/bar';12 upload._createXhr = xhrCreator({ size: testFileSize, uploadTime: 200, stepTime: 50 });13 files = createFiles(2, testFileSize, 'application/x-octet-stream');14 file = createFile(testFileSize, 'application/x-octet-stream');15 });16 describe('files property', () => {17 it('should push files to `files` Array property', () => {18 expect(upload).to.have.property('files').that.is.an('array').that.is.empty;19 files.forEach(upload._addFile.bind(upload));20 expect(upload.files[0]).to.equal(files[1]);21 expect(upload.files[1]).to.equal(files[0]);22 });23 it('should notify files property changes', () => {24 const spy = sinon.spy();25 upload.addEventListener('files-changed', spy);26 upload.files = files;27 expect(spy.calledOnce).to.be.true;28 });29 });30 describe('with add button', () => {31 let input;32 let addFiles;33 let inputClickSpy;34 beforeEach(() => {35 addFiles = upload.$.addFiles;36 input = upload.$.fileInput;37 // While the synthetic "Add Files" button click event is not trusted and38 // it should generate a non-trusted click event on the hidden file input,39 // at the time of writing Chrome and Firefox still open the file dialog.40 // Use stub calling `preventDefault` to prevent dialog from opening.41 inputClickSpy = sinon.stub().callsFake((e) => e.preventDefault());42 input.addEventListener('click', inputClickSpy);43 });44 it('should open file dialog by click', () => {45 click(addFiles);46 expect(inputClickSpy.calledOnce).to.be.true;47 });48 it('should open file dialog by touchend', () => {49 const event = makeSoloTouchEvent('touchend', null, addFiles);50 expect(inputClickSpy.calledOnce).to.be.true;51 expect(event.defaultPrevented).to.be.true;52 });53 it('should reset input.value before dialog', () => {54 // We can't simply assign `files` property of input[type="file"].55 // Tweaking __proto__ to make it assignable below.56 Object.setPrototypeOf(input, HTMLElement.prototype);57 delete input.value;58 input.value = 'foo';59 click(addFiles);60 expect(input.value).to.be.empty;61 });62 it('should add files from dialog', () => {63 // We can't simply assign `files` property of input[type="file"].64 // Tweaking __proto__ to make it assignable below.65 Object.setPrototypeOf(input, HTMLElement.prototype);66 input.files = files;67 change(input);68 expect(upload.files[0]).to.equal(files[1]);69 expect(upload.files[1]).to.equal(files[0]);70 });71 it('should disable add button when max files added', () => {72 const addButton = upload.$.addButton;73 // Enabled with default maxFiles value74 expect(addButton.disabled).to.be.false;75 upload.maxFiles = 1;76 expect(addButton.disabled).to.be.false;77 upload._addFile(createFile(100, 'image/jpeg'));78 expect(addButton.disabled).to.be.true;79 });80 it('should not open upload dialog when max files added', () => {81 upload.maxFiles = 0;82 click(addFiles);83 expect(inputClickSpy.called).to.be.false;84 });85 it('should set max-files-reached style attribute when max files added', () => {86 upload.maxFiles = 0;87 expect(upload.hasAttribute('max-files-reached')).to.be.true;88 });89 it('should not set max-files-reached style attribute when less than max files added', () => {90 expect(upload.hasAttribute('max-files-reached')).to.be.false;91 });92 });93 (touchDevice ? describe.skip : describe)('Dropping file', () => {94 // Using dispatchEvent instead of fire in this cases because95 // we have to pass the info in the dataTransfer property96 function createDndEvent(type) {97 const e = new Event(type);98 e.dataTransfer = { files: createFiles(2, testFileSize, 'application/x-bin') };99 return e;100 }101 it('should set dragover property on dragover', () => {102 expect(upload._dragover).not.to.be.ok;103 expect(upload.hasAttribute('dragover')).to.be.false;104 upload.dispatchEvent(createDndEvent('dragover'));105 expect(upload._dragover).to.be.ok;106 expect(upload.hasAttribute('dragover')).to.be.true;107 });108 it('should remove dragover property on dragleave', () => {109 upload.dispatchEvent(createDndEvent('dragover'));110 expect(upload._dragover).to.be.ok;111 expect(upload.hasAttribute('dragover')).to.be.true;112 upload.dispatchEvent(createDndEvent('dragleave'));113 expect(upload._dragover).not.to.be.ok;114 expect(upload.hasAttribute('dragover')).to.be.false;115 });116 it('should not have dragover property when max files added', () => {117 upload.maxFiles = 1;118 upload._addFile(createFile(100, 'image/jpeg'));119 upload.dispatchEvent(createDndEvent('dragover'));120 expect(upload._dragover).to.be.true;121 expect(upload._dragoverValid).to.be.false;122 });123 describe('nodrop flag', () => {124 let fileAddSpy, dropEvent;125 beforeEach(() => {126 fileAddSpy = sinon.spy();127 upload.addEventListener('files-changed', fileAddSpy);128 dropEvent = createDndEvent('drop');129 });130 it('should fire `files-changed` event when dropping files and drop is enabled', () => {131 upload.nodrop = false;132 upload.dispatchEvent(dropEvent);133 expect(fileAddSpy.called).to.be.true;134 });135 it('should not fire `files-changed` event when dropping files and drop is disabled', () => {136 upload.nodrop = true;137 upload.dispatchEvent(dropEvent);138 expect(fileAddSpy.called).to.be.false;139 });140 it('should not set dragover property on dragover', () => {141 upload.nodrop = true;142 expect(upload._dragover).not.to.be.ok;143 expect(upload.hasAttribute('dragover')).to.be.false;144 upload.dispatchEvent(createDndEvent('dragover'));145 expect(upload._dragover).not.to.be.ok;146 expect(upload.hasAttribute('dragover')).to.be.false;147 });148 it('should not set dragoverValid property on dragover', () => {149 upload.nodrop = true;150 expect(upload._dragoverValid).not.to.be.ok;151 expect(upload.hasAttribute('dragover')).to.be.false;152 upload.dispatchEvent(createDndEvent('dragover'));153 expect(upload._dragoverValid).not.to.be.ok;154 expect(upload.hasAttribute('dragover')).to.be.false;155 });156 it('should hide `drop files here` label and icon when drop is disabled', () => {157 upload.nodrop = true;158 expect(window.getComputedStyle(upload.$.dropLabelContainer).display).to.equal('none');159 });160 });161 });162 describe('start upload', () => {163 it('should automatically start upload', () => {164 const uploadStartSpy = sinon.spy();165 upload.addEventListener('upload-start', uploadStartSpy);166 files.forEach(upload._addFile.bind(upload));167 expect(uploadStartSpy.calledTwice).to.be.true;168 expect(upload.files[0].held).to.be.false;169 });170 it('should not automatically start upload when noAuto flag is set', () => {171 const uploadStartSpy = sinon.spy();172 upload.noAuto = true;173 upload.addEventListener('upload-start', uploadStartSpy);174 files.forEach(upload._addFile.bind(upload));175 expect(uploadStartSpy.called).to.be.false;176 expect(upload.files[0].held).to.be.true;177 });178 });179 describe('validate files', () => {180 it('should reject files when maxFiles is reached', (done) => {181 upload.maxFiles = 1;182 upload.addEventListener('file-reject', (e) => {183 expect(e.detail.error).to.be.ok;184 done();185 });186 upload._addFiles([file, file]);187 });188 it('should reject files with excessive size', (done) => {189 upload.maxFileSize = testFileSize - 1;190 upload.addEventListener('file-reject', (e) => {191 expect(e.detail.error).to.be.ok;192 done();193 });194 upload._addFiles([file]);195 });196 it('should reject files with incorrect contentType', (done) => {197 upload.accept = 'image/*,video/*';198 upload.addEventListener('file-reject', (e) => {199 expect(upload.files.length).to.equal(0);200 expect(e.detail.error).to.equal('Incorrect File Type.');201 done();202 });203 upload._addFiles([file]);204 });205 it('should allow files with correct extension', () => {206 upload.accept = 'image/*,.foo,video/*';207 file.name = 'bar.FOO';208 upload._addFiles([file]);209 expect(upload.files.length).to.equal(1);210 });211 it('should allow files with correct mime type', () => {212 upload.accept = 'application/x-octet-stream';213 upload._addFiles([file]);214 expect(upload.files.length).to.equal(1);215 });216 it('should allow wildcards', () => {217 upload.accept = 'application/*';218 upload._addFiles([file]);219 expect(upload.files.length).to.equal(1);220 });221 it('should allow files matching other than the first wildcard', () => {222 upload.accept = 'text/*,application/*,image/*,video/*,audio/*';223 upload._addFiles([file]);224 expect(upload.files.length).to.equal(1);225 });226 });...
dragEvent.js
Source:dragEvent.js
1export default {2 data() {3 return {4 isStage: false,5 dragoverBox: {6 target: null,7 componentId: '',8 rect: {},9 hint: '',10 placement: 'inside',11 style: {},12 },13 }14 },15 methods: {16 repaintDragoverBox() {17 if (!this.dragoverBox.target) return18 this.$nextTick(() => {19 const containerRect = this.getContainerRect()20 const rect = this.dragoverBox.target.getBoundingClientRect()21 const { scrollTop, scrollLeft } = this.$el22 const top = Math.floor(rect.top - containerRect.top + scrollTop)23 const left = Math.floor(rect.left - containerRect.left + scrollLeft)24 this.dragoverBox.style = {25 display: 'block',26 width: `${Math.floor(rect.width)}px`,27 height: `${Math.floor(rect.height)}px`,28 top: `${top}px`,29 left: `${left}px`,30 }31 })32 },33 ondragover(e) {34 e.preventDefault()35 if (!this.$el.contains(e.target)) {36 this.dragoverBox = {37 target: null,38 componentId: '',39 rect: {},40 hint: '',41 placement: 'inside',42 style: {},43 }44 return45 }46 const targerNode = e.target.closest('.layout-container')47 if (!targerNode) return48 if (this.dragoverBox.target !== targerNode) {49 this.dragoverBox.target = targerNode50 this.isStage = targerNode.classList.contains('editor-container-screen')51 this.dragoverBox.componentId = this.dragoverBox.target.dataset.componentId52 this.dragoverBox.rect = this.dragoverBox.target.getBoundingClientRect()53 }54 // å¤æç¹ä¸ç©å½¢ç¸äº¤ï¼å¯è®¾ç½®å移éï¼åºåå级æå
¥æå级æå
¥ä»¥åæ示信æ¯55 if (this.dragoverBox.target) {56 const { componentName } = this.dragoverBox.target.dataset57 const offset = {58 x: 0,59 y: 15,60 }61 if (componentName !== 'NestedLayoutContainer' && componentName !== 'PositionLayoutContainer') {62 offset.y = this.dragoverBox.rect.height / 263 }64 const point = {65 x: e.clientX,66 y: e.clientY,67 }68 // up69 const rect1 = {70 x: this.dragoverBox.rect.x + offset.x,71 y: this.dragoverBox.rect.y,72 w: this.dragoverBox.rect.width - offset.x * 2,73 h: offset.y,74 }75 // down76 const rect2 = {77 x: this.dragoverBox.rect.x + offset.x,78 y: this.dragoverBox.rect.y + this.dragoverBox.rect.height - offset.y,79 w: this.dragoverBox.rect.width - offset.x * 2,80 h: offset.y,81 }82 // inside83 const rect3 = {84 x: this.dragoverBox.rect.x + offset.x,85 y: this.dragoverBox.rect.y + offset.y,86 w: this.dragoverBox.rect.width - offset.x * 2,87 h: this.dragoverBox.rect.height - offset.y * 2,88 }89 if (this.pointInRect(point, rect1)) this.dragoverBox.placement = 'up'90 if (this.pointInRect(point, rect2)) this.dragoverBox.placement = 'down'91 if (this.pointInRect(point, rect3)) this.dragoverBox.placement = 'inside'92 if (this.isStage) this.dragoverBox.placement = 'inside'93 // console.log('pointInRect', point, rect, this.pointInRect(point, rect), e, this.dragoverBox)94 this.dragoverBox.hint = `insert ${componentName} ${this.dragoverBox.placement}`95 }96 this.repaintDragoverBox()97 },98 pointInRect(point, rect) {99 return point.x >= rect.x && point.y >= rect.y && point.x <= rect.x + rect.w && point.y <= rect.y + rect.h100 },101 ondrop(e) {102 e.preventDefault()103 if (this.dragoverBox.componentId) {104 const id = this.dragoverBox.componentId105 this.findParentComponentById(id)106 let newComponent = null107 let targetComponent = null108 if (this.project.components.id === id) {109 targetComponent = this.project.components110 } else {111 targetComponent = this.component.children.find(item => item.id === id)112 }113 try {114 const dragData = e.dataTransfer.getData('Text')115 const praseDragData = JSON.parse(dragData)116 newComponent = praseDragData117 newComponent.layout = 'nestedLayout'118 this.asyncLoadComponent(newComponent.name)119 if (targetComponent.name === 'PositionLayoutContainer') {120 if (this.dragoverBox.placement === 'inside') {121 const rect = e.target.getBoundingClientRect()122 const css = {123 position: 'absolute',124 top: `${e.clientY - rect.top}px`,125 left: `${e.clientX - rect.left}px`,126 }127 newComponent.layout = 'positionLayout'128 newComponent.properties.css = Object.assign({}, newComponent.properties.css, css)129 console.log('ondrop event: ', e, rect, newComponent, targetComponent, this)130 }131 }132 this.dropEvent(newComponent, targetComponent)133 } catch (error) {134 console.log('drop error:', error)135 }136 }137 this.dragoverBox = {138 target: null,139 componentId: '',140 rect: {},141 hint: '',142 placement: 'inside',143 style: {},144 }145 },146 dropEvent(newComponent, targetComponent) {147 console.log('nested drop:', newComponent, targetComponent, this)148 let message = ''149 let event = ''150 if (this.dragoverBox.placement === 'up') {151 event = 'componentInsertAbove'152 message = `insert ${newComponent.properties.name} above ${targetComponent.properties.name}`153 } else if (this.dragoverBox.placement === 'down') {154 event = 'componentInsertBelow'155 message = `insert ${newComponent.properties.name} below ${targetComponent.properties.name}`156 } else {157 switch (targetComponent.name) {158 case 'NestedLayoutContainer': {159 event = 'componentInsertInto'160 message = `insert ${newComponent.properties.name} into ${targetComponent.properties.name}`161 break162 }163 case 'PositionLayoutContainer': {164 event = 'componentInsertInto'165 message = `insert ${newComponent.properties.name} into ${targetComponent.properties.name}`166 break167 }168 default:169 console.log(`Sorry, we are out of ${targetComponent.name}.`)170 }171 }172 this.emitEvent(event, newComponent, targetComponent.id)173 this.emitEvent('snapshotProject')174 this.$Message({175 showClose: true,176 message,177 type: 'success',178 })179 // éè¿drop eventæå
¥ç»ä»¶æ°æ®ï¼DOMéç»æ¶é´ä¸ç¡®å®ï¼ä½¿ç¨this.$nextTick()ï¼ä»ä¸è¡ï¼ææ¶å 个延è¿180 setTimeout(() => {181 this.currentComponentId = newComponent.id182 this.componentSelectedStack = [newComponent.id]183 }, 200)184 },185 },186 created() {187 this.$EventStack.register('editor-container', 'dragover', this.ondragover)188 this.$EventStack.register('editor-container', 'drop', this.ondrop)189 },190 destroyed() {191 this.$EventStack.dispose('editor-container', 'dragover')192 this.$EventStack.dispose('editor-container', 'drop')193 },...
drag-and-drop.spec.js
Source:drag-and-drop.spec.js
1/*global fireEvent, isIE9 */2describe('Drag and Drop TestCase', function () {3 'use strict';4 beforeEach(function () {5 setupTestHelpers.call(this);6 this.el = this.createElement('div', 'editor', 'lore ipsum');7 });8 afterEach(function () {9 this.cleanupTest();10 });11 describe('drag', function () {12 it('should add medium-editor-dragover class', function () {13 var editor = this.newMediumEditor(this.el);14 fireEvent(editor.elements[0], 'dragover');15 expect(editor.elements[0].className).toContain('medium-editor-dragover');16 });17 it('should add medium-editor-dragover class even when data is invalid', function () {18 var editor = this.newMediumEditor(this.el, {19 imageDragging: false20 });21 fireEvent(editor.elements[0], 'dragover');22 expect(editor.elements[0].className).toContain('medium-editor-dragover');23 });24 it('should remove medium-editor-dragover class on drag leave', function () {25 var editor = this.newMediumEditor(this.el);26 fireEvent(editor.elements[0], 'dragover');27 expect(editor.elements[0].className).toContain('medium-editor-dragover');28 fireEvent(editor.elements[0], 'dragleave');29 expect(editor.elements[0].className).not.toContain('medium-editor-dragover');30 });31 });32 describe('drop', function () {33 it('should remove medium-editor-dragover class and add the image to the editor content', function () {34 spyOn(MediumEditor.util, 'insertHTMLCommand').and.callThrough();35 var editor = this.newMediumEditor(this.el);36 fireEvent(editor.elements[0], 'dragover');37 expect(editor.elements[0].className).toContain('medium-editor-dragover');38 fireEvent(editor.elements[0], 'drop');39 expect(editor.elements[0].className).not.toContain('medium-editor-dragover');40 // File API just doesn't work in IE9, so only verify this functionality if it's not IE941 if (!isIE9()) {42 expect(MediumEditor.util.insertHTMLCommand).toHaveBeenCalled();43 }44 });45 it('should remove medium-editor-dragover class and NOT add the image to the editor content', function () {46 spyOn(MediumEditor.util, 'insertHTMLCommand').and.callThrough();47 var editor = this.newMediumEditor(this.el, { imageDragging: false });48 fireEvent(editor.elements[0], 'dragover');49 expect(editor.elements[0].className).toContain('medium-editor-dragover');50 fireEvent(editor.elements[0], 'drop');51 expect(editor.elements[0].className).not.toContain('medium-editor-dragover');52 expect(MediumEditor.util.insertHTMLCommand).not.toHaveBeenCalled();53 });54 });...
fileDrop.js
Source:fileDrop.js
1import getHandleFileImport from '../../../tools/getHandleFileImport';2import { IMPORT_DRAGOVER_END, IMPORT_DRAGOVER_START } from '../actions';3const fileDrop = (store) => {4 const root = document.querySelector('#app');5 const handleFileImport = getHandleFileImport(store);6 let dragoverTimeout;7 let dragging = false;8 // detect start and end of dragover as there is no native dragend ecent for files9 root.addEventListener('dragover', (ev) => {10 ev.preventDefault();11 if (!dragging) {12 store.dispatch({13 type: IMPORT_DRAGOVER_START,14 });15 }16 window.clearTimeout(dragoverTimeout);17 dragging = true;18 dragoverTimeout = window.setTimeout(() => {19 dragging = false;20 store.dispatch({21 type: IMPORT_DRAGOVER_END,22 });23 }, 250);24 });25 root.addEventListener('drop', (ev) => {26 ev.preventDefault();27 let files;28 if (ev.dataTransfer.items) {29 files = [...ev.dataTransfer.items]30 .filter(({ kind }) => kind === 'file')31 .map((item) => item.getAsFile());32 } else {33 files = [...ev.dataTransfer.files];34 }35 handleFileImport(files);36 });37 return (next) => (action) => {38 next(action);39 };40};...
Cover.js
Source:Cover.js
1/* @flow */2import React from 'react';3import PropTypes from 'prop-types';4import {default as Component} from '../Common/plugs/index.js'; //æä¾style, classnameæ¹æ³5export default class Cover extends Component {6 constructor(props) {7 super(props);8 this.state = {9 dragOver: false10 };11 }12 handleDragover(e) {13 e.preventDefault();14 this.setState({ dragOver: true });15 }16 handleDragleave(e) {17 e.preventDefault();18 this.setState({ dragOver: false });19 }20 onDrop(e) {21 e.preventDefault();22 this.setState({ dragOver: false });23 this.props.onFile(e.dataTransfer.files);24 }25 render(){26 const { dragOver } = this.state;27 return (28 <div29 className={this.classNames({30 'ishow-upload-dragger': true,31 'is-dragover': dragOver32 })}33 onDrop={e => this.onDrop(e)}34 onDragOver={e => this.handleDragover(e)}35 onDragLeave={e => this.handleDragleave(e)}36 >37 {this.props.children}38 </div>39 );40 }41}42Cover.propTypes = {43 onFile: PropTypes.func44};45Cover.defaultProps = {46 onFile: Function...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.dragOver('#lst-ib');6 await page.type('#lst-ib', 'Hello World');7 await page.screenshot({path: 'example.png'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch();13 const page = await browser.newPage();14 await page.screenshot({path: 'example.png'});15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 await page.screenshot({path: 'example.png'});22 await browser.close();23})();24const puppeteer = require('puppeteer');25(async () => {26 const browser = await puppeteer.launch();27 const page = await browser.newPage();28 await page.exposeFunction('add', (a, b) => a + b);29 await page.evaluate(async () => {30 const result = await add(9, 4);31 });32 await browser.close();33})();34const puppeteer = require('puppeteer');35(async () => {36 const browser = await puppeteer.launch();37 const page = await browser.newPage();38 await page.focus('input');39 await page.screenshot({path: 'example.png'});40 await browser.close();41})();42const puppeteer = require('puppeteer');43(async () => {44 const browser = await puppeteer.launch();45 const page = await browser.newPage();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!