x4js 1.4.50 → 1.4.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/component.ts CHANGED
@@ -1,2351 +1,2344 @@
1
- /**
2
- * ___ ___ __
3
- * \ \/ / / _
4
- * \ / /_| |_
5
- * / \____ _|
6
- * /__/\__\ |_|
7
- *
8
- * @file components.ts
9
- * @author Etienne Cochard
10
- *
11
- * Copyright (c) 2019-2022 R-libre ingenierie
12
- *
13
- * Permission is hereby granted, free of charge, to any person obtaining a copy
14
- * of this software and associated documentation files (the "Software"), to deal
15
- * in the Software without restriction, including without limitation the rights
16
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
17
- * of the Software, and to permit persons to whom the Software is furnished to do so,
18
- * subject to the following conditions:
19
- * The above copyright notice and this permission notice shall be included in all copies
20
- * or substantial portions of the Software.
21
- *
22
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
23
- * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
24
- * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
25
- * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
27
- * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
- */
29
-
30
-
31
- /**
32
- * @todo
33
- * create Container class
34
- */
35
-
36
- import { pascalCase, Rect, isString, isArray, Size, isNumber, asap, HtmlString, isHtmlString, Constructor, getMousePos } from './tools';
37
- import { x4document } from './x4dom';
38
-
39
- import { Stylesheet, ComputedStyle } from './styles';
40
- import { _tr } from './i18n';
41
- import { BasicEvent, EventCallback } from './x4events';
42
- import { BaseComponent, BaseComponentProps, BaseComponentEventMap } from './base_component';
43
- import { IDOMEvents, X4ElementEventMap } from './dom_events';
44
-
45
- export { HtmlString, isHtmlString, html } from './tools'
46
-
47
- export interface EventHandler<T> {
48
- (ev: T): any;
49
- }
50
-
51
- export interface ICaptureInfo {
52
- initiator: Component;
53
- handler: EventHandler<UIEvent>;
54
- iframes: NodeListOf<HTMLIFrameElement>;
55
- }
56
-
57
- /** @ignore classname prefix for system classes */
58
- const _x4_ns_prefix = 'x-';
59
-
60
- // -- elements -----------
61
-
62
- /** @ignore where event handlers are stored */
63
- const _x4_el_store = Symbol();
64
-
65
- /** @ignore where Component is stored in dom */
66
- const _x4_el_sym = Symbol();
67
-
68
- /** @ignore properties without 'px' unit */
69
- export const _x4_unitless = {
70
- animationIterationCount: 1, borderImageOutset: 1, borderImageSlice: 1, borderImageWidth: 1, boxFlex: 1, boxFlexGroup: 1,
71
- boxOrdinalGroup: 1, columnCount: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, flexOrder: 1,
72
- gridRow: 1, gridColumn: 1, fontWeight: 1, lineClamp: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, tabSize: 1, widows: 1,
73
- zIndex: 1, zoom: 1,
74
-
75
- // SVG-related _properties
76
- fillOpacity: 1, floodOpacity: 1, stopOpacity: 1, strokeDasharray: 1, strokeDashoffset: 1, strokeMiterlimit: 1, strokeOpacity: 1,
77
- strokeWidth: 1,
78
- };
79
-
80
- /** @ignore this events must be defined on domNode (do not bubble) */
81
- const unbubbleEvents = {
82
- mouseleave: 1, mouseenter: 1, load: 1, unload: 1, scroll: 1, focus: 1, blur: 1, rowexit: 1, beforeunload: 1, stop: 1,
83
- dragdrop: 1, dragenter: 1, dragexit: 1, draggesture: 1, dragover: 1, contextmenu: 1, create: 2, sizechange: 2
84
- };
85
-
86
- /** @ignore */
87
- const passiveEvents = {
88
- touchstart: 1, touchmove: 1, touchend: 1,
89
- //pointerdown: 1, pointermove: 1, pointerup: 1,
90
- };
91
-
92
- /** ignore */
93
- const reNumber = /^-?\d+(\.\d+)?$/;
94
-
95
-
96
- /**
97
- *
98
- */
99
-
100
- export type VoidCallback = () => void;
101
-
102
- export type ComponentOrString = Component | string | HtmlString;
103
- export type ComponentContent = ComponentOrString | ComponentOrString[];
104
-
105
- interface IMap<T> {
106
- [key: string]: T;
107
- }
108
-
109
- /**
110
- * DblClick Event
111
- * double click event
112
- */
113
-
114
- export interface EvDblClick extends BasicEvent {
115
- }
116
-
117
- export function EvDblClick(context = null) {
118
- return BasicEvent<EvDblClick>({ context });
119
- }
120
-
121
- /**
122
- * DblFocus Event
123
- * double click event
124
- */
125
-
126
- export interface EvFocus extends BasicEvent {
127
- readonly focus: boolean;
128
- }
129
-
130
- export function EvFocus( focus = true, context = null) {
131
- return BasicEvent<EvFocus>({ focus, context });
132
- }
133
-
134
- /**
135
- * basic event map of Component
136
- */
137
-
138
- export interface CEventMap extends BaseComponentEventMap {
139
- }
140
-
141
-
142
-
143
-
144
- /**
145
- * Basic properties of every Component
146
- */
147
-
148
- export interface CProps<T extends CEventMap = CEventMap> extends BaseComponentProps<T> {
149
- tag?: string; // dom Tag <div> if not specified
150
- ns?: string; // namespace (usefull for svg)
151
- cls?: string; // elements classes (space separated), prefix class name with @ to make it system wide
152
- id?: string; // element id
153
- style?: IMap<string | number>; // element style
154
- attrs?: object; // element attributes
155
-
156
- dom_events?: IDOMEvents; // DOM event handlers
157
- data?: any; // element user data (you can store everything you need here)
158
- content?: ComponentContent; // array of sub components
159
- tooltip?: string; // tooltip text
160
- ref?: string; // internal reference for itemWithRef
161
-
162
- // shortcuts for element style
163
- left?: number;
164
- top?: number;
165
- width?: number | string;
166
- height?: number | string;
167
- tabIndex?: number | boolean;
168
-
169
- flex?: number | string; // add @flex class to the element
170
- enabled?: boolean; // add @disabled to the element if false
171
- }
172
-
173
- interface CInternalProps {
174
- dom_events: any;
175
- classes: IMap<boolean>;
176
- uid: number;
177
- inrender: boolean;
178
- }
179
-
180
- /**
181
- *
182
- */
183
-
184
- export class Component<P extends CProps<BaseComponentEventMap> = CProps<BaseComponentEventMap>, E extends BaseComponentEventMap = BaseComponentEventMap> extends BaseComponent<P, E> {
185
- private m_dom: HTMLElement;
186
- private m_iprops: CInternalProps;
187
-
188
- private static __sb_width; // scrollbar width
189
- private static __comp_guid = 1000; // component global unique id
190
- private static __privateEvents: any = {};
191
- private static __sizeObserver: ResizeObserver; // resize observer
192
- private static __createObserver: MutationObserver; // creation observer
193
- //private static __intersectionObserver: IntersectionObserver; // visibility observer
194
-
195
- private static __capture: ICaptureInfo = null;
196
- private static __capture_mask = null;
197
- private static __css = null;
198
-
199
- constructor(props: P = null ) {
200
- super(props ?? {} as P );
201
-
202
- this.m_iprops = {
203
- classes: {},
204
- dom_events: {},
205
- uid: Component.__comp_guid++,
206
- inrender: false,
207
- };
208
-
209
- // prepare iprops
210
- if( this.m_props.cls ) {
211
- this.addClass( this.m_props.cls );
212
- }
213
- }
214
-
215
- /**
216
- *
217
- */
218
-
219
- get uid() {
220
- return this.m_iprops.uid;
221
- }
222
-
223
- /**
224
- * change the component content
225
- * @param content new content or null
226
- */
227
-
228
- setContent(content: ComponentContent, refreshAll = false ) {
229
- this.m_props.content = content ?? [];
230
-
231
- if( this.m_iprops.inrender || !this.m_dom ) {
232
- return;
233
- }
234
-
235
- if (refreshAll) {
236
- this.update();
237
- }
238
- else {
239
- this._updateContent();
240
- }
241
- }
242
-
243
-
244
- /**
245
- * add a new child to the component content
246
- * @param content
247
- */
248
-
249
- appendChild(content: ComponentContent) {
250
-
251
- if (!content) {
252
- return;
253
- }
254
-
255
- const append = (c) => {
256
-
257
- if (!this.m_props.content) {
258
- this.m_props.content = [];
259
- }
260
- else if (!isArray(this.m_props.content)) {
261
- this.m_props.content = [this.m_props.content];
262
- }
263
-
264
- this.m_props.content.push(c);
265
- if (this.m_dom) {
266
- this._appendChild(c);
267
- }
268
- }
269
-
270
- if (isArray(content)) {
271
- content.forEach(append);
272
- }
273
- else {
274
- append(content);
275
- }
276
- }
277
-
278
- /**
279
- *
280
- */
281
-
282
- setTag( tag: string, namespace?: string ) {
283
- this.m_props.tag = tag;
284
- if( namespace ) {
285
- this.m_props.ns = namespace;
286
- }
287
- }
288
-
289
- /**
290
- * get the Component value
291
- * @param name name to get
292
- * /
293
-
294
- getProp(name: string): any {
295
- return this.m_props[name];
296
- }
297
-
298
- / **
299
- * change a Component value
300
- * @param name name to set
301
- * @param value new value
302
- * /
303
-
304
- setProp(name: string, value?: any) {
305
- (this.m_props as any)[name] = value;
306
- }
307
- */
308
-
309
- /**
310
- * get the Component data value
311
- * @param name name to get
312
- */
313
-
314
- getData(name: string | Symbol): any {
315
- if (this.m_props.data !== undefined) {
316
- return this.m_props.data[name.toString()];
317
- }
318
-
319
- return undefined;
320
- }
321
-
322
- /**
323
- * set the Component data value
324
- * @param name name to get
325
- * @param value
326
- */
327
-
328
- setData(name: string | Symbol , value: any) {
329
-
330
- let data = this.m_props.data;
331
- if (data === undefined) {
332
- data = this.m_props.data = {};
333
- }
334
-
335
- data[name.toString()] = value;
336
- }
337
-
338
-
339
- /**
340
- * return the DOM associated with the Component (if any)
341
- */
342
-
343
- get dom(): HTMLElement {
344
- return this.m_dom;
345
- }
346
-
347
- /**
348
- * shows the element
349
- * @param show
350
- */
351
-
352
- show(show?: boolean) {
353
- if (show === undefined || show === true) {
354
- this.removeClass('@hidden');
355
- }
356
- else {
357
- this.addClass('@hidden');
358
- }
359
- }
360
-
361
- /**
362
- * hides the element
363
- */
364
- hide() {
365
- this.addClass('@hidden');
366
- }
367
-
368
- /**
369
- * enable or disable the element
370
- * @param enable
371
- */
372
-
373
- enable(enable?: boolean) {
374
- if (enable === undefined || enable === true) {
375
- this.removeClass('@disable');
376
- this.removeAttribute('disabled');
377
- }
378
- else {
379
- this.disable();
380
- }
381
- }
382
-
383
- /**
384
- * disable the element
385
- */
386
-
387
- disable() {
388
- this.addClass('@disable');
389
- this.setAttribute('disabled', '');
390
- }
391
-
392
- /**
393
- * set the focus on the element
394
- */
395
-
396
- focus() {
397
- console.assert(!!this.m_dom);
398
- this.m_dom.focus();
399
- }
400
-
401
- /**
402
- * change the object style
403
- * @param style - style to add
404
- * @example ```typescript
405
- * el.setStyle( {left:100} );
406
- */
407
-
408
- public setStyle(style: object) {
409
- for (let s in style) {
410
- this.setStyleValue(s, style[s]);
411
- }
412
- }
413
-
414
- /**
415
- * change a style value
416
- * @param name string style nale
417
- * @param value any style value or null to remove style
418
- */
419
-
420
- setStyleValue(name: string, value: any) {
421
- let style = this.m_props.style;
422
- if (!style) {
423
- style = this.m_props.style = {};
424
- }
425
-
426
- style[name] = value;
427
- this._setDomStyleValue(name, value);
428
- }
429
-
430
- private _setDomStyleValue(name: string, value: string | number) {
431
- if (this.m_dom) {
432
-
433
- if (value === undefined) {
434
- value = null;
435
- }
436
- else if (!_x4_unitless[name] && (isNumber(value) || reNumber.test(value))) {
437
- value = value + 'px';
438
- }
439
-
440
- this.m_dom.style[name] = value;
441
- }
442
- }
443
-
444
- /**
445
- * compute the element style
446
- * @return all styles computed
447
- */
448
-
449
- public getComputedStyle(pseudoElt?: string): ComputedStyle {
450
- if (this.dom) {
451
- return new ComputedStyle(getComputedStyle(this.dom, pseudoElt ?? null));
452
- }
453
-
454
- return new ComputedStyle(this.m_props.style as any);
455
- }
456
-
457
- /**
458
- * return a single stype value
459
- * @param name - value to get
460
- */
461
-
462
- public getStyleValue(name: string) {
463
- return this.getComputedStyle()[name];
464
- }
465
-
466
- /**
467
- * define the elements attributes
468
- * @param attrs
469
- */
470
-
471
- public setAttributes(attrs: any) {
472
- for (let a in attrs) {
473
- this.setAttribute(a, attrs[a]);
474
- }
475
- }
476
-
477
- /**
478
- * change a single attribute
479
- * @param name attribute name
480
- * @param value new value
481
- */
482
-
483
- public setAttribute(name: string, value: any) {
484
-
485
- if (value === false || value === undefined) {
486
- this.removeAttribute(name);
487
- }
488
- else {
489
- if (value === true) {
490
- value = '';
491
- }
492
- else if (isNumber(value)) {
493
- value = '' + value;
494
- }
495
-
496
- let attrs = this.m_props.attrs;
497
- if (!attrs) {
498
- attrs = this.m_props.attrs = {};
499
- }
500
-
501
- attrs[name] = value;
502
- this._setDomAttribute(name, value);
503
- }
504
- }
505
-
506
- private _setDomAttribute(name: string, value: string) {
507
- if (this.m_dom) {
508
- this.m_dom.setAttribute(name, value);
509
- }
510
- }
511
-
512
- /**
513
- * remove an atrribute
514
- * @param name name of the attribute
515
- */
516
- public removeAttribute(name: string) {
517
- let attrs = this.m_props.attrs;
518
- if (!attrs) {
519
- return;
520
- }
521
-
522
- delete attrs[name];
523
-
524
- if (this.m_dom) {
525
- this.m_dom.removeAttribute(name);
526
- }
527
- }
528
-
529
- /**
530
- * get an attribute value
531
- * @param {string} name - attribute name
532
- * @return {string} attribute value
533
- * @example ```typescript
534
- * let chk = el.getAttribute( 'checked' );
535
- * @review double cache
536
- */
537
-
538
- public getAttribute(name: string): string {
539
- if (this.m_dom) {
540
- return this.m_dom.getAttribute(name);
541
- }
542
- else {
543
- if (!this.m_props.attrs) {
544
- return undefined;
545
- }
546
-
547
- return this.m_props.attrs[name];
548
- }
549
- }
550
-
551
- /**
552
- * check if the element has an attribute
553
- * @param name attribute name
554
- * @return true is attribute is present
555
- * @example ```typescript
556
- * if( el.hasAttribute('checked') ) {
557
- * }
558
- */
559
-
560
- public hasAttribute(name: string): boolean {
561
- if (this.m_dom) {
562
- return this.m_dom.hasAttribute(name);
563
- }
564
- else {
565
- return this.m_props.attrs.hasOwnProperty(name);
566
- }
567
- }
568
-
569
-
570
- /**
571
- * a some classnames to the component
572
- * classes can be separated by a space
573
- * @param cls class to add
574
- * @example ```typescript
575
- * addClass( 'my class name @flex' );
576
- */
577
-
578
- public addClass(name: string) {
579
-
580
- if (name === null || name === undefined) {
581
- return;
582
- }
583
-
584
- name = name.trim();
585
- if (name === '') {
586
- return;
587
- }
588
-
589
- let add = (c) => {
590
-
591
- if (c === undefined || c === null || c === '') {
592
- return;
593
- }
594
-
595
- c = this._makeCls(c);
596
-
597
- // update vdom
598
- classes[c] = true;
599
-
600
- // update dom
601
- if (this.m_dom) {
602
- this.m_dom.classList.add(c);
603
- }
604
- }
605
-
606
- let classes = this.m_iprops.classes;
607
- if (name.indexOf(' ') < 0) {
608
- add(name);
609
- }
610
- else {
611
- let names = name.split(' ');
612
- names.forEach((n) => add(n));
613
- }
614
- }
615
-
616
- /**
617
- * Remove a class from the element
618
- * @param {string|array} name - classes in string form can be space separated
619
- *
620
- * @example ```typescript
621
- * el.removeClass( 'myclass' );
622
- * el.removeClass( 'myclass1 myclass2' );
623
- */
624
-
625
- public removeClass(name: string): void {
626
-
627
- if (name === undefined) {
628
- return;
629
- }
630
-
631
- let remove = (c) => {
632
- if (c === undefined || c === null || c === '') {
633
- return;
634
- }
635
-
636
- c = this._makeCls(c);
637
-
638
- delete this.m_iprops.classes[c];
639
- if (this.m_dom) {
640
- this.m_dom.classList.remove(c);
641
- }
642
- }
643
-
644
- // faster
645
- if (name.indexOf(' ') < 0) {
646
- remove(name);
647
- }
648
- else {
649
- // build class list
650
- let classes = name.trim().split(' ');
651
- for (let c of classes) {
652
- if (c !== undefined && c !== null && c !== '') {
653
- remove(c);
654
- }
655
- }
656
- }
657
- }
658
-
659
- /**
660
- *
661
- * @param cls
662
- * @param set
663
- */
664
-
665
- public setClass(cls: string, set: boolean) {
666
- if (set) { this.addClass(cls); }
667
- else { this.removeClass(cls); }
668
- return this;
669
- }
670
-
671
- /**
672
- * Toggle a class from the element (if present remove, if absent add)
673
- * @param {string|string[]} name - classes in string form can be space separated
674
- * @example ```typescript
675
- * el.toggleClass( 'myclass' );
676
- * el.toggleClass( 'myclass1 myclass2');
677
- * el.toggleClass( ['myclass1','myclass2']);
678
- */
679
-
680
- public toggleClass(name: string): void {
681
-
682
- let toggle = (c) => {
683
- if (c === undefined && c === null && c === '') {
684
- return;
685
- }
686
-
687
- c = this._makeCls(c);
688
- if (this.m_iprops.classes[c]) {
689
- delete this.m_iprops.classes[c]
690
- }
691
- else {
692
- this.m_iprops.classes[c] = true;
693
- }
694
-
695
- if (this.m_dom) {
696
- this.m_dom.classList.toggle(c);
697
- }
698
- }
699
-
700
- // faster
701
- if (name.indexOf(' ') < 0) {
702
- toggle(name);
703
- }
704
- else {
705
-
706
- // build class list
707
- let classes = name.trim().split(' ');
708
- for (let c of classes) {
709
- toggle(c);
710
- }
711
- }
712
- }
713
-
714
- /**
715
- * check if the object has the class
716
- * @param cls
717
- */
718
-
719
- public hasClass(cls: string): boolean {
720
-
721
- let c = this._makeCls(cls);
722
- if (this.m_dom) {
723
- return this.dom.classList.contains(c);
724
- }
725
- else {
726
- return !!this.m_iprops.classes[c];
727
- }
728
- }
729
-
730
- /**
731
- * remove all classes from the object
732
- * this is usefull for component recycling & reusing
733
- */
734
-
735
- public clearClasses() {
736
- this.m_iprops.classes = {};
737
- if (this.m_dom) {
738
- return this.m_dom.classList.value = '';
739
- }
740
- }
741
-
742
- public _build(): HTMLElement {
743
- if (this.m_dom) {
744
- return this.m_dom;
745
- }
746
-
747
- this._createDOM();
748
- return this.m_dom;
749
- }
750
-
751
- public render(props: P) {
752
- if( this.m_props.tag=='footer') {
753
- debugger;
754
- }
755
- }
756
-
757
- public _createDOM(): HTMLElement {
758
-
759
- if (this.m_dom) {
760
- return this.m_dom;
761
- }
762
-
763
- // setup props
764
- const props = this.m_props;
765
-
766
- if( props.tabIndex!==undefined ) {
767
- this._setTabIndex( props.tabIndex );
768
- }
769
- this.render(props);
770
-
771
- // shortcuts ---------
772
- if (props.left !== undefined) { this.setStyleValue('left', props.left); }
773
- if (props.top !== undefined) { this.setStyleValue('top', props.top); }
774
- if (props.width !== undefined) { this.setStyleValue('width', props.width); }
775
- if (props.height !== undefined) { this.setStyleValue('height', props.height); }
776
-
777
- if (props.flex !== undefined) {
778
- this.addClass('@flex');
779
- if (props.flex != 1) {
780
- this.setStyleValue('flex', props.flex);
781
- }
782
- }
783
-
784
- if (props.enabled === false) {
785
- this.disable();
786
- }
787
-
788
- // shortcut: tip
789
- if (props.tooltip !== undefined) {
790
- this.setAttribute('tip', props.tooltip.replace(/\n/gi, '<br/>'));
791
- }
792
-
793
-
794
- // prepare iprops
795
- if (props.dom_events) {
796
- for (let ename in props.dom_events) {
797
- this._setDomEvent(ename, props.dom_events[ename]);
798
- }
799
- }
800
-
801
- this._genClassName();
802
- this.m_props.cls = undefined; // now classes are tranfered to m_iprops
803
-
804
- // create self
805
- let vdom = this.m_iprops;
806
-
807
- if (props.ns) {
808
- this.m_dom = <HTMLElement>x4document.createElementNS(props.ns, props.tag ?? 'div');
809
- }
810
- else {
811
- this.m_dom = x4document.createElement( (props.tag ?? 'div') as any );
812
- }
813
-
814
- this.m_dom[_x4_el_sym] = this;
815
-
816
- //let me = Object.getPrototypeOf(this);
817
- //console.log( 'create', this.m_iprops.uid, me.constructor.name );
818
-
819
- // classes
820
- this.m_dom.classList.add(...Object.keys(vdom.classes));
821
-
822
- // styles
823
- let sty = props.style;
824
- if (sty) {
825
- for (let s in sty) {
826
- this._setDomStyleValue(s, sty[s]);
827
- }
828
- }
829
-
830
- // attributes
831
- let att = props.attrs;
832
- if (att) {
833
- for (let a in att) {
834
- const attr = att[a];
835
- if( attr!==false && attr!==undefined ) {
836
- this._setDomAttribute(a, att[a]);
837
- }
838
- }
839
- }
840
-
841
- // special properties
842
- if (this.m_props.id) {
843
- this._setDomAttribute('id', this.m_props.id);
844
- }
845
-
846
- // events
847
- let evt = this.m_iprops.dom_events;
848
- if (evt) {
849
- for (let e in evt) {
850
- let handlers = evt[e];
851
- for (let h of handlers) {
852
- this.createEvent(e, h);
853
- }
854
- }
855
- }
856
-
857
- // create children
858
- let content = props.content;
859
- if (content) {
860
-
861
- if (!isArray(content)) {
862
- content = [content];
863
- }
864
-
865
- content.forEach((el) => {
866
- if (!el) {
867
- return;
868
- }
869
-
870
- if (isString(el)) {
871
- this.m_dom.insertAdjacentText('beforeend', el);
872
- }
873
- else if (isHtmlString(el)) {
874
- this.m_dom.insertAdjacentHTML('beforeend', el as string);
875
- }
876
- else if (el instanceof Component) {
877
- this.m_dom.append(el._build());
878
- }
879
- else {
880
- console.log( 'unknown element type: ', el );
881
- }
882
- });
883
- }
884
-
885
- // wait for dom insertion inside document.body
886
- if (!Component.__createObserver) {
887
- Component.__createObserver = new MutationObserver(Component._observeCreation);
888
- Component.__createObserver.observe(x4document.body, { childList: true, subtree: true });
889
- }
890
-
891
- return this.m_dom;
892
- }
893
-
894
- protected _setTabIndex(tabIndex: number | boolean, defValue = 0) {
895
-
896
- if (tabIndex === true) {
897
- tabIndex = 0;
898
- }
899
- else if (tabIndex === undefined) {
900
- tabIndex = defValue;
901
- }
902
-
903
- if (tabIndex !== false && tabIndex !== undefined) {
904
- this.setAttribute('tabindex', tabIndex);
905
- }
906
-
907
- this.m_props.tabIndex = tabIndex;
908
- }
909
-
910
- private static _observeCreation(mutations: MutationRecord[]) {
911
-
912
- // notify descendants that we have been created (dom exists)
913
-
914
- for (let mutation of mutations) {
915
-
916
- if (mutation.type == 'childList') {
917
-
918
- for (let i = 0, n = mutation.addedNodes.length; i < n; i++) {
919
-
920
- let add = mutation.addedNodes[i] as HTMLElement;
921
- let el = add[_x4_el_sym] as Component;
922
-
923
- if (el) {
924
- el.enumChilds((c: Component) => {
925
-
926
- if (c.dom && c.m_iprops.dom_events && c.m_iprops.dom_events.create) {
927
- c.dom.dispatchEvent(new Event('create'));
928
- }
929
-
930
- c.componentCreated();
931
-
932
- }, true);
933
-
934
- if (el.m_iprops.dom_events && el.m_iprops.dom_events.create) {
935
- el.dom.dispatchEvent(new Event('create'));
936
- }
937
-
938
- el.componentCreated();
939
- }
940
- }
941
- }
942
- }
943
- }
944
-
945
- public dispose() {
946
- if (this.m_dom) {
947
- this._dispose(true,true);
948
- }
949
- }
950
-
951
- protected _dispose(with_dom: boolean, timers: boolean ) {
952
-
953
- let _dom = this.m_dom;
954
-
955
- // free attached resources
956
- delete _dom[_x4_el_sym];
957
- delete _dom[_x4_el_store];
958
-
959
- //
960
- if (with_dom) {
961
- _dom.remove();
962
- }
963
-
964
- // notify every child that they will be removed
965
- this.enumChilds((c: Component) => {
966
- c._dispose(false,true);
967
- });
968
-
969
- this.m_dom = null;
970
-
971
- if( timers ) {
972
- this.disposeTimers();
973
- }
974
-
975
- this.componentDisposed();
976
- // todo: pb on update this.removeAllListeners( null );
977
- }
978
-
979
- componentDisposed() {
980
- }
981
-
982
- componentCreated() {
983
- }
984
-
985
-
986
-
987
-
988
-
989
-
990
-
991
- /**
992
- *
993
- */
994
-
995
- public update(delay = 0) {
996
-
997
- if (this.m_dom) {
998
-
999
- const _update = () => {
1000
- let oldDOM = this.m_dom;
1001
- this._dispose(false,false);
1002
-
1003
- let newDOM = this._build();
1004
- console.assert( !!oldDOM.parentNode, 'update in componentCreated is not allowed, use updateContent' );
1005
-
1006
- oldDOM.parentNode.replaceChild(newDOM, oldDOM);
1007
- }
1008
-
1009
- if (delay) {
1010
- this.singleShot(_update, delay);
1011
- }
1012
- else {
1013
- _update();
1014
- }
1015
- }
1016
- }
1017
-
1018
- /**
1019
- * empty the node
1020
- */
1021
- public _empty( ) {
1022
- //this.m_dom.innerHTML = '';
1023
-
1024
- const el = this.m_dom;
1025
- if( !el ) {
1026
- return;
1027
- }
1028
-
1029
- while (el.firstChild) {
1030
- el.removeChild(el.firstChild);
1031
- }
1032
- }
1033
-
1034
- public _updateContent() {
1035
-
1036
- if (!this.m_dom) {
1037
- return;
1038
- }
1039
-
1040
- this._empty( );
1041
-
1042
- let content = this.m_props.content;
1043
-
1044
- // create children
1045
- if (content) {
1046
-
1047
- if (!isArray(content)) {
1048
- content = [content];
1049
- }
1050
-
1051
- content.forEach((el) => {
1052
- if (!el) {
1053
- return;
1054
- }
1055
-
1056
- if (isHtmlString(el)) {
1057
- this.m_dom.insertAdjacentHTML('beforeend', el as string);
1058
- }
1059
- else if (el instanceof Component) {
1060
- this.m_dom.append(el._build());
1061
- }
1062
- else {
1063
- this.m_dom.insertAdjacentText('beforeend', el + '');
1064
- }
1065
- });
1066
- }
1067
-
1068
- }
1069
-
1070
- /**
1071
- * @return the bounding rectangle
1072
- * @example ```typescript
1073
- * let rc = el.getBoundingRect( );
1074
- * console.log( rc.left, rc.top, rc.right, rc.bottom );
1075
- */
1076
-
1077
- public getBoundingRect(withMargins = false): Rect {
1078
- console.assert(this.dom != null, 'cannot get bounding rect of an non DOM element');
1079
- let r = this.dom.getBoundingClientRect();
1080
-
1081
- let rc = new Rect(r.left, r.top, r.width, r.height);
1082
-
1083
- if (withMargins) {
1084
-
1085
- let st = this.getComputedStyle();
1086
-
1087
- let tm = st.parse('marginTop'),
1088
- bm = st.parse('marginBottom'),
1089
- lm = st.parse('marginLeft'),
1090
- rm = st.parse('marginRight');
1091
-
1092
- rc.left -= lm;
1093
- rc.width += lm + rm;
1094
-
1095
- rc.top -= tm;
1096
- rc.height += tm + bm;
1097
- }
1098
-
1099
- return rc;
1100
- }
1101
-
1102
- /**
1103
- * append a new dom event handler
1104
- * @param name - you can specify multiple names separated by a space
1105
- * @param handler
1106
- * @example
1107
- *
1108
- * this.setDomEvent( 'drag drop', this._handleDrag, this );
1109
- * this.setDomEvent( 'dblclick', this._handleDblClick, this );
1110
- */
1111
-
1112
- public setDomEvent<K extends keyof X4ElementEventMap>(type: K, listener: (this: HTMLDivElement, ev: X4ElementEventMap[K]) => void) {
1113
- let _listener = listener as EventListener;
1114
- this._setDomEvent(type as string, _listener);
1115
- }
1116
-
1117
- private _setDomEvent(type: string, listener: EventListener) {
1118
-
1119
- // add event to the vdom
1120
- if (!this.m_iprops.dom_events) {
1121
- this.m_iprops.dom_events = {};
1122
- }
1123
-
1124
- let listeners = this.m_iprops.dom_events[type];
1125
- if (!listeners) {
1126
- listeners = this.m_iprops.dom_events[type] = [listener];
1127
- }
1128
- else {
1129
- listeners.push(listener);
1130
- }
1131
-
1132
- if (this.m_dom) {
1133
- //this.m_dom.addEventListener(type, listener);
1134
- this.createEvent(type, listener);
1135
- }
1136
- }
1137
-
1138
- /**
1139
- *
1140
- */
1141
-
1142
- public clearDomEvent<K extends keyof X4ElementEventMap>(type: K) {
1143
- if (!this.m_iprops.dom_events) {
1144
- return;
1145
- }
1146
-
1147
- delete this.m_iprops.dom_events[type];
1148
-
1149
- let _dom = this.m_dom;
1150
- if (_dom) {
1151
- let store = _dom[_x4_el_store];
1152
- if (store) {
1153
- delete store[type];
1154
- }
1155
- }
1156
- }
1157
-
1158
- /**
1159
- *
1160
- * @param name
1161
- * @param handler
1162
- */
1163
-
1164
- public createEvent(name: string, handler: Function) {
1165
-
1166
- let _dom = this.m_dom;
1167
- let store = _dom[_x4_el_store];
1168
-
1169
- if (!store) {
1170
- store = _dom[_x4_el_store] = {};
1171
- }
1172
-
1173
- if (!store[name]) {
1174
- // no handler for this event...
1175
- store[name] = [handler];
1176
- }
1177
- else {
1178
- // append the handler
1179
- store[name].push(handler);
1180
- }
1181
-
1182
- if (unbubbleEvents[name] === 1) {
1183
- _dom['on' + name] = Component._dispatchUnbubbleEvent;
1184
- }
1185
- else if (!Component.__privateEvents[name]) {
1186
- Component.__privateEvents[name] = true; // todo count it
1187
-
1188
- if (passiveEvents[name]) {
1189
- x4document.addEventListener(name as any, Component._dispatchEvent, { passive: false, capture: true });
1190
- }
1191
- else {
1192
- x4document.addEventListener(name as any, Component._dispatchEvent, true);
1193
- }
1194
- }
1195
-
1196
- if (name === 'sizechange') {
1197
- if (!Component.__sizeObserver) {
1198
- Component.__sizeObserver = new ResizeObserver(Component._observeSize);
1199
- }
1200
-
1201
- Component.__sizeObserver.observe(this.m_dom);
1202
- }
1203
- }
1204
-
1205
- /**
1206
- * dispatch a dom event to the appropriated component
1207
- * called by the system
1208
- */
1209
-
1210
- private static _dispatchEvent(ev: any) {
1211
-
1212
- let target = ev.target,
1213
- noup = unbubbleEvents[ev.type] === 2;
1214
-
1215
- while (target) {
1216
- if (target[_x4_el_store]) {
1217
- let store = target[_x4_el_store][ev.type];
1218
- if (store) {
1219
- let el = target[_x4_el_sym];
1220
- let root = el?.root ?? null;
1221
-
1222
- if (store instanceof Array) {
1223
- store.some((fn) => {
1224
- fn(ev, root);
1225
- if (!el.dom) {
1226
- return true;
1227
- }
1228
- });
1229
- }
1230
- else {
1231
- store(ev, root);
1232
- }
1233
-
1234
- if (ev.cancelBubble || ev.defaultPrevented || noup) {
1235
- break;
1236
- }
1237
- }
1238
- }
1239
-
1240
- target = target.parentNode;
1241
-
1242
- // no need to go above
1243
- if (target == document) {
1244
- break;
1245
- }
1246
- }
1247
- }
1248
-
1249
- /**
1250
- * dispatch a dom event to the appropriated component
1251
- * called by the system
1252
- */
1253
-
1254
- private static _dispatchUnbubbleEvent(ev: any) {
1255
-
1256
- let target = ev.currentTarget || ev.target,
1257
- eventType = ev.type;
1258
-
1259
- let eventStore = target[_x4_el_store],
1260
- store = eventStore && eventStore[eventType];
1261
-
1262
- if (store) {
1263
-
1264
- let el = target[_x4_el_sym];
1265
- let root = el?.root ?? null;
1266
-
1267
- if (store instanceof Array) {
1268
- store.forEach((fn) => {
1269
- fn(ev, root);
1270
- });
1271
- }
1272
- else {
1273
- store(ev, root);
1274
- }
1275
- }
1276
- }
1277
-
1278
- /**
1279
- * called when a size change on an observed component
1280
- */
1281
-
1282
- private static _observeSize(entries: ResizeObserverEntry[]) {
1283
-
1284
- entries.forEach((entry) => {
1285
- let dom = entry.target as HTMLElement;
1286
- if (dom.offsetParent !== null) {
1287
- dom.dispatchEvent(new Event('sizechange'));
1288
- }
1289
- });
1290
- }
1291
-
1292
- /**
1293
- * enum all children recursively
1294
- * @param recursive - if true do a full sub-child search
1295
- * @param cb - callback
1296
- * return true to stop enumeration
1297
- */
1298
-
1299
- enumChilds(cb: (child: Component) => boolean | void, recursive = false): boolean {
1300
-
1301
- // use dom if available
1302
- if (this.m_dom) {
1303
-
1304
- let el = this.m_dom.firstChild;
1305
-
1306
- while (el) {
1307
- // get component (if any)
1308
- let cel = el[_x4_el_sym];
1309
- if (cel) {
1310
- cb(cel);
1311
-
1312
- if (recursive && cel.enumChilds(cb, true) === true) {
1313
- return true;
1314
- }
1315
- }
1316
-
1317
- el = el.nextSibling;
1318
- }
1319
- }
1320
- else {
1321
- let content = this.m_props.content;
1322
- if (!content) {
1323
- return;
1324
- }
1325
-
1326
- if (!isArray(content)) {
1327
- content = [content];
1328
- }
1329
-
1330
- content.some((el) => {
1331
- if (!el || isString(el) || isHtmlString(el)) {
1332
- return;
1333
- }
1334
-
1335
- if (cb(el)) {
1336
- return true;
1337
- }
1338
-
1339
- if (recursive && el.enumChilds(cb, true) === true) {
1340
- return true;
1341
- }
1342
- });
1343
- }
1344
-
1345
- return false;
1346
- }
1347
-
1348
- /**
1349
- * apprend a child to the DOM
1350
- * @param props child to append (or string)
1351
- */
1352
-
1353
- private _appendChild(el: ComponentOrString) {
1354
-
1355
- if (isString(el)) {
1356
- this.m_dom.insertAdjacentText('beforeend', el);
1357
- }
1358
- else if (isHtmlString(el)) {
1359
- this.m_dom.insertAdjacentHTML('beforeend', el as string);
1360
- }
1361
- else {
1362
- let component: Component = el;
1363
-
1364
- try {
1365
- component._build();
1366
- this.m_dom.appendChild(component.m_dom);
1367
- }
1368
- catch (e) {
1369
- console.error(e);
1370
- }
1371
- }
1372
- }
1373
-
1374
- /**
1375
- * generate classes from the component inheritance
1376
- * @example
1377
- * Button extends Component will give
1378
- * x-comp x-button
1379
- */
1380
-
1381
- private _genClassName() {
1382
-
1383
- this.addClass('@comp');
1384
-
1385
- let me = Object.getPrototypeOf(this);
1386
- while (me && me.constructor !== Component) {
1387
- let clsname = me.constructor.name;
1388
- this.addClass('@' + pascalCase(clsname));
1389
-
1390
- me = Object.getPrototypeOf(me);
1391
- }
1392
-
1393
- //done in ctor now
1394
- //this.addClass(this.m_props.cls);
1395
- }
1396
-
1397
- /**
1398
- * prepend the system class name prefix on a name if needed (if class starts with @)
1399
- */
1400
-
1401
- private _makeCls(cls: string): string {
1402
- if (cls[0] == '@') {
1403
- return cls = _x4_ns_prefix + cls.substring(1);
1404
- }
1405
- else {
1406
- return cls;
1407
- }
1408
- }
1409
-
1410
- /**
1411
- *
1412
- */
1413
-
1414
- private static dispatchCaptures(event: Event) {
1415
- Component.__capture.handler(event as UIEvent);
1416
- }
1417
-
1418
- /**
1419
- * capture mouse events
1420
- * @param capture name of the current capture
1421
- * @param callback funciton to call on captured mouse events
1422
- *
1423
- * @example
1424
- * Component.setCapture( this, ( ev: MouseEvent, initiator: Component ) => {
1425
- * if( ev.type=='mousemove' ) {
1426
- * this.setStyle( {
1427
- * left: ev.clientX,
1428
- * top: ev.clientY
1429
- * } );
1430
- * }
1431
- * else if( ev.type=='mouseup' ) {
1432
- * Component.releaseCapture( );
1433
- * }
1434
- * } );
1435
- */
1436
-
1437
- protected static setCapture(initiator: Component, listener: EventHandler<UIEvent>) {
1438
-
1439
- console.assert(!Component.__capture);
1440
- if (Component.__capture) {
1441
- debugger;
1442
- }
1443
-
1444
- // todo: review that
1445
-
1446
- let iframes = x4document.querySelectorAll<HTMLIFrameElement>("iframe");
1447
- iframes.forEach( f => {
1448
- flyWrap(f).setStyleValue( 'pointer-events', 'none' );
1449
- });
1450
-
1451
- let overs = x4document.querySelectorAll(":hover");
1452
-
1453
- let cursor = null;
1454
- if (overs.length) {
1455
- let elementOver = <HTMLElement>overs[overs.length - 1];
1456
- let style = window.getComputedStyle(elementOver);
1457
- cursor = style.cursor;
1458
- }
1459
-
1460
- Component.__capture_mask = x4document.createElement('div');
1461
- let mask = flyWrap(Component.__capture_mask);
1462
- mask.addClass('@capture-mask');
1463
-
1464
- if (cursor) {
1465
- mask.setStyleValue('cursor', cursor);
1466
- }
1467
-
1468
- x4document.body.appendChild(mask.dom);
1469
-
1470
- x4document.addEventListener('mousedown', Component.dispatchCaptures);
1471
- x4document.addEventListener('mousemove', Component.dispatchCaptures);
1472
- x4document.addEventListener('mouseup', Component.dispatchCaptures);
1473
-
1474
- x4document.addEventListener('touchstart', Component.dispatchCaptures);
1475
- x4document.addEventListener('touchmove', Component.dispatchCaptures);
1476
- x4document.addEventListener('touchend', Component.dispatchCaptures);
1477
-
1478
- Component.__capture = {
1479
- initiator,
1480
- handler: listener,
1481
- iframes
1482
- };
1483
- }
1484
-
1485
- protected static releaseCapture() {
1486
-
1487
- console.assert(!!Component.__capture);
1488
-
1489
- x4document.removeEventListener('touchstart', Component.dispatchCaptures);
1490
- x4document.removeEventListener('touchmove', Component.dispatchCaptures);
1491
- x4document.removeEventListener('touchend', Component.dispatchCaptures);
1492
-
1493
- x4document.removeEventListener('mousedown', Component.dispatchCaptures);
1494
- x4document.removeEventListener('mousemove', Component.dispatchCaptures);
1495
- x4document.removeEventListener('mouseup', Component.dispatchCaptures);
1496
-
1497
- Component.__capture.iframes.forEach( f => {
1498
- flyWrap(f).setStyleValue( 'pointer-events', null );
1499
- })
1500
-
1501
- Component.__capture = null;
1502
- if (Component.__capture_mask) {
1503
- x4document.body.removeChild(Component.__capture_mask);
1504
- Component.__capture_mask = null;
1505
- }
1506
- }
1507
-
1508
- /**
1509
- * ensure the component is visible
1510
- * @param: alignToTop
1511
- */
1512
-
1513
- public scrollIntoView(arg?: boolean | ScrollIntoViewOptions) {
1514
- if (this.m_dom) {
1515
-
1516
- const rel = new Rect( this.dom.getBoundingClientRect( ) );
1517
-
1518
- let top = undefined;
1519
- let bot = undefined;
1520
- let left = undefined;
1521
- let right = undefined;
1522
-
1523
- let pn = this.dom.parentElement;
1524
- const bdy = x4document.body;
1525
-
1526
- while( pn && pn!=bdy ) {
1527
-
1528
- const pr = pn.getBoundingClientRect( );
1529
-
1530
- if( top===undefined || top<pr.top ) {
1531
- top = pr.top;
1532
- }
1533
-
1534
- if( bot===undefined || bot>pr.bottom ) {
1535
- bot = pr.bottom;
1536
- }
1537
-
1538
- if( left===undefined || left<pr.left ) {
1539
- left = pr.left;
1540
- }
1541
-
1542
- if( right===undefined || right>pr.right ) {
1543
- right = pr.right;
1544
- }
1545
-
1546
- pn = pn.parentElement;
1547
- }
1548
-
1549
- if( top===undefined || rel.top<top || rel.bottom>bot || rel.left<left || rel.right>right ) {
1550
- //this.m_dom.scrollIntoView( true );
1551
- this.m_dom.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'start' });
1552
- }
1553
-
1554
- //this.m_dom.scrollIntoView(arg);
1555
- }
1556
- }
1557
-
1558
- /**
1559
- * search for a given css selector
1560
- * @param selector
1561
- * @returns child or null
1562
- */
1563
-
1564
- public queryItem<T extends Component>(selector: string): T {
1565
- let result = <HTMLElement>this.dom.querySelector(selector);
1566
- return result ? Component.getElement<T>(result) : null;
1567
- }
1568
-
1569
- public queryAll(selector: string, cb?: (el: Component) => void): HTMLElement[] {
1570
- let elements:HTMLElement[] = Array.from( this.m_dom.querySelectorAll<HTMLElement>(selector) );
1571
-
1572
- if( cb ) {
1573
- elements.forEach((el) => {
1574
- cb(flyWrap(el as HTMLElement));
1575
- });
1576
- }
1577
-
1578
- return elements;
1579
- }
1580
-
1581
- /**
1582
- * find a child with the given ID
1583
- * @param id id (without '#')
1584
- * @returns child or null
1585
- *
1586
- * @example
1587
- * let btn = this.childWithId<Button>( 'myButtonId' );
1588
- */
1589
- public itemWithId<T extends Component>(id: string): T {
1590
- let result = <HTMLElement>this.dom.querySelector('#' + id);
1591
- return result ? Component.getElement<T>(result) : null;
1592
- }
1593
-
1594
- /**
1595
- * find a child with given ref
1596
- * @param ref
1597
- * @return found child or null
1598
- */
1599
-
1600
- public itemWithRef<T = Component>(ref: string): T {
1601
-
1602
- let result = null;
1603
- this.enumChilds((c: Component) => {
1604
- if (c.m_props.ref === ref) {
1605
- result = c;
1606
- return true;
1607
- }
1608
- }, true);
1609
-
1610
- return result as T;
1611
- }
1612
-
1613
- /**
1614
- *
1615
- */
1616
-
1617
- get ref() {
1618
- return this.m_props.ref;
1619
- }
1620
-
1621
- /**
1622
- *
1623
- */
1624
-
1625
- static getCss(): Stylesheet {
1626
- if (!Component.__css) {
1627
- Component.__css = new Stylesheet();
1628
- }
1629
-
1630
- return Component.__css;
1631
- }
1632
-
1633
- /**
1634
- * return the parent element
1635
- * care, object must have been created (dom!=null)
1636
- */
1637
-
1638
- public getParent(): Component {
1639
- console.assert(!!this.m_dom);
1640
-
1641
- let elParent = this.dom.parentNode;
1642
- return Component.getElement(<HTMLElement>elParent);
1643
- }
1644
-
1645
- /**
1646
- * get a component from a DOM element
1647
- * move up to the hierarchy to find the request class type.
1648
- * @param dom
1649
- * @param classname
1650
- * @returns
1651
- *
1652
- * @example
1653
- *
1654
- * with a DOM like that:
1655
- * Button
1656
- * Label
1657
- * Icon <- the DOM you have (dom-icon)
1658
- *
1659
- * let btn = Component.getElement( dom-icon, Button );
1660
- */
1661
-
1662
- static getElement<T extends Component>(dom: HTMLElement | Element, classname?: Constructor<T> | string ): T {
1663
-
1664
- if (classname) {
1665
-
1666
- const srhCls = isString(classname);
1667
-
1668
- while (dom) {
1669
- let el: Component = dom[_x4_el_sym];
1670
-
1671
- if( srhCls ) {
1672
- if( el && el.hasClass(classname) ) {
1673
- return el as T;
1674
- }
1675
- }
1676
- else if (el instanceof classname) {
1677
- return el;
1678
- }
1679
-
1680
- dom = dom.parentElement;
1681
- }
1682
-
1683
- return null;
1684
- }
1685
- else {
1686
- return dom ? dom[_x4_el_sym] : null;
1687
- }
1688
- }
1689
-
1690
- /**
1691
- * compute the scrollbar size ( width = height)
1692
- */
1693
-
1694
- static getScrollbarSize() {
1695
-
1696
- if (Component.__sb_width === undefined) {
1697
- let outerDiv = x4document.createElement('div');
1698
- outerDiv.style.cssText = 'overflow:auto;position:absolute;top:0;width:100px;height:100px';
1699
-
1700
- let innerDiv = x4document.createElement('div');
1701
- innerDiv.style.width = '200px';
1702
- innerDiv.style.height = '200px';
1703
-
1704
- outerDiv.appendChild(innerDiv);
1705
- x4document.body.appendChild(outerDiv);
1706
-
1707
- Component.__sb_width = outerDiv.offsetWidth - outerDiv.clientWidth;
1708
- x4document.body.removeChild(outerDiv);
1709
- }
1710
-
1711
- return Component.__sb_width;
1712
- }
1713
-
1714
- /**
1715
- * check if the Component is visible to the user
1716
- */
1717
-
1718
- isUserVisible(): boolean {
1719
- if (!this.m_dom) {
1720
- return false;
1721
- }
1722
-
1723
- return (this.m_dom.offsetParent !== null);
1724
- }
1725
- }
1726
-
1727
- /** @ignore */
1728
- let fly_element: Component = null;
1729
-
1730
- /**
1731
- * warp <b>temporarily</b> a DOM element to be able to acces to exact API
1732
- * @param dom dom element to wrap
1733
- * @review qui libere le fly_element ? -> timeout
1734
- */
1735
-
1736
- export function flyWrap<T extends Component>(dom: HTMLElement | EventTarget): T {
1737
-
1738
- if (dom[_x4_el_sym]) {
1739
- return dom[_x4_el_sym];
1740
- }
1741
-
1742
- let f = fly_element;
1743
- if (!f) { f = fly_element = new Component({}); }
1744
- (<any>f).m_dom = dom;
1745
-
1746
- return f as T;
1747
- }
1748
-
1749
-
1750
-
1751
-
1752
-
1753
-
1754
-
1755
-
1756
- /**
1757
- * simple flex spacer
1758
- */
1759
-
1760
- export class Flex extends Component {
1761
-
1762
- constructor(props: CProps = {}) {
1763
- if (!props.flex) {
1764
- props.flex = 1;
1765
- }
1766
-
1767
- super(props);
1768
- }
1769
- }
1770
-
1771
- /**
1772
- * simple space between 2 elements
1773
- */
1774
-
1775
- export class Space extends Component {
1776
-
1777
- m_size: number | string;
1778
-
1779
- constructor(size: number | string) {
1780
- super({});
1781
-
1782
- this.m_size = size;
1783
- }
1784
-
1785
- componentCreated() {
1786
-
1787
- // try to find if we are in a hz / vt / abs container
1788
- let dom = this.dom;
1789
- let style = null;
1790
-
1791
- while (dom) {
1792
- let el: Component = dom[_x4_el_sym];
1793
- if (el.hasClass('@hlayout')) {
1794
- style = { width: this.m_size };
1795
- break;
1796
- }
1797
- else if (el.hasClass('@vlayout')) {
1798
- style = { height: this.m_size };
1799
- break;
1800
- }
1801
-
1802
- dom = dom.parentElement;
1803
- }
1804
-
1805
- if (!style) {
1806
- style = { width: this.m_size, height: this.m_size };
1807
- }
1808
-
1809
- this.setStyle(style);
1810
- }
1811
- }
1812
-
1813
- /**
1814
- * sizable separator
1815
- */
1816
-
1817
- type SizeMode = null | 'minimize' | 'maximize' | 'restore';
1818
-
1819
- export interface EvSize extends BasicEvent {
1820
- readonly size: Size;
1821
- readonly mode: SizeMode;
1822
- }
1823
-
1824
- export function EvSize(size: Size, mode: SizeMode = null, context = null ): EvSize {
1825
- return BasicEvent<EvSize>({ size, mode, context });
1826
- }
1827
-
1828
- interface SeparatorEventMap extends CEventMap {
1829
- resize?: EvSize;
1830
- }
1831
-
1832
- interface SeparatorProps extends CProps<SeparatorEventMap> {
1833
- readonly orientation: 'vertical' | 'horizontal'; // vertical means vertical sizer so it resize horizontally
1834
- readonly sizing: 'before' | 'after';
1835
- readonly collapsible?: boolean;
1836
- }
1837
-
1838
- export class Separator extends Component<SeparatorProps, SeparatorEventMap> {
1839
-
1840
- m_irect: Rect;
1841
- m_delta: number;
1842
- m_target: Component;
1843
-
1844
- constructor(props: SeparatorProps) {
1845
- super(props);
1846
-
1847
- this.setDomEvent('mousedown', (e) => this._mousedown(e));
1848
- this.setDomEvent('touchstart', (e) => this._mousedown(e));
1849
- this.setDomEvent('dblclick', (e) => this._collapse(e) );
1850
- }
1851
-
1852
- render() {
1853
- this.addClass(this.m_props.orientation);
1854
- }
1855
-
1856
- private _collapse( ev: UIEvent ) {
1857
- if( this.m_props.collapsible ) {
1858
- this._findTarget();
1859
- if( this.m_target ) {
1860
- this.m_target.toggleClass( '@collapsed' );
1861
- }
1862
- }
1863
- }
1864
-
1865
- private _mousedown(ev: UIEvent) {
1866
-
1867
- if (ev.type == 'touchstart') {
1868
- let te = ev as TouchEvent;
1869
- if (te.touches.length == 1) {
1870
- this._startMoving(te.touches[0].pageX, te.touches[0].pageY, ev);
1871
- }
1872
- }
1873
- else {
1874
- let me = ev as MouseEvent;
1875
- this._startMoving(me.pageX, me.pageY, ev);
1876
- }
1877
- }
1878
-
1879
- _startMoving(x: number, y: number, ev: UIEvent) {
1880
- //if( this.m_props.callback ) {
1881
- // this.m_props.callback( ev, this );
1882
- //}
1883
- //else
1884
- {
1885
- this._findTarget();
1886
-
1887
- if (this.m_target) {
1888
-
1889
- if (this.m_props.orientation == 'horizontal') {
1890
- if (this.m_props.sizing == 'before') {
1891
- this.m_delta = x - this.m_irect.right;
1892
- }
1893
- else {
1894
- this.m_delta = x - this.m_irect.left;
1895
- }
1896
- }
1897
- else {
1898
- if (this.m_props.sizing == 'before') {
1899
- this.m_delta = y - this.m_irect.bottom;
1900
- }
1901
- else {
1902
- this.m_delta = y - this.m_irect.top;
1903
- }
1904
- }
1905
-
1906
- ev.preventDefault();
1907
- ev.stopPropagation();
1908
-
1909
- this.m_target.addClass('sizing');
1910
-
1911
- Component.setCapture(this, (e) => this._pointerMoved(e));
1912
- }
1913
- }
1914
- }
1915
-
1916
- private _pointerMoved(ev: UIEvent) {
1917
-
1918
- let __move = (ex, ey) => {
1919
-
1920
- if (this.m_props.orientation == 'horizontal') {
1921
-
1922
- let width;
1923
- if (this.m_props.sizing == 'after') {
1924
- width = this.m_irect.right - (ex - this.m_delta);
1925
- }
1926
- else {
1927
- width = (ex - this.m_delta) - this.m_irect.left
1928
- }
1929
-
1930
- if (width > 0) {
1931
- let size = new Size(width, 0);
1932
- this.emit('resize', EvSize(size));
1933
-
1934
- this.m_target.setStyleValue('width', size.width);
1935
- this.m_target.setStyleValue('flex', null); // for flex>1
1936
- this.m_target.removeClass('@flex');
1937
- }
1938
- }
1939
- else {
1940
-
1941
- let height;
1942
- if (this.m_props.sizing == 'after') {
1943
- height = this.m_irect.bottom - (ey - this.m_delta);
1944
- }
1945
- else {
1946
- height = (ey - this.m_delta) - this.m_irect.top;
1947
- }
1948
-
1949
- if (height > 0) {
1950
- let size = new Size(0, height);
1951
- this.emit('resize', EvSize(size));
1952
-
1953
- this.m_target.setStyleValue('height', size.height);
1954
- this.m_target.setStyleValue('flex', null); // for flex>1
1955
- this.m_target.removeClass('@flex');
1956
- }
1957
- }
1958
- }
1959
-
1960
- if (ev.type == 'mousemove') {
1961
-
1962
- let mev = ev as MouseEvent;
1963
- __move(mev.pageX, mev.pageY);
1964
-
1965
- ev.preventDefault();
1966
- ev.stopPropagation();
1967
- }
1968
- else if (ev.type == 'touchmove') {
1969
-
1970
- let tev = ev as TouchEvent;
1971
- __move(tev.touches[0].pageX, tev.touches[0].pageY);
1972
-
1973
- ev.preventDefault();
1974
- ev.stopPropagation();
1975
- }
1976
- else if (ev.type == 'mouseup' || ev.type == 'touchend') {
1977
- this.m_target.removeClass('sizing');
1978
-
1979
- Component.releaseCapture();
1980
- ev.preventDefault();
1981
- ev.stopPropagation();
1982
- }
1983
- }
1984
-
1985
- private _findTarget() {
1986
-
1987
- if (!this.m_target) {
1988
-
1989
- if (this.m_props.sizing == 'before') {
1990
- let prevDom = this.dom.previousElementSibling;
1991
- let prevEl = prevDom ? Component.getElement(prevDom as HTMLElement) : null;
1992
- this.m_target = prevEl;
1993
- }
1994
- else {
1995
- let nextDom = this.dom.nextElementSibling;
1996
- let nextEl = nextDom ? Component.getElement(nextDom as HTMLElement) : null;
1997
- this.m_target = nextEl;
1998
- }
1999
- }
2000
-
2001
- if (this.m_target) {
2002
- this.m_irect = this.m_target.getBoundingRect();
2003
- }
2004
- else {
2005
- this.m_irect = null;
2006
- }
2007
- }
2008
- }
2009
-
2010
-
2011
-
2012
-
2013
- // :: SIZERBAR ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
2014
-
2015
- /**
2016
- * properties
2017
- */
2018
-
2019
- type SizerOverlaySens = 'left' | 'top' | 'right' | 'bottom' | 'topleft' | 'topright' | 'bottomleft' | 'bottomright';
2020
-
2021
- export interface EvOverlayResize extends BasicEvent {
2022
- ui_event: UIEvent;
2023
- sens: SizerOverlaySens;
2024
- }
2025
-
2026
- export function EvOverlayResize(ui_event: UIEvent, sens: SizerOverlaySens, context: any = null) {
2027
- return BasicEvent<EvOverlayResize>({ ui_event, sens, context });
2028
- }
2029
-
2030
- interface SizerOverlayEventMap extends CEventMap {
2031
- resize: EvSize;
2032
- rawresize: EvOverlayResize;
2033
- }
2034
-
2035
-
2036
- export interface SizerOverlayProps extends CProps<SizerOverlayEventMap> {
2037
- sens: SizerOverlaySens;
2038
- target: Component;
2039
-
2040
- resize?: EventCallback<EvSize>; // shortcut to events: { size: ... }
2041
- }
2042
-
2043
- export class SizerOverlay extends Component<SizerOverlayProps, SizerOverlayEventMap> {
2044
-
2045
- private m_delta: number;
2046
- private m_irect: Rect;
2047
-
2048
- constructor(props: SizerOverlayProps) {
2049
- super(props);
2050
-
2051
- this.addClass(props.sens);
2052
- this.setDomEvent('mousedown', (e) => this._mousedown(e));
2053
- this.setDomEvent('touchstart', (e) => this._mousedown(e));
2054
- this.setDomEvent('dblclick', (e) => this.resetflex(e)); // todo: add option for that
2055
-
2056
- props.target.appendChild(this);
2057
-
2058
- if( props.resize ) {
2059
- this.on( 'resize', this.m_props.resize );
2060
- }
2061
- }
2062
-
2063
- resetflex(event: UIEvent) {
2064
- this.m_props.target.addClass('@flex');
2065
- this.emit('resize', EvSize( { width: -1, height: 0})); // todo: see that
2066
- event.preventDefault();
2067
- event.stopPropagation();
2068
- }
2069
-
2070
- // @review move that in component
2071
-
2072
- _mousedown(ev: UIEvent) {
2073
-
2074
- ev.preventDefault();
2075
- ev.stopPropagation();
2076
-
2077
- let eev = EvOverlayResize(ev, this.m_props.sens);
2078
- this.emit('rawresize', eev);
2079
- if (eev.defaultPrevented) {
2080
- return;
2081
- }
2082
-
2083
- let pos = getMousePos(ev, true);
2084
- this.m_irect = this.m_props.target.getBoundingRect();
2085
-
2086
- if (this.m_props.sens == 'right') {
2087
- this.m_delta = pos.x - this.m_irect.right;
2088
- }
2089
- else if (this.m_props.sens == 'left') {
2090
- this.m_delta = pos.x - this.m_irect.left;
2091
- }
2092
- else if (this.m_props.sens == 'bottom') {
2093
- this.m_delta = pos.y - this.m_irect.bottom;
2094
- }
2095
- else if (this.m_props.sens == 'top') {
2096
- this.m_delta = pos.y - this.m_irect.top;
2097
- }
2098
-
2099
- this.m_props.target.addClass('sizing');
2100
- Component.setCapture(this, (e) => this._handle_mouse(e));
2101
- }
2102
-
2103
- private _is_horz() {
2104
- return this.m_props.sens == 'left' || this.m_props.sens == 'right';
2105
- }
2106
-
2107
- public get sens() {
2108
- return this.m_props.sens;
2109
- }
2110
-
2111
- private _handle_mouse(ev: UIEvent) {
2112
- let __move = (ex, ey) => {
2113
- if (this._is_horz()) {
2114
-
2115
- let width;
2116
- if (this.m_props.sens == 'left') {
2117
- width = this.m_irect.right - (ex - this.m_delta);
2118
- }
2119
- else {
2120
- width = (ex - this.m_delta) - this.m_irect.left
2121
- }
2122
-
2123
- if (width > 0) {
2124
- let size = {
2125
- width,
2126
- height: undefined
2127
- };
2128
-
2129
- this.emit('resize', EvSize(size));
2130
-
2131
- this.m_props.target.setStyleValue('width', size.width);
2132
- this.m_props.target.setStyleValue('flex', null); // for flex>1
2133
- this.m_props.target.removeClass('@flex');
2134
- }
2135
- }
2136
- else {
2137
-
2138
- let height;
2139
- if (this.m_props.sens == 'top') {
2140
- height = this.m_irect.bottom - (ey - this.m_delta);
2141
- }
2142
- else {
2143
- height = (ey - this.m_delta) - this.m_irect.top;
2144
- }
2145
-
2146
- if (height > 0) {
2147
- let size = new Size(0, height);
2148
- this.emit('resize', EvSize(size));
2149
-
2150
- this.m_props.target.setStyleValue('height', size.height);
2151
- this.m_props.target.setStyleValue('flex', null); // for flex>1
2152
- this.m_props.target.removeClass('@flex');
2153
- }
2154
- }
2155
- }
2156
-
2157
- if (ev.type == 'mousemove') {
2158
-
2159
- let mev = ev as MouseEvent;
2160
- __move(mev.pageX, mev.pageY);
2161
-
2162
- ev.preventDefault();
2163
- ev.stopPropagation();
2164
- }
2165
- else if (ev.type == 'touchmove') {
2166
-
2167
- let tev = ev as TouchEvent;
2168
- __move(tev.touches[0].pageX, tev.touches[0].pageY);
2169
-
2170
- ev.preventDefault();
2171
- ev.stopPropagation();
2172
- }
2173
- else if (ev.type == 'mouseup' || ev.type == 'touchend') {
2174
- this.m_props.target.removeClass('sizing');
2175
-
2176
- Component.releaseCapture();
2177
- ev.preventDefault();
2178
- ev.stopPropagation();
2179
- }
2180
- }
2181
- }
2182
-
2183
- /**
2184
- * sequence: Shift+Ctrl+Alt+A
2185
- */
2186
-
2187
- export interface Shortcut {
2188
- sequence: string;
2189
- name: string;
2190
- immediate: boolean;
2191
- callback?: (domTarget) => void;
2192
- }
2193
-
2194
- interface EvShortcut extends BasicEvent {
2195
- name: string;
2196
- }
2197
-
2198
- function EvShortcut(name: string) {
2199
- return BasicEvent<EvShortcut>({ name });
2200
- }
2201
-
2202
- export interface ContainerEventMap extends CEventMap {
2203
- shortcut: EvShortcut;
2204
- }
2205
-
2206
- export interface ContainerProps<E extends ContainerEventMap = ContainerEventMap> extends CProps<E> {
2207
- }
2208
-
2209
- /**
2210
- * you can construct a Container as usual with it's properties but also directly with it's children array
2211
- *
2212
- * @example
2213
- * new Container( [
2214
- * child1,
2215
- * child2
2216
- * ])
2217
- */
2218
-
2219
- export class Container<P extends ContainerProps = ContainerProps, E extends ContainerEventMap = ContainerEventMap> extends Component<P, E> {
2220
-
2221
- private m_shortcuts: Shortcut[];
2222
-
2223
- constructor( props: P | ComponentOrString[] ) {
2224
- if( isArray(props) ) {
2225
- super( {content: props} as P );
2226
- }
2227
- else {
2228
- super( props );
2229
- }
2230
- }
2231
-
2232
- /**
2233
- * add an application shortcut
2234
- * @param sequence key sequence Shift+Ctrl+Alt+K
2235
- * @param callback callback to call
2236
- */
2237
-
2238
- public addShortcut(sequence: string | string[], name: string, callback: EventHandler<KeyboardEvent> = null, immediate = false) {
2239
-
2240
- // first time
2241
- if (!this.m_shortcuts) {
2242
- this.m_shortcuts = [];
2243
- this.setDomEvent('keydown', (e) => this._handleKeydown(e));
2244
- }
2245
-
2246
- if (!isArray(sequence)) {
2247
- sequence = [sequence];
2248
- }
2249
-
2250
- sequence.forEach((seq: string) => {
2251
- let reseq = '';
2252
-
2253
- let shift = seq.match(/SHIFT/i);
2254
- if (shift) {
2255
- seq = seq.replace(/SHIFT/i, '');
2256
- reseq += 'shift+';
2257
- }
2258
-
2259
- let ctrl = seq.match(/CTRL/i);
2260
- if (ctrl) {
2261
- seq = seq.replace(/CTRL/i, '');
2262
- reseq += 'ctrl+';
2263
- }
2264
-
2265
- let cmd = seq.match(/CMD/i);
2266
- if (cmd) {
2267
- seq = seq.replace(/CMD/i, '');
2268
- reseq += 'cmd+';
2269
- }
2270
-
2271
- let alt = seq.match(/ALT/i);
2272
- if (alt) {
2273
- seq = seq.replace(/ALT/i, '');
2274
- reseq += 'alt+';
2275
- }
2276
-
2277
- reseq += seq.replace('+', '').toLowerCase();
2278
-
2279
- this.m_shortcuts.push({
2280
- sequence: reseq,
2281
- name,
2282
- immediate,
2283
- callback
2284
- });
2285
- });
2286
- }
2287
-
2288
- /**
2289
- * remove all shortcuts for a target
2290
- */
2291
-
2292
- removeShortcuts() {
2293
- if (this.m_shortcuts) {
2294
- this.m_shortcuts = [];
2295
- }
2296
- }
2297
-
2298
- /** @ignore this function is binded */
2299
- private _handleKeydown(e: KeyboardEvent) {
2300
-
2301
- if (!this.m_shortcuts) {
2302
- return;
2303
- }
2304
-
2305
- let seq = '';
2306
-
2307
- if (e.shiftKey) {
2308
- seq += 'shift+';
2309
- }
2310
-
2311
- if (e.ctrlKey) {
2312
- seq += 'ctrl+';
2313
- }
2314
-
2315
- if (e.metaKey) {
2316
- seq += 'cmd+';
2317
- }
2318
-
2319
- if (e.altKey) {
2320
- seq += 'alt+';
2321
- }
2322
-
2323
- seq += e.key.toLowerCase();
2324
- //console.log( seq );
2325
-
2326
- this.m_shortcuts.some((sk) => {
2327
- if (sk.sequence == seq) {
2328
-
2329
- if (sk.callback) {
2330
- if (sk.immediate) {
2331
- sk.callback(e);
2332
- }
2333
- else {
2334
- asap(() => { sk.callback(e); });
2335
- }
2336
- }
2337
- else {
2338
- this.emit('shortcut', EvShortcut(sk.name));
2339
- }
2340
-
2341
- e.preventDefault();
2342
- e.stopPropagation();
2343
- return true;
2344
- }
2345
- });
2346
- }
2347
- }
2348
-
2349
- export type ComponentConstructor<T> = new (props: CProps) => T;
2350
-
2351
-
1
+ /**
2
+ * ___ ___ __
3
+ * \ \/ / / _
4
+ * \ / /_| |_
5
+ * / \____ _|
6
+ * /__/\__\ |_|
7
+ *
8
+ * @file components.ts
9
+ * @author Etienne Cochard
10
+ *
11
+ * Copyright (c) 2019-2022 R-libre ingenierie
12
+ *
13
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ * of this software and associated documentation files (the "Software"), to deal
15
+ * in the Software without restriction, including without limitation the rights
16
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
17
+ * of the Software, and to permit persons to whom the Software is furnished to do so,
18
+ * subject to the following conditions:
19
+ * The above copyright notice and this permission notice shall be included in all copies
20
+ * or substantial portions of the Software.
21
+ *
22
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
23
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
24
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
25
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
27
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
+ */
29
+
30
+
31
+ /**
32
+ * @todo
33
+ * create Container class
34
+ */
35
+
36
+ import { pascalCase, Rect, isString, isArray, Size, isNumber, asap, HtmlString, isHtmlString, Constructor, getMousePos } from './tools';
37
+ import { x4document } from './x4dom';
38
+
39
+ import { Stylesheet, ComputedStyle } from './styles';
40
+ import { _tr } from './i18n';
41
+ import { BasicEvent, EventCallback } from './x4events';
42
+ import { BaseComponent, BaseComponentProps, BaseComponentEventMap } from './base_component';
43
+ import { IDOMEvents, X4ElementEventMap } from './dom_events';
44
+
45
+ export { HtmlString, isHtmlString, html } from './tools'
46
+
47
+ export interface EventHandler<T> {
48
+ (ev: T): any;
49
+ }
50
+
51
+ export interface ICaptureInfo {
52
+ initiator: Component;
53
+ handler: EventHandler<UIEvent>;
54
+ iframes: NodeListOf<HTMLIFrameElement>;
55
+ }
56
+
57
+ /** @ignore classname prefix for system classes */
58
+ const _x4_ns_prefix = 'x-';
59
+
60
+ // -- elements -----------
61
+
62
+ /** @ignore where event handlers are stored */
63
+ const _x4_el_store = Symbol();
64
+
65
+ /** @ignore where Component is stored in dom */
66
+ const _x4_el_sym = Symbol();
67
+
68
+ /** @ignore properties without 'px' unit */
69
+ export const _x4_unitless = {
70
+ animationIterationCount: 1, borderImageOutset: 1, borderImageSlice: 1, borderImageWidth: 1, boxFlex: 1, boxFlexGroup: 1,
71
+ boxOrdinalGroup: 1, columnCount: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, flexOrder: 1,
72
+ gridRow: 1, gridColumn: 1, fontWeight: 1, lineClamp: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, tabSize: 1, widows: 1,
73
+ zIndex: 1, zoom: 1,
74
+
75
+ // SVG-related _properties
76
+ fillOpacity: 1, floodOpacity: 1, stopOpacity: 1, strokeDasharray: 1, strokeDashoffset: 1, strokeMiterlimit: 1, strokeOpacity: 1,
77
+ strokeWidth: 1,
78
+ };
79
+
80
+ /** @ignore this events must be defined on domNode (do not bubble) */
81
+ const unbubbleEvents = {
82
+ mouseleave: 1, mouseenter: 1, load: 1, unload: 1, scroll: 1, focus: 1, blur: 1, rowexit: 1, beforeunload: 1, stop: 1,
83
+ dragdrop: 1, dragenter: 1, dragexit: 1, draggesture: 1, dragover: 1, contextmenu: 1, create: 2, sizechange: 2
84
+ };
85
+
86
+ /** @ignore */
87
+ const passiveEvents = {
88
+ touchstart: 1, touchmove: 1, touchend: 1,
89
+ //pointerdown: 1, pointermove: 1, pointerup: 1,
90
+ };
91
+
92
+ /** ignore */
93
+ const reNumber = /^-?\d+(\.\d+)?$/;
94
+
95
+
96
+ /**
97
+ *
98
+ */
99
+
100
+ export type VoidCallback = () => void;
101
+
102
+ export type ComponentOrString = Component | string | HtmlString;
103
+ export type ComponentContent = ComponentOrString | ComponentOrString[];
104
+
105
+ interface IMap<T> {
106
+ [key: string]: T;
107
+ }
108
+
109
+ /**
110
+ * DblClick Event
111
+ * double click event
112
+ */
113
+
114
+ export interface EvDblClick extends BasicEvent {
115
+ }
116
+
117
+ export function EvDblClick(context = null) {
118
+ return BasicEvent<EvDblClick>({ context });
119
+ }
120
+
121
+ /**
122
+ * DblFocus Event
123
+ * double click event
124
+ */
125
+
126
+ export interface EvFocus extends BasicEvent {
127
+ readonly focus: boolean;
128
+ }
129
+
130
+ export function EvFocus( focus = true, context = null) {
131
+ return BasicEvent<EvFocus>({ focus, context });
132
+ }
133
+
134
+ /**
135
+ * basic event map of Component
136
+ */
137
+
138
+ export interface CEventMap extends BaseComponentEventMap {
139
+ }
140
+
141
+
142
+
143
+
144
+ /**
145
+ * Basic properties of every Component
146
+ */
147
+
148
+ export interface CProps<T extends CEventMap = CEventMap> extends BaseComponentProps<T> {
149
+ tag?: string; // dom Tag <div> if not specified
150
+ ns?: string; // namespace (usefull for svg)
151
+ cls?: string; // elements classes (space separated), prefix class name with @ to make it system wide
152
+ id?: string; // element id
153
+ style?: IMap<string | number>; // element style
154
+ attrs?: object; // element attributes
155
+
156
+ dom_events?: IDOMEvents; // DOM event handlers
157
+ data?: any; // element user data (you can store everything you need here)
158
+ content?: ComponentContent; // array of sub components
159
+ tooltip?: string; // tooltip text
160
+ ref?: string; // internal reference for itemWithRef
161
+
162
+ // shortcuts for element style
163
+ left?: number;
164
+ top?: number;
165
+ width?: number | string;
166
+ height?: number | string;
167
+ tabIndex?: number | boolean;
168
+
169
+ flex?: number | string; // add @flex class to the element
170
+ enabled?: boolean; // add @disabled to the element if false
171
+ }
172
+
173
+ interface CInternalProps {
174
+ dom_events: any;
175
+ classes: IMap<boolean>;
176
+ uid: number;
177
+ inrender: boolean;
178
+ }
179
+
180
+ /**
181
+ *
182
+ */
183
+
184
+ export class Component<P extends CProps<CEventMap> = CProps<CEventMap>, E extends CEventMap = CEventMap> extends BaseComponent<P, E> {
185
+ private m_dom: HTMLElement;
186
+ private m_iprops: CInternalProps;
187
+
188
+ private static __sb_width; // scrollbar width
189
+ private static __comp_guid = 1000; // component global unique id
190
+ private static __privateEvents: any = {};
191
+ private static __sizeObserver: ResizeObserver; // resize observer
192
+ private static __createObserver: MutationObserver; // creation observer
193
+ //private static __intersectionObserver: IntersectionObserver; // visibility observer
194
+
195
+ private static __capture: ICaptureInfo = null;
196
+ private static __capture_mask = null;
197
+ private static __css = null;
198
+
199
+ constructor(props: P = null ) {
200
+ super(props ?? {} as P );
201
+
202
+ this.m_iprops = {
203
+ classes: {},
204
+ dom_events: {},
205
+ uid: Component.__comp_guid++,
206
+ inrender: false,
207
+ };
208
+
209
+ // prepare iprops
210
+ if( this.m_props.cls ) {
211
+ this.addClass( this.m_props.cls );
212
+ }
213
+ }
214
+
215
+ /**
216
+ *
217
+ */
218
+
219
+ get uid() {
220
+ return this.m_iprops.uid;
221
+ }
222
+
223
+ /**
224
+ * change the component content
225
+ * @param content new content or null
226
+ */
227
+
228
+ setContent(content: ComponentContent, refreshAll = false ) {
229
+ this.m_props.content = content ?? [];
230
+
231
+ if( this.m_iprops.inrender || !this.m_dom ) {
232
+ return;
233
+ }
234
+
235
+ if (refreshAll) {
236
+ this.update();
237
+ }
238
+ else {
239
+ this._updateContent();
240
+ }
241
+ }
242
+
243
+
244
+ /**
245
+ * add a new child to the component content
246
+ * @param content
247
+ */
248
+
249
+ appendChild(content: ComponentContent) {
250
+
251
+ if (!content) {
252
+ return;
253
+ }
254
+
255
+ const append = (c) => {
256
+
257
+ if (!this.m_props.content) {
258
+ this.m_props.content = [];
259
+ }
260
+ else if (!isArray(this.m_props.content)) {
261
+ this.m_props.content = [this.m_props.content];
262
+ }
263
+
264
+ this.m_props.content.push(c);
265
+ if (this.m_dom) {
266
+ this._appendChild(c);
267
+ }
268
+ }
269
+
270
+ if (isArray(content)) {
271
+ content.forEach(append);
272
+ }
273
+ else {
274
+ append(content);
275
+ }
276
+ }
277
+
278
+ /**
279
+ *
280
+ */
281
+
282
+ setTag( tag: string, namespace?: string ) {
283
+ this.m_props.tag = tag;
284
+ if( namespace ) {
285
+ this.m_props.ns = namespace;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * get the Component data value
291
+ * @param name name to get
292
+ */
293
+
294
+ getData(name: string | Symbol): any {
295
+ if (this.m_props.data !== undefined) {
296
+ return this.m_props.data[name.toString()];
297
+ }
298
+
299
+ return undefined;
300
+ }
301
+
302
+ /**
303
+ * set the Component data value
304
+ * @param name name to get
305
+ * @param value
306
+ */
307
+
308
+ setData(name: string | Symbol , value: any) {
309
+
310
+ let data = this.m_props.data;
311
+ if (data === undefined) {
312
+ data = this.m_props.data = {};
313
+ }
314
+
315
+ data[name.toString()] = value;
316
+ }
317
+
318
+
319
+ /**
320
+ * return the DOM associated with the Component (if any)
321
+ */
322
+
323
+ get dom(): HTMLElement {
324
+ return this.m_dom;
325
+ }
326
+
327
+ /**
328
+ * shows the element
329
+ * @param show
330
+ */
331
+
332
+ show(show?: boolean) {
333
+ if (show === undefined || show === true) {
334
+ this.removeClass('@hidden');
335
+ }
336
+ else {
337
+ this.addClass('@hidden');
338
+ }
339
+ }
340
+
341
+ /**
342
+ * hides the element
343
+ */
344
+ hide() {
345
+ this.addClass('@hidden');
346
+ }
347
+
348
+ /**
349
+ * enable or disable the element
350
+ * @param enable
351
+ */
352
+
353
+ enable(enable?: boolean) {
354
+ if (enable === undefined || enable === true) {
355
+ this.removeClass('@disable');
356
+ this.removeAttribute('disabled');
357
+ }
358
+ else {
359
+ this.disable();
360
+ }
361
+ }
362
+
363
+ /**
364
+ * disable the element
365
+ */
366
+
367
+ disable() {
368
+ this.addClass('@disable');
369
+ this.setAttribute('disabled', '');
370
+ }
371
+
372
+ /**
373
+ * set the focus on the element
374
+ */
375
+
376
+ focus() {
377
+ console.assert(!!this.m_dom);
378
+ this.m_dom.focus();
379
+ }
380
+
381
+ /**
382
+ * change the object style
383
+ * @param style - style to add
384
+ * @example ```typescript
385
+ * el.setStyle( {left:100} );
386
+ */
387
+
388
+ public setStyle(style: object) {
389
+ for (let s in style) {
390
+ this.setStyleValue(s, style[s]);
391
+ }
392
+ }
393
+
394
+ /**
395
+ * change a style value
396
+ * @param name string style nale
397
+ * @param value any style value or null to remove style
398
+ */
399
+
400
+ setStyleValue(name: string, value: any) {
401
+ let style = this.m_props.style;
402
+ if (!style) {
403
+ style = this.m_props.style = {};
404
+ }
405
+
406
+ style[name] = value;
407
+ this._setDomStyleValue(name, value);
408
+ }
409
+
410
+ private _setDomStyleValue(name: string, value: string | number) {
411
+ if (this.m_dom) {
412
+
413
+ if (value === undefined) {
414
+ value = null;
415
+ }
416
+ else if (!_x4_unitless[name] && (isNumber(value) || reNumber.test(value))) {
417
+ value = value + 'px';
418
+ }
419
+
420
+ this.m_dom.style[name] = value;
421
+ }
422
+ }
423
+
424
+ /**
425
+ * compute the element style
426
+ * @return all styles computed
427
+ */
428
+
429
+ public getComputedStyle(pseudoElt?: string): ComputedStyle {
430
+ if (this.dom) {
431
+ return new ComputedStyle(getComputedStyle(this.dom, pseudoElt ?? null));
432
+ }
433
+
434
+ return new ComputedStyle(this.m_props.style as any);
435
+ }
436
+
437
+ /**
438
+ * return a single stype value
439
+ * @param name - value to get
440
+ */
441
+
442
+ public getStyleValue(name: string) {
443
+ return this.getComputedStyle()[name];
444
+ }
445
+
446
+ /**
447
+ * define the elements attributes
448
+ * @param attrs
449
+ */
450
+
451
+ public setAttributes(attrs: any) {
452
+ for (let a in attrs) {
453
+ this.setAttribute(a, attrs[a]);
454
+ }
455
+ }
456
+
457
+ /**
458
+ * change a single attribute
459
+ * @param name attribute name
460
+ * @param value new value
461
+ */
462
+
463
+ public setAttribute(name: string, value: any) {
464
+
465
+ if (value === false || value === undefined) {
466
+ this.removeAttribute(name);
467
+ }
468
+ else {
469
+ if (value === true) {
470
+ value = '';
471
+ }
472
+ else if (isNumber(value)) {
473
+ value = '' + value;
474
+ }
475
+
476
+ let attrs = this.m_props.attrs;
477
+ if (!attrs) {
478
+ attrs = this.m_props.attrs = {};
479
+ }
480
+
481
+ attrs[name] = value;
482
+ this._setDomAttribute(name, value);
483
+ }
484
+ }
485
+
486
+ private _setDomAttribute(name: string, value: string) {
487
+ if (this.m_dom) {
488
+ this.m_dom.setAttribute(name, value);
489
+ }
490
+ }
491
+
492
+ /**
493
+ * remove an atrribute
494
+ * @param name name of the attribute
495
+ */
496
+ public removeAttribute(name: string) {
497
+ let attrs = this.m_props.attrs;
498
+ if (!attrs) {
499
+ return;
500
+ }
501
+
502
+ delete attrs[name];
503
+
504
+ if (this.m_dom) {
505
+ this.m_dom.removeAttribute(name);
506
+ }
507
+ }
508
+
509
+ /**
510
+ * get an attribute value
511
+ * @param {string} name - attribute name
512
+ * @return {string} attribute value
513
+ * @example ```typescript
514
+ * let chk = el.getAttribute( 'checked' );
515
+ * @review double cache
516
+ */
517
+
518
+ public getAttribute(name: string): string {
519
+ if (this.m_dom) {
520
+ return this.m_dom.getAttribute(name);
521
+ }
522
+ else {
523
+ if (!this.m_props.attrs) {
524
+ return undefined;
525
+ }
526
+
527
+ return this.m_props.attrs[name];
528
+ }
529
+ }
530
+
531
+ /**
532
+ * check if the element has an attribute
533
+ * @param name attribute name
534
+ * @return true is attribute is present
535
+ * @example ```typescript
536
+ * if( el.hasAttribute('checked') ) {
537
+ * }
538
+ */
539
+
540
+ public hasAttribute(name: string): boolean {
541
+ if (this.m_dom) {
542
+ return this.m_dom.hasAttribute(name);
543
+ }
544
+ else {
545
+ return this.m_props.attrs.hasOwnProperty(name);
546
+ }
547
+ }
548
+
549
+
550
+ /**
551
+ * a some classnames to the component
552
+ * classes can be separated by a space
553
+ * @param cls class to add
554
+ * @example ```typescript
555
+ * addClass( 'my class name @flex' );
556
+ */
557
+
558
+ public addClass(name: string) {
559
+
560
+ if (name === null || name === undefined) {
561
+ return;
562
+ }
563
+
564
+ name = name.trim();
565
+ if (name === '') {
566
+ return;
567
+ }
568
+
569
+ let add = (c) => {
570
+
571
+ if (c === undefined || c === null || c === '') {
572
+ return;
573
+ }
574
+
575
+ c = this._makeCls(c);
576
+
577
+ // update vdom
578
+ classes[c] = true;
579
+
580
+ // update dom
581
+ if (this.m_dom) {
582
+ this.m_dom.classList.add(c);
583
+ }
584
+ }
585
+
586
+ let classes = this.m_iprops.classes;
587
+ if (name.indexOf(' ') < 0) {
588
+ add(name);
589
+ }
590
+ else {
591
+ let names = name.split(' ');
592
+ names.forEach((n) => add(n));
593
+ }
594
+ }
595
+
596
+ /**
597
+ * Remove a class from the element
598
+ * @param {string|array} name - classes in string form can be space separated
599
+ *
600
+ * @example ```typescript
601
+ * el.removeClass( 'myclass' );
602
+ * el.removeClass( 'myclass1 myclass2' );
603
+ */
604
+
605
+ public removeClass(name: string): void {
606
+
607
+ if (name === undefined) {
608
+ return;
609
+ }
610
+
611
+ let remove = (c) => {
612
+ if (c === undefined || c === null || c === '') {
613
+ return;
614
+ }
615
+
616
+ c = this._makeCls(c);
617
+
618
+ delete this.m_iprops.classes[c];
619
+ if (this.m_dom) {
620
+ this.m_dom.classList.remove(c);
621
+ }
622
+ }
623
+
624
+ // faster
625
+ if (name.indexOf(' ') < 0) {
626
+ remove(name);
627
+ }
628
+ else {
629
+ // build class list
630
+ let classes = name.trim().split(' ');
631
+ for (let c of classes) {
632
+ if (c !== undefined && c !== null && c !== '') {
633
+ remove(c);
634
+ }
635
+ }
636
+ }
637
+ }
638
+
639
+ /**
640
+ *
641
+ * @param cls
642
+ * @param set
643
+ */
644
+
645
+ public setClass(cls: string, set: boolean) {
646
+ if (set) { this.addClass(cls); }
647
+ else { this.removeClass(cls); }
648
+ return this;
649
+ }
650
+
651
+ /**
652
+ * Toggle a class from the element (if present remove, if absent add)
653
+ * @param {string|string[]} name - classes in string form can be space separated
654
+ * @example ```typescript
655
+ * el.toggleClass( 'myclass' );
656
+ * el.toggleClass( 'myclass1 myclass2');
657
+ * el.toggleClass( ['myclass1','myclass2']);
658
+ */
659
+
660
+ public toggleClass(name: string): void {
661
+
662
+ let toggle = (c) => {
663
+ if (c === undefined && c === null && c === '') {
664
+ return;
665
+ }
666
+
667
+ c = this._makeCls(c);
668
+ if (this.m_iprops.classes[c]) {
669
+ delete this.m_iprops.classes[c]
670
+ }
671
+ else {
672
+ this.m_iprops.classes[c] = true;
673
+ }
674
+
675
+ if (this.m_dom) {
676
+ this.m_dom.classList.toggle(c);
677
+ }
678
+ }
679
+
680
+ // faster
681
+ if (name.indexOf(' ') < 0) {
682
+ toggle(name);
683
+ }
684
+ else {
685
+
686
+ // build class list
687
+ let classes = name.trim().split(' ');
688
+ for (let c of classes) {
689
+ toggle(c);
690
+ }
691
+ }
692
+ }
693
+
694
+ /**
695
+ * check if the object has the class
696
+ * @param cls
697
+ */
698
+
699
+ public hasClass(cls: string): boolean {
700
+
701
+ let c = this._makeCls(cls);
702
+ if (this.m_dom) {
703
+ return this.dom.classList.contains(c);
704
+ }
705
+ else {
706
+ return !!this.m_iprops.classes[c];
707
+ }
708
+ }
709
+
710
+ /**
711
+ * remove all classes from the object
712
+ * this is usefull for component recycling & reusing
713
+ */
714
+
715
+ public clearClasses() {
716
+ this.m_iprops.classes = {};
717
+ if (this.m_dom) {
718
+ return this.m_dom.classList.value = '';
719
+ }
720
+ }
721
+
722
+ public _build(): HTMLElement {
723
+ if (this.m_dom) {
724
+ return this.m_dom;
725
+ }
726
+
727
+ this._createDOM();
728
+ return this.m_dom;
729
+ }
730
+
731
+ public render(props: P) {
732
+ }
733
+
734
+ public _createDOM(): HTMLElement {
735
+
736
+ if (this.m_dom) {
737
+ return this.m_dom;
738
+ }
739
+
740
+ // setup props
741
+ const props = this.m_props;
742
+
743
+ if( props.tabIndex!==undefined ) {
744
+ this._setTabIndex( props.tabIndex );
745
+ }
746
+ this.render(props);
747
+
748
+ // shortcuts ---------
749
+ if (props.left !== undefined) { this.setStyleValue('left', props.left); }
750
+ if (props.top !== undefined) { this.setStyleValue('top', props.top); }
751
+ if (props.width !== undefined) { this.setStyleValue('width', props.width); }
752
+ if (props.height !== undefined) { this.setStyleValue('height', props.height); }
753
+
754
+ if (props.flex !== undefined) {
755
+ this.addClass('@flex');
756
+ if (props.flex != 1) {
757
+ this.setStyleValue('flex', props.flex);
758
+ }
759
+ }
760
+
761
+ if (props.enabled === false) {
762
+ this.disable();
763
+ }
764
+
765
+ // shortcut: tip
766
+ if (props.tooltip !== undefined) {
767
+ this.setAttribute('tip', props.tooltip.replace(/\n/gi, '<br/>'));
768
+ }
769
+
770
+
771
+ // prepare iprops
772
+ if (props.dom_events) {
773
+ for (let ename in props.dom_events) {
774
+ this._setDomEvent(ename, props.dom_events[ename]);
775
+ }
776
+ }
777
+
778
+ this._genClassName();
779
+ this.m_props.cls = undefined; // now classes are tranfered to m_iprops
780
+
781
+ // create self
782
+ let vdom = this.m_iprops;
783
+
784
+ if (props.ns) {
785
+ this.m_dom = <HTMLElement>x4document.createElementNS(props.ns, props.tag ?? 'div');
786
+ }
787
+ else {
788
+ this.m_dom = x4document.createElement( (props.tag ?? 'div') as any );
789
+ }
790
+
791
+ this.m_dom[_x4_el_sym] = this;
792
+
793
+ //let me = Object.getPrototypeOf(this);
794
+ //console.log( 'create', this.m_iprops.uid, me.constructor.name );
795
+
796
+ // classes
797
+ this.m_dom.classList.add(...Object.keys(vdom.classes));
798
+
799
+ // styles
800
+ let sty = props.style;
801
+ if (sty) {
802
+ for (let s in sty) {
803
+ this._setDomStyleValue(s, sty[s]);
804
+ }
805
+ }
806
+
807
+ // attributes
808
+ let att = props.attrs;
809
+ if (att) {
810
+ for (let a in att) {
811
+ const attr = att[a];
812
+ if( attr!==false && attr!==undefined ) {
813
+ this._setDomAttribute(a, att[a]);
814
+ }
815
+ }
816
+ }
817
+
818
+ // special properties
819
+ if (this.m_props.id) {
820
+ this._setDomAttribute('id', this.m_props.id);
821
+ }
822
+
823
+ // events
824
+ let evt = this.m_iprops.dom_events;
825
+ if (evt) {
826
+ for (let e in evt) {
827
+ let handlers = evt[e];
828
+ for (let h of handlers) {
829
+ this.createEvent(e, h);
830
+ }
831
+ }
832
+ }
833
+
834
+ // create children
835
+ let content = props.content;
836
+ if (content) {
837
+
838
+ if (!isArray(content)) {
839
+ content = [content];
840
+ }
841
+
842
+ content.forEach((el) => {
843
+ if (!el) {
844
+ return;
845
+ }
846
+
847
+ if (isString(el)) {
848
+ this.m_dom.insertAdjacentText('beforeend', el);
849
+ }
850
+ else if (isHtmlString(el)) {
851
+ this.m_dom.insertAdjacentHTML('beforeend', el as string);
852
+ }
853
+ else if (el instanceof Component) {
854
+ this.m_dom.append(el._build());
855
+ }
856
+ else {
857
+ console.log( 'unknown element type: ', el );
858
+ }
859
+ });
860
+ }
861
+
862
+ // wait for dom insertion inside document.body
863
+ if (!Component.__createObserver) {
864
+ Component.__createObserver = new MutationObserver(Component._observeCreation);
865
+ Component.__createObserver.observe(x4document.body, { childList: true, subtree: true });
866
+ }
867
+
868
+ return this.m_dom;
869
+ }
870
+
871
+ protected _setTabIndex(tabIndex: number | boolean, defValue = 0) {
872
+
873
+ if (tabIndex === true) {
874
+ tabIndex = 0;
875
+ }
876
+ else if (tabIndex === undefined) {
877
+ tabIndex = defValue;
878
+ }
879
+
880
+ if (tabIndex !== false && tabIndex !== undefined) {
881
+ this.setAttribute('tabindex', tabIndex);
882
+ }
883
+
884
+ this.m_props.tabIndex = tabIndex;
885
+ }
886
+
887
+ private static _observeCreation(mutations: MutationRecord[]) {
888
+
889
+ // notify descendants that we have been created (dom exists)
890
+
891
+ for (let mutation of mutations) {
892
+
893
+ if (mutation.type == 'childList') {
894
+
895
+ for (let i = 0, n = mutation.addedNodes.length; i < n; i++) {
896
+
897
+ let add = mutation.addedNodes[i] as HTMLElement;
898
+ let el = add[_x4_el_sym] as Component;
899
+
900
+ if (el) {
901
+ el.enumChilds((c: Component) => {
902
+
903
+ if (c.dom && c.m_iprops.dom_events && c.m_iprops.dom_events.create) {
904
+ c.dom.dispatchEvent(new Event('create'));
905
+ }
906
+
907
+ c.componentCreated();
908
+
909
+ }, true);
910
+
911
+ if (el.m_iprops.dom_events && el.m_iprops.dom_events.create) {
912
+ el.dom.dispatchEvent(new Event('create'));
913
+ }
914
+
915
+ el.componentCreated();
916
+ }
917
+ }
918
+ }
919
+ }
920
+ }
921
+
922
+ public dispose() {
923
+ if (this.m_dom) {
924
+ this._dispose(true,true);
925
+ }
926
+ }
927
+
928
+ protected _dispose(with_dom: boolean, timers: boolean ) {
929
+
930
+ let _dom = this.m_dom;
931
+
932
+ // free attached resources
933
+ delete _dom[_x4_el_sym];
934
+ delete _dom[_x4_el_store];
935
+
936
+ //
937
+ if (with_dom) {
938
+ _dom.remove();
939
+ }
940
+
941
+ // notify every child that they will be removed
942
+ this.enumChilds((c: Component) => {
943
+ c._dispose(false,true);
944
+ });
945
+
946
+ this.m_dom = null;
947
+
948
+ if( timers ) {
949
+ this.disposeTimers();
950
+ }
951
+
952
+ this.componentDisposed();
953
+ // todo: pb on update this.removeAllListeners( null );
954
+ }
955
+
956
+ componentDisposed() {
957
+ }
958
+
959
+ componentCreated() {
960
+ }
961
+
962
+
963
+
964
+
965
+
966
+
967
+
968
+ /**
969
+ *
970
+ */
971
+
972
+ public update(delay = 0) {
973
+
974
+ if (this.m_dom) {
975
+
976
+ const _update = () => {
977
+ let oldDOM = this.m_dom;
978
+ this._dispose(false,false);
979
+
980
+ let newDOM = this._build();
981
+ console.assert( !!oldDOM.parentNode, 'update in componentCreated is not allowed, use updateContent' );
982
+
983
+ oldDOM.parentNode.replaceChild(newDOM, oldDOM);
984
+ }
985
+
986
+ if (delay) {
987
+ this.singleShot(_update, delay);
988
+ }
989
+ else {
990
+ _update();
991
+ }
992
+ }
993
+ }
994
+
995
+ /**
996
+ * empty the node
997
+ */
998
+ public _empty( ) {
999
+ //this.m_dom.innerHTML = '';
1000
+
1001
+ const el = this.m_dom;
1002
+ if( !el ) {
1003
+ return;
1004
+ }
1005
+
1006
+ while (el.firstChild) {
1007
+ el.removeChild(el.firstChild);
1008
+ }
1009
+ }
1010
+
1011
+ public _updateContent() {
1012
+
1013
+ if (!this.m_dom) {
1014
+ return;
1015
+ }
1016
+
1017
+ this._empty( );
1018
+
1019
+ let content = this.m_props.content;
1020
+
1021
+ // create children
1022
+ if (content) {
1023
+
1024
+ if (!isArray(content)) {
1025
+ content = [content];
1026
+ }
1027
+
1028
+ content.forEach((el) => {
1029
+ if (!el) {
1030
+ return;
1031
+ }
1032
+
1033
+ if (isHtmlString(el)) {
1034
+ this.m_dom.insertAdjacentHTML('beforeend', el as string);
1035
+ }
1036
+ else if (el instanceof Component) {
1037
+ this.m_dom.append(el._build());
1038
+ }
1039
+ else {
1040
+ this.m_dom.insertAdjacentText('beforeend', el + '');
1041
+ }
1042
+ });
1043
+ }
1044
+
1045
+ }
1046
+
1047
+ /**
1048
+ * @return the bounding rectangle
1049
+ * @example ```typescript
1050
+ * let rc = el.getBoundingRect( );
1051
+ * console.log( rc.left, rc.top, rc.right, rc.bottom );
1052
+ */
1053
+
1054
+ public getBoundingRect(withMargins = false): Rect {
1055
+ console.assert(this.dom != null, 'cannot get bounding rect of an non DOM element');
1056
+ let r = this.dom.getBoundingClientRect();
1057
+
1058
+ let rc = new Rect(r.left, r.top, r.width, r.height);
1059
+
1060
+ if (withMargins) {
1061
+
1062
+ let st = this.getComputedStyle();
1063
+
1064
+ let tm = st.parse('marginTop'),
1065
+ bm = st.parse('marginBottom'),
1066
+ lm = st.parse('marginLeft'),
1067
+ rm = st.parse('marginRight');
1068
+
1069
+ rc.left -= lm;
1070
+ rc.width += lm + rm;
1071
+
1072
+ rc.top -= tm;
1073
+ rc.height += tm + bm;
1074
+ }
1075
+
1076
+ return rc;
1077
+ }
1078
+
1079
+ /**
1080
+ * append a new dom event handler
1081
+ * @param name - you can specify multiple names separated by a space
1082
+ * @param handler
1083
+ * @example
1084
+ *
1085
+ * this.setDomEvent( 'drag drop', this._handleDrag, this );
1086
+ * this.setDomEvent( 'dblclick', this._handleDblClick, this );
1087
+ */
1088
+
1089
+ public setDomEvent<K extends keyof X4ElementEventMap>(type: K, listener: (this: HTMLDivElement, ev: X4ElementEventMap[K]) => void) {
1090
+ let _listener = listener as EventListener;
1091
+ this._setDomEvent(type as string, _listener);
1092
+ }
1093
+
1094
+ private _setDomEvent(type: string, listener: EventListener) {
1095
+
1096
+ // add event to the vdom
1097
+ if (!this.m_iprops.dom_events) {
1098
+ this.m_iprops.dom_events = {};
1099
+ }
1100
+
1101
+ let listeners = this.m_iprops.dom_events[type];
1102
+ if (!listeners) {
1103
+ listeners = this.m_iprops.dom_events[type] = [listener];
1104
+ }
1105
+ else {
1106
+ listeners.push(listener);
1107
+ }
1108
+
1109
+ if (this.m_dom) {
1110
+ //this.m_dom.addEventListener(type, listener);
1111
+ this.createEvent(type, listener);
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ *
1117
+ */
1118
+
1119
+ public clearDomEvent<K extends keyof X4ElementEventMap>(type: K) {
1120
+ if (!this.m_iprops.dom_events) {
1121
+ return;
1122
+ }
1123
+
1124
+ delete this.m_iprops.dom_events[type];
1125
+
1126
+ let _dom = this.m_dom;
1127
+ if (_dom) {
1128
+ let store = _dom[_x4_el_store];
1129
+ if (store) {
1130
+ delete store[type];
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ /**
1136
+ *
1137
+ * @param name
1138
+ * @param handler
1139
+ */
1140
+
1141
+ public createEvent(name: string, handler: Function) {
1142
+
1143
+ let _dom = this.m_dom;
1144
+ let store = _dom[_x4_el_store];
1145
+
1146
+ if (!store) {
1147
+ store = _dom[_x4_el_store] = {};
1148
+ }
1149
+
1150
+ if (!store[name]) {
1151
+ // no handler for this event...
1152
+ store[name] = [handler];
1153
+ }
1154
+ else {
1155
+ // append the handler
1156
+ store[name].push(handler);
1157
+ }
1158
+
1159
+ if (unbubbleEvents[name] === 1) {
1160
+ _dom['on' + name] = Component._dispatchUnbubbleEvent;
1161
+ }
1162
+ else if (!Component.__privateEvents[name]) {
1163
+ Component.__privateEvents[name] = true; // todo count it
1164
+
1165
+ if (passiveEvents[name]) {
1166
+ x4document.addEventListener(name as any, Component._dispatchEvent, { passive: false, capture: true });
1167
+ }
1168
+ else {
1169
+ x4document.addEventListener(name as any, Component._dispatchEvent, true);
1170
+ }
1171
+ }
1172
+
1173
+ if (name === 'sizechange') {
1174
+ if (!Component.__sizeObserver) {
1175
+ Component.__sizeObserver = new ResizeObserver(Component._observeSize);
1176
+ }
1177
+
1178
+ Component.__sizeObserver.observe(this.m_dom);
1179
+ }
1180
+ }
1181
+
1182
+ /**
1183
+ * dispatch a dom event to the appropriated component
1184
+ * called by the system
1185
+ */
1186
+
1187
+ private static _dispatchEvent(ev: any) {
1188
+
1189
+ let target = ev.target,
1190
+ noup = unbubbleEvents[ev.type] === 2;
1191
+
1192
+ while (target) {
1193
+ if (target[_x4_el_store]) {
1194
+ let store = target[_x4_el_store][ev.type];
1195
+ if (store) {
1196
+ let el = target[_x4_el_sym];
1197
+ let root = el?.root ?? null;
1198
+
1199
+ if (store instanceof Array) {
1200
+ store.some((fn) => {
1201
+ fn(ev, root);
1202
+ if (!el.dom) {
1203
+ return true;
1204
+ }
1205
+ });
1206
+ }
1207
+ else {
1208
+ store(ev, root);
1209
+ }
1210
+
1211
+ if (ev.cancelBubble || ev.defaultPrevented || noup) {
1212
+ break;
1213
+ }
1214
+ }
1215
+ }
1216
+
1217
+ target = target.parentNode;
1218
+
1219
+ // no need to go above
1220
+ if (target == document) {
1221
+ break;
1222
+ }
1223
+ }
1224
+ }
1225
+
1226
+ /**
1227
+ * dispatch a dom event to the appropriated component
1228
+ * called by the system
1229
+ */
1230
+
1231
+ private static _dispatchUnbubbleEvent(ev: any) {
1232
+
1233
+ let target = ev.currentTarget || ev.target,
1234
+ eventType = ev.type;
1235
+
1236
+ let eventStore = target[_x4_el_store],
1237
+ store = eventStore && eventStore[eventType];
1238
+
1239
+ if (store) {
1240
+
1241
+ let el = target[_x4_el_sym];
1242
+ let root = el?.root ?? null;
1243
+
1244
+ if (store instanceof Array) {
1245
+ store.forEach((fn) => {
1246
+ fn(ev, root);
1247
+ });
1248
+ }
1249
+ else {
1250
+ store(ev, root);
1251
+ }
1252
+ }
1253
+ }
1254
+
1255
+ /**
1256
+ * called when a size change on an observed component
1257
+ */
1258
+
1259
+ private static _observeSize(entries: ResizeObserverEntry[]) {
1260
+
1261
+ entries.forEach((entry) => {
1262
+ let dom = entry.target as HTMLElement;
1263
+ if (dom.offsetParent !== null) {
1264
+ dom.dispatchEvent(new Event('sizechange'));
1265
+ }
1266
+ });
1267
+ }
1268
+
1269
+ /**
1270
+ * enum all children recursively
1271
+ * @param recursive - if true do a full sub-child search
1272
+ * @param cb - callback
1273
+ * return true to stop enumeration
1274
+ */
1275
+
1276
+ enumChilds(cb: (child: Component) => boolean | void, recursive = false): boolean {
1277
+
1278
+ // use dom if available
1279
+ if (this.m_dom) {
1280
+
1281
+ let el = this.m_dom.firstChild;
1282
+
1283
+ while (el) {
1284
+ // get component (if any)
1285
+ let cel = el[_x4_el_sym];
1286
+ if (cel) {
1287
+ cb(cel);
1288
+
1289
+ if (recursive && cel.enumChilds(cb, true) === true) {
1290
+ return true;
1291
+ }
1292
+ }
1293
+
1294
+ el = el.nextSibling;
1295
+ }
1296
+ }
1297
+ else {
1298
+ let content = this.m_props.content;
1299
+ if (!content) {
1300
+ return;
1301
+ }
1302
+
1303
+ if (!isArray(content)) {
1304
+ content = [content];
1305
+ }
1306
+
1307
+ content.some((el) => {
1308
+ if (!el || isString(el) || isHtmlString(el)) {
1309
+ return;
1310
+ }
1311
+
1312
+ if (cb(el)) {
1313
+ return true;
1314
+ }
1315
+
1316
+ if (recursive && el.enumChilds(cb, true) === true) {
1317
+ return true;
1318
+ }
1319
+ });
1320
+ }
1321
+
1322
+ return false;
1323
+ }
1324
+
1325
+ /**
1326
+ * apprend a child to the DOM
1327
+ * @param props child to append (or string)
1328
+ */
1329
+
1330
+ private _appendChild(el: ComponentOrString) {
1331
+
1332
+ if (isString(el)) {
1333
+ this.m_dom.insertAdjacentText('beforeend', el);
1334
+ }
1335
+ else if (isHtmlString(el)) {
1336
+ this.m_dom.insertAdjacentHTML('beforeend', el as string);
1337
+ }
1338
+ else {
1339
+ let component: Component = el;
1340
+
1341
+ try {
1342
+ component._build();
1343
+ this.m_dom.appendChild(component.m_dom);
1344
+ }
1345
+ catch (e) {
1346
+ console.error(e);
1347
+ }
1348
+ }
1349
+ }
1350
+
1351
+ /**
1352
+ * generate classes from the component inheritance
1353
+ * @example
1354
+ * Button extends Component will give
1355
+ * x-comp x-button
1356
+ */
1357
+
1358
+ private _genClassName() {
1359
+
1360
+ this.addClass('@comp');
1361
+
1362
+ let me = Object.getPrototypeOf(this);
1363
+ while (me && me.constructor !== Component) {
1364
+ let clsname = me.constructor.name;
1365
+ this.addClass('@' + pascalCase(clsname));
1366
+
1367
+ me = Object.getPrototypeOf(me);
1368
+ }
1369
+
1370
+ //done in ctor now
1371
+ //this.addClass(this.m_props.cls);
1372
+ }
1373
+
1374
+ /**
1375
+ * prepend the system class name prefix on a name if needed (if class starts with @)
1376
+ */
1377
+
1378
+ private _makeCls(cls: string): string {
1379
+ if (cls[0] == '@') {
1380
+ return cls = _x4_ns_prefix + cls.substring(1);
1381
+ }
1382
+ else {
1383
+ return cls;
1384
+ }
1385
+ }
1386
+
1387
+ /**
1388
+ *
1389
+ */
1390
+
1391
+ private static dispatchCaptures(event: Event) {
1392
+ Component.__capture.handler(event as UIEvent);
1393
+ }
1394
+
1395
+ /**
1396
+ * capture mouse events
1397
+ * @param capture name of the current capture
1398
+ * @param callback funciton to call on captured mouse events
1399
+ *
1400
+ * @example
1401
+ * Component.setCapture( this, ( ev: MouseEvent, initiator: Component ) => {
1402
+ * if( ev.type=='mousemove' ) {
1403
+ * this.setStyle( {
1404
+ * left: ev.clientX,
1405
+ * top: ev.clientY
1406
+ * } );
1407
+ * }
1408
+ * else if( ev.type=='mouseup' ) {
1409
+ * Component.releaseCapture( );
1410
+ * }
1411
+ * } );
1412
+ */
1413
+
1414
+ protected static setCapture(initiator: Component, listener: EventHandler<UIEvent>) {
1415
+
1416
+ console.assert(!Component.__capture);
1417
+ if (Component.__capture) {
1418
+ debugger;
1419
+ }
1420
+
1421
+ // todo: review that
1422
+
1423
+ let iframes = x4document.querySelectorAll<HTMLIFrameElement>("iframe");
1424
+ iframes.forEach( f => {
1425
+ flyWrap(f).setStyleValue( 'pointer-events', 'none' );
1426
+ });
1427
+
1428
+ let overs = x4document.querySelectorAll(":hover");
1429
+
1430
+ let cursor = null;
1431
+ if (overs.length) {
1432
+ let elementOver = <HTMLElement>overs[overs.length - 1];
1433
+ let style = window.getComputedStyle(elementOver);
1434
+ cursor = style.cursor;
1435
+ }
1436
+
1437
+ Component.__capture_mask = x4document.createElement('div');
1438
+ let mask = flyWrap(Component.__capture_mask);
1439
+ mask.addClass('@capture-mask');
1440
+
1441
+ if (cursor) {
1442
+ mask.setStyleValue('cursor', cursor);
1443
+ }
1444
+
1445
+ x4document.body.appendChild(mask.dom);
1446
+
1447
+ x4document.addEventListener('mousedown', Component.dispatchCaptures);
1448
+ x4document.addEventListener('mousemove', Component.dispatchCaptures);
1449
+ x4document.addEventListener('mouseup', Component.dispatchCaptures);
1450
+
1451
+ x4document.addEventListener('touchstart', Component.dispatchCaptures);
1452
+ x4document.addEventListener('touchmove', Component.dispatchCaptures);
1453
+ x4document.addEventListener('touchend', Component.dispatchCaptures);
1454
+
1455
+ Component.__capture = {
1456
+ initiator,
1457
+ handler: listener,
1458
+ iframes
1459
+ };
1460
+ }
1461
+
1462
+ protected static releaseCapture() {
1463
+
1464
+ console.assert(!!Component.__capture);
1465
+
1466
+ x4document.removeEventListener('touchstart', Component.dispatchCaptures);
1467
+ x4document.removeEventListener('touchmove', Component.dispatchCaptures);
1468
+ x4document.removeEventListener('touchend', Component.dispatchCaptures);
1469
+
1470
+ x4document.removeEventListener('mousedown', Component.dispatchCaptures);
1471
+ x4document.removeEventListener('mousemove', Component.dispatchCaptures);
1472
+ x4document.removeEventListener('mouseup', Component.dispatchCaptures);
1473
+
1474
+ Component.__capture.iframes.forEach( f => {
1475
+ flyWrap(f).setStyleValue( 'pointer-events', null );
1476
+ })
1477
+
1478
+ Component.__capture = null;
1479
+ if (Component.__capture_mask) {
1480
+ x4document.body.removeChild(Component.__capture_mask);
1481
+ Component.__capture_mask = null;
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * ensure the component is visible
1487
+ * @param: alignToTop
1488
+ */
1489
+
1490
+ public scrollIntoView(arg?: boolean | ScrollIntoViewOptions) {
1491
+ if (this.m_dom) {
1492
+
1493
+ const rel = new Rect( this.dom.getBoundingClientRect( ) );
1494
+
1495
+ let top = undefined;
1496
+ let bot = undefined;
1497
+ let left = undefined;
1498
+ let right = undefined;
1499
+
1500
+ let pn = this.dom.parentElement;
1501
+ const bdy = x4document.body;
1502
+
1503
+ while( pn && pn!=bdy ) {
1504
+
1505
+ const pr = pn.getBoundingClientRect( );
1506
+
1507
+ if( top===undefined || top<pr.top ) {
1508
+ top = pr.top;
1509
+ }
1510
+
1511
+ if( bot===undefined || bot>pr.bottom ) {
1512
+ bot = pr.bottom;
1513
+ }
1514
+
1515
+ if( left===undefined || left<pr.left ) {
1516
+ left = pr.left;
1517
+ }
1518
+
1519
+ if( right===undefined || right>pr.right ) {
1520
+ right = pr.right;
1521
+ }
1522
+
1523
+ pn = pn.parentElement;
1524
+ }
1525
+
1526
+ if( top===undefined || rel.top<top || rel.bottom>bot || rel.left<left || rel.right>right ) {
1527
+ //this.m_dom.scrollIntoView( true );
1528
+ this.m_dom.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'start' });
1529
+ }
1530
+
1531
+ //this.m_dom.scrollIntoView(arg);
1532
+ }
1533
+ }
1534
+
1535
+ /**
1536
+ * search for a given css selector
1537
+ * @param selector
1538
+ * @returns child or null
1539
+ */
1540
+
1541
+ public queryItem<T extends Component>(selector: string): T {
1542
+ let result = <HTMLElement>this.dom.querySelector(selector);
1543
+ return result ? Component.getElement<T>(result) : null;
1544
+ }
1545
+
1546
+ public queryAll(selector: string, cb?: (el: Component) => void): HTMLElement[] {
1547
+ let elements:HTMLElement[] = Array.from( this.m_dom.querySelectorAll<HTMLElement>(selector) );
1548
+
1549
+ if( cb ) {
1550
+ elements.forEach((el) => {
1551
+ cb(flyWrap(el as HTMLElement));
1552
+ });
1553
+ }
1554
+
1555
+ return elements;
1556
+ }
1557
+
1558
+ /**
1559
+ * find a child with the given ID
1560
+ * @param id id (without '#')
1561
+ * @returns child or null
1562
+ *
1563
+ * @example
1564
+ * let btn = this.childWithId<Button>( 'myButtonId' );
1565
+ */
1566
+ public itemWithId<T extends Component>(id: string): T {
1567
+ let result = <HTMLElement>this.dom.querySelector('#' + id);
1568
+ return result ? Component.getElement<T>(result) : null;
1569
+ }
1570
+
1571
+ /**
1572
+ * find a child with given ref
1573
+ * @param ref
1574
+ * @return found child or null
1575
+ */
1576
+
1577
+ public itemWithRef<T = Component>(ref: string): T {
1578
+
1579
+ let result = null;
1580
+ this.enumChilds((c: Component) => {
1581
+ if (c.m_props.ref === ref) {
1582
+ result = c;
1583
+ return true;
1584
+ }
1585
+ }, true);
1586
+
1587
+ return result as T;
1588
+ }
1589
+
1590
+ /**
1591
+ *
1592
+ */
1593
+
1594
+ get ref() {
1595
+ return this.m_props.ref;
1596
+ }
1597
+
1598
+ /**
1599
+ *
1600
+ */
1601
+
1602
+ static getCss(): Stylesheet {
1603
+ if (!Component.__css) {
1604
+ Component.__css = new Stylesheet();
1605
+ }
1606
+
1607
+ return Component.__css;
1608
+ }
1609
+
1610
+ /**
1611
+ * return the parent element
1612
+ * care, object must have been created (dom!=null)
1613
+ */
1614
+
1615
+ public getParent(): Component {
1616
+ console.assert(!!this.m_dom);
1617
+
1618
+ let elParent = this.dom.parentNode;
1619
+ return Component.getElement(<HTMLElement>elParent);
1620
+ }
1621
+
1622
+ /**
1623
+ * get a component from a DOM element
1624
+ * move up to the hierarchy to find the request class type.
1625
+ * @param dom
1626
+ * @param classname
1627
+ * @returns
1628
+ *
1629
+ * @example
1630
+ *
1631
+ * with a DOM like that:
1632
+ * Button
1633
+ * Label
1634
+ * Icon <- the DOM you have (dom-icon)
1635
+ *
1636
+ * let btn = Component.getElement( dom-icon, Button );
1637
+ */
1638
+
1639
+ static getElement<T extends Component>(dom: HTMLElement | Element, classname?: Constructor<T> | string ): T {
1640
+
1641
+ if (classname) {
1642
+
1643
+ const srhCls = isString(classname);
1644
+
1645
+ while (dom) {
1646
+ let el: Component = dom[_x4_el_sym];
1647
+
1648
+ if( srhCls ) {
1649
+ if( el && el.hasClass(classname) ) {
1650
+ return el as T;
1651
+ }
1652
+ }
1653
+ else if (el instanceof classname) {
1654
+ return el;
1655
+ }
1656
+
1657
+ dom = dom.parentElement;
1658
+ }
1659
+
1660
+ return null;
1661
+ }
1662
+ else {
1663
+ return dom ? dom[_x4_el_sym] : null;
1664
+ }
1665
+ }
1666
+
1667
+ /**
1668
+ * compute the scrollbar size ( width = height)
1669
+ */
1670
+
1671
+ static getScrollbarSize() {
1672
+
1673
+ if (Component.__sb_width === undefined) {
1674
+ let outerDiv = x4document.createElement('div');
1675
+ outerDiv.style.cssText = 'overflow:auto;position:absolute;top:0;width:100px;height:100px';
1676
+
1677
+ let innerDiv = x4document.createElement('div');
1678
+ innerDiv.style.width = '200px';
1679
+ innerDiv.style.height = '200px';
1680
+
1681
+ outerDiv.appendChild(innerDiv);
1682
+ x4document.body.appendChild(outerDiv);
1683
+
1684
+ Component.__sb_width = outerDiv.offsetWidth - outerDiv.clientWidth;
1685
+ x4document.body.removeChild(outerDiv);
1686
+ }
1687
+
1688
+ return Component.__sb_width;
1689
+ }
1690
+
1691
+ /**
1692
+ * check if the Component is visible to the user
1693
+ */
1694
+
1695
+ isUserVisible(): boolean {
1696
+ if (!this.m_dom) {
1697
+ return false;
1698
+ }
1699
+
1700
+ return (this.m_dom.offsetParent !== null);
1701
+ }
1702
+ }
1703
+
1704
+ /** @ignore */
1705
+ let fly_element: Component = null;
1706
+
1707
+ /**
1708
+ * warp <b>temporarily</b> a DOM element to be able to acces to exact API
1709
+ * @param dom dom element to wrap
1710
+ * @review qui libere le fly_element ? -> timeout
1711
+ */
1712
+
1713
+ export function flyWrap<T extends Component>(dom: HTMLElement | EventTarget): T {
1714
+
1715
+ if (dom[_x4_el_sym]) {
1716
+ return dom[_x4_el_sym];
1717
+ }
1718
+
1719
+ let f = fly_element;
1720
+ if (!f) { f = fly_element = new Component({}); }
1721
+ (<any>f).m_dom = dom;
1722
+
1723
+ return f as T;
1724
+ }
1725
+
1726
+
1727
+
1728
+
1729
+
1730
+
1731
+
1732
+
1733
+ /**
1734
+ * simple flex spacer
1735
+ */
1736
+
1737
+ export class Flex extends Component {
1738
+
1739
+ constructor(props: CProps = {}) {
1740
+ if (!props.flex) {
1741
+ props.flex = 1;
1742
+ }
1743
+
1744
+ super(props);
1745
+ }
1746
+ }
1747
+
1748
+ /**
1749
+ * simple space between 2 elements
1750
+ */
1751
+
1752
+ export class Space extends Component {
1753
+
1754
+ m_size: number | string;
1755
+
1756
+ constructor(size: number | string) {
1757
+ super({});
1758
+
1759
+ this.m_size = size;
1760
+ }
1761
+
1762
+ componentCreated() {
1763
+
1764
+ // try to find if we are in a hz / vt / abs container
1765
+ let dom = this.dom;
1766
+ let style = null;
1767
+
1768
+ while (dom) {
1769
+ let el: Component = dom[_x4_el_sym];
1770
+ if (el.hasClass('@hlayout')) {
1771
+ style = { width: this.m_size };
1772
+ break;
1773
+ }
1774
+ else if (el.hasClass('@vlayout')) {
1775
+ style = { height: this.m_size };
1776
+ break;
1777
+ }
1778
+
1779
+ dom = dom.parentElement;
1780
+ }
1781
+
1782
+ if (!style) {
1783
+ style = { width: this.m_size, height: this.m_size };
1784
+ }
1785
+
1786
+ this.setStyle(style);
1787
+ }
1788
+ }
1789
+
1790
+ /**
1791
+ * sizable separator
1792
+ */
1793
+
1794
+ type SizeMode = null | 'minimize' | 'maximize' | 'restore';
1795
+
1796
+ export interface EvSize extends BasicEvent {
1797
+ readonly size: Size;
1798
+ readonly mode: SizeMode;
1799
+ }
1800
+
1801
+ export function EvSize(size: Size, mode: SizeMode = null, context = null ): EvSize {
1802
+ return BasicEvent<EvSize>({ size, mode, context });
1803
+ }
1804
+
1805
+ interface SeparatorEventMap extends CEventMap {
1806
+ resize?: EvSize;
1807
+ }
1808
+
1809
+ interface SeparatorProps extends CProps<SeparatorEventMap> {
1810
+ readonly orientation: 'vertical' | 'horizontal'; // vertical means vertical sizer so it resize horizontally
1811
+ readonly sizing: 'before' | 'after';
1812
+ readonly collapsible?: boolean;
1813
+ }
1814
+
1815
+ export class Separator extends Component<SeparatorProps, SeparatorEventMap> {
1816
+
1817
+ m_irect: Rect;
1818
+ m_delta: number;
1819
+ m_target: Component;
1820
+
1821
+ constructor(props: SeparatorProps) {
1822
+ super(props);
1823
+
1824
+ this.setDomEvent('mousedown', (e) => this._mousedown(e));
1825
+ this.setDomEvent('touchstart', (e) => this._mousedown(e));
1826
+ this.setDomEvent('dblclick', (e) => this._collapse(e) );
1827
+ }
1828
+
1829
+ render() {
1830
+ this.addClass(this.m_props.orientation);
1831
+ }
1832
+
1833
+ private _collapse( ev: UIEvent ) {
1834
+ if( this.m_props.collapsible ) {
1835
+ this._findTarget();
1836
+ if( this.m_target ) {
1837
+ this.m_target.toggleClass( '@collapsed' );
1838
+ }
1839
+ }
1840
+ }
1841
+
1842
+ private _mousedown(ev: UIEvent) {
1843
+
1844
+ if (ev.type == 'touchstart') {
1845
+ let te = ev as TouchEvent;
1846
+ if (te.touches.length == 1) {
1847
+ this._startMoving(te.touches[0].pageX, te.touches[0].pageY, ev);
1848
+ }
1849
+ }
1850
+ else {
1851
+ let me = ev as MouseEvent;
1852
+ this._startMoving(me.pageX, me.pageY, ev);
1853
+ }
1854
+ }
1855
+
1856
+ _startMoving(x: number, y: number, ev: UIEvent) {
1857
+ //if( this.m_props.callback ) {
1858
+ // this.m_props.callback( ev, this );
1859
+ //}
1860
+ //else
1861
+ {
1862
+ this._findTarget();
1863
+
1864
+ if (this.m_target) {
1865
+
1866
+ if (this.m_props.orientation == 'horizontal') {
1867
+ if (this.m_props.sizing == 'before') {
1868
+ this.m_delta = x - this.m_irect.right;
1869
+ }
1870
+ else {
1871
+ this.m_delta = x - this.m_irect.left;
1872
+ }
1873
+ }
1874
+ else {
1875
+ if (this.m_props.sizing == 'before') {
1876
+ this.m_delta = y - this.m_irect.bottom;
1877
+ }
1878
+ else {
1879
+ this.m_delta = y - this.m_irect.top;
1880
+ }
1881
+ }
1882
+
1883
+ ev.preventDefault();
1884
+ ev.stopPropagation();
1885
+
1886
+ this.m_target.addClass('sizing');
1887
+
1888
+ Component.setCapture(this, (e) => this._pointerMoved(e));
1889
+ }
1890
+ }
1891
+ }
1892
+
1893
+ private _pointerMoved(ev: UIEvent) {
1894
+
1895
+ let __move = (ex, ey) => {
1896
+
1897
+ if (this.m_props.orientation == 'horizontal') {
1898
+
1899
+ let width;
1900
+ if (this.m_props.sizing == 'after') {
1901
+ width = this.m_irect.right - (ex - this.m_delta);
1902
+ }
1903
+ else {
1904
+ width = (ex - this.m_delta) - this.m_irect.left
1905
+ }
1906
+
1907
+ if (width > 0) {
1908
+ let size = new Size(width, 0);
1909
+ this.emit('resize', EvSize(size));
1910
+
1911
+ this.m_target.setStyleValue('width', size.width);
1912
+ this.m_target.setStyleValue('flex', null); // for flex>1
1913
+ this.m_target.removeClass('@flex');
1914
+ }
1915
+ }
1916
+ else {
1917
+
1918
+ let height;
1919
+ if (this.m_props.sizing == 'after') {
1920
+ height = this.m_irect.bottom - (ey - this.m_delta);
1921
+ }
1922
+ else {
1923
+ height = (ey - this.m_delta) - this.m_irect.top;
1924
+ }
1925
+
1926
+ if (height > 0) {
1927
+ let size = new Size(0, height);
1928
+ this.emit('resize', EvSize(size));
1929
+
1930
+ this.m_target.setStyleValue('height', size.height);
1931
+ this.m_target.setStyleValue('flex', null); // for flex>1
1932
+ this.m_target.removeClass('@flex');
1933
+ }
1934
+ }
1935
+ }
1936
+
1937
+ if (ev.type == 'mousemove') {
1938
+
1939
+ let mev = ev as MouseEvent;
1940
+ __move(mev.pageX, mev.pageY);
1941
+
1942
+ ev.preventDefault();
1943
+ ev.stopPropagation();
1944
+ }
1945
+ else if (ev.type == 'touchmove') {
1946
+
1947
+ let tev = ev as TouchEvent;
1948
+ __move(tev.touches[0].pageX, tev.touches[0].pageY);
1949
+
1950
+ ev.preventDefault();
1951
+ ev.stopPropagation();
1952
+ }
1953
+ else if (ev.type == 'mouseup' || ev.type == 'touchend') {
1954
+ this.m_target.removeClass('sizing');
1955
+
1956
+ Component.releaseCapture();
1957
+ ev.preventDefault();
1958
+ ev.stopPropagation();
1959
+ }
1960
+ }
1961
+
1962
+ private _findTarget() {
1963
+
1964
+ if (!this.m_target) {
1965
+
1966
+ if (this.m_props.sizing == 'before') {
1967
+ let prevDom = this.dom.previousElementSibling;
1968
+ let prevEl = prevDom ? Component.getElement(prevDom as HTMLElement) : null;
1969
+ this.m_target = prevEl;
1970
+ }
1971
+ else {
1972
+ let nextDom = this.dom.nextElementSibling;
1973
+ let nextEl = nextDom ? Component.getElement(nextDom as HTMLElement) : null;
1974
+ this.m_target = nextEl;
1975
+ }
1976
+ }
1977
+
1978
+ if (this.m_target) {
1979
+ this.m_irect = this.m_target.getBoundingRect();
1980
+ }
1981
+ else {
1982
+ this.m_irect = null;
1983
+ }
1984
+ }
1985
+ }
1986
+
1987
+
1988
+
1989
+
1990
+ // :: SIZERBAR ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
1991
+
1992
+ /**
1993
+ * properties
1994
+ */
1995
+
1996
+ type SizerOverlaySens = 'left' | 'top' | 'right' | 'bottom' | 'topleft' | 'topright' | 'bottomleft' | 'bottomright';
1997
+
1998
+ export interface EvOverlayResize extends BasicEvent {
1999
+ ui_event: UIEvent;
2000
+ sens: SizerOverlaySens;
2001
+ }
2002
+
2003
+ export function EvOverlayResize(ui_event: UIEvent, sens: SizerOverlaySens, context: any = null) {
2004
+ return BasicEvent<EvOverlayResize>({ ui_event, sens, context });
2005
+ }
2006
+
2007
+ interface SizerOverlayEventMap extends CEventMap {
2008
+ resize: EvSize;
2009
+ rawresize: EvOverlayResize;
2010
+ }
2011
+
2012
+
2013
+ export interface SizerOverlayProps extends CProps<SizerOverlayEventMap> {
2014
+ sens: SizerOverlaySens;
2015
+ target: Component;
2016
+
2017
+ resize?: EventCallback<EvSize>; // shortcut to events: { size: ... }
2018
+ }
2019
+
2020
+ export class SizerOverlay extends Component<SizerOverlayProps, SizerOverlayEventMap> {
2021
+
2022
+ private m_delta: number;
2023
+ private m_irect: Rect;
2024
+
2025
+ constructor(props: SizerOverlayProps) {
2026
+ super(props);
2027
+
2028
+ this.addClass(props.sens);
2029
+ this.setDomEvent('mousedown', (e) => this._mousedown(e));
2030
+ this.setDomEvent('touchstart', (e) => this._mousedown(e));
2031
+ this.setDomEvent('dblclick', (e) => this.resetflex(e)); // todo: add option for that
2032
+
2033
+ props.target.appendChild(this);
2034
+
2035
+ if( props.resize ) {
2036
+ this.on( 'resize', this.m_props.resize );
2037
+ }
2038
+ }
2039
+
2040
+ resetflex(event: UIEvent) {
2041
+ this.m_props.target.addClass('@flex');
2042
+ this.emit('resize', EvSize( { width: -1, height: 0})); // todo: see that
2043
+ event.preventDefault();
2044
+ event.stopPropagation();
2045
+ }
2046
+
2047
+ // @review move that in component
2048
+
2049
+ _mousedown(ev: UIEvent) {
2050
+
2051
+ ev.preventDefault();
2052
+ ev.stopPropagation();
2053
+
2054
+ let eev = EvOverlayResize(ev, this.m_props.sens);
2055
+ this.emit('rawresize', eev);
2056
+ if (eev.defaultPrevented) {
2057
+ return;
2058
+ }
2059
+
2060
+ let pos = getMousePos(ev, true);
2061
+ this.m_irect = this.m_props.target.getBoundingRect();
2062
+
2063
+ if (this.m_props.sens == 'right') {
2064
+ this.m_delta = pos.x - this.m_irect.right;
2065
+ }
2066
+ else if (this.m_props.sens == 'left') {
2067
+ this.m_delta = pos.x - this.m_irect.left;
2068
+ }
2069
+ else if (this.m_props.sens == 'bottom') {
2070
+ this.m_delta = pos.y - this.m_irect.bottom;
2071
+ }
2072
+ else if (this.m_props.sens == 'top') {
2073
+ this.m_delta = pos.y - this.m_irect.top;
2074
+ }
2075
+
2076
+ this.m_props.target.addClass('sizing');
2077
+ Component.setCapture(this, (e) => this._handle_mouse(e));
2078
+ }
2079
+
2080
+ private _is_horz() {
2081
+ return this.m_props.sens == 'left' || this.m_props.sens == 'right';
2082
+ }
2083
+
2084
+ public get sens() {
2085
+ return this.m_props.sens;
2086
+ }
2087
+
2088
+ private _handle_mouse(ev: UIEvent) {
2089
+ let __move = (ex, ey) => {
2090
+ if (this._is_horz()) {
2091
+
2092
+ let width;
2093
+ if (this.m_props.sens == 'left') {
2094
+ width = this.m_irect.right - (ex - this.m_delta);
2095
+ }
2096
+ else {
2097
+ width = (ex - this.m_delta) - this.m_irect.left
2098
+ }
2099
+
2100
+ if (width > 0) {
2101
+ let size = {
2102
+ width,
2103
+ height: undefined
2104
+ };
2105
+
2106
+ this.emit('resize', EvSize(size));
2107
+
2108
+ this.m_props.target.setStyleValue('width', size.width);
2109
+ this.m_props.target.setStyleValue('flex', null); // for flex>1
2110
+ this.m_props.target.removeClass('@flex');
2111
+ }
2112
+ }
2113
+ else {
2114
+
2115
+ let height;
2116
+ if (this.m_props.sens == 'top') {
2117
+ height = this.m_irect.bottom - (ey - this.m_delta);
2118
+ }
2119
+ else {
2120
+ height = (ey - this.m_delta) - this.m_irect.top;
2121
+ }
2122
+
2123
+ if (height > 0) {
2124
+ let size = new Size(0, height);
2125
+ this.emit('resize', EvSize(size));
2126
+
2127
+ this.m_props.target.setStyleValue('height', size.height);
2128
+ this.m_props.target.setStyleValue('flex', null); // for flex>1
2129
+ this.m_props.target.removeClass('@flex');
2130
+ }
2131
+ }
2132
+ }
2133
+
2134
+ if (ev.type == 'mousemove') {
2135
+
2136
+ let mev = ev as MouseEvent;
2137
+ __move(mev.pageX, mev.pageY);
2138
+
2139
+ ev.preventDefault();
2140
+ ev.stopPropagation();
2141
+ }
2142
+ else if (ev.type == 'touchmove') {
2143
+
2144
+ let tev = ev as TouchEvent;
2145
+ __move(tev.touches[0].pageX, tev.touches[0].pageY);
2146
+
2147
+ ev.preventDefault();
2148
+ ev.stopPropagation();
2149
+ }
2150
+ else if (ev.type == 'mouseup' || ev.type == 'touchend') {
2151
+ this.m_props.target.removeClass('sizing');
2152
+
2153
+ Component.releaseCapture();
2154
+ ev.preventDefault();
2155
+ ev.stopPropagation();
2156
+ }
2157
+ }
2158
+ }
2159
+
2160
+ /**
2161
+ * sequence: Shift+Ctrl+Alt+A
2162
+ */
2163
+
2164
+ export interface Shortcut {
2165
+ sequence: string;
2166
+ name: string;
2167
+ immediate: boolean;
2168
+ callback?: (domTarget) => void;
2169
+ }
2170
+
2171
+ interface EvShortcut extends BasicEvent {
2172
+ name: string;
2173
+ }
2174
+
2175
+ function EvShortcut(name: string) {
2176
+ return BasicEvent<EvShortcut>({ name });
2177
+ }
2178
+
2179
+ export interface ContainerEventMap extends CEventMap {
2180
+ shortcut: EvShortcut;
2181
+ }
2182
+
2183
+ export interface ContainerProps<E extends ContainerEventMap = ContainerEventMap> extends CProps<E> {
2184
+ }
2185
+
2186
+ /**
2187
+ * you can construct a Container as usual with it's properties but also directly with it's children array
2188
+ *
2189
+ * @example
2190
+ * new Container( [
2191
+ * child1,
2192
+ * child2
2193
+ * ])
2194
+ */
2195
+
2196
+ export class Container<P extends ContainerProps = ContainerProps, E extends ContainerEventMap = ContainerEventMap> extends Component<P, E> {
2197
+
2198
+ private m_shortcuts: Shortcut[];
2199
+
2200
+ constructor( props: P | ComponentOrString[] ) {
2201
+ if( isArray(props) ) {
2202
+ super( {content: props} as P );
2203
+ }
2204
+ else {
2205
+ super( props );
2206
+ }
2207
+ }
2208
+
2209
+ /**
2210
+ * add an application shortcut
2211
+ * @param sequence key sequence Shift+Ctrl+Alt+K
2212
+ * @param callback callback to call
2213
+ */
2214
+
2215
+ public addShortcut(sequence: string | string[], name: string, callback: EventHandler<KeyboardEvent> = null, immediate = false) {
2216
+
2217
+ // first time
2218
+ if (!this.m_shortcuts) {
2219
+ this.m_shortcuts = [];
2220
+ this.setDomEvent('keydown', (e) => this._handleKeydown(e));
2221
+ }
2222
+
2223
+ if (!isArray(sequence)) {
2224
+ sequence = [sequence];
2225
+ }
2226
+
2227
+ sequence.forEach((seq: string) => {
2228
+ let reseq = '';
2229
+
2230
+ let shift = seq.match(/SHIFT/i);
2231
+ if (shift) {
2232
+ seq = seq.replace(/SHIFT/i, '');
2233
+ reseq += 'shift+';
2234
+ }
2235
+
2236
+ let ctrl = seq.match(/CTRL/i);
2237
+ if (ctrl) {
2238
+ seq = seq.replace(/CTRL/i, '');
2239
+ reseq += 'ctrl+';
2240
+ }
2241
+
2242
+ let cmd = seq.match(/CMD/i);
2243
+ if (cmd) {
2244
+ seq = seq.replace(/CMD/i, '');
2245
+ reseq += 'cmd+';
2246
+ }
2247
+
2248
+ let alt = seq.match(/ALT/i);
2249
+ if (alt) {
2250
+ seq = seq.replace(/ALT/i, '');
2251
+ reseq += 'alt+';
2252
+ }
2253
+
2254
+ reseq += seq.replace('+', '').toLowerCase();
2255
+
2256
+ this.m_shortcuts.push({
2257
+ sequence: reseq,
2258
+ name,
2259
+ immediate,
2260
+ callback
2261
+ });
2262
+ });
2263
+ }
2264
+
2265
+ /**
2266
+ * remove all shortcuts for a target
2267
+ */
2268
+
2269
+ removeShortcuts() {
2270
+ if (this.m_shortcuts) {
2271
+ this.m_shortcuts = [];
2272
+ }
2273
+ }
2274
+
2275
+ /** @ignore this function is binded */
2276
+ private _handleKeydown(e: KeyboardEvent) {
2277
+
2278
+ if (!this.m_shortcuts) {
2279
+ return;
2280
+ }
2281
+
2282
+ let seq = '';
2283
+
2284
+ if (e.shiftKey) {
2285
+ seq += 'shift+';
2286
+ }
2287
+
2288
+ if (e.ctrlKey) {
2289
+ seq += 'ctrl+';
2290
+ }
2291
+
2292
+ if (e.metaKey) {
2293
+ seq += 'cmd+';
2294
+ }
2295
+
2296
+ if (e.altKey) {
2297
+ seq += 'alt+';
2298
+ }
2299
+
2300
+ seq += e.key.toLowerCase();
2301
+ //console.log( seq );
2302
+
2303
+ this.m_shortcuts.some((sk) => {
2304
+ if (sk.sequence == seq) {
2305
+
2306
+ if (sk.callback) {
2307
+ if (sk.immediate) {
2308
+ sk.callback(e);
2309
+ }
2310
+ else {
2311
+ asap(() => { sk.callback(e); });
2312
+ }
2313
+ }
2314
+ else {
2315
+ this.emit('shortcut', EvShortcut(sk.name));
2316
+ }
2317
+
2318
+ e.preventDefault();
2319
+ e.stopPropagation();
2320
+ return true;
2321
+ }
2322
+ });
2323
+ }
2324
+ }
2325
+
2326
+ export type ComponentConstructor<T> = new (props: CProps) => T;
2327
+
2328
+ /**
2329
+ *
2330
+ */
2331
+
2332
+ export class TSXComponent<P extends CProps<CEventMap> = CProps<CEventMap>, E extends CEventMap = CEventMap> extends Component<P,E> {
2333
+ public render(props: P) {
2334
+ const tsx = this.renderTSX( props );
2335
+ if( tsx ) {
2336
+ this.setContent( tsx );
2337
+ }
2338
+ }
2339
+
2340
+ public renderTSX( props: P ): Component | Component[] {
2341
+ return undefined;
2342
+ }
2343
+ }
2344
+