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