-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathct-dialog.ts
More file actions
executable file
·616 lines (569 loc) · 16.8 KB
/
Copy pathct-dialog.ts
File metadata and controls
executable file
·616 lines (569 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/**
@license
Copyright (c) 2020 Herberth Obregón. All rights reserved.
This code may only be used under the BSD style license found at
https://open.grupoconectate.com/LICENSE.txt The complete set of authors may be found at
https://open.grupoconectate.com/AUTHORS.txt The complete set of contributors may be
found at https://open.grupoconectate.com/CONTRIBUTORS.txt Code distributed by Herberth Obregón as
part of the Conectate Open Source Project is also subject to an additional IP rights grant
found at https://open.grupoconectate.com/PATENTS.txt
*/
import { getClient, sleep } from "./ct-helpers.js";
import { CtLit, css, customElement, html, property, state } from "./ct-lit.js";
type Modal = { destroy: () => void; close: (e?: Event | null, type?: "click" | "keyup" | "popstate") => Promise<Event> };
declare global {
interface Window {
customModals: {
history: { id: string; modal: Modal }[];
toDelete: Modal | null;
closePopState: (() => void) | null;
closeESC: (() => void) | null;
};
}
}
window.customModals ||= {
history: [],
toDelete: null,
closePopState: null,
closeESC: null
};
function addCustomEventListener(event: string, callback: any) {
window.addEventListener(event, callback, false);
return () => window.removeEventListener(event, callback, false);
}
if (window.customModals.closePopState == null)
window.customModals.closePopState = addCustomEventListener("popstate", async (e: PopStateEvent) => {
// Si el dialogo que se esta cerrando es el mismo que el que se abrio, lo cierro [REF.1]
if (window.customModals.history.length == 0) return;
let dialogPop = window.customModals.history[window.customModals.history.length - 1];
if (dialogPop.modal) {
// Lo elimino de la lista de dialogos
if (window.customModals.toDelete == dialogPop.modal) {
window.customModals.toDelete = null;
dialogPop.modal.destroy();
} else {
await dialogPop.modal.close(e, "popstate");
}
}
});
if (window.customModals.closeESC == null)
window.customModals.closeESC = addCustomEventListener("keyup", (e: KeyboardEvent) => {
if (e.key === "Escape") {
if (window.customModals.history.length == 0) return;
let dialogPop = window.customModals.history[window.customModals.history.length - 1];
// if (dialogPop.dialog.interactiveDismissDisabled) return;
dialogPop.modal.close(e, "keyup");
}
});
let dialogID = 0;
/**
* Creates and displays a dialog with the specified content
*
* @param {HTMLElement} el - The HTML element to display within the dialog
* @param {string} [id] - Optional identifier for the dialog
* @param {ConectateHistory} [history] - Optional history object for browser history integration
* @returns {CtDialog} The created dialog instance
*/
export function showCtDialog(el: HTMLElement, id?: string, history?: ConectateHistory): CtDialog {
let ctDialog: CtDialog;
// Inserto el ID del dialogo que voy a mostrar
ctDialog = new CtDialog();
ctDialog.dialogID = id || `${dialogID++}`;
window.customModals.history.push({ id: ctDialog.dialogID, modal: ctDialog });
history && (ctDialog.history = history);
ctDialog.show();
ctDialog.element = el;
return ctDialog;
}
/**
* Closes a specific dialog or all dialogs if none specified
*
* @param {CtDialog} [id] - Optional dialog instance to close
* @returns {Promise<number>} Promise that resolves when the dialog(s) is closed
*/
export function closeCtDialog(id?: CtDialog) {
return new Promise(async resolve => {
let m = document.querySelectorAll("ct-dialog") as NodeListOf<CtDialog>;
for (let mod = 0; mod < m.length; mod++) {
let modal = m[mod];
if (modal == null) return;
if (id == modal || id == null) {
await modal.close();
}
}
resolve(0);
});
}
// @ts-ignore
window.showCtDialog = showCtDialog;
// @ts-ignore
window.closeCtDialog = closeCtDialog;
/**
* Animation types available for dialogs
*/
type typeDialog = "alert" | "cupertino" | "slide-right" | "slide-left" | "bottom-sheet";
/**
* Size preferences for dialogs
*/
export enum DialogSizePreferences {
/** Full screen dialog */
fullsreen = 0,
/** 80% of window width with max-width */
fullsize = 1
}
/**
* Interface for history integration
*/
export interface ConectateHistory {
/** Page title for history entry */
title: string;
/** URL for history entry */
href: string;
}
/**
* ## `ct-dialog`
* A versatile dialog component that supports multiple animation styles and modal behaviors.
*
* ### Usage
* ```javascript
* import { showCtDialog, closeCtDialog } from "./ct-dialog.js";
*
* // Create content for the dialog
* const content = document.createElement('div');
* content.textContent = 'This is a dialog';
*
* // Show the dialog
* const dialog = showCtDialog(content);
*
* // Configure dialog
* dialog.setAnimation('slide-right');
* dialog.interactiveDismissDisabled = true; // Prevent closing by clicking outside
*
* // Close dialog
* dialog.close();
* // or
* closeCtDialog(dialog);
* ```
*
* ### Animation Types
* - `alert`: Standard modal dialog (default)
* - `cupertino`: iOS-style dialog animation
* - `slide-right`: Dialog slides in from the right
* - `slide-left`: Dialog slides in from the left
* - `bottom-sheet`: Dialog slides up from the bottom
*
* @group lit-ct-components
* @element ct-dialog
* @fires close - Fired when the dialog closes
* @fires open - Fired when the dialog opens
* @csspart overlay - The overlay that covers the screen behind the dialog
* @csspart container - The container of the dialog content
* @cssProp --ct-dialog-width - Width of the dialog (default: 25cm)
* @cssProp --ct-dialog-height - Height of the dialog (default: 80%)
* @cssProp --ct-dialog-background - Background color of the dialog
* @cssProp --ct-dialog-border-radius - Border radius of the dialog
* @cssProp --ct-dialog-box-shadow - Shadow of the dialog
*/
@customElement("ct-dialog")
export class CtDialog extends CtLit {
/** Flag for checking CriOS browser */
static checkForCriOS = false;
/** Element to hide overflow on when dialog is open */
static hiddenOverflow: HTMLElement | null = globalThis?.document?.body;
static styles = [
css`
@keyframes in-modalFadeEffect {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes in-scale-ct {
from {
transform: scale(0.1);
}
to {
transform: scale(1);
}
}
@keyframes in-scale-cupertino {
from {
transform: scale(1.2);
}
to {
transform: scale(1);
}
}
@keyframes in-slide-right {
from {
transform: translateX(100%);
transition-timing-function: ease-in-out;
}
to {
transform: translateX(0);
}
}
@keyframes in-slide-left {
from {
transform: translateX(-100%);
transition-timing-function: ease-in-out;
}
to {
transform: translateX(0);
}
}
@keyframes in-bottom-sheet {
from {
transform: translateY(100%);
transition-timing-function: ease-in-out;
}
to {
transform: translateY(0);
}
}
`,
css`
:host {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: fixed;
z-index: var(--zi-modal, 110);
left: env(safe-area-inset-right, 0);
top: env(safe-area-inset-top, 0);
right: env(safe-area-inset-right, 0);
bottom: env(safe-area-inset-bottom, 0);
overflow-y: auto;
overflow-x: hidden;
animation: in-modalFadeEffect 0.2s;
font-family: "Roboto", sans-serif !important;
box-align: center;
box-orient: vertical;
box-sizing: border-box;
}
:host([type="bottom-sheet"]) {
justify-content: flex-end;
}
.overlay {
position: fixed;
left: env(safe-area-inset-right, 0);
top: env(safe-area-inset-top, 0);
right: env(safe-area-inset-right, 0);
bottom: env(safe-area-inset-bottom, 0);
background-color: rgba(0, 0, 0, 0.65);
animation: in-modalFadeEffect 0.2s;
transition: backdrop-filter 200ms;
z-index: -1;
}
/* @supports (backdrop-filter: blur(12px)) {
.overlay {
backdrop-filter: blur(12px);
}
} */
.anim-normal {
animation: in-scale-cupertino 0.25s;
}
.anim-cupertino {
animation: in-scale-cupertino 0.25s;
}
.anim-slide-right {
animation: in-slide-right 0.5s;
}
.anim-slide-left {
animation: in-slide-left 0.5s;
}
.anim-bottom-sheet {
animation: in-bottom-sheet 0.5s;
}
.no-anim {
animation: none;
}
.c {
display: block;
position: relative;
max-height: var(--ct-dialog-height, 80%);
max-height: var(--ct-dialog-height, 85dvh);
max-width: var(--ct-dialog-width, 25cm);
width: 100%;
/* height: max-content; */
overflow: auto;
margin: 0;
box-sizing: border-box;
z-index: 200;
}
`
];
dialogID?: string;
@property({ type: Boolean }) interactiveDismissDisabled: boolean = false;
@property({ type: String, reflect: true }) role: string = "alert";
@property({ type: String, reflect: true }) type: typeDialog = "alert";
@property({ type: String, reflect: true, attribute: "aria-modal" })
ariaModal: string = "true";
// Vars
disableHistoryAPI: boolean = false;
_closeViaPopState: any;
_clseDialogESC: any;
/** Esto es para esperar que efectivamente se haya hecho el push state */
mappingContainer?: Promise<any>;
history!: ConectateHistory;
// @property({ type: Object }) element?: HTMLElement | TemplateResult;
@state() _element?: HTMLElement;
@property({ type: Array }) preferences: any[] = [];
resolveMapping!: (value?: {} | PromiseLike<{}>) => void;
finish!: () => void;
get element() {
return this._element;
}
set element(val) {
let old = this._element;
this._element = val;
this.requestUpdate("element", old);
// Calc for dvh
let client = getClient();
let oldChrome = client.browser == "chrome" && client.browserVersion < 108;
let oldSafari = client.browser == "safari" && client.browserVersion < 16.4;
let oldFirefox = client.browser == "firefox";
/**
* [FIX]
* [Windows Vista] Chrome v75 height 0px;
* [MacOs] Overflow fix
*/
this.updateComplete.then(async () => {
await sleep(300);
let bodyY = Math.min(document.body.getBoundingClientRect().height, window.innerHeight);
let elementY = this._element!.offsetHeight;
// console.log('bodyY', bodyY, 'elementY', elementY, elementY / bodyY);
if (bodyY > elementY) {
// Reviso si es menor al 5% de la pantalla
if ((elementY / bodyY) * 100 < 5) {
console.warn("[ct-dialog] El elemento no es visible");
if (this._element) this._element.style.height = `var(--ct-dialog-height, ${Math.floor(bodyY * 0.8)}px)`;
} else if ((elementY / bodyY) * 100 >= 80) {
// console.warn("El elemento esta desbordado");
if (this._element && !this.preferences.includes(DialogSizePreferences.fullsreen) && (oldChrome || oldSafari || oldFirefox)) {
this._element.style.height = `var(--ct-dialog-height, ${Math.floor(bodyY * 0.8)}px)`;
}
}
}
});
// if (getClient().os == "ios") {
// this.updateComplete.then(async () => {
// if (this._element) this._element.style.borderRadius = "0px";
// });
// }
}
render() {
return html`
${this.getStylesPref(this.preferences)}
<div
class="overlay"
@click="${(e: MouseEvent) => {
e.stopPropagation();
if (this.interactiveDismissDisabled) return;
this.close(e, "click");
}}"
></div>
${this.element}
`;
}
getStylesPref(pref: DialogSizePreferences[]) {
return pref.map(i => {
switch (i) {
case DialogSizePreferences.fullsreen:
return html`
<style>
.c {
max-height: 92% !important;
max-height: 100dvh;
max-width: 100vw !important;
max-width: 100dvw !important;
}
</style>
`;
}
});
}
disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener("popstate", this._closeViaPopState, false);
document.removeEventListener("keyup", this._clseDialogESC, false);
}
computeAnimation(anim: typeDialog) {
switch (anim) {
case "alert":
return "anim-normal";
case "cupertino":
return "anim-cupertino";
case "slide-left":
return "anim-slide-left";
case "slide-right":
return "anim-slide-right";
case "bottom-sheet":
return "anim-bottom-sheet";
}
}
constructor() {
super();
this.mappingContainer = new Promise(resolve => {
this.resolveMapping = resolve;
});
}
firstUpdated() {
// Checkeo que no sea Chrome de iOS porque esa mierda no sirve aquí 😡
if (CtDialog.checkForCriOS && navigator.userAgent.match(/CriOS\/([0-9\.]+)/)) this.disableHistoryAPI = true;
if (this.history == null) this.history = { title: document.title, href: window.location.href };
// Crea una entrada en el History API identica que solo va a servir para usar 'Atras' en Moviles y cerrar el dialogo
if (!this.disableHistoryAPI) window.history.pushState({ dialogID: this.dialogID }, this.history.title, this.history.href);
this.resolveMapping();
if (this.element?.classList) {
this.element.classList.add("c");
this.element.classList.add(this.computeAnimation(this.type));
}
}
enableHistoryAPI(value = true) {
this.disableHistoryAPI = !value;
return this;
}
fullscreenMode() {
this.preferences = [...this.preferences, DialogSizePreferences.fullsreen];
return this;
}
fullsizeMode() {
this.preferences = [...this.preferences, DialogSizePreferences.fullsize];
return this;
}
setAnimation(anim: typeDialog) {
this.type = anim;
return this;
}
show() {
document.body.appendChild(this);
if (CtDialog.hiddenOverflow) {
CtDialog.hiddenOverflow.style.overflow = "hidden";
}
}
async waitForDefined(param: () => any, timeout = 10_000) {
while (param() == undefined) {
await new Promise(resolve => setTimeout(resolve, 200));
timeout -= 200;
if (timeout <= 0) return false;
}
return param();
}
close(e?: Event | null, type?: "click" | "keyup" | "popstate") {
// Este dialog lo elimino de las lista de dialogos
return new Promise<Event>(async resolve => {
let finish = async () => {
if (!document.body.contains(this)) {
console.warn(`dialogID ya no se encuentra en el DOM`, this);
resolve(e as Event);
return;
}
// Si lo cerre manual o por ESC, elimino la entrada del History API. Como ya se eliminó el dialogo de la lista, `this.close()` no se ejecutará [REF.1]
if (type != "popstate" && !this.disableHistoryAPI) {
window.customModals.toDelete = this;
window.history.back();
} else {
this.destroy();
}
await sleep(250);
resolve(e as Event);
};
// espero que haga el mapping en el container
await this.mappingContainer;
let index = window.customModals.history.findIndex(d => d.modal == this);
let isLast = index == window.customModals.history.length - 1;
if (!isLast) {
// Cierro todos los dialogos que estan por encima de este
for (let i = window.customModals.history.length - 1; i > index; i--) {
await window.customModals.history[i].modal.close();
}
}
if (!document.body.animate) {
await finish();
return;
}
let anim = this.animate([{ opacity: 1 }, { opacity: 0 }], {
duration: 250,
fill: "both"
});
this.element!?.animate(this.getAnimOut(this.type), {
duration: 270,
fill: "both"
});
anim.onfinish = () => finish();
});
}
getAnimOut(type: typeDialog) {
switch (type) {
case "alert":
return [
{ transform: "scale(1)", opacity: 1 },
{ transform: "scale(1.2)", opacity: 0 }
];
case "cupertino":
return [
{ transform: "scale(1)", opacity: 1 },
{ transform: "scale(0.1)", opacity: 0 }
];
case "slide-left":
return [
{ transform: "translateX(0)", opacity: 1 },
{ transform: "translateX(-100%)", opacity: 0 }
];
case "slide-right":
return [
{ transform: "translateX(0)", opacity: 1 },
{ transform: "translateX(100%)", opacity: 0 }
];
case "bottom-sheet":
return [
{ transform: "translateY(0)", opacity: 1 },
{ transform: "translateY(100%)", opacity: 0 }
];
}
}
destroy() {
window.customModals.history.splice(
window.customModals.history.findIndex(d => d.modal == this),
1
);
// Elimino el dialogo
document.body.removeChild(this);
if (CtDialog.hiddenOverflow && window.customModals.history.length == 0) {
CtDialog.hiddenOverflow.style.overflow = "";
}
this.dispatchEvent(new CustomEvent("close"));
this.dispatchEvent(new CustomEvent("on-close"));
}
/**
* @deprecated Use close() instead. The method will be removed in the next major version.
*/
closeDialog(e?: Event | null) {
return this.close(e, "click");
}
static get properties() {
return {
/**
*
*/
dialogID: { type: String, reflect: true },
/**
* Entrada para el History API de tipe {title,href}
*/
history: {
type: Object
},
element: { type: Object },
free: { type: Object }
};
}
}
declare global {
interface HTMLElementTagNameMap {
"ct-dialog": CtDialog;
}
}