UNPKG

49.5 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('rxjs'), require('rxjs/operators')) :
3 typeof define === 'function' && define.amd ? define('angular-resizable-element', ['exports', '@angular/core', '@angular/common', 'rxjs', 'rxjs/operators'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['angular-resizable-element'] = {}, global.ng.core, global.ng.common, global.rxjs, global.rxjs.operators));
5}(this, (function (exports, core, common, rxjs, operators) { 'use strict';
6
7 /*! *****************************************************************************
8 Copyright (c) Microsoft Corporation.
9
10 Permission to use, copy, modify, and/or distribute this software for any
11 purpose with or without fee is hereby granted.
12
13 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19 PERFORMANCE OF THIS SOFTWARE.
20 ***************************************************************************** */
21 /* global Reflect, Promise */
22 var extendStatics = function (d, b) {
23 extendStatics = Object.setPrototypeOf ||
24 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25 function (d, b) { for (var p in b)
26 if (Object.prototype.hasOwnProperty.call(b, p))
27 d[p] = b[p]; };
28 return extendStatics(d, b);
29 };
30 function __extends(d, b) {
31 if (typeof b !== "function" && b !== null)
32 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
33 extendStatics(d, b);
34 function __() { this.constructor = d; }
35 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36 }
37 var __assign = function () {
38 __assign = Object.assign || function __assign(t) {
39 for (var s, i = 1, n = arguments.length; i < n; i++) {
40 s = arguments[i];
41 for (var p in s)
42 if (Object.prototype.hasOwnProperty.call(s, p))
43 t[p] = s[p];
44 }
45 return t;
46 };
47 return __assign.apply(this, arguments);
48 };
49 function __rest(s, e) {
50 var t = {};
51 for (var p in s)
52 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
53 t[p] = s[p];
54 if (s != null && typeof Object.getOwnPropertySymbols === "function")
55 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
56 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
57 t[p[i]] = s[p[i]];
58 }
59 return t;
60 }
61 function __decorate(decorators, target, key, desc) {
62 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
63 if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
64 r = Reflect.decorate(decorators, target, key, desc);
65 else
66 for (var i = decorators.length - 1; i >= 0; i--)
67 if (d = decorators[i])
68 r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
69 return c > 3 && r && Object.defineProperty(target, key, r), r;
70 }
71 function __param(paramIndex, decorator) {
72 return function (target, key) { decorator(target, key, paramIndex); };
73 }
74 function __metadata(metadataKey, metadataValue) {
75 if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
76 return Reflect.metadata(metadataKey, metadataValue);
77 }
78 function __awaiter(thisArg, _arguments, P, generator) {
79 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
80 return new (P || (P = Promise))(function (resolve, reject) {
81 function fulfilled(value) { try {
82 step(generator.next(value));
83 }
84 catch (e) {
85 reject(e);
86 } }
87 function rejected(value) { try {
88 step(generator["throw"](value));
89 }
90 catch (e) {
91 reject(e);
92 } }
93 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
94 step((generator = generator.apply(thisArg, _arguments || [])).next());
95 });
96 }
97 function __generator(thisArg, body) {
98 var _ = { label: 0, sent: function () { if (t[0] & 1)
99 throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
100 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
101 function verb(n) { return function (v) { return step([n, v]); }; }
102 function step(op) {
103 if (f)
104 throw new TypeError("Generator is already executing.");
105 while (_)
106 try {
107 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
108 return t;
109 if (y = 0, t)
110 op = [op[0] & 2, t.value];
111 switch (op[0]) {
112 case 0:
113 case 1:
114 t = op;
115 break;
116 case 4:
117 _.label++;
118 return { value: op[1], done: false };
119 case 5:
120 _.label++;
121 y = op[1];
122 op = [0];
123 continue;
124 case 7:
125 op = _.ops.pop();
126 _.trys.pop();
127 continue;
128 default:
129 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
130 _ = 0;
131 continue;
132 }
133 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
134 _.label = op[1];
135 break;
136 }
137 if (op[0] === 6 && _.label < t[1]) {
138 _.label = t[1];
139 t = op;
140 break;
141 }
142 if (t && _.label < t[2]) {
143 _.label = t[2];
144 _.ops.push(op);
145 break;
146 }
147 if (t[2])
148 _.ops.pop();
149 _.trys.pop();
150 continue;
151 }
152 op = body.call(thisArg, _);
153 }
154 catch (e) {
155 op = [6, e];
156 y = 0;
157 }
158 finally {
159 f = t = 0;
160 }
161 if (op[0] & 5)
162 throw op[1];
163 return { value: op[0] ? op[1] : void 0, done: true };
164 }
165 }
166 var __createBinding = Object.create ? (function (o, m, k, k2) {
167 if (k2 === undefined)
168 k2 = k;
169 Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
170 }) : (function (o, m, k, k2) {
171 if (k2 === undefined)
172 k2 = k;
173 o[k2] = m[k];
174 });
175 function __exportStar(m, o) {
176 for (var p in m)
177 if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
178 __createBinding(o, m, p);
179 }
180 function __values(o) {
181 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
182 if (m)
183 return m.call(o);
184 if (o && typeof o.length === "number")
185 return {
186 next: function () {
187 if (o && i >= o.length)
188 o = void 0;
189 return { value: o && o[i++], done: !o };
190 }
191 };
192 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
193 }
194 function __read(o, n) {
195 var m = typeof Symbol === "function" && o[Symbol.iterator];
196 if (!m)
197 return o;
198 var i = m.call(o), r, ar = [], e;
199 try {
200 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
201 ar.push(r.value);
202 }
203 catch (error) {
204 e = { error: error };
205 }
206 finally {
207 try {
208 if (r && !r.done && (m = i["return"]))
209 m.call(i);
210 }
211 finally {
212 if (e)
213 throw e.error;
214 }
215 }
216 return ar;
217 }
218 /** @deprecated */
219 function __spread() {
220 for (var ar = [], i = 0; i < arguments.length; i++)
221 ar = ar.concat(__read(arguments[i]));
222 return ar;
223 }
224 /** @deprecated */
225 function __spreadArrays() {
226 for (var s = 0, i = 0, il = arguments.length; i < il; i++)
227 s += arguments[i].length;
228 for (var r = Array(s), k = 0, i = 0; i < il; i++)
229 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
230 r[k] = a[j];
231 return r;
232 }
233 function __spreadArray(to, from, pack) {
234 if (pack || arguments.length === 2)
235 for (var i = 0, l = from.length, ar; i < l; i++) {
236 if (ar || !(i in from)) {
237 if (!ar)
238 ar = Array.prototype.slice.call(from, 0, i);
239 ar[i] = from[i];
240 }
241 }
242 return to.concat(ar || Array.prototype.slice.call(from));
243 }
244 function __await(v) {
245 return this instanceof __await ? (this.v = v, this) : new __await(v);
246 }
247 function __asyncGenerator(thisArg, _arguments, generator) {
248 if (!Symbol.asyncIterator)
249 throw new TypeError("Symbol.asyncIterator is not defined.");
250 var g = generator.apply(thisArg, _arguments || []), i, q = [];
251 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
252 function verb(n) { if (g[n])
253 i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
254 function resume(n, v) { try {
255 step(g[n](v));
256 }
257 catch (e) {
258 settle(q[0][3], e);
259 } }
260 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
261 function fulfill(value) { resume("next", value); }
262 function reject(value) { resume("throw", value); }
263 function settle(f, v) { if (f(v), q.shift(), q.length)
264 resume(q[0][0], q[0][1]); }
265 }
266 function __asyncDelegator(o) {
267 var i, p;
268 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
269 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
270 }
271 function __asyncValues(o) {
272 if (!Symbol.asyncIterator)
273 throw new TypeError("Symbol.asyncIterator is not defined.");
274 var m = o[Symbol.asyncIterator], i;
275 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
276 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
277 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
278 }
279 function __makeTemplateObject(cooked, raw) {
280 if (Object.defineProperty) {
281 Object.defineProperty(cooked, "raw", { value: raw });
282 }
283 else {
284 cooked.raw = raw;
285 }
286 return cooked;
287 }
288 ;
289 var __setModuleDefault = Object.create ? (function (o, v) {
290 Object.defineProperty(o, "default", { enumerable: true, value: v });
291 }) : function (o, v) {
292 o["default"] = v;
293 };
294 function __importStar(mod) {
295 if (mod && mod.__esModule)
296 return mod;
297 var result = {};
298 if (mod != null)
299 for (var k in mod)
300 if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
301 __createBinding(result, mod, k);
302 __setModuleDefault(result, mod);
303 return result;
304 }
305 function __importDefault(mod) {
306 return (mod && mod.__esModule) ? mod : { default: mod };
307 }
308 function __classPrivateFieldGet(receiver, state, kind, f) {
309 if (kind === "a" && !f)
310 throw new TypeError("Private accessor was defined without a getter");
311 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
312 throw new TypeError("Cannot read private member from an object whose class did not declare it");
313 return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
314 }
315 function __classPrivateFieldSet(receiver, state, value, kind, f) {
316 if (kind === "m")
317 throw new TypeError("Private method is not writable");
318 if (kind === "a" && !f)
319 throw new TypeError("Private accessor was defined without a setter");
320 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
321 throw new TypeError("Cannot write private member to an object whose class did not declare it");
322 return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
323 }
324
325 var ɵ0 = function () {
326 // In case we're in Node.js environment.
327 if (typeof window === 'undefined') {
328 return false;
329 }
330 else {
331 return ('ontouchstart' in window ||
332 navigator.maxTouchPoints > 0 ||
333 navigator.msMaxTouchPoints > 0);
334 }
335 };
336 /**
337 * @hidden
338 */
339 var IS_TOUCH_DEVICE = (ɵ0)();
340
341 /** Creates a deep clone of an element. */
342 function deepCloneNode(node) {
343 var clone = node.cloneNode(true);
344 var descendantsWithId = clone.querySelectorAll('[id]');
345 var nodeName = node.nodeName.toLowerCase();
346 // Remove the `id` to avoid having multiple elements with the same id on the page.
347 clone.removeAttribute('id');
348 descendantsWithId.forEach(function (descendant) {
349 descendant.removeAttribute('id');
350 });
351 if (nodeName === 'canvas') {
352 transferCanvasData(node, clone);
353 }
354 else if (nodeName === 'input' ||
355 nodeName === 'select' ||
356 nodeName === 'textarea') {
357 transferInputData(node, clone);
358 }
359 transferData('canvas', node, clone, transferCanvasData);
360 transferData('input, textarea, select', node, clone, transferInputData);
361 return clone;
362 }
363 /** Matches elements between an element and its clone and allows for their data to be cloned. */
364 function transferData(selector, node, clone, callback) {
365 var descendantElements = node.querySelectorAll(selector);
366 if (descendantElements.length) {
367 var cloneElements = clone.querySelectorAll(selector);
368 for (var i = 0; i < descendantElements.length; i++) {
369 callback(descendantElements[i], cloneElements[i]);
370 }
371 }
372 }
373 // Counter for unique cloned radio button names.
374 var cloneUniqueId = 0;
375 /** Transfers the data of one input element to another. */
376 function transferInputData(source, clone) {
377 // Browsers throw an error when assigning the value of a file input programmatically.
378 if (clone.type !== 'file') {
379 clone.value = source.value;
380 }
381 // Radio button `name` attributes must be unique for radio button groups
382 // otherwise original radio buttons can lose their checked state
383 // once the clone is inserted in the DOM.
384 if (clone.type === 'radio' && clone.name) {
385 clone.name = "mat-clone-" + clone.name + "-" + cloneUniqueId++;
386 }
387 }
388 /** Transfers the data of one canvas element to another. */
389 function transferCanvasData(source, clone) {
390 var context = clone.getContext('2d');
391 if (context) {
392 // In some cases `drawImage` can throw (e.g. if the canvas size is 0x0).
393 // We can't do much about it so just ignore the error.
394 try {
395 context.drawImage(source, 0, 0);
396 }
397 catch (_a) { }
398 }
399 }
400
401 function getNewBoundingRectangle(startingRect, edges, clientX, clientY) {
402 var newBoundingRect = {
403 top: startingRect.top,
404 bottom: startingRect.bottom,
405 left: startingRect.left,
406 right: startingRect.right,
407 };
408 if (edges.top) {
409 newBoundingRect.top += clientY;
410 }
411 if (edges.bottom) {
412 newBoundingRect.bottom += clientY;
413 }
414 if (edges.left) {
415 newBoundingRect.left += clientX;
416 }
417 if (edges.right) {
418 newBoundingRect.right += clientX;
419 }
420 newBoundingRect.height = newBoundingRect.bottom - newBoundingRect.top;
421 newBoundingRect.width = newBoundingRect.right - newBoundingRect.left;
422 return newBoundingRect;
423 }
424 function getElementRect(element, ghostElementPositioning) {
425 var translateX = 0;
426 var translateY = 0;
427 var style = element.nativeElement.style;
428 var transformProperties = [
429 'transform',
430 '-ms-transform',
431 '-moz-transform',
432 '-o-transform',
433 ];
434 var transform = transformProperties
435 .map(function (property) { return style[property]; })
436 .find(function (value) { return !!value; });
437 if (transform && transform.includes('translate')) {
438 translateX = transform.replace(/.*translate3?d?\((-?[0-9]*)px, (-?[0-9]*)px.*/, '$1');
439 translateY = transform.replace(/.*translate3?d?\((-?[0-9]*)px, (-?[0-9]*)px.*/, '$2');
440 }
441 if (ghostElementPositioning === 'absolute') {
442 return {
443 height: element.nativeElement.offsetHeight,
444 width: element.nativeElement.offsetWidth,
445 top: element.nativeElement.offsetTop - translateY,
446 bottom: element.nativeElement.offsetHeight +
447 element.nativeElement.offsetTop -
448 translateY,
449 left: element.nativeElement.offsetLeft - translateX,
450 right: element.nativeElement.offsetWidth +
451 element.nativeElement.offsetLeft -
452 translateX,
453 };
454 }
455 else {
456 var boundingRect = element.nativeElement.getBoundingClientRect();
457 return {
458 height: boundingRect.height,
459 width: boundingRect.width,
460 top: boundingRect.top - translateY,
461 bottom: boundingRect.bottom - translateY,
462 left: boundingRect.left - translateX,
463 right: boundingRect.right - translateX,
464 scrollTop: element.nativeElement.scrollTop,
465 scrollLeft: element.nativeElement.scrollLeft,
466 };
467 }
468 }
469 var DEFAULT_RESIZE_CURSORS = Object.freeze({
470 topLeft: 'nw-resize',
471 topRight: 'ne-resize',
472 bottomLeft: 'sw-resize',
473 bottomRight: 'se-resize',
474 leftOrRight: 'col-resize',
475 topOrBottom: 'row-resize',
476 });
477 function getResizeCursor(edges, cursors) {
478 if (edges.left && edges.top) {
479 return cursors.topLeft;
480 }
481 else if (edges.right && edges.top) {
482 return cursors.topRight;
483 }
484 else if (edges.left && edges.bottom) {
485 return cursors.bottomLeft;
486 }
487 else if (edges.right && edges.bottom) {
488 return cursors.bottomRight;
489 }
490 else if (edges.left || edges.right) {
491 return cursors.leftOrRight;
492 }
493 else if (edges.top || edges.bottom) {
494 return cursors.topOrBottom;
495 }
496 else {
497 return '';
498 }
499 }
500 function getEdgesDiff(_a) {
501 var edges = _a.edges, initialRectangle = _a.initialRectangle, newRectangle = _a.newRectangle;
502 var edgesDiff = {};
503 Object.keys(edges).forEach(function (edge) {
504 edgesDiff[edge] = (newRectangle[edge] || 0) - (initialRectangle[edge] || 0);
505 });
506 return edgesDiff;
507 }
508 var RESIZE_ACTIVE_CLASS = 'resize-active';
509 var RESIZE_GHOST_ELEMENT_CLASS = 'resize-ghost-element';
510 var MOUSE_MOVE_THROTTLE_MS = 50;
511 /**
512 * Place this on an element to make it resizable. For example:
513 *
514 * ```html
515 * <div
516 * mwlResizable
517 * [resizeEdges]="{bottom: true, right: true, top: true, left: true}"
518 * [enableGhostResize]="true">
519 * </div>
520 * ```
521 * Or in case they are sibling elements:
522 * ```html
523 * <div mwlResizable #resizableElement="mwlResizable"></div>
524 * <div mwlResizeHandle [resizableContainer]="resizableElement" [resizeEdges]="{bottom: true, right: true}"></div>
525 * ```
526 */
527 var ResizableDirective = /** @class */ (function () {
528 /**
529 * @hidden
530 */
531 function ResizableDirective(platformId, renderer, elm, zone) {
532 this.platformId = platformId;
533 this.renderer = renderer;
534 this.elm = elm;
535 this.zone = zone;
536 /**
537 * Set to `true` to enable a temporary resizing effect of the element in between the `resizeStart` and `resizeEnd` events.
538 */
539 this.enableGhostResize = false;
540 /**
541 * A snap grid that resize events will be locked to.
542 *
543 * e.g. to only allow the element to be resized every 10px set it to `{left: 10, right: 10}`
544 */
545 this.resizeSnapGrid = {};
546 /**
547 * The mouse cursors that will be set on the resize edges
548 */
549 this.resizeCursors = DEFAULT_RESIZE_CURSORS;
550 /**
551 * Define the positioning of the ghost element (can be fixed or absolute)
552 */
553 this.ghostElementPositioning = 'fixed';
554 /**
555 * Allow elements to be resized to negative dimensions
556 */
557 this.allowNegativeResizes = false;
558 /**
559 * The mouse move throttle in milliseconds, default: 50 ms
560 */
561 this.mouseMoveThrottleMS = MOUSE_MOVE_THROTTLE_MS;
562 /**
563 * Called when the mouse is pressed and a resize event is about to begin. `$event` is a `ResizeEvent` object.
564 */
565 this.resizeStart = new core.EventEmitter();
566 /**
567 * Called as the mouse is dragged after a resize event has begun. `$event` is a `ResizeEvent` object.
568 */
569 this.resizing = new core.EventEmitter();
570 /**
571 * Called after the mouse is released after a resize event. `$event` is a `ResizeEvent` object.
572 */
573 this.resizeEnd = new core.EventEmitter();
574 /**
575 * @hidden
576 */
577 this.mouseup = new rxjs.Subject();
578 /**
579 * @hidden
580 */
581 this.mousedown = new rxjs.Subject();
582 /**
583 * @hidden
584 */
585 this.mousemove = new rxjs.Subject();
586 this.destroy$ = new rxjs.Subject();
587 this.pointerEventListeners = PointerEventListeners.getInstance(renderer, zone);
588 }
589 /**
590 * @hidden
591 */
592 ResizableDirective.prototype.ngOnInit = function () {
593 var _this = this;
594 var mousedown$ = rxjs.merge(this.pointerEventListeners.pointerDown, this.mousedown);
595 var mousemove$ = rxjs.merge(this.pointerEventListeners.pointerMove, this.mousemove).pipe(operators.tap(function (_a) {
596 var event = _a.event;
597 if (currentResize) {
598 try {
599 event.preventDefault();
600 }
601 catch (e) {
602 // just adding try-catch not to see errors in console if there is a passive listener for same event somewhere
603 // browser does nothing except of writing errors to console
604 }
605 }
606 }), operators.share());
607 var mouseup$ = rxjs.merge(this.pointerEventListeners.pointerUp, this.mouseup);
608 var currentResize;
609 var removeGhostElement = function () {
610 if (currentResize && currentResize.clonedNode) {
611 _this.elm.nativeElement.parentElement.removeChild(currentResize.clonedNode);
612 _this.renderer.setStyle(_this.elm.nativeElement, 'visibility', 'inherit');
613 }
614 };
615 var getResizeCursors = function () {
616 return Object.assign(Object.assign({}, DEFAULT_RESIZE_CURSORS), _this.resizeCursors);
617 };
618 var mousedrag = mousedown$
619 .pipe(operators.mergeMap(function (startCoords) {
620 function getDiff(moveCoords) {
621 return {
622 clientX: moveCoords.clientX - startCoords.clientX,
623 clientY: moveCoords.clientY - startCoords.clientY,
624 };
625 }
626 var getSnapGrid = function () {
627 var snapGrid = { x: 1, y: 1 };
628 if (currentResize) {
629 if (_this.resizeSnapGrid.left && currentResize.edges.left) {
630 snapGrid.x = +_this.resizeSnapGrid.left;
631 }
632 else if (_this.resizeSnapGrid.right &&
633 currentResize.edges.right) {
634 snapGrid.x = +_this.resizeSnapGrid.right;
635 }
636 if (_this.resizeSnapGrid.top && currentResize.edges.top) {
637 snapGrid.y = +_this.resizeSnapGrid.top;
638 }
639 else if (_this.resizeSnapGrid.bottom &&
640 currentResize.edges.bottom) {
641 snapGrid.y = +_this.resizeSnapGrid.bottom;
642 }
643 }
644 return snapGrid;
645 };
646 function getGrid(coords, snapGrid) {
647 return {
648 x: Math.ceil(coords.clientX / snapGrid.x),
649 y: Math.ceil(coords.clientY / snapGrid.y),
650 };
651 }
652 return rxjs.merge(mousemove$.pipe(operators.take(1)).pipe(operators.map(function (coords) { return [, coords]; })), mousemove$.pipe(operators.pairwise()))
653 .pipe(operators.map(function (_a) {
654 var _b = __read(_a, 2), previousCoords = _b[0], newCoords = _b[1];
655 return [
656 previousCoords ? getDiff(previousCoords) : previousCoords,
657 getDiff(newCoords),
658 ];
659 }))
660 .pipe(operators.filter(function (_a) {
661 var _b = __read(_a, 2), previousCoords = _b[0], newCoords = _b[1];
662 if (!previousCoords) {
663 return true;
664 }
665 var snapGrid = getSnapGrid();
666 var previousGrid = getGrid(previousCoords, snapGrid);
667 var newGrid = getGrid(newCoords, snapGrid);
668 return (previousGrid.x !== newGrid.x || previousGrid.y !== newGrid.y);
669 }))
670 .pipe(operators.map(function (_a) {
671 var _b = __read(_a, 2), newCoords = _b[1];
672 var snapGrid = getSnapGrid();
673 return {
674 clientX: Math.round(newCoords.clientX / snapGrid.x) * snapGrid.x,
675 clientY: Math.round(newCoords.clientY / snapGrid.y) * snapGrid.y,
676 };
677 }))
678 .pipe(operators.takeUntil(rxjs.merge(mouseup$, mousedown$)));
679 }))
680 .pipe(operators.filter(function () { return !!currentResize; }));
681 mousedrag
682 .pipe(operators.map(function (_a) {
683 var clientX = _a.clientX, clientY = _a.clientY;
684 return getNewBoundingRectangle(currentResize.startingRect, currentResize.edges, clientX, clientY);
685 }))
686 .pipe(operators.filter(function (newBoundingRect) {
687 return (_this.allowNegativeResizes ||
688 !!(newBoundingRect.height &&
689 newBoundingRect.width &&
690 newBoundingRect.height > 0 &&
691 newBoundingRect.width > 0));
692 }))
693 .pipe(operators.filter(function (newBoundingRect) {
694 return _this.validateResize
695 ? _this.validateResize({
696 rectangle: newBoundingRect,
697 edges: getEdgesDiff({
698 edges: currentResize.edges,
699 initialRectangle: currentResize.startingRect,
700 newRectangle: newBoundingRect,
701 }),
702 })
703 : true;
704 }), operators.takeUntil(this.destroy$))
705 .subscribe(function (newBoundingRect) {
706 if (currentResize && currentResize.clonedNode) {
707 _this.renderer.setStyle(currentResize.clonedNode, 'height', newBoundingRect.height + "px");
708 _this.renderer.setStyle(currentResize.clonedNode, 'width', newBoundingRect.width + "px");
709 _this.renderer.setStyle(currentResize.clonedNode, 'top', newBoundingRect.top + "px");
710 _this.renderer.setStyle(currentResize.clonedNode, 'left', newBoundingRect.left + "px");
711 }
712 if (_this.resizing.observers.length > 0) {
713 _this.zone.run(function () {
714 _this.resizing.emit({
715 edges: getEdgesDiff({
716 edges: currentResize.edges,
717 initialRectangle: currentResize.startingRect,
718 newRectangle: newBoundingRect,
719 }),
720 rectangle: newBoundingRect,
721 });
722 });
723 }
724 currentResize.currentRect = newBoundingRect;
725 });
726 mousedown$
727 .pipe(operators.map(function (_a) {
728 var edges = _a.edges;
729 return edges || {};
730 }), operators.filter(function (edges) {
731 return Object.keys(edges).length > 0;
732 }), operators.takeUntil(this.destroy$))
733 .subscribe(function (edges) {
734 if (currentResize) {
735 removeGhostElement();
736 }
737 var startingRect = getElementRect(_this.elm, _this.ghostElementPositioning);
738 currentResize = {
739 edges: edges,
740 startingRect: startingRect,
741 currentRect: startingRect,
742 };
743 var resizeCursors = getResizeCursors();
744 var cursor = getResizeCursor(currentResize.edges, resizeCursors);
745 _this.renderer.setStyle(document.body, 'cursor', cursor);
746 _this.setElementClass(_this.elm, RESIZE_ACTIVE_CLASS, true);
747 if (_this.enableGhostResize) {
748 currentResize.clonedNode = deepCloneNode(_this.elm.nativeElement);
749 _this.elm.nativeElement.parentElement.appendChild(currentResize.clonedNode);
750 _this.renderer.setStyle(_this.elm.nativeElement, 'visibility', 'hidden');
751 _this.renderer.setStyle(currentResize.clonedNode, 'position', _this.ghostElementPositioning);
752 _this.renderer.setStyle(currentResize.clonedNode, 'left', currentResize.startingRect.left + "px");
753 _this.renderer.setStyle(currentResize.clonedNode, 'top', currentResize.startingRect.top + "px");
754 _this.renderer.setStyle(currentResize.clonedNode, 'height', currentResize.startingRect.height + "px");
755 _this.renderer.setStyle(currentResize.clonedNode, 'width', currentResize.startingRect.width + "px");
756 _this.renderer.setStyle(currentResize.clonedNode, 'cursor', getResizeCursor(currentResize.edges, resizeCursors));
757 _this.renderer.addClass(currentResize.clonedNode, RESIZE_GHOST_ELEMENT_CLASS);
758 currentResize.clonedNode.scrollTop = currentResize.startingRect
759 .scrollTop;
760 currentResize.clonedNode.scrollLeft = currentResize.startingRect
761 .scrollLeft;
762 }
763 if (_this.resizeStart.observers.length > 0) {
764 _this.zone.run(function () {
765 _this.resizeStart.emit({
766 edges: getEdgesDiff({
767 edges: edges,
768 initialRectangle: startingRect,
769 newRectangle: startingRect,
770 }),
771 rectangle: getNewBoundingRectangle(startingRect, {}, 0, 0),
772 });
773 });
774 }
775 });
776 mouseup$.pipe(operators.takeUntil(this.destroy$)).subscribe(function () {
777 if (currentResize) {
778 _this.renderer.removeClass(_this.elm.nativeElement, RESIZE_ACTIVE_CLASS);
779 _this.renderer.setStyle(document.body, 'cursor', '');
780 _this.renderer.setStyle(_this.elm.nativeElement, 'cursor', '');
781 if (_this.resizeEnd.observers.length > 0) {
782 _this.zone.run(function () {
783 _this.resizeEnd.emit({
784 edges: getEdgesDiff({
785 edges: currentResize.edges,
786 initialRectangle: currentResize.startingRect,
787 newRectangle: currentResize.currentRect,
788 }),
789 rectangle: currentResize.currentRect,
790 });
791 });
792 }
793 removeGhostElement();
794 currentResize = null;
795 }
796 });
797 };
798 /**
799 * @hidden
800 */
801 ResizableDirective.prototype.ngOnDestroy = function () {
802 // browser check for angular universal, because it doesn't know what document is
803 if (common.isPlatformBrowser(this.platformId)) {
804 this.renderer.setStyle(document.body, 'cursor', '');
805 }
806 this.mousedown.complete();
807 this.mouseup.complete();
808 this.mousemove.complete();
809 this.destroy$.next();
810 };
811 ResizableDirective.prototype.setElementClass = function (elm, name, add) {
812 if (add) {
813 this.renderer.addClass(elm.nativeElement, name);
814 }
815 else {
816 this.renderer.removeClass(elm.nativeElement, name);
817 }
818 };
819 return ResizableDirective;
820 }());
821 ResizableDirective.decorators = [
822 { type: core.Directive, args: [{
823 selector: '[mwlResizable]',
824 exportAs: 'mwlResizable',
825 },] }
826 ];
827 ResizableDirective.ctorParameters = function () { return [
828 { type: undefined, decorators: [{ type: core.Inject, args: [core.PLATFORM_ID,] }] },
829 { type: core.Renderer2 },
830 { type: core.ElementRef },
831 { type: core.NgZone }
832 ]; };
833 ResizableDirective.propDecorators = {
834 validateResize: [{ type: core.Input }],
835 enableGhostResize: [{ type: core.Input }],
836 resizeSnapGrid: [{ type: core.Input }],
837 resizeCursors: [{ type: core.Input }],
838 ghostElementPositioning: [{ type: core.Input }],
839 allowNegativeResizes: [{ type: core.Input }],
840 mouseMoveThrottleMS: [{ type: core.Input }],
841 resizeStart: [{ type: core.Output }],
842 resizing: [{ type: core.Output }],
843 resizeEnd: [{ type: core.Output }]
844 };
845 var PointerEventListeners = /** @class */ (function () {
846 function PointerEventListeners(renderer, zone) {
847 this.pointerDown = new rxjs.Observable(function (observer) {
848 var unsubscribeMouseDown;
849 var unsubscribeTouchStart;
850 zone.runOutsideAngular(function () {
851 unsubscribeMouseDown = renderer.listen('document', 'mousedown', function (event) {
852 observer.next({
853 clientX: event.clientX,
854 clientY: event.clientY,
855 event: event,
856 });
857 });
858 if (IS_TOUCH_DEVICE) {
859 unsubscribeTouchStart = renderer.listen('document', 'touchstart', function (event) {
860 observer.next({
861 clientX: event.touches[0].clientX,
862 clientY: event.touches[0].clientY,
863 event: event,
864 });
865 });
866 }
867 });
868 return function () {
869 unsubscribeMouseDown();
870 if (IS_TOUCH_DEVICE) {
871 unsubscribeTouchStart();
872 }
873 };
874 }).pipe(operators.share());
875 this.pointerMove = new rxjs.Observable(function (observer) {
876 var unsubscribeMouseMove;
877 var unsubscribeTouchMove;
878 zone.runOutsideAngular(function () {
879 unsubscribeMouseMove = renderer.listen('document', 'mousemove', function (event) {
880 observer.next({
881 clientX: event.clientX,
882 clientY: event.clientY,
883 event: event,
884 });
885 });
886 if (IS_TOUCH_DEVICE) {
887 unsubscribeTouchMove = renderer.listen('document', 'touchmove', function (event) {
888 observer.next({
889 clientX: event.targetTouches[0].clientX,
890 clientY: event.targetTouches[0].clientY,
891 event: event,
892 });
893 });
894 }
895 });
896 return function () {
897 unsubscribeMouseMove();
898 if (IS_TOUCH_DEVICE) {
899 unsubscribeTouchMove();
900 }
901 };
902 }).pipe(operators.share());
903 this.pointerUp = new rxjs.Observable(function (observer) {
904 var unsubscribeMouseUp;
905 var unsubscribeTouchEnd;
906 var unsubscribeTouchCancel;
907 zone.runOutsideAngular(function () {
908 unsubscribeMouseUp = renderer.listen('document', 'mouseup', function (event) {
909 observer.next({
910 clientX: event.clientX,
911 clientY: event.clientY,
912 event: event,
913 });
914 });
915 if (IS_TOUCH_DEVICE) {
916 unsubscribeTouchEnd = renderer.listen('document', 'touchend', function (event) {
917 observer.next({
918 clientX: event.changedTouches[0].clientX,
919 clientY: event.changedTouches[0].clientY,
920 event: event,
921 });
922 });
923 unsubscribeTouchCancel = renderer.listen('document', 'touchcancel', function (event) {
924 observer.next({
925 clientX: event.changedTouches[0].clientX,
926 clientY: event.changedTouches[0].clientY,
927 event: event,
928 });
929 });
930 }
931 });
932 return function () {
933 unsubscribeMouseUp();
934 if (IS_TOUCH_DEVICE) {
935 unsubscribeTouchEnd();
936 unsubscribeTouchCancel();
937 }
938 };
939 }).pipe(operators.share());
940 }
941 PointerEventListeners.getInstance = function (renderer, zone) {
942 if (!PointerEventListeners.instance) {
943 PointerEventListeners.instance = new PointerEventListeners(renderer, zone);
944 }
945 return PointerEventListeners.instance;
946 };
947 return PointerEventListeners;
948 }());
949
950 /**
951 * An element placed inside a `mwlResizable` directive to be used as a drag and resize handle
952 *
953 * For example
954 *
955 * ```html
956 * <div mwlResizable>
957 * <div mwlResizeHandle [resizeEdges]="{bottom: true, right: true}"></div>
958 * </div>
959 * ```
960 * Or in case they are sibling elements:
961 * ```html
962 * <div mwlResizable #resizableElement="mwlResizable"></div>
963 * <div mwlResizeHandle [resizableContainer]="resizableElement" [resizeEdges]="{bottom: true, right: true}"></div>
964 * ```
965 */
966 var ResizeHandleDirective = /** @class */ (function () {
967 function ResizeHandleDirective(renderer, element, zone, resizableDirective) {
968 this.renderer = renderer;
969 this.element = element;
970 this.zone = zone;
971 this.resizableDirective = resizableDirective;
972 /**
973 * The `Edges` object that contains the edges of the parent element that dragging the handle will trigger a resize on
974 */
975 this.resizeEdges = {};
976 this.eventListeners = {};
977 this.destroy$ = new rxjs.Subject();
978 }
979 ResizeHandleDirective.prototype.ngOnInit = function () {
980 var _this = this;
981 this.zone.runOutsideAngular(function () {
982 _this.listenOnTheHost('mousedown').subscribe(function (event) {
983 _this.onMousedown(event, event.clientX, event.clientY);
984 });
985 _this.listenOnTheHost('mouseup').subscribe(function (event) {
986 _this.onMouseup(event.clientX, event.clientY);
987 });
988 if (IS_TOUCH_DEVICE) {
989 _this.listenOnTheHost('touchstart').subscribe(function (event) {
990 _this.onMousedown(event, event.touches[0].clientX, event.touches[0].clientY);
991 });
992 rxjs.merge(_this.listenOnTheHost('touchend'), _this.listenOnTheHost('touchcancel')).subscribe(function (event) {
993 _this.onMouseup(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
994 });
995 }
996 });
997 };
998 ResizeHandleDirective.prototype.ngOnDestroy = function () {
999 this.destroy$.next();
1000 this.unsubscribeEventListeners();
1001 };
1002 /**
1003 * @hidden
1004 */
1005 ResizeHandleDirective.prototype.onMousedown = function (event, clientX, clientY) {
1006 var _this = this;
1007 event.preventDefault();
1008 if (!this.eventListeners.touchmove) {
1009 this.eventListeners.touchmove = this.renderer.listen(this.element.nativeElement, 'touchmove', function (touchMoveEvent) {
1010 _this.onMousemove(touchMoveEvent, touchMoveEvent.targetTouches[0].clientX, touchMoveEvent.targetTouches[0].clientY);
1011 });
1012 }
1013 if (!this.eventListeners.mousemove) {
1014 this.eventListeners.mousemove = this.renderer.listen(this.element.nativeElement, 'mousemove', function (mouseMoveEvent) {
1015 _this.onMousemove(mouseMoveEvent, mouseMoveEvent.clientX, mouseMoveEvent.clientY);
1016 });
1017 }
1018 this.resizable.mousedown.next({
1019 clientX: clientX,
1020 clientY: clientY,
1021 edges: this.resizeEdges,
1022 });
1023 };
1024 /**
1025 * @hidden
1026 */
1027 ResizeHandleDirective.prototype.onMouseup = function (clientX, clientY) {
1028 this.unsubscribeEventListeners();
1029 this.resizable.mouseup.next({
1030 clientX: clientX,
1031 clientY: clientY,
1032 edges: this.resizeEdges,
1033 });
1034 };
1035 Object.defineProperty(ResizeHandleDirective.prototype, "resizable", {
1036 // directive might be passed from DI or as an input
1037 get: function () {
1038 return this.resizableDirective || this.resizableContainer;
1039 },
1040 enumerable: false,
1041 configurable: true
1042 });
1043 ResizeHandleDirective.prototype.onMousemove = function (event, clientX, clientY) {
1044 this.resizable.mousemove.next({
1045 clientX: clientX,
1046 clientY: clientY,
1047 edges: this.resizeEdges,
1048 event: event,
1049 });
1050 };
1051 ResizeHandleDirective.prototype.unsubscribeEventListeners = function () {
1052 var _this = this;
1053 Object.keys(this.eventListeners).forEach(function (type) {
1054 _this.eventListeners[type]();
1055 delete _this.eventListeners[type];
1056 });
1057 };
1058 ResizeHandleDirective.prototype.listenOnTheHost = function (eventName) {
1059 return rxjs.fromEvent(this.element.nativeElement, eventName).pipe(operators.takeUntil(this.destroy$));
1060 };
1061 return ResizeHandleDirective;
1062 }());
1063 ResizeHandleDirective.decorators = [
1064 { type: core.Directive, args: [{
1065 selector: '[mwlResizeHandle]',
1066 },] }
1067 ];
1068 ResizeHandleDirective.ctorParameters = function () { return [
1069 { type: core.Renderer2 },
1070 { type: core.ElementRef },
1071 { type: core.NgZone },
1072 { type: ResizableDirective, decorators: [{ type: core.Optional }] }
1073 ]; };
1074 ResizeHandleDirective.propDecorators = {
1075 resizeEdges: [{ type: core.Input }],
1076 resizableContainer: [{ type: core.Input }]
1077 };
1078
1079 var ResizableModule = /** @class */ (function () {
1080 function ResizableModule() {
1081 }
1082 return ResizableModule;
1083 }());
1084 ResizableModule.decorators = [
1085 { type: core.NgModule, args: [{
1086 declarations: [ResizableDirective, ResizeHandleDirective],
1087 exports: [ResizableDirective, ResizeHandleDirective],
1088 },] }
1089 ];
1090
1091 /*
1092 * Public API Surface of angular-resizable-element
1093 */
1094
1095 /**
1096 * Generated bundle index. Do not edit.
1097 */
1098
1099 exports.ResizableDirective = ResizableDirective;
1100 exports.ResizableModule = ResizableModule;
1101 exports.ResizeHandleDirective = ResizeHandleDirective;
1102
1103 Object.defineProperty(exports, '__esModule', { value: true });
1104
1105})));
1106//# sourceMappingURL=angular-resizable-element.umd.js.map