x4js 1.4.49 → 1.4.52

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