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