@daracl/dialog 0.0.7 → 0.0.8

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/dist/index.js CHANGED
@@ -1,6 +1,14 @@
1
- // src/index.js
2
- var DIALOG_IDX = 0;
3
- var iconStyleMap = {
1
+ /*!
2
+ * @daracl/dialog v0.0.8
3
+ * Copyright 2024-2026 darainfo and other contributors;
4
+ * Licensed MIT
5
+ */
6
+ import { sanitizeHtml, isSafeUrl } from "@daracl/core/utils";
7
+ let DIALOG_IDX = 0;
8
+ let STACK_SEQ = 0;
9
+ const HIDDEN_ELEMENT_ID = "daraclDialogHidden";
10
+ const THEME_ATTRIBUTE = "data-daracl-theme";
11
+ const iconStyleMap = {
4
12
  primary: "primary",
5
13
  secondary: "secondary",
6
14
  info: "info",
@@ -8,7 +16,18 @@ var iconStyleMap = {
8
16
  warning: "warning",
9
17
  danger: "danger"
10
18
  };
11
- var defaultOptions = {
19
+ const FOCUSABLE_SELECTOR = [
20
+ "a[href]",
21
+ "area[href]",
22
+ "button:not([disabled])",
23
+ "input:not([disabled]):not([type=hidden])",
24
+ "select:not([disabled])",
25
+ "textarea:not([disabled])",
26
+ "iframe",
27
+ "[contenteditable=true]",
28
+ "[tabindex]:not([tabindex='-1'])"
29
+ ].join(",");
30
+ let defaultOptions = {
12
31
  width: 400,
13
32
  height: 300,
14
33
  styleClass: "",
@@ -29,6 +48,10 @@ var defaultOptions = {
29
48
  enableMaxButton: true,
30
49
  // 닫기 버튼 활성화 여부
31
50
  enableCloseButton: true,
51
+ // ESC 로 닫기
52
+ closeOnEscape: true,
53
+ // 포커스 이동 / 복원
54
+ autoFocus: true,
32
55
  // 최소 높이
33
56
  minHeight: 130,
34
57
  // 최소 넓이
@@ -42,30 +65,63 @@ var defaultOptions = {
42
65
  // open 후 호출 메소드
43
66
  };
44
67
  function dialogHiddenElement() {
45
- if (document.getElementById("daraclDialogHidden") == null) {
46
- document.querySelector("body")?.insertAdjacentHTML("beforeend", `<div id="daraclDialogHidden" class="daracl-dialog-hidden"></div>`);
68
+ let hiddenElement = document.getElementById(HIDDEN_ELEMENT_ID);
69
+ if (hiddenElement == null) {
70
+ hiddenElement = document.createElement("div");
71
+ hiddenElement.id = HIDDEN_ELEMENT_ID;
72
+ hiddenElement.className = "daracl-dialog-hidden";
73
+ document.body.appendChild(hiddenElement);
47
74
  }
48
- return document.getElementById("daraclDialogHidden");
75
+ return hiddenElement;
49
76
  }
50
- var Dialog = class _Dialog {
51
- static VERSION = APP_VERSION;
77
+ function toCssLength(value) {
78
+ if (value === void 0 || value === null || value === "") return "";
79
+ if (typeof value === "number" || /^\d+(\.\d+)?$/.test(String(value))) return value + "px";
80
+ return String(value);
81
+ }
82
+ function addClassNames(element, className) {
83
+ if (typeof className !== "string") return;
84
+ className.split(/\s+/).filter((name) => name !== "").forEach((name) => element.classList.add(name));
85
+ }
86
+ function isActivateKey(e) {
87
+ return e.key === "Enter" || e.key === " " || e.key === "Spacebar";
88
+ }
89
+ function eventPoint(e) {
90
+ const touch = e.touches && e.touches[0] ? e.touches[0] : e.changedTouches && e.changedTouches[0] ? e.changedTouches[0] : e;
91
+ return { clientX: touch.clientX, clientY: touch.clientY, pageX: touch.pageX, pageY: touch.pageY };
92
+ }
93
+ class Dialog {
94
+ static VERSION = "0.0.8";
95
+ /**
96
+ * @param {DialogOptions | string} options 옵션. 문자열이면 template 으로 쓴다.
97
+ */
52
98
  constructor(options) {
53
99
  if (typeof options === "string") {
54
- options = { items: options };
100
+ options = /** @type {DialogOptions} */
101
+ { template: options, items: options };
55
102
  }
56
103
  this.options = Object.assign({}, defaultOptions, options);
57
104
  this.idx = DIALOG_IDX += 1;
105
+ this.eventList = [];
106
+ this.timerSet = /* @__PURE__ */ new Set();
58
107
  const dialogWrapperElement = document.createElement("div");
59
108
  dialogWrapperElement.className = `daracl-dialog-wrapper hide dd-${DIALOG_IDX}`;
109
+ dialogWrapperElement.setAttribute("role", "dialog");
110
+ dialogWrapperElement.setAttribute("tabindex", "-1");
111
+ if (this.options.isModal === true) {
112
+ dialogWrapperElement.setAttribute("aria-modal", "true");
113
+ }
60
114
  const style = dialogWrapperElement.style;
61
- style.zIndex = this.options.zIndex + DIALOG_IDX;
62
- style.width = this.options.width == "auto" ? "auto" : this.options.width + "px";
63
- style.height = this.options.height == "auto" ? "auto" : this.options.height + "px";
64
- style.minHeight = this.options.minHeight + "px";
65
- style.minWidth = this.options.minWidth + "px";
115
+ style.zIndex = String(this.options.zIndex + DIALOG_IDX);
116
+ style.width = toCssLength(this.options.width);
117
+ style.height = toCssLength(this.options.height);
118
+ style.minHeight = toCssLength(this.options.minHeight);
119
+ style.minWidth = toCssLength(this.options.minWidth);
66
120
  dialogHiddenElement().appendChild(dialogWrapperElement);
67
121
  this.dialogWrapperElement = dialogWrapperElement;
122
+ this.setTheme(this.options.theme);
68
123
  this.dialogTemplate();
124
+ this.addEvent(dialogWrapperElement, "keydown", this.onKeydown);
69
125
  if (this.options.draggable !== false) {
70
126
  this.initDrag();
71
127
  }
@@ -77,18 +133,110 @@ var Dialog = class _Dialog {
77
133
  this.show();
78
134
  }
79
135
  }
136
+ /**
137
+ * @param {DialogOptions | string} options
138
+ * @returns {Dialog}
139
+ */
80
140
  static create(options) {
81
- return new _Dialog(options);
141
+ return new Dialog(options);
82
142
  }
83
143
  /**
84
144
  * default options 셋팅
85
145
  *
86
146
  * @static
87
- * @typedef {Object} defaultOptions
147
+ * @param {DialogOptions} options
88
148
  */
89
149
  static setOptions(options) {
90
150
  defaultOptions = Object.assign({}, defaultOptions, options);
91
151
  }
152
+ /**
153
+ * 문자열 HTML 을 sanitize 옵션에 따라 target 에 추가한다.
154
+ *
155
+ * @param {Element} target 추가할 요소
156
+ * @param {string | number | Node | null | undefined} value 내용
157
+ * @param {boolean} trusted template 처럼 기본적으로 신뢰된 HTML 로 취급하는 값인지 여부
158
+ */
159
+ appendHtml(target, value, trusted) {
160
+ if (value === void 0 || value === null) return;
161
+ if (typeof Node !== "undefined" && value instanceof Node) {
162
+ target.appendChild(value);
163
+ return;
164
+ }
165
+ const html = String(value);
166
+ const sanitize = this.options.sanitize;
167
+ if (typeof sanitize === "function") {
168
+ const result = sanitize(html);
169
+ if (typeof Node !== "undefined" && result instanceof Node) {
170
+ target.appendChild(result);
171
+ } else {
172
+ target.insertAdjacentHTML("beforeend", result == null ? "" : String(result));
173
+ }
174
+ return;
175
+ }
176
+ if (sanitize === false || trusted && sanitize !== true) {
177
+ target.insertAdjacentHTML("beforeend", html);
178
+ return;
179
+ }
180
+ target.appendChild(sanitizeHtml(html));
181
+ }
182
+ /**
183
+ * 포커스 가능한 요소 목록
184
+ * @returns {HTMLElement[]}
185
+ */
186
+ getFocusableElements() {
187
+ if (!this.dialogWrapperElement) return [];
188
+ return Array.prototype.slice.call(this.dialogWrapperElement.querySelectorAll(FOCUSABLE_SELECTOR)).filter((el) => !el.closest(".resizer"));
189
+ }
190
+ /**
191
+ * ESC 닫기, 모달일 때 Tab focus trap
192
+ * @param {KeyboardEvent} e
193
+ */
194
+ onKeydown = (e) => {
195
+ if (!this.options) return;
196
+ if ((e.key === "Escape" || e.key === "Esc") && this.options.closeOnEscape !== false && this.options.enableCloseButton !== false) {
197
+ e.stopPropagation();
198
+ this.hide();
199
+ return;
200
+ }
201
+ if (e.key === "Tab" && this.options.isModal === true) {
202
+ const focusable = this.getFocusableElements();
203
+ if (focusable.length === 0) {
204
+ e.preventDefault();
205
+ this.dialogWrapperElement.focus();
206
+ return;
207
+ }
208
+ const first = focusable[0];
209
+ const last = focusable[focusable.length - 1];
210
+ const active = document.activeElement;
211
+ if (e.shiftKey && (active === first || active === this.dialogWrapperElement)) {
212
+ e.preventDefault();
213
+ last.focus();
214
+ } else if (!e.shiftKey && active === last) {
215
+ e.preventDefault();
216
+ first.focus();
217
+ }
218
+ }
219
+ };
220
+ /**
221
+ * 지연 실행 타이머 등록 (destroy 에서 정리한다)
222
+ * @param {() => void} fn
223
+ * @param {number} delay
224
+ * @returns {ReturnType<typeof setTimeout>}
225
+ */
226
+ setTimer(fn, delay) {
227
+ const timer = setTimeout(() => {
228
+ this.timerSet.delete(timer);
229
+ fn();
230
+ }, delay);
231
+ this.timerSet.add(timer);
232
+ return timer;
233
+ }
234
+ /** @param {ReturnType<typeof setTimeout> | undefined} timer */
235
+ clearTimer(timer) {
236
+ if (timer === void 0) return;
237
+ clearTimeout(timer);
238
+ this.timerSet.delete(timer);
239
+ }
92
240
  /** 사이즈 조절 초기화 */
93
241
  initResize() {
94
242
  const dialogElement = this.dialogWrapperElement;
@@ -98,29 +246,29 @@ var Dialog = class _Dialog {
98
246
  let moveMode = "";
99
247
  let offsetX = -1, offsetY = -1;
100
248
  let isResizeTop, isResizeLeft;
101
- this.addEvent(reslzeElement, "mousedown touchdown", (e) => {
249
+ this.addEvent(reslzeElement, "mousedown touchstart", (e) => {
102
250
  if (this.isMaximise()) {
103
251
  return false;
104
252
  }
105
- moveMode = e.target.getAttribute("data-mode");
253
+ moveMode = /** @type {HTMLElement} */
254
+ e.currentTarget.getAttribute("data-mode") || "";
106
255
  isResizeTop = moveMode.indexOf("t") > -1;
107
256
  isResizeLeft = moveMode.indexOf("l") > -1;
108
257
  offsetX = isResizeLeft ? dialogElement.getBoundingClientRect().left : -1;
109
258
  offsetY = isResizeTop ? dialogElement.getBoundingClientRect().top : -1;
110
259
  e.preventDefault();
111
- const oe = e.touches;
112
- startX = oe && oe[0] ? oe[0].pageX : e.pageX;
113
- startY = oe && oe[0] ? oe[0].pageY : e.pageY;
260
+ const point = eventPoint(e);
261
+ startX = point.pageX;
262
+ startY = point.pageY;
114
263
  dialogWidth = dialogElement.clientWidth;
115
264
  dialogHeight = dialogElement.clientHeight;
116
265
  if (!dialogElement.classList.contains("transform-disable")) {
117
- const offsetX2 = e.clientX - dialogElement.getBoundingClientRect().left;
118
- const offsetY2 = e.clientY - dialogElement.getBoundingClientRect().top;
119
- this.setPosition(e, offsetX2, offsetY2, dialogWidth, dialogHeight);
266
+ const rect = dialogElement.getBoundingClientRect();
267
+ this.setPosition(point, point.clientX - rect.left, point.clientY - rect.top, dialogWidth, dialogHeight);
120
268
  dialogElement.classList.add("transform-disable");
121
269
  }
122
270
  this.addEvent(document, "mousemove touchmove", onResizeMouseMove);
123
- this.addEvent(document, "mouseup touchup", onResizeMouseUp);
271
+ this.addEvent(document, "mouseup touchend touchcancel", onResizeMouseUp);
124
272
  });
125
273
  let startTime = -1;
126
274
  let moveTimer;
@@ -130,12 +278,13 @@ var Dialog = class _Dialog {
130
278
  startTime = (/* @__PURE__ */ new Date()).getTime();
131
279
  }
132
280
  if ((/* @__PURE__ */ new Date()).getTime() - moveDelay <= startTime) {
133
- clearTimeout(moveTimer);
281
+ this.clearTimer(moveTimer);
134
282
  }
135
- const oe1 = e.touches;
136
- moveTimer = setTimeout(() => {
283
+ const point = eventPoint(e);
284
+ moveTimer = this.setTimer(() => {
137
285
  startTime = -1;
138
- let moveX = (oe1 && oe1[0] ? oe1[0].pageX : e.pageX) - startX, moveY = (oe1 && oe1[0] ? oe1[0].pageY : e.pageY) - startY;
286
+ if (!this.options) return;
287
+ let moveX = point.pageX - startX, moveY = point.pageY - startY;
139
288
  moveY = isResizeTop ? moveY * -1 : moveY;
140
289
  moveX = isResizeLeft ? moveX * -1 : moveX;
141
290
  let resizeHeight = dialogHeight + moveY, resizeWidth = dialogWidth + moveX;
@@ -174,9 +323,10 @@ var Dialog = class _Dialog {
174
323
  }, moveDelay);
175
324
  };
176
325
  const onResizeMouseUp = () => {
177
- clearTimeout(moveTimer);
326
+ this.clearTimer(moveTimer);
327
+ startTime = -1;
178
328
  this.removeEvent(document, "mousemove touchmove", onResizeMouseMove);
179
- this.removeEvent(document, "mouseup touchup", onResizeMouseUp);
329
+ this.removeEvent(document, "mouseup touchend touchcancel", onResizeMouseUp);
180
330
  };
181
331
  }
182
332
  /**
@@ -185,31 +335,41 @@ var Dialog = class _Dialog {
185
335
  initDrag() {
186
336
  const dialogElement = this.dialogWrapperElement;
187
337
  const dragElement = this.dialogWrapperElement.querySelector(".dialog-header");
338
+ if (!dragElement) return;
188
339
  let isDragging = false;
189
340
  let offsetX, offsetY, dialogWidth, dialogHeight;
190
341
  let isDrag = false;
191
- this.addEvent(dragElement, "mousedown touchdown", (e) => {
192
- const tagName = e.target.tagName;
342
+ this.addEvent(dragElement, "mousedown touchstart", (e) => {
343
+ const target = (
344
+ /** @type {HTMLElement} */
345
+ e.target
346
+ );
347
+ const tagName = target.tagName || "";
193
348
  if (tagName.search(/(input|textarea|select|button)/gi) > -1) {
194
349
  return true;
195
350
  }
351
+ if (target.closest && target.closest(".btn-area")) {
352
+ return true;
353
+ }
196
354
  if (this.isMaximise()) {
197
355
  return false;
198
356
  }
199
357
  e.preventDefault();
358
+ const point = eventPoint(e);
359
+ const rect = dialogElement.getBoundingClientRect();
200
360
  dialogWidth = dialogElement.clientWidth;
201
361
  dialogHeight = dialogElement.clientHeight;
202
362
  isDragging = true;
203
- offsetX = e.clientX - dialogElement.getBoundingClientRect().left;
204
- offsetY = e.clientY - dialogElement.getBoundingClientRect().top;
363
+ offsetX = point.clientX - rect.left;
364
+ offsetY = point.clientY - rect.top;
205
365
  if (!isDrag) {
206
- this.setPosition(e, offsetX, offsetY, dialogWidth, dialogHeight);
366
+ this.setPosition(point, offsetX, offsetY, dialogWidth, dialogHeight);
207
367
  isDrag = true;
208
368
  dialogElement.classList.add("transform-disable");
209
369
  }
210
370
  dialogElement.classList.add("move-on");
211
371
  this.addEvent(document, "mousemove touchmove", onMouseMove);
212
- this.addEvent(document, "mouseup touchup", onMouseUp);
372
+ this.addEvent(document, "mouseup touchend touchcancel", onMouseUp);
213
373
  });
214
374
  let startTime = -1;
215
375
  let moveTimer;
@@ -220,26 +380,29 @@ var Dialog = class _Dialog {
220
380
  startTime = (/* @__PURE__ */ new Date()).getTime();
221
381
  }
222
382
  if ((/* @__PURE__ */ new Date()).getTime() - moveDelay <= startTime) {
223
- clearTimeout(moveTimer);
383
+ this.clearTimer(moveTimer);
224
384
  }
225
- moveTimer = setTimeout(() => {
385
+ const point = eventPoint(e);
386
+ moveTimer = this.setTimer(() => {
226
387
  startTime = -1;
227
- this.setPosition(e, offsetX, offsetY, dialogWidth, dialogHeight);
388
+ if (!this.dialogWrapperElement) return;
389
+ this.setPosition(point, offsetX, offsetY, dialogWidth, dialogHeight);
228
390
  }, moveDelay);
229
391
  }
230
392
  };
231
393
  const onMouseUp = () => {
232
394
  isDragging = false;
233
- clearTimeout(moveTimer);
395
+ startTime = -1;
396
+ this.clearTimer(moveTimer);
234
397
  dialogElement.classList.remove("move-on");
235
398
  this.removeEvent(document, "mousemove touchmove", onMouseMove);
236
- this.removeEvent(document, "mouseup touchup", onMouseUp);
399
+ this.removeEvent(document, "mouseup touchend touchcancel", onMouseUp);
237
400
  };
238
401
  }
239
402
  /**
240
403
  * dialog position
241
404
  *
242
- * @param {Event} e event
405
+ * @param {{clientX: number, clientY: number}} e event 또는 좌표
243
406
  * @param {Number} offsetX offset x
244
407
  * @param {Number} offsetY offset y
245
408
  * @param {Number} dialogWidth dialog width
@@ -257,94 +420,201 @@ var Dialog = class _Dialog {
257
420
  this.dialogWrapperElement.style.left = minX + "px";
258
421
  this.dialogWrapperElement.style.top = minY + "px";
259
422
  }
423
+ /**
424
+ * span 버튼에 role / tabindex / 키보드 동작을 붙인다.
425
+ * @param {HTMLElement} element
426
+ * @param {string} eventName 마우스 이벤트 이름 (기존 동작 유지: 닫기 · 최대화는 click, 하단 버튼은 mousedown)
427
+ * @param {(e: Event) => void} handler
428
+ */
429
+ bindButton(element, eventName, handler) {
430
+ element.setAttribute("role", "button");
431
+ element.setAttribute("tabindex", "0");
432
+ this.addEvent(element, eventName, handler);
433
+ this.addEvent(element, "keydown", (e) => {
434
+ if (isActivateKey(
435
+ /** @type {KeyboardEvent} */
436
+ e
437
+ )) {
438
+ e.preventDefault();
439
+ handler(e);
440
+ }
441
+ });
442
+ }
260
443
  dialogTemplate() {
261
- const enableHeader = this.options.enableHeader !== false;
444
+ const options = this.options;
445
+ const enableHeader = options.enableHeader !== false;
446
+ const enableFooter = options.enableFooter !== false;
262
447
  const dialog = document.createElement("div");
263
- const styleClass = this.options.styleClass ?? "";
264
- dialog.className = `daracl-dialog ${styleClass}`;
265
- let dialogHtml = [];
448
+ dialog.className = "daracl-dialog";
449
+ addClassNames(dialog, options.styleClass ?? "");
266
450
  if (enableHeader) {
267
- dialogHtml.push(
268
- `<div class="dialog-header" >
269
- ${this.options.title ?? ""}
270
- <div class="btn-area">
271
- ${this.options.enableMaxButton ? `<span class="dialog-maximise"></span>` : ""}
272
- ${this.options.enableCloseButton ? `<span class="dialog-close"></span>` : ""}
273
- </div>
274
- </div>`
275
- );
451
+ const header = document.createElement("div");
452
+ header.className = "dialog-header";
453
+ this.appendHtml(header, options.title ?? "", false);
454
+ const label = (header.textContent || "").trim();
455
+ if (label !== "") {
456
+ this.dialogWrapperElement.setAttribute("aria-label", label);
457
+ }
458
+ const btnArea = document.createElement("div");
459
+ btnArea.className = "btn-area";
460
+ if (options.enableMaxButton) {
461
+ const maxButton2 = document.createElement("span");
462
+ maxButton2.className = "dialog-maximise";
463
+ maxButton2.setAttribute("aria-label", "Maximize");
464
+ maxButton2.setAttribute("title", "Maximize");
465
+ btnArea.appendChild(maxButton2);
466
+ }
467
+ if (options.enableCloseButton) {
468
+ const closeButton2 = document.createElement("span");
469
+ closeButton2.className = "dialog-close";
470
+ closeButton2.setAttribute("aria-label", "Close");
471
+ closeButton2.setAttribute("title", "Close");
472
+ btnArea.appendChild(closeButton2);
473
+ }
474
+ header.appendChild(btnArea);
475
+ dialog.appendChild(header);
276
476
  }
277
- dialogHtml.push(
278
- `<div class="dialog-body ${iconStyleMap[this.options.icon] ?? ""}" style="height: calc(100% ${enableHeader ? " - 40px" : ""}${this.options.enableFooter ? " - 45px" : ""})"><div class="dialog-move-overay"></div><div class="dialog-content">`
279
- );
280
- if (this.options.url) {
281
- dialogHtml.push(`<iframe src="${this.options.url}" class="dialog-frame"></iframe>`);
282
- } else {
283
- if (typeof this.options.template === "string") {
284
- dialogHtml.push(this.options.template);
477
+ const body = document.createElement("div");
478
+ body.className = "dialog-body";
479
+ if (Object.prototype.hasOwnProperty.call(iconStyleMap, options.icon)) {
480
+ body.classList.add(iconStyleMap[options.icon]);
481
+ }
482
+ body.style.height = `calc(100%${enableHeader ? " - 40px" : ""}${enableFooter ? " - 45px" : ""})`;
483
+ const moveOverlay = document.createElement("div");
484
+ moveOverlay.className = "dialog-move-overay";
485
+ body.appendChild(moveOverlay);
486
+ const content = document.createElement("div");
487
+ content.className = "dialog-content";
488
+ body.appendChild(content);
489
+ if (options.url) {
490
+ const url = String(options.url);
491
+ if (isSafeUrl(url)) {
492
+ const frame = document.createElement("iframe");
493
+ frame.className = "dialog-frame";
494
+ frame.src = url;
495
+ if (typeof options.title === "string") frame.title = (this.dialogWrapperElement.getAttribute("aria-label") || "").slice(0, 200);
496
+ content.appendChild(frame);
285
497
  } else {
286
- dialogHtml.push(this.options.template());
498
+ console.warn("[daracl.dialog] unsafe url blocked : " + url.slice(0, 100));
287
499
  }
500
+ } else if (typeof options.template === "function") {
501
+ this.appendHtml(content, options.template(), true);
502
+ } else {
503
+ this.appendHtml(content, options.template, true);
288
504
  }
289
- dialogHtml.push("</div></div>");
290
- const buttons = this.options.buttons ?? [];
291
- if (this.options.enableFooter !== false) {
292
- dialogHtml.push('<div class="dialog-footer"><div class="btn-area">');
505
+ dialog.appendChild(body);
506
+ const buttons = options.buttons ?? [];
507
+ if (enableFooter) {
508
+ const footer = document.createElement("div");
509
+ footer.className = "dialog-footer";
510
+ const btnArea = document.createElement("div");
511
+ btnArea.className = "btn-area";
293
512
  for (let i = 0; i < buttons.length; i++) {
294
- const button = buttons[i];
295
- const styleClass2 = button.styleClass ?? "success";
296
- dialogHtml.push(`<span class="dialog-btn dialog-btn-${i} ${styleClass2}">${button.label}</span>`);
513
+ const button = (
514
+ /** @type {DialogButton} */
515
+ buttons[i] ?? {}
516
+ );
517
+ const btnElement = document.createElement("span");
518
+ btnElement.className = `dialog-btn dialog-btn-${i}`;
519
+ addClassNames(btnElement, button.styleClass ?? "success");
520
+ this.appendHtml(btnElement, button.label ?? "", false);
521
+ this.bindButton(btnElement, "mousedown", (e) => {
522
+ if (typeof button.callback === "function") {
523
+ button.callback(e);
524
+ }
525
+ });
526
+ btnArea.appendChild(btnElement);
297
527
  }
298
- dialogHtml.push("</div></div>");
528
+ footer.appendChild(btnArea);
529
+ dialog.appendChild(footer);
299
530
  }
300
- if (this.options.resizable === true) {
301
- dialogHtml.push(`
302
- <div class="resizer top" data-mode="t"></div>
303
- <div class="resizer left" data-mode="l"></div>
304
- <div class="resizer right" data-mode="r"></div>
305
- <div class="resizer bottom" data-mode="b"></div>
306
-
307
- <div class="resizer top-left" data-mode="tl"></div>
308
- <div class="resizer top-right" data-mode="tr"></div>
309
- <div class="resizer bottom-left" data-mode="bl"></div>
310
- <div class="resizer bottom-right" data-mode="br"></div>
311
- `);
531
+ if (options.resizable === true) {
532
+ [
533
+ ["top", "t"],
534
+ ["left", "l"],
535
+ ["right", "r"],
536
+ ["bottom", "b"],
537
+ ["top-left", "tl"],
538
+ ["top-right", "tr"],
539
+ ["bottom-left", "bl"],
540
+ ["bottom-right", "br"]
541
+ ].forEach(([className, mode]) => {
542
+ const resizer = document.createElement("div");
543
+ resizer.className = `resizer ${className}`;
544
+ resizer.setAttribute("data-mode", mode);
545
+ dialog.appendChild(resizer);
546
+ });
312
547
  }
313
- dialog.innerHTML = dialogHtml.join("");
314
548
  this.dialogWrapperElement.appendChild(dialog);
315
- if (this.options.enableMaxButton) {
316
- dialog.querySelector(".dialog-maximise").addEventListener("click", () => {
317
- this.maximise(dialog);
549
+ const maxButton = (
550
+ /** @type {HTMLElement | null} */
551
+ dialog.querySelector(".dialog-header .dialog-maximise")
552
+ );
553
+ if (maxButton) {
554
+ this.bindButton(maxButton, "click", () => {
555
+ this.maximise();
318
556
  });
319
557
  }
320
- if (this.options.enableCloseButton) {
321
- dialog.querySelector(".dialog-close").addEventListener("click", () => {
322
- this.hide(dialog);
558
+ const closeButton = (
559
+ /** @type {HTMLElement | null} */
560
+ dialog.querySelector(".dialog-header .dialog-close")
561
+ );
562
+ if (closeButton) {
563
+ this.bindButton(closeButton, "click", () => {
564
+ this.hide();
323
565
  });
324
566
  }
325
- if (this.options.enableFooter !== false) {
326
- for (let i = 0; i < buttons.length; i++) {
327
- const button = buttons[i];
328
- const btnElement = this.dialogWrapperElement.querySelector(`.dialog-footer .dialog-btn-${i}`);
329
- btnElement.addEventListener("mousedown", (e) => {
330
- if (button.callback) {
331
- button.callback(e);
332
- }
333
- });
567
+ }
568
+ /**
569
+ * dialog 별 테마 지정. 빈 값이면 해제하고 상위 요소의 data-daracl-theme 를 따른다.
570
+ *
571
+ * @param {string} [themeName] light, dark
572
+ * @returns {Dialog}
573
+ */
574
+ setTheme(themeName) {
575
+ if (!this.dialogWrapperElement) return this;
576
+ this.themeName = themeName ? String(themeName) : "";
577
+ [this.dialogWrapperElement, this.dialogOverrayElement].forEach((element) => {
578
+ if (!element) return;
579
+ if (this.themeName) {
580
+ element.setAttribute(THEME_ATTRIBUTE, this.themeName);
581
+ } else {
582
+ element.removeAttribute(THEME_ATTRIBUTE);
334
583
  }
335
- }
584
+ });
585
+ return this;
586
+ }
587
+ /**
588
+ * dialog 가 보이는지 여부
589
+ * @returns {boolean}
590
+ */
591
+ isOpen() {
592
+ return !!this.dialogWrapperElement && !this.dialogWrapperElement.classList.contains("hide");
336
593
  }
337
594
  /**
338
595
  * show dialog message
339
- * @param {*} viewItems
340
- * @returns
596
+ * @returns {Dialog}
341
597
  */
342
598
  show = () => {
599
+ if (!this.dialogWrapperElement || !this.dialogWrapperElement.classList.contains("hide")) {
600
+ return this;
601
+ }
602
+ STACK_SEQ = Math.max(STACK_SEQ, DIALOG_IDX) + 2;
603
+ const zIndex = this.options.zIndex + STACK_SEQ;
604
+ this.returnFocusElement = typeof document !== "undefined" ? (
605
+ /** @type {HTMLElement | null} */
606
+ document.activeElement
607
+ ) : null;
608
+ this.dialogWrapperElement.style.zIndex = String(zIndex);
343
609
  this.dialogWrapperElement.classList.remove("hide");
344
610
  if (this.options.isModal === true) {
611
+ this.removeDialogOverrayElement();
345
612
  const dialogOverrayElement = document.createElement("div");
346
613
  dialogOverrayElement.className = "daracl-dialog-overlay";
347
- dialogOverrayElement.style.zIndex = this.options.zIndex + this.idx;
614
+ dialogOverrayElement.style.zIndex = String(zIndex - 1);
615
+ if (this.themeName) {
616
+ dialogOverrayElement.setAttribute(THEME_ATTRIBUTE, this.themeName);
617
+ }
348
618
  const hiddenElement = dialogHiddenElement();
349
619
  const firstChild = hiddenElement.firstChild;
350
620
  if (firstChild) {
@@ -354,6 +624,16 @@ var Dialog = class _Dialog {
354
624
  }
355
625
  this.dialogOverrayElement = dialogOverrayElement;
356
626
  }
627
+ if (this.options.autoFocus !== false) {
628
+ const focusable = this.getFocusableElements();
629
+ const contentFirst = focusable.find((el) => el.closest(".dialog-content")) || focusable.find((el) => el.closest(".dialog-footer"));
630
+ const target = contentFirst || this.dialogWrapperElement;
631
+ try {
632
+ target.focus({ preventScroll: true });
633
+ } catch (e) {
634
+ target.focus();
635
+ }
636
+ }
357
637
  if (typeof this.options.afterOpen === "function") {
358
638
  this.options.afterOpen.call(this, this.dialogWrapperElement);
359
639
  }
@@ -361,18 +641,46 @@ var Dialog = class _Dialog {
361
641
  };
362
642
  /**
363
643
  * dialog hide
644
+ * @returns {Dialog}
364
645
  */
365
646
  hide = () => {
647
+ if (!this.dialogWrapperElement) return this;
648
+ const wasOpen = this.isOpen();
649
+ const hadFocus = this.dialogWrapperElement.contains(document.activeElement);
366
650
  this.dialogWrapperElement.classList.add("hide");
367
651
  if (this.options.isModal === true) {
368
- dialogHiddenElement().removeChild(this.dialogOverrayElement);
652
+ this.removeDialogOverrayElement();
369
653
  }
654
+ if (wasOpen) {
655
+ this.restoreFocus(hadFocus);
656
+ }
657
+ return this;
370
658
  };
659
+ /**
660
+ * 열기 전에 포커스가 있던 요소로 되돌린다.
661
+ * @param {boolean} hadFocus 포커스가 dialog 안에 있었는지 여부
662
+ */
663
+ restoreFocus(hadFocus) {
664
+ const returnElement = this.returnFocusElement;
665
+ this.returnFocusElement = null;
666
+ if (!this.options || this.options.autoFocus === false || !hadFocus) return;
667
+ if (returnElement && typeof returnElement.focus === "function" && document.body.contains(returnElement)) {
668
+ returnElement.focus();
669
+ }
670
+ }
671
+ removeDialogOverrayElement() {
672
+ const overlay = this.dialogOverrayElement;
673
+ this.dialogOverrayElement = void 0;
674
+ if (overlay && overlay.parentNode) {
675
+ overlay.parentNode.removeChild(overlay);
676
+ }
677
+ }
371
678
  /**
372
679
  * maximise hide
373
680
  *
374
681
  */
375
682
  maximise = () => {
683
+ if (!this.dialogWrapperElement) return;
376
684
  const classList = this.dialogWrapperElement.classList;
377
685
  if (classList.contains("maximise")) {
378
686
  classList.remove("maximise");
@@ -381,41 +689,67 @@ var Dialog = class _Dialog {
381
689
  }
382
690
  };
383
691
  isMaximise() {
384
- return this.dialogWrapperElement.classList.contains("maximise");
692
+ return !!this.dialogWrapperElement && this.dialogWrapperElement.classList.contains("maximise");
385
693
  }
694
+ /**
695
+ * 이벤트 등록. 등록한 이벤트는 destroy 에서 모두 해제한다.
696
+ * @param {EventTarget | NodeList | EventTarget[]} elements
697
+ * @param {string} events 공백으로 구분한 이벤트 이름
698
+ * @param {EventListener} fnHandler
699
+ */
386
700
  addEvent(elements, events, fnHandler) {
387
- events.split(" ").forEach(function(e) {
388
- if (elements instanceof NodeList) {
389
- for (let element of elements) {
390
- element.addEventListener(e, fnHandler, false);
391
- }
392
- } else {
393
- elements.addEventListener(e, fnHandler, false);
394
- }
701
+ const targets = elements instanceof NodeList || Array.isArray(elements) ? Array.prototype.slice.call(elements) : [elements];
702
+ events.split(" ").forEach((e) => {
703
+ if (e === "") return;
704
+ targets.forEach((element) => {
705
+ if (!element) return;
706
+ if (this.eventList.some(([el, name, fn]) => el === element && name === e && fn === fnHandler)) return;
707
+ element.addEventListener(e, fnHandler, false);
708
+ this.eventList.push([element, e, fnHandler]);
709
+ });
395
710
  });
396
711
  }
712
+ /**
713
+ * @param {EventTarget | NodeList | EventTarget[]} elements
714
+ * @param {string} events 공백으로 구분한 이벤트 이름
715
+ * @param {EventListener} fnHandler
716
+ */
397
717
  removeEvent(elements, events, fnHandler) {
398
- events.split(" ").forEach(function(e) {
399
- if (elements instanceof NodeList) {
400
- for (let element of elements) {
401
- element.removeEventListener(e, fnHandler);
402
- }
403
- } else {
404
- elements.removeEventListener(e, fnHandler);
405
- }
718
+ const targets = elements instanceof NodeList || Array.isArray(elements) ? Array.prototype.slice.call(elements) : [elements];
719
+ events.split(" ").forEach((e) => {
720
+ targets.forEach((element) => {
721
+ if (!element) return;
722
+ element.removeEventListener(e, fnHandler, false);
723
+ this.eventList = this.eventList.filter(([el, name, fn]) => !(el === element && name === e && fn === fnHandler));
724
+ });
406
725
  });
407
726
  }
408
727
  /**
409
- * dialog destroy
728
+ * dialog destroy. 이벤트 · 타이머 · overlay · DOM 을 모두 정리한다. 여러 번 호출해도 된다.
410
729
  */
411
730
  destroy = () => {
412
- dialogHiddenElement().removeChild(this.dialogWrapperElement);
731
+ if (!this.dialogWrapperElement) return;
732
+ const wasOpen = this.isOpen();
733
+ const hadFocus = this.dialogWrapperElement.contains(document.activeElement);
734
+ this.eventList.forEach(([element, name, fn]) => element.removeEventListener(name, fn, false));
735
+ this.eventList = [];
736
+ this.timerSet.forEach((timer) => clearTimeout(timer));
737
+ this.timerSet.clear();
738
+ this.removeDialogOverrayElement();
739
+ if (wasOpen) {
740
+ this.restoreFocus(hadFocus);
741
+ }
742
+ const wrapper = this.dialogWrapperElement;
743
+ if (wrapper.parentNode) {
744
+ wrapper.parentNode.removeChild(wrapper);
745
+ }
413
746
  this.dialogWrapperElement = null;
414
747
  this.options = null;
415
748
  this.idx = -1;
416
749
  };
417
- };
750
+ }
418
751
  export {
752
+ Dialog,
419
753
  Dialog as default
420
754
  };
421
755
  //# sourceMappingURL=index.js.map