@daracl/dialog 0.0.7 → 0.0.9

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