aboutsummaryrefslogtreecommitdiff
path: root/src/ClientUtils.ts
blob: a4d9dd8922bf0965afcd8df7b17b1b84ef78d0e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import * as Color from 'color';
import * as React from 'react';
import { ColorResult } from 'react-color';
import * as rp from 'request-promise';
import { numberRange, decimalToHexString } from './Utils';
import { CollectionViewType, DocumentType } from './client/documents/DocumentTypes';
import { Colors } from './client/views/global/globalEnums';
import { CreateImage } from './client/views/nodes/WebBoxRenderer';

export function DashColor(color: string) {
    try {
        return color ? Color(color.toLowerCase()) : Color('transparent');
    } catch (e) {
        if (color.includes('gradient')) console.log("using color 'white' in place of :" + color);
        else console.log('COLOR error:', e);
        return Color('white');
    }
}

export function lightOrDark(color: any) {
    if (color === 'transparent' || !color) return Colors.BLACK;
    if (color.startsWith?.('linear')) return Colors.BLACK;
    if (DashColor(color).isLight()) return Colors.BLACK;
    return Colors.WHITE;
}

export function returnTransparent() {
    return 'transparent';
}

export function returnTrue() {
    return true;
}

export function returnIgnore(): 'ignore' {
    return 'ignore';
}
export function returnAlways(): 'always' {
    return 'always';
}
export function returnNever(): 'never' {
    return 'never';
}

export function returnDefault(): 'default' {
    return 'default';
}

export function return18() {
    return 18;
}

export function returnFalse() {
    return false;
}

export function returnAll(): 'all' {
    return 'all';
}

export function returnNone(): 'none' {
    return 'none';
}

export function returnVal(val1?: number, val2?: number) {
    return val1 || (val2 !== undefined ? val2 : 0);
}

export function returnOne() {
    return 1;
}

export function returnZero() {
    return 0;
}

export function returnEmptyString() {
    return '';
}

export function returnEmptyFilter() {
    return [] as string[];
}

export function returnEmptyDoclist() {
    return [] as any[];
}

// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace ClientUtils {
    export const CLICK_TIME = 300;
    export const DRAG_THRESHOLD = 4;
    export const SNAP_THRESHOLD = 10;
    let _currentUserEmail: string = '';
    export function CurrentUserEmail() {
        return _currentUserEmail;
    }
    export function SetCurrentUserEmail(email: string) {
        _currentUserEmail = email;
    }
    export function isClick(x: number, y: number, downX: number, downY: number, downTime: number) {
        return Date.now() - downTime < ClientUtils.CLICK_TIME && Math.abs(x - downX) < ClientUtils.DRAG_THRESHOLD && Math.abs(y - downY) < ClientUtils.DRAG_THRESHOLD;
    }

    export function cleanDocumentTypeExt(type: DocumentType) {
        switch (type) {
            case DocumentType.PDF:   return 'PDF';
            case DocumentType.IMG:   return 'Img';
            case DocumentType.AUDIO: return 'Aud';
            case DocumentType.COL:   return 'Col';
            case DocumentType.RTF:   return 'Rtf';
            default:                 return type.charAt(0).toUpperCase() + type.substring(1,3);
        } // prettier-ignore
    }
    export function cleanDocumentType(type: DocumentType, colType: CollectionViewType) {
        switch (type) {
            case DocumentType.PDF:   return 'PDF';
            case DocumentType.IMG:   return 'Image';
            case DocumentType.AUDIO: return 'Audio';
            case DocumentType.COL:   return 'Collection:'+colType;
            case DocumentType.RTF:   return 'Text';
            default:                 return type.charAt(0).toUpperCase() + type.slice(1);
        } // prettier-ignore
    }

    export function readUploadedFileAsText(inputFile: File) {
        // eslint-disable-next-line no-undef
        const temporaryFileReader = new FileReader();

        return new Promise((resolve, reject) => {
            temporaryFileReader.onerror = () => {
                temporaryFileReader.abort();
                reject(new DOMException('Problem parsing input file.'));
            };

            temporaryFileReader.onload = () => {
                resolve(temporaryFileReader.result);
            };
            temporaryFileReader.readAsText(inputFile);
        });
    }

    /**
     * Uploads an image buffer to the server and stores with specified filename.  by default the image
     * is stored at multiple resolutions each retrieved by using the filename appended with _o, _s, _m, _l (indicating original, small, medium, or large)
     * @param imageUri the bytes of the image
     * @param returnedFilename the base filename to store the image on the server
     * @param nosuffix optionally suppress creating multiple resolution images
     */
    export async function convertDataUri(imageUri: string, returnedFilename: string, nosuffix = false, replaceRootFilename: string | undefined = undefined) {
        try {
            const posting = ClientUtils.prepend('/uploadURI');
            const returnedUri = await rp.post(posting, {
                body: {
                    uri: imageUri,
                    name: returnedFilename,
                    nosuffix,
                    replaceRootFilename,
                },
                json: true,
            });
            return returnedUri;
        } catch (e) {
            console.log('ConvertDataURI :' + e);
        }
        return undefined;
    }

    export function GetScreenTransform(ele?: HTMLElement | null): { scale: number; translateX: number; translateY: number } {
        if (!ele) {
            return { scale: 1, translateX: 1, translateY: 1 };
        }
        const rect = ele.getBoundingClientRect();
        const scale = ele.offsetWidth === 0 && rect.width === 0 ? 1 : rect.width / ele.offsetWidth;
        const translateX = rect.left;
        const translateY = rect.top;

        return { scale, translateX, translateY };
    }

    /**
     * A convenience method. Prepends the full path (i.e. http://localhost:<port>) to the
     * requested extension
     * @param extension the specified sub-path to append to the window origin
     */
    export function prepend(extension: string): string {
        return window.location.origin + extension;
    }
    export function fileUrl(filename: string): string {
        return prepend(`/files/${filename}`);
    }

    export function shareUrl(documentId: string): string {
        return prepend(`/doc/${documentId}?sharing=true`);
    }

    export function CorsProxy(url: string): string {
        return prepend('/corsProxy/') + encodeURIComponent(url);
    }

    export function CopyText(text: string) {
        navigator.clipboard.writeText(text);
    }

    export function colorString(color: ColorResult) {
        return color.hex.startsWith('#') && color.hex.length < 8 ? color.hex + (color.rgb.a ? decimalToHexString(Math.round(color.rgb.a * 255)) : 'ff') : color.hex;
    }

    export function fromRGBAstr(rgba: string) {
        const rm = rgba.match(/rgb[a]?\(([ 0-9]+)/);
        const r = rm ? Number(rm[1]) : 0;
        const gm = rgba.match(/rgb[a]?\([ 0-9]+,([ 0-9]+)/);
        const g = gm ? Number(gm[1]) : 0;
        const bm = rgba.match(/rgb[a]?\([ 0-9]+,[ 0-9]+,([ 0-9]+)/);
        const b = bm ? Number(bm[1]) : 0;
        const am = rgba.match(/rgba?\([ 0-9]+,[ 0-9]+,[ 0-9]+,([ .0-9]+)/);
        const a = am ? Number(am[1]) : 1;
        return { r: r, g: g, b: b, a: a };
    }

    const isTransparentFunctionHack = 'isTransparent(__value__)';
    export const noRecursionHack = '__noRecursion';

    // special case filters
    export const noDragDocsFilter = 'noDragDocs::any::check';
    export const TransparentBackgroundFilter = `backgroundColor::${isTransparentFunctionHack},${noRecursionHack}::check`; // bcz: hack.  noRecursion should probably be either another ':' delimited field, or it should be a modifier to the comparision (eg., check, x, etc) field
    export const OpaqueBackgroundFilter = `backgroundColor::${isTransparentFunctionHack},${noRecursionHack}::x`; // bcz: hack.  noRecursion should probably be either another ':' delimited field, or it should be a modifier to the comparision (eg., check, x, etc) field

    export function IsRecursiveFilter(val: string) {
        return !val.includes(noRecursionHack);
    }
    export function HasFunctionFilter(val: string) {
        if (val.includes(isTransparentFunctionHack)) return (color: string) => color !== '' && DashColor(color).alpha() !== 1;
        // add other function filters here...
        return undefined;
    }

    export function toRGBAstr(col: { r: number; g: number; b: number; a?: number }) {
        return 'rgba(' + col.r + ',' + col.g + ',' + col.b + (col.a !== undefined ? ',' + col.a : '') + ')';
    }

    export function HSLtoRGB(h: number, s: number, l: number) {
        // Must be fractions of 1
        // s /= 100;
        // l /= 100;

        const c = (1 - Math.abs(2 * l - 1)) * s;
        const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
        const m = l - c / 2;
        let r = 0;
        let g = 0;
        let b = 0;
        if (h >= 0 && h < 60) {
            r = c;
            g = x;
            b = 0;
        } else if (h >= 60 && h < 120) {
            r = x;
            g = c;
            b = 0;
        } else if (h >= 120 && h < 180) {
            r = 0;
            g = c;
            b = x;
        } else if (h >= 180 && h < 240) {
            r = 0;
            g = x;
            b = c;
        } else if (h >= 240 && h < 300) {
            r = x;
            g = 0;
            b = c;
        } else if (h >= 300 && h < 360) {
            r = c;
            g = 0;
            b = x;
        }
        r = Math.round((r + m) * 255);
        g = Math.round((g + m) * 255);
        b = Math.round((b + m) * 255);
        return { r: r, g: g, b: b };
    }

    export function RGBToHSL(red: number, green: number, blue: number) {
        // Make r, g, and b fractions of 1
        const r = red / 255;
        const g = green / 255;
        const b = blue / 255;

        // Find greatest and smallest channel values
        const cmin = Math.min(r, g, b);
        const cmax = Math.max(r, g, b);
        const delta = cmax - cmin;
        let h = 0;
        let s = 0;
        let l = 0;
        // Calculate hue

        // No difference
        if (delta === 0) h = 0;
        // Red is max
        else if (cmax === r) h = ((g - b) / delta) % 6;
        // Green is max
        else if (cmax === g) h = (b - r) / delta + 2;
        // Blue is max
        else h = (r - g) / delta + 4;

        h = Math.round(h * 60);

        // Make negative hues positive behind 360°
        if (h < 0) h += 360; // Calculate lightness

        l = (cmax + cmin) / 2;

        // Calculate saturation
        s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));

        // Multiply l and s by 100
        // s = +(s * 100).toFixed(1);
        // l = +(l * 100).toFixed(1);

        return { h: h, s: s, l: l };
    }

    export function lightenRGB(rVal: number, gVal: number, bVal: number, percent: number): [number, number, number] {
        const amount = 1 + percent/100;
        const r = rVal * amount;
        const g = gVal * amount;
        const b = bVal * amount;

        const threshold = 255.999;
        const maxVal = Math.max(r, g, b);
        if (maxVal <= threshold) {
            return [Math.round(r), Math.round(g), Math.round(b)];
        }
        const total = r + g + b;
        if (total >= 3 * threshold) {
            return [Math.round(threshold), Math.round(threshold), Math.round(threshold)];
        }
        const x = (3 * threshold - total) / (3 * maxVal - total);
        const gray = threshold - x * maxVal;
        return [Math.round(gray + x * r), Math.round(gray + x * g), Math.round(gray + x * b)];
    }

    export function scrollIntoView(targetY: number, targetHgt: number, scrollTop: number, contextHgt: number, minSpacing: number, scrollHeight: number) {
        if (!targetHgt) return targetY; // if there's no height, then assume that
        if (scrollTop + contextHgt < Math.min(scrollHeight, targetY + minSpacing + targetHgt)) {
            return Math.ceil(targetY + minSpacing + targetHgt - contextHgt);
        }
        if (scrollTop >= Math.max(0, targetY - minSpacing)) {
            return Math.max(0, Math.floor(targetY - minSpacing));
        }
        return undefined;
    }

    

    export function GetClipboardText(): string {
        const textArea = document.createElement('textarea');
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            document.execCommand('paste');
        } catch (err) {
            /* empty */
        }

        const val = textArea.value;
        document.body.removeChild(textArea);
        return val;
    }
}

export function OmitKeys(obj: any, keys: string[], pattern?: string, addKeyFunc?: (dup: any) => void): { omit: any; extract: any } {
    const omit: any = { ...obj };
    const extract: any = {};
    keys.forEach(key => {
        extract[key] = omit[key];
        delete omit[key];
    });
    pattern &&
        Array.from(Object.keys(omit))
            .filter(key => key.match(pattern))
            .forEach(key => {
                extract[key] = omit[key];
                delete omit[key];
            });
    addKeyFunc?.(omit);
    return { omit, extract };
}

export function WithKeys(obj: any, keys: string[], addKeyFunc?: (dup: any) => void) {
    const dup: any = {};
    keys.forEach(key => {
        dup[key] = obj[key];
    });
    addKeyFunc && addKeyFunc(dup);
    return dup;
}

export function incrementTitleCopy(title: string) {
    const numstr = title.match(/.*(\{([0-9]*)\})+/);
    const copyNumStr = `{${1 + (numstr ? +numstr[2] : 0)}}`;
    return (numstr ? title.replace(numstr[1], '') : title) + copyNumStr;
}

const easeFunc = (transition: 'ease' | 'linear' | undefined, currentTime: number, start: number, change: number, duration: number) => {
    if (transition === 'linear') {
        const newCurrentTime = currentTime / duration; //  currentTime / (duration / 2);
        return start + newCurrentTime * change;
    }

    let newCurrentTime = currentTime / (duration / 2);
    if (newCurrentTime < 1) {
        return (change / 2) * newCurrentTime * newCurrentTime + start;
    }

    newCurrentTime -= 1;
    return (-change / 2) * (newCurrentTime * (newCurrentTime - 2) - 1) + start;
};

export function smoothScroll(duration: number, element: HTMLElement | HTMLElement[], to: number, transition: 'ease' | 'linear' | undefined, stopper?: () => void) {
    stopper?.();
    const elements = element instanceof HTMLElement ? [element] : element;
    const starts = elements.map(ele => ele.scrollTop);
    const startDate = new Date().getTime();
    let _stop = false;
    const stop = () => {
        _stop = true;
    };
    const animateScroll = () => {
        const currentDate = new Date().getTime();
        const currentTime = currentDate - startDate;
        const setScrollTop = (ele: HTMLElement, value: number) => {
            ele.scrollTop = value;
        };
        if (!_stop) {
            if (currentTime < duration) {
                elements.forEach((ele, i) => currentTime && setScrollTop(ele, easeFunc(transition, Math.min(currentTime, duration), starts[i], to - starts[i], duration)));
                requestAnimationFrame(animateScroll);
            } else {
                elements.forEach(ele => setScrollTop(ele, to));
            }
        }
    };
    animateScroll();
    return stop;
}

export function smoothScrollHorizontal(duration: number, element: HTMLElement | HTMLElement[], to: number) {
    const elements = element instanceof HTMLElement ? [element] : element;
    const starts = elements.map(ele => ele.scrollLeft);
    const startDate = new Date().getTime();

    const animateScroll = () => {
        const currentDate = new Date().getTime();
        const currentTime = currentDate - startDate;
        elements.forEach((ele, i) => {
            ele.scrollLeft = easeFunc('ease', currentTime, starts[i], to - starts[i], duration);
        });

        if (currentTime < duration) {
            requestAnimationFrame(animateScroll);
        } else {
            elements.forEach(ele => {
                ele.scrollLeft = to;
            });
        }
    };
    animateScroll();
}

export function addStyleSheet() {
    const style = document.createElement('style');
    const sheets = document.head.appendChild(style);
    return sheets.sheet;
}
export function addStyleSheetRule(sheet: CSSStyleSheet | null, selector: string, css: string | {[key:string]: string}, selectorPrefix = '.') {
    const propText =
        typeof css === 'string'
            ? css
            : Object.keys(css)
                  .map(p => p + ':' + (p === 'content' ? "'" + css[p] + "'" : css[p]))
                  .join(';');
    return sheet?.insertRule(selectorPrefix + selector + '{' + propText + '}', sheet.cssRules.length);
}
export function removeStyleSheetRule(sheet: CSSStyleSheet|null, rule: number) {
    if (sheet?.rules.length) {
        sheet.removeRule(rule);
        return true;
    }
    return false;
}
export function clearStyleSheetRules(sheet: CSSStyleSheet|null) {
    if (sheet?.rules.length) {
        numberRange(sheet.rules.length).map(() => sheet.removeRule(0));
        return true;
    }
    return false;
}

export function simulateMouseClick(element: Element | null | undefined, x: number, y: number, sx: number, sy: number, rightClick = true) {
    if (!element) return;
    ['pointerdown', 'pointerup'].forEach(event => {
        const me = new PointerEvent(event, {
            view: window,
            bubbles: true,
            cancelable: true,
            button: 2,
            pointerType: 'mouse',
            clientX: x,
            clientY: y,
            screenX: sx,
            screenY: sy,
        });
        (me as any).dash = true;
        element.dispatchEvent(me);
    });

    if (rightClick) {
        const me = new MouseEvent('contextmenu', {
            view: window,
            bubbles: true,
            cancelable: true,
            button: 2,
            clientX: x,
            clientY: y,
            movementX: 0,
            movementY: 0,
            screenX: sx,
            screenY: sy,
        });
        (me as any).dash = true;
        element.dispatchEvent(me);
    }
}

export function getWordAtPoint(elem: any, x: number, y: number): string | undefined {
    if (elem.tagName === 'INPUT') return 'input';
    if (elem.tagName === 'TEXTAREA') return 'textarea';
    if (elem.nodeType === elem.TEXT_NODE || elem.textContent) {
        const range = elem.ownerDocument.createRange();
        range.selectNodeContents(elem);
        let currentPos = 0;
        const endPos = range.endOffset;
        while (currentPos + 1 <= endPos) {
            range.setStart(elem, currentPos);
            range.setEnd(elem, currentPos + 1);
            const rangeRect = range.getBoundingClientRect();
            if (rangeRect.left <= x && rangeRect.right >= x && rangeRect.top <= y && rangeRect.bottom >= y) {
                range.expand?.('word'); // doesn't exist in firefox
                const ret = range.toString();
                range.detach();
                return ret;
            }
            currentPos += 1;
        }
    } else {
        Array.from(elem.childNodes).forEach((childNode: any) => {
            const range = childNode.ownerDocument.createRange();
            range.selectNodeContents(childNode);
            const rangeRect = range.getBoundingClientRect();
            if (rangeRect.left <= x && rangeRect.right >= x && rangeRect.top <= y && rangeRect.bottom >= y) {
                range.detach();
                const word = getWordAtPoint(childNode, x, y);
                if (word) return word;
            } else {
                range.detach();
            }
            return undefined;
        });
    }
    return undefined;
}

export function isTargetChildOf(ele: HTMLDivElement | null, target: Element | null) {
    let entered = false;
    for (let child = target; !entered && child; child = child.parentElement) {
        entered = child === ele;
    }
    return entered;
}

export function StopEvent(e: React.PointerEvent | React.MouseEvent | React.KeyboardEvent) {
    e.stopPropagation();
    e.preventDefault();
}

export function setupMoveUpEvents(
    target: object,
    e: React.PointerEvent,
    moveEvent: (e: PointerEvent, down: number[], delta: number[]) => boolean,
    upEvent: (e: PointerEvent, movement: number[], isClick: boolean) => any,
    clickEvent: (e: PointerEvent, doubleTap?: boolean) => any,
    // eslint-disable-next-line default-param-last
    stopPropagation: boolean = true,
    // eslint-disable-next-line default-param-last
    stopMovePropagation: boolean = true,
    noDoubleTapTimeout?: () => void
) {
    const targetAny = target as any;
    const doubleTapTimeout = 300;
    targetAny._doubleTap = Date.now() - (target as any)._lastTap < doubleTapTimeout;
    targetAny._lastTap = Date.now();
    targetAny._downX = targetAny._lastX = e.clientX;
    targetAny._downY = targetAny._lastY = e.clientY;
    targetAny._noClick = false;
    let moving = false;

    const _moveEvent = (moveEv: PointerEvent): void => {
        if (moving || Math.abs(moveEv.clientX - (target as any)._downX) > ClientUtils.DRAG_THRESHOLD || Math.abs(moveEv.clientY - (target as any)._downY) > ClientUtils.DRAG_THRESHOLD) {
            moving = true;
            if ((target as any)._doubleTime) {
                clearTimeout((target as any)._doubleTime);
                targetAny._doubleTime = undefined;
            }
            if (moveEvent(moveEv, [(target as any)._downX, (target as any)._downY], [moveEv.clientX - (target as any)._lastX, moveEv.clientY - (target as any)._lastY])) {
                document.removeEventListener('pointermove', _moveEvent);
                // eslint-disable-next-line no-use-before-define
                document.removeEventListener('pointerup', _upEvent);
            }
        }
        targetAny._lastX = moveEv.clientX;
        targetAny._lastY = moveEv.clientY;
        stopMovePropagation && moveEv.stopPropagation();
    };
    const _upEvent = (upEv: PointerEvent): void => {
        const isClick = Math.abs(upEv.clientX - targetAny._downX) < 4 && Math.abs(upEv.clientY - targetAny._downY) < 4;
        upEvent(upEv, [upEv.clientX - targetAny._downX, upEv.clientY - targetAny._downY], isClick);
        if (isClick) {
            if (!targetAny._doubleTime && noDoubleTapTimeout) {
                targetAny._doubleTime = setTimeout(() => {
                    noDoubleTapTimeout?.();
                    targetAny._doubleTime = undefined;
                }, doubleTapTimeout);
            }
            if (targetAny._doubleTime && targetAny._doubleTap) {
                clearTimeout(targetAny._doubleTime);
                targetAny._doubleTime = undefined;
            }
            targetAny._noClick = clickEvent(upEv, targetAny._doubleTap);
        }
        document.removeEventListener('pointermove', _moveEvent);
        document.removeEventListener('pointerup', _upEvent, true);
    };
    const _clickEvent = (clickev: MouseEvent): void => {
        if ((target as any)._noClick) clickev.stopPropagation();
        document.removeEventListener('click', _clickEvent, true);
    };
    if (stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
    document.addEventListener('pointermove', _moveEvent);
    document.addEventListener('pointerup', _upEvent, true);
    document.addEventListener('click', _clickEvent, true);
}

export function DivHeight(ele: HTMLElement): number {
    return Number(getComputedStyle(ele).height.replace('px', ''));
}
export function DivWidth(ele: HTMLElement): number {
    return Number(getComputedStyle(ele).width.replace('px', ''));
}

export function dateRangeStrToDates(dateStr: string) {
    // dateStr in yyyy-mm-dd format
    const dateRangeParts = dateStr.split('|'); // splits into from and to date
    const fromParts = dateRangeParts[0].split('-');
    const toParts = dateRangeParts[1].split('-');

    const fromYear = parseInt(fromParts[0]);
    const fromMonth = parseInt(fromParts[1]) - 1;
    const fromDay = parseInt(fromParts[2]);

    const toYear = parseInt(toParts[0]);
    const toMonth = parseInt(toParts[1]) - 1;
    const toDay = parseInt(toParts[2]);

    return [new Date(fromYear, fromMonth, fromDay), new Date(toYear, toMonth, toDay)];
}

function replaceCanvases(oldDiv: HTMLElement, newDiv: HTMLElement) {
    if (oldDiv.childNodes && newDiv) {
        for (let i = 0; i < oldDiv.childNodes.length; i++) {
            replaceCanvases(oldDiv.childNodes[i] as HTMLElement, newDiv.childNodes[i] as HTMLElement);
        }
    }
    if (oldDiv instanceof HTMLCanvasElement) {
        if (oldDiv.className === 'collectionFreeFormView-grid') {
            const newCan = newDiv as HTMLCanvasElement;
            const parEle = newCan.parentElement as HTMLElement;
            parEle.removeChild(newCan);
            parEle.appendChild(document.createElement('div'));
        } else {
            const canvas = oldDiv;
            const img = document.createElement('img'); // create a Image Element
            try {
                img.src = canvas.toDataURL(); // image source
            } catch (e) {
                console.log(e);
            }
            img.style.width = canvas.style.width;
            img.style.height = canvas.style.height;
            const newCan = newDiv as HTMLCanvasElement;
            if (newCan) {
                const parEle = newCan.parentElement as HTMLElement;
                parEle.removeChild(newCan);
                parEle.appendChild(img);
            }
        }
    }
}

export function UpdateIcon(
    filename: string,
    docViewContent: HTMLElement,
    width: number,
    height: number,
    panelWidth: number,
    panelHeight: number,
    scrollTop: number,
    realNativeHeight: number,
    noSuffix: boolean,
    replaceRootFilename: string | undefined,
    cb: (iconFile: string, nativeWidth: number, nativeHeight: number) => any
) {
    const newDiv = docViewContent.cloneNode(true) as HTMLDivElement;
    newDiv.style.width = width.toString();
    newDiv.style.height = height.toString();
    console.log('width: ' + newDiv.style.width)
    replaceCanvases(docViewContent, newDiv);
    const htmlString = new XMLSerializer().serializeToString(newDiv);
    const nativeWidth = width;
    const nativeHeight = height;
    return CreateImage(ClientUtils.prepend(''), document.styleSheets, htmlString, nativeWidth, (nativeWidth * panelHeight) / panelWidth, (scrollTop * panelHeight) / realNativeHeight)
        .then(async (dataUrl: any) => {
            const returnedFilename = await ClientUtils.convertDataUri(dataUrl, filename, noSuffix, replaceRootFilename);
            cb(returnedFilename as string, nativeWidth, nativeHeight);
        })
        .catch((error: any) => console.error('oops, something went wrong!', error));
}