@designbasekorea/ui-wc 0.8.12 → 0.9.0
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/CHANGELOG.md +56 -0
- package/LICENSE-PAYMENT-LOGOS.md +437 -0
- package/README.md +61 -23
- package/dist/esm/components/db-achievement-list.d.ts +31 -0
- package/dist/esm/components/db-achievement-list.js +1 -0
- package/dist/esm/components/db-achievement-modal.d.ts +38 -0
- package/dist/esm/components/db-achievement-modal.js +1 -0
- package/dist/esm/components/db-ai-chain-of-thought.d.ts +14 -0
- package/dist/esm/components/db-ai-chain-of-thought.js +1 -0
- package/dist/esm/components/db-ai-chat.js +1 -1
- package/dist/esm/components/db-ai-checkpoint.d.ts +14 -0
- package/dist/esm/components/db-ai-checkpoint.js +1 -0
- package/dist/esm/components/db-ai-confirmation.d.ts +14 -0
- package/dist/esm/components/db-ai-confirmation.js +1 -0
- package/dist/esm/components/db-ai-context.d.ts +15 -0
- package/dist/esm/components/db-ai-context.js +1 -0
- package/dist/esm/components/db-ai-conversation.d.ts +21 -0
- package/dist/esm/components/db-ai-conversation.js +1 -0
- package/dist/esm/components/db-ai-execution-quote.d.ts +41 -0
- package/dist/esm/components/db-ai-execution-quote.js +1 -0
- package/dist/esm/components/db-ai-file-tree.d.ts +14 -0
- package/dist/esm/components/db-ai-file-tree.js +1 -0
- package/dist/esm/components/db-ai-glow.d.ts +1 -1
- package/dist/esm/components/db-ai-inline-citation.d.ts +16 -0
- package/dist/esm/components/db-ai-inline-citation.js +1 -0
- package/dist/esm/components/db-ai-message.d.ts +19 -0
- package/dist/esm/components/db-ai-message.js +1 -0
- package/dist/esm/components/db-ai-model-select.d.ts +36 -0
- package/dist/esm/components/db-ai-model-select.js +1 -0
- package/dist/esm/components/db-ai-plan.d.ts +14 -0
- package/dist/esm/components/db-ai-plan.js +1 -0
- package/dist/esm/components/db-ai-queue.d.ts +14 -0
- package/dist/esm/components/db-ai-queue.js +1 -0
- package/dist/esm/components/db-ai-reasoning.d.ts +14 -0
- package/dist/esm/components/db-ai-reasoning.js +1 -0
- package/dist/esm/components/db-ai-sources.d.ts +14 -0
- package/dist/esm/components/db-ai-sources.js +1 -0
- package/dist/esm/components/db-ai-stack-trace.d.ts +14 -0
- package/dist/esm/components/db-ai-stack-trace.js +1 -0
- package/dist/esm/components/db-ai-subagent.d.ts +14 -0
- package/dist/esm/components/db-ai-subagent.js +1 -0
- package/dist/esm/components/db-ai-task-status.d.ts +26 -0
- package/dist/esm/components/db-ai-task-status.js +1 -0
- package/dist/esm/components/db-ai-task.d.ts +14 -0
- package/dist/esm/components/db-ai-task.js +1 -0
- package/dist/esm/components/db-ai-terminal.d.ts +14 -0
- package/dist/esm/components/db-ai-terminal.js +1 -0
- package/dist/esm/components/db-ai-test-results.d.ts +14 -0
- package/dist/esm/components/db-ai-test-results.js +1 -0
- package/dist/esm/components/db-ai-tool.d.ts +14 -0
- package/dist/esm/components/db-ai-tool.js +1 -0
- package/dist/esm/components/db-attachment-list.d.ts +38 -0
- package/dist/esm/components/db-attachment-list.js +1 -0
- package/dist/esm/components/db-bento-card.d.ts +55 -0
- package/dist/esm/components/db-bento-card.js +1 -0
- package/dist/esm/components/db-bento-grid.d.ts +25 -0
- package/dist/esm/components/db-bento-grid.js +1 -0
- package/dist/esm/components/db-boarding-pass-stack.d.ts +49 -0
- package/dist/esm/components/db-boarding-pass-stack.js +1 -0
- package/dist/esm/components/db-boarding-pass.d.ts +32 -0
- package/dist/esm/components/db-boarding-pass.js +1 -0
- package/dist/esm/components/db-border-beam.d.ts +52 -0
- package/dist/esm/components/db-border-beam.js +1 -0
- package/dist/esm/components/db-button.d.ts +1 -1
- package/dist/esm/components/db-button.js +1 -1
- package/dist/esm/components/db-chat-composer.d.ts +2 -0
- package/dist/esm/components/db-chat-composer.js +1 -1
- package/dist/esm/components/db-chat-message.d.ts +1 -1
- package/dist/esm/components/db-chat-orb.d.ts +1 -1
- package/dist/esm/components/db-chat-widget.d.ts +1 -1
- package/dist/esm/components/db-color-picker.d.ts +1 -0
- package/dist/esm/components/db-color-picker.js +1 -1
- package/dist/esm/components/db-confetti.d.ts +90 -0
- package/dist/esm/components/db-confetti.js +1 -0
- package/dist/esm/components/db-context-bar.d.ts +13 -0
- package/dist/esm/components/db-context-bar.js +1 -0
- package/dist/esm/components/db-credit-balance.d.ts +17 -0
- package/dist/esm/components/db-credit-balance.js +1 -0
- package/dist/esm/components/db-credit-card.d.ts +51 -0
- package/dist/esm/components/db-credit-card.js +1 -0
- package/dist/esm/components/db-credit-dropdown.d.ts +31 -0
- package/dist/esm/components/db-credit-dropdown.js +1 -0
- package/dist/esm/components/db-credit-history.d.ts +31 -0
- package/dist/esm/components/db-credit-history.js +1 -0
- package/dist/esm/components/db-credit-recharge-modal.d.ts +35 -0
- package/dist/esm/components/db-credit-recharge-modal.js +1 -0
- package/dist/esm/components/db-credit-recharge.d.ts +39 -0
- package/dist/esm/components/db-credit-recharge.js +1 -0
- package/dist/esm/components/db-design-canvas.d.ts +137 -0
- package/dist/esm/components/db-design-canvas.js +1 -0
- package/dist/esm/components/db-design-toolbar.d.ts +60 -0
- package/dist/esm/components/db-design-toolbar.js +1 -0
- package/dist/esm/components/db-device-mockup.d.ts +100 -0
- package/dist/esm/components/db-device-mockup.js +1 -0
- package/dist/esm/components/db-download-progress.d.ts +1 -1
- package/dist/esm/components/db-drawer.js +1 -1
- package/dist/esm/components/db-dropdown.d.ts +2 -0
- package/dist/esm/components/db-dropdown.js +1 -1
- package/dist/esm/components/db-email-verify.d.ts +1 -1
- package/dist/esm/components/db-file-uploader.d.ts +10 -0
- package/dist/esm/components/db-filter-bar.d.ts +34 -0
- package/dist/esm/components/db-filter-bar.js +1 -0
- package/dist/esm/components/db-flight-status.d.ts +33 -0
- package/dist/esm/components/db-flight-status.js +1 -0
- package/dist/esm/components/db-floating-action-button.d.ts +24 -14
- package/dist/esm/components/db-floating-action-button.js +1 -1
- package/dist/esm/components/db-footer.d.ts +3 -0
- package/dist/esm/components/db-footer.js +1 -1
- package/dist/esm/components/db-form.js +1 -1
- package/dist/esm/components/db-glyph-matrix.d.ts +58 -0
- package/dist/esm/components/db-glyph-matrix.js +1 -0
- package/dist/esm/components/db-icons.d.ts +1 -1
- package/dist/esm/components/db-icons.js +1 -1
- package/dist/esm/components/db-menu-item.d.ts +2 -0
- package/dist/esm/components/db-menu-item.js +1 -1
- package/dist/esm/components/db-modal.d.ts +1 -1
- package/dist/esm/components/db-modal.js +1 -1
- package/dist/esm/components/db-navbar.d.ts +3 -1
- package/dist/esm/components/db-navbar.js +1 -1
- package/dist/esm/components/db-navigation-rail.d.ts +1 -1
- package/dist/esm/components/db-node.d.ts +83 -0
- package/dist/esm/components/db-node.js +1 -0
- package/dist/esm/components/db-notification-dropdown.d.ts +30 -0
- package/dist/esm/components/db-notification-dropdown.js +1 -0
- package/dist/esm/components/db-notification-inbox.d.ts +25 -0
- package/dist/esm/components/db-notification-inbox.js +1 -0
- package/dist/esm/components/db-otp-input.d.ts +1 -1
- package/dist/esm/components/db-phone-verify.d.ts +1 -1
- package/dist/esm/components/db-plan-overview.d.ts +26 -0
- package/dist/esm/components/db-plan-overview.js +1 -0
- package/dist/esm/components/db-popover.js +1 -1
- package/dist/esm/components/db-progressive-blur.d.ts +35 -0
- package/dist/esm/components/db-progressive-blur.js +1 -0
- package/dist/esm/components/db-receipt.d.ts +37 -0
- package/dist/esm/components/db-receipt.js +1 -0
- package/dist/esm/components/db-search-bar.js +1 -1
- package/dist/esm/components/db-segment-control.js +1 -1
- package/dist/esm/components/db-select.js +1 -1
- package/dist/esm/components/db-sidebar.d.ts +14 -1
- package/dist/esm/components/db-sidebar.js +1 -1
- package/dist/esm/components/db-split-view.d.ts +2 -0
- package/dist/esm/components/db-split-view.js +1 -1
- package/dist/esm/components/db-textarea.js +1 -1
- package/dist/esm/components/db-ticket.d.ts +18 -0
- package/dist/esm/components/db-ticket.js +1 -0
- package/dist/esm/components/db-time-picker.d.ts +1 -1
- package/dist/esm/components/db-tool-button.d.ts +57 -0
- package/dist/esm/components/db-tool-button.js +1 -0
- package/dist/esm/components/db-tweet-card.d.ts +101 -0
- package/dist/esm/components/db-tweet-card.js +1 -0
- package/dist/esm/components/db-two-factor.d.ts +1 -1
- package/dist/esm/components/db-voice-control.d.ts +25 -0
- package/dist/esm/components/db-voice-control.js +1 -0
- package/dist/esm/components/db-workspace-invite-modal.d.ts +51 -0
- package/dist/esm/components/db-workspace-invite-modal.js +1 -0
- package/dist/esm/components/db-workspace-members.d.ts +36 -0
- package/dist/esm/components/db-workspace-members.js +1 -0
- package/dist/esm/components/device-mockup-style.js +1 -0
- package/dist/esm/components/flight-route.js +1 -0
- package/dist/esm/components/node-style.js +1 -0
- package/dist/esm/components/paper-card.d.ts +26 -0
- package/dist/esm/components/paper-card.js +1 -0
- package/dist/esm/components/random-gradient-palettes.d.ts +4 -0
- package/dist/esm/core/ai-element.d.ts +47 -0
- package/dist/esm/core/ai-element.js +1 -0
- package/dist/esm/core/credit-ui.js +1 -0
- package/dist/esm/core/i18n.d.ts +153 -0
- package/dist/esm/core/i18n.js +1 -1
- package/dist/esm/core/notification-ui.d.ts +17 -0
- package/dist/esm/core/notification-ui.js +1 -0
- package/dist/esm/helpers/payment-brands.d.ts +56 -0
- package/dist/esm/helpers/payment-brands.js +1 -0
- package/dist/esm/helpers/toast.d.ts +2 -3
- package/dist/esm/index.d.ts +62 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/node_modules/@designbasekorea/ui-contracts/dist/components.js +1 -1
- package/dist/esm/ui-contracts/dist/components.d.d.ts +76 -0
- package/dist/esm/ui-contracts/dist/primitives.d.d.ts +21 -0
- package/dist/index.cjs +1 -1
- package/dist/index.css +1 -1
- package/dist/index.d.ts +2149 -23
- package/dist/index.esm.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +786 -6727
- package/dist/react/index.esm.js +1 -1
- package/package.json +13 -7
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { DbElement } from '../core/base-element.js';
|
|
2
|
+
import './db-badge.js';
|
|
3
|
+
|
|
4
|
+
declare const NODE_VARIANTS: readonly ["default", "compact"];
|
|
5
|
+
declare const NODE_STATUSES: readonly ["idle", "running", "success", "error"];
|
|
6
|
+
type DbNodePortType = 'any' | 'text' | 'image' | 'number' | 'boolean';
|
|
7
|
+
type DbNodePort = {
|
|
8
|
+
id: string;
|
|
9
|
+
label: string;
|
|
10
|
+
type?: DbNodePortType;
|
|
11
|
+
connected?: boolean;
|
|
12
|
+
disabled?: boolean;
|
|
13
|
+
};
|
|
14
|
+
type DbNodePortSelect = {
|
|
15
|
+
nodeId: string;
|
|
16
|
+
portId: string;
|
|
17
|
+
direction: 'input' | 'output';
|
|
18
|
+
type: DbNodePortType;
|
|
19
|
+
};
|
|
20
|
+
type DbNodePortDrag = DbNodePortSelect & {
|
|
21
|
+
clientX: number;
|
|
22
|
+
clientY: number;
|
|
23
|
+
phase: 'start' | 'move' | 'end' | 'cancel';
|
|
24
|
+
};
|
|
25
|
+
type DbNodeMove = {
|
|
26
|
+
nodeId: string;
|
|
27
|
+
deltaX: number;
|
|
28
|
+
deltaY: number;
|
|
29
|
+
phase: 'start' | 'move' | 'end' | 'cancel' | 'keyboard';
|
|
30
|
+
};
|
|
31
|
+
/** A composable workflow node. The consumer owns graph coordinates and connections. */
|
|
32
|
+
declare class DbNode extends DbElement {
|
|
33
|
+
static get observedAttributes(): string[];
|
|
34
|
+
private readonly root;
|
|
35
|
+
private inputPorts;
|
|
36
|
+
private outputPorts;
|
|
37
|
+
private portsDirty;
|
|
38
|
+
private drag;
|
|
39
|
+
private portDrag;
|
|
40
|
+
private suppressPortClick;
|
|
41
|
+
private deleteButton;
|
|
42
|
+
private headingButton;
|
|
43
|
+
private titleEl;
|
|
44
|
+
private iconBox;
|
|
45
|
+
private descriptionEl;
|
|
46
|
+
private statusEl;
|
|
47
|
+
private statusBadge;
|
|
48
|
+
private collapseButton;
|
|
49
|
+
private runButton;
|
|
50
|
+
private body;
|
|
51
|
+
private footer;
|
|
52
|
+
private inputList;
|
|
53
|
+
private outputList;
|
|
54
|
+
get inputs(): DbNodePort[];
|
|
55
|
+
set inputs(value: DbNodePort[]);
|
|
56
|
+
get outputs(): DbNodePort[];
|
|
57
|
+
set outputs(value: DbNodePort[]);
|
|
58
|
+
/** Anchor element for a graph renderer; use its bounding rect to position edges. */
|
|
59
|
+
getPortElement(id: string, direction: 'input' | 'output'): HTMLButtonElement | null;
|
|
60
|
+
connectedCallback(): void;
|
|
61
|
+
disconnectedCallback(): void;
|
|
62
|
+
attributeChangedCallback(name: string): void;
|
|
63
|
+
private normalizePorts;
|
|
64
|
+
private readPorts;
|
|
65
|
+
private nodeId;
|
|
66
|
+
private el;
|
|
67
|
+
private action;
|
|
68
|
+
private build;
|
|
69
|
+
private emitMove;
|
|
70
|
+
private finishDrag;
|
|
71
|
+
private renderPorts;
|
|
72
|
+
private emitPortDrag;
|
|
73
|
+
private cancelPortDrag;
|
|
74
|
+
private sync;
|
|
75
|
+
}
|
|
76
|
+
declare global {
|
|
77
|
+
interface HTMLElementTagNameMap {
|
|
78
|
+
'db-node': DbNode;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export { DbNode, NODE_STATUSES, NODE_VARIANTS };
|
|
83
|
+
export type { DbNodeMove, DbNodePort, DbNodePortDrag, DbNodePortSelect, DbNodePortType };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DbElement as t}from"../core/base-element.js";import{createDbIcon as e}from"./db-icons.js";import"./db-badge.js";import{nodeStyle as i}from"./node-style.js";const s=["default","compact"],n=["idle","running","success","error"],o=new Set(["any","text","image","number","boolean"]),r={any:"일반",text:"텍스트",image:"이미지",number:"숫자",boolean:"조건"},a={idle:"대기",running:"실행 중",success:"완료",error:"오류"};class DbNode extends t{constructor(){super(...arguments),this.root=this.attachShadow({mode:"open"}),this.inputPorts=[],this.outputPorts=[],this.portsDirty=!0,this.drag=null,this.portDrag=null,this.suppressPortClick=!1}static get observedAttributes(){return["node-id","heading","description","icon","variant","status","selected","collapsed","disabled","movable","runnable","collapsible","inputs","outputs","detail","deletable"]}get inputs(){return this.inputPorts.map(t=>({...t}))}set inputs(t){const e=this.normalizePorts(t);JSON.stringify(e)!==JSON.stringify(this.inputPorts)&&(this.inputPorts=e,this.portsDirty=!0,this.sync())}get outputs(){return this.outputPorts.map(t=>({...t}))}set outputs(t){const e=this.normalizePorts(t);JSON.stringify(e)!==JSON.stringify(this.outputPorts)&&(this.outputPorts=e,this.portsDirty=!0,this.sync())}getPortElement(t,e){const i="input"===e?this.inputList:this.outputList;return[...i?.querySelectorAll("button")||[]].find(e=>e.dataset.portId===t)||null}connectedCallback(){this.root.childElementCount||this.build(),this.upgradeProperties(["inputs","outputs"]);for(const t of["inputs","outputs"])this.hasAttribute(t)&&this.readPorts(t);this.sync()}disconnectedCallback(){this.finishDrag("end"),this.cancelPortDrag(),super.disconnectedCallback()}attributeChangedCallback(t){"inputs"!==t&&"outputs"!==t||this.readPorts(t),"disabled"===t&&this.hasAttribute("disabled")&&(this.finishDrag("end"),this.cancelPortDrag()),this.sync()}normalizePorts(t){if(!Array.isArray(t))return[];const e=new Set;return t.filter(t=>t&&"string"==typeof t.id&&t.id&&"string"==typeof t.label&&!e.has(t.id)&&e.add(t.id)).map(t=>({id:t.id,label:t.label,type:o.has(t.type)?t.type:"any",connected:!!t.connected,disabled:!!t.disabled}))}readPorts(t){let e=[];try{e=JSON.parse(this.getAttribute(t)||"[]")}catch{}"inputs"===t?this.inputPorts=this.normalizePorts(e):this.outputPorts=this.normalizePorts(e),this.portsDirty=!0}nodeId(){return this.getAttribute("node-id")||this.id}el(t,e){const i=document.createElement(t);return i.className=e,i}action(t,i){const s=this.el("button","action");return s.type="button",s.setAttribute("aria-label",t),s.title=t,s.append(e(i,16)),s}build(){const t=document.createElement("style");t.textContent=i;const e=this.el("article","frame");e.part.add("frame");const s=this.el("header","header");s.part.add("header"),this.headingButton=this.el("button","heading"),this.headingButton.type="button",this.iconBox=this.el("span","icon"),this.iconBox.setAttribute("aria-hidden","true"),this.titleEl=this.el("span","title"),this.headingButton.append(this.iconBox,this.titleEl),this.statusEl=this.el("span","status"),this.statusEl.setAttribute("role","status"),this.statusBadge=document.createElement("db-badge"),this.statusBadge.setAttribute("size","s"),this.statusBadge.setAttribute("type","outlined"),this.statusEl.append(this.statusBadge);const n=this.el("div","actions"),o=document.createElement("slot");o.name="actions",this.runButton=this.action("노드 실행","play-outline"),this.runButton.classList.add("action--run"),this.collapseButton=this.action("노드 접기","chevron-up"),this.deleteButton=this.action("노드 삭제","close"),this.deleteButton.addEventListener("click",()=>this.dbEmit("delete",{nodeId:this.nodeId()},{cancelable:!0})),n.append(o,this.runButton,this.collapseButton,this.deleteButton),s.append(this.headingButton,this.statusEl,n),this.descriptionEl=this.el("p","description"),this.inputList=this.el("div","ports ports--input"),this.inputList.part.add("inputs"),this.outputList=this.el("div","ports ports--output"),this.outputList.part.add("outputs"),this.body=this.el("div","body"),this.body.part.add("body"),this.body.append(document.createElement("slot")),this.footer=this.el("footer","footer");const r=document.createElement("slot");r.name="footer",this.footer.append(r);this.root.addEventListener("slotchange",()=>{this.body.hidden=this.hasAttribute("collapsed")||!this.body.querySelector("slot").assignedNodes({flatten:!0}).some(t=>1===t.nodeType||!!t.textContent?.trim()),this.footer.hidden=this.hasAttribute("collapsed")||!r.assignedNodes({flatten:!0}).length}),e.append(s,this.descriptionEl,this.inputList,this.body,this.outputList,this.footer),this.root.append(t,e);const isEditor=t=>t.composedPath().some(t=>t instanceof HTMLElement&&(t.isContentEditable||t.matches("input, textarea, db-input, db-textarea, db-markdown-editor")));this.addEventListener("selectstart",t=>{isEditor(t)||t.preventDefault()}),this.addEventListener("dragstart",t=>{isEditor(t)||t.preventDefault()}),this.headingButton.addEventListener("click",()=>{this.hasAttribute("disabled")||this.dbEmit("select",{nodeId:this.nodeId()})}),this.collapseButton.addEventListener("click",()=>{const t=!this.hasAttribute("collapsed");this.toggleAttribute("collapsed",t),this.dbEmit("collapse",{nodeId:this.nodeId(),collapsed:t})}),this.runButton.addEventListener("click",()=>this.dbEmit("run",{nodeId:this.nodeId()},{cancelable:!0})),this.headingButton.addEventListener("pointerdown",t=>{this.hasAttribute("movable")&&!this.hasAttribute("disabled")&&0===t.button&&(this.drag={id:t.pointerId,x:t.clientX,y:t.clientY,lastX:t.clientX,lastY:t.clientY},this.headingButton.setPointerCapture(t.pointerId),this.emitMove("start",0,0))}),this.headingButton.addEventListener("pointermove",t=>{this.drag?.id===t.pointerId&&(this.drag.lastX=t.clientX,this.drag.lastY=t.clientY,this.emitMove("move",t.clientX-this.drag.x,t.clientY-this.drag.y))}),this.headingButton.addEventListener("pointerup",t=>{this.drag?.id===t.pointerId&&(this.drag.lastX=t.clientX,this.drag.lastY=t.clientY,this.finishDrag("end"))}),this.headingButton.addEventListener("pointercancel",()=>this.finishDrag("end")),this.headingButton.addEventListener("lostpointercapture",()=>this.finishDrag("end")),this.headingButton.addEventListener("keydown",t=>{if("Escape"===t.key&&this.drag)return void this.finishDrag("cancel");if(!this.hasAttribute("movable")||this.hasAttribute("disabled"))return;const e={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};if(e[t.key]){t.preventDefault();const[i,s]=e[t.key],n=t.shiftKey?4:16;this.emitMove("keyboard",i*n,s*n)}})}emitMove(t,e,i){this.dbEmit("move",{nodeId:this.nodeId(),deltaX:e,deltaY:i,phase:t})}finishDrag(t){const e=this.drag;e&&(this.drag=null,this.emitMove(t,"cancel"===t?0:e.lastX-e.x,"cancel"===t?0:e.lastY-e.y),this.headingButton.hasPointerCapture(e.id)&&this.headingButton.releasePointerCapture(e.id))}renderPorts(t,e,i){const s=this.root.activeElement,n=s&&t.contains(s)?s.dataset.portId:void 0;this.cancelPortDrag(),t.replaceChildren(),t.hidden=!e.length;for(const s of e){const e=this.el("div","port-row");e.dataset.type=s.type||"any";const n=this.el("button","port");n.type="button",n.part.add("port"),n.dataset.portId=s.id,n.dataset.direction=i,n.disabled=this.hasAttribute("disabled")||!!s.disabled,n.dataset.connected=String(!!s.connected),n.setAttribute("aria-label",`${"input"===i?"입력":"출력"} · ${s.label} · ${r[s.type||"any"]}`),n.setAttribute("aria-pressed",String(!!s.connected));const o=this.el("span","port-dot");n.append(o);const a=this.el("span","port-label");a.textContent=s.label;const d=this.el("span","port-type");d.textContent=r[s.type||"any"];const h={nodeId:this.nodeId(),portId:s.id,direction:i,type:s.type||"any"};n.addEventListener("click",()=>{this.suppressPortClick||this.dbEmit("port-select",h)}),n.addEventListener("pointerdown",t=>{0!==t.button||n.disabled||(this.portDrag={id:t.pointerId,button:n,port:h,x:t.clientX,y:t.clientY,moved:!1},this.suppressPortClick=!1,n.setPointerCapture(t.pointerId))}),n.addEventListener("pointermove",t=>{const e=this.portDrag;e&&e.id===t.pointerId&&(!e.moved&&Math.hypot(t.clientX-e.x,t.clientY-e.y)>=4&&(e.moved=!0,this.suppressPortClick=!0,this.emitPortDrag("start",e.x,e.y)),e.moved&&this.emitPortDrag("move",t.clientX,t.clientY))}),n.addEventListener("pointerup",t=>{this.portDrag?.id===t.pointerId&&(this.portDrag.moved&&this.emitPortDrag("end",t.clientX,t.clientY),this.portDrag=null,n.hasPointerCapture(t.pointerId)&&n.releasePointerCapture(t.pointerId),setTimeout(()=>{this.suppressPortClick=!1},0))}),n.addEventListener("pointercancel",()=>this.cancelPortDrag()),n.addEventListener("lostpointercapture",()=>this.cancelPortDrag()),n.addEventListener("keydown",t=>{"Escape"===t.key&&this.cancelPortDrag()}),e.append(n,a,d),t.append(e)}n&&this.getPortElement(n,i)?.focus({preventScroll:!0})}emitPortDrag(t,e,i){this.portDrag&&this.dbEmit("port-drag",{...this.portDrag.port,phase:t,clientX:e,clientY:i})}cancelPortDrag(){const t=this.portDrag;t&&(t.moved&&this.emitPortDrag("cancel",t.x,t.y),this.portDrag=null,t.button.hasPointerCapture(t.id)&&t.button.releasePointerCapture(t.id))}sync(){if(!this.headingButton)return;const t=this.hasAttribute("disabled"),i=this.hasAttribute("collapsed");this.setAttribute("aria-disabled",String(t)),this.root.querySelector(".frame").inert=t,this.dataset.variant=s.includes(this.getAttribute("variant"))?this.getAttribute("variant"):"default";const o=n.find(t=>t===this.getAttribute("status"))||"idle";this.dataset.status=o,this.titleEl.textContent=this.getAttribute("heading")||"새 노드",this.headingButton.disabled=t,this.headingButton.setAttribute("aria-pressed",String(this.hasAttribute("selected"))),this.headingButton.title=this.hasAttribute("movable")?"드래그 또는 방향키로 이동":"노드 선택";const r=this.getAttribute("icon");if(this.iconBox.hidden=!r,r?this.iconBox.replaceChildren(e(r,16)):this.iconBox.replaceChildren(),this.descriptionEl.textContent=this.getAttribute("description")||"",this.descriptionEl.hidden=i||!this.descriptionEl.textContent,this.statusBadge.textContent=a[o],this.statusBadge.setAttribute("variant","error"===o?"danger":"success"===o?"success":"info"),this.statusEl.hidden="idle"===o,this.collapseButton.hidden=!this.hasAttribute("collapsible"),this.collapseButton.disabled=t,this.collapseButton.setAttribute("aria-expanded",String(!i)),this.collapseButton.setAttribute("aria-label",i?"노드 펼치기":"노드 접기"),this.collapseButton.title=i?"노드 펼치기":"노드 접기",this.collapseButton.replaceChildren(e(i?"chevron-down":"chevron-up",16)),this.deleteButton.hidden=!this.hasAttribute("deletable"),this.deleteButton.disabled=t,this.runButton.hidden=!this.hasAttribute("runnable"),this.runButton.disabled=t||"running"===o,this.body.hidden=i||!this.body.querySelector("slot").assignedNodes({flatten:!0}).some(t=>1===t.nodeType||!!t.textContent?.trim()),this.footer.hidden=i||!this.footer.querySelector("slot").assignedNodes({flatten:!0}).length,this.portsDirty)this.renderPorts(this.inputList,this.inputPorts,"input"),this.renderPorts(this.outputList,this.outputPorts,"output"),this.portsDirty=!1;else for(const e of[this.inputList,this.outputList])for(const i of e.querySelectorAll("button")){const s=e===this.inputList?this.inputPorts:this.outputPorts;i.disabled=t||!!s.find(t=>t.id===i.dataset.portId)?.disabled}}}customElements.get("db-node")||customElements.define("db-node",DbNode);export{DbNode,n as NODE_STATUSES,s as NODE_VARIANTS};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { DbElement } from '../core/base-element.js';
|
|
2
|
+
import { DbNotificationItem } from '../core/notification-ui.js';
|
|
3
|
+
import './db-badge.js';
|
|
4
|
+
import './db-notification-inbox.js';
|
|
5
|
+
|
|
6
|
+
/** Header wrapper around the same controlled inbox. Native Popover preserves listeners and focus. */
|
|
7
|
+
declare class DbNotificationDropdown extends DbElement {
|
|
8
|
+
private trigger?;
|
|
9
|
+
private panel?;
|
|
10
|
+
private inbox?;
|
|
11
|
+
private itemData;
|
|
12
|
+
private readonly panelId;
|
|
13
|
+
static get observedAttributes(): string[];
|
|
14
|
+
get notifications(): DbNotificationItem[];
|
|
15
|
+
set notifications(value: DbNotificationItem[]);
|
|
16
|
+
get open(): boolean;
|
|
17
|
+
set open(value: boolean);
|
|
18
|
+
connectedCallback(): void;
|
|
19
|
+
disconnectedCallback(): void;
|
|
20
|
+
attributeChangedCallback(): void;
|
|
21
|
+
private sync;
|
|
22
|
+
private position;
|
|
23
|
+
}
|
|
24
|
+
declare global {
|
|
25
|
+
interface HTMLElementTagNameMap {
|
|
26
|
+
'db-notification-dropdown': DbNotificationDropdown;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export { DbNotificationDropdown };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DbElement as t}from"../core/base-element.js";import{creditAction as i,creditNumber as e}from"../core/credit-ui.js";import{parseNotifications as n}from"../core/notification-ui.js";import{dbUid as s}from"../core/uid.js";import{t as o}from"../core/i18n.js";import{createDbIcon as a}from"./db-icons.js";import"./db-badge.js";import"./db-notification-inbox.js";class DbNotificationDropdown extends t{constructor(){super(...arguments),this.itemData=[],this.panelId=s("notification-dropdown")}static get observedAttributes(){return["open","label","unread-count","loading","pending","error","disabled"]}get notifications(){return this.itemData.map(t=>({...t}))}set notifications(t){this.itemData=n(t),this.isConnected&&this.sync()}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(t){this.toggleAttribute("open",t)}connectedCallback(){this.upgradeProperties(["notifications","open"]),this.panel||(this.classList.add("designbase-wc-notification-dropdown"),this.trigger=i("notification-toggle","",!1),this.trigger.setAttribute("aria-haspopup","dialog"),this.trigger.setAttribute("aria-controls",this.panelId),this.panel=document.createElement("div"),this.panel.id=this.panelId,this.panel.popover="auto",this.panel.className="designbase-wc-notification-dropdown__panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-modal","false"),this.inbox=document.createElement("db-notification-inbox"),this.panel.append(this.inbox),this.append(this.trigger,this.panel)),this.cleanups.listen(this.trigger,"db-click",()=>{this.hasAttribute("disabled")||(this.open=!this.open)}),this.cleanups.listen(this.trigger,"keydown",t=>{"ArrowDown"!==t.key||this.hasAttribute("disabled")||(t.preventDefault(),this.open=!0)}),this.cleanups.listen(this.panel,"toggle",()=>{const t=this.panel.matches(":popover-open");t!==this.open&&this.toggleAttribute("open",t),this.trigger.setAttribute("aria-expanded",String(t)),this.dbEmit("open-change",{open:t})}),this.cleanups.listen(this.inbox,"db-notification-open",()=>{this.open=!1,this.trigger?.focus()}),this.cleanups.listen(document,"focusin",t=>{this.open&&t.target instanceof Node&&!this.contains(t.target)&&(this.open=!1)}),this.cleanups.listen(window,"resize",()=>this.position()),this.cleanups.listen(window,"scroll",()=>this.position(),{capture:!0,passive:!0}),this.sync()}disconnectedCallback(){this.panel?.matches(":popover-open")&&this.panel.hidePopover(),super.disconnectedCallback()}attributeChangedCallback(){this.isConnected&&this.sync()}sync(){if(!this.trigger||!this.panel||!this.inbox)return;const t=this.getAttribute("label")||o("notification.title"),i=this.hasAttribute("unread-count")?e(this.getAttribute("unread-count")):this.itemData.filter(t=>t.unread).length;if(this.trigger.replaceChildren(a("bell-active",18)),null===i||i>0){const t=document.createElement("db-badge");t.setAttribute("variant","primary"),t.setAttribute("type",null===i?"text":"number"),t.setAttribute("size","s"),null===i?t.textContent="—":t.setAttribute("count",String(i)),t.setAttribute("aria-hidden","true"),this.trigger.append(t)}this.trigger.setAttribute("aria-label",`${t} · ${o("notification.unread")} ${null===i?o("notification.countUnknown"):i}`),this.trigger.setAttribute("aria-expanded",String(this.open)),this.trigger.toggleAttribute("disabled",this.hasAttribute("disabled")),this.panel.setAttribute("aria-label",t),this.inbox.notifications=this.itemData;for(const t of["label","loading","pending","error","disabled"]){const i=this.getAttribute(t);null===i?this.inbox.removeAttribute(t):this.inbox.getAttribute(t)!==i&&this.inbox.setAttribute(t,i)}this.open&&!this.hasAttribute("disabled")?this.panel.matches(":popover-open")||(this.panel.showPopover(),this.position(),this.inbox.querySelector("db-button:not([disabled])")?.focus()):this.panel.matches(":popover-open")&&this.panel.hidePopover(),this.position()}position(){if(!this.panel?.matches(":popover-open")||!this.trigger)return;const t=this.trigger.getBoundingClientRect();this.panel.style.left=`${Math.max(8,Math.min(t.right-this.panel.offsetWidth,innerWidth-this.panel.offsetWidth-8))}px`,this.panel.style.top=`${Math.max(8,Math.min(t.bottom+8,innerHeight-this.panel.offsetHeight-8))}px`}}customElements.get("db-notification-dropdown")||customElements.define("db-notification-dropdown",DbNotificationDropdown);export{DbNotificationDropdown};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DbElement } from '../core/base-element.js';
|
|
2
|
+
import { DbNotificationItem } from '../core/notification-ui.js';
|
|
3
|
+
export { DbNotificationAction, DbNotificationReadAll } from '../core/notification-ui.js';
|
|
4
|
+
import './db-button.js';
|
|
5
|
+
|
|
6
|
+
/** Controlled data, local filter. The app confirms read state; opening never marks an item read implicitly. */
|
|
7
|
+
declare class DbNotificationInbox extends DbElement {
|
|
8
|
+
private itemData;
|
|
9
|
+
private filter;
|
|
10
|
+
private restoreFocus;
|
|
11
|
+
static get observedAttributes(): string[];
|
|
12
|
+
get notifications(): DbNotificationItem[];
|
|
13
|
+
set notifications(value: DbNotificationItem[]);
|
|
14
|
+
connectedCallback(): void;
|
|
15
|
+
attributeChangedCallback(): void;
|
|
16
|
+
private blocked;
|
|
17
|
+
private render;
|
|
18
|
+
}
|
|
19
|
+
declare global {
|
|
20
|
+
interface HTMLElementTagNameMap {
|
|
21
|
+
'db-notification-inbox': DbNotificationInbox;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { DbNotificationInbox, DbNotificationItem };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DbElement as t}from"../core/base-element.js";import{textNode as i,creditAction as e,replaceView as n}from"../core/credit-ui.js";import{parseNotifications as a}from"../core/notification-ui.js";import{t as o}from"../core/i18n.js";import"./db-button.js";class DbNotificationInbox extends t{constructor(){super(...arguments),this.itemData=[],this.filter="all",this.restoreFocus=!1}static get observedAttributes(){return["label","loading","pending","error","disabled"]}get notifications(){return this.itemData.map(t=>({...t}))}set notifications(t){this.itemData=a(t),this.isConnected&&this.render()}connectedCallback(){this.upgradeProperties(["notifications"]),this.cleanups.listen(this,"db-click",t=>{if(!(t.target instanceof HTMLElement)||this.blocked())return;const i=t.target.dataset.action;if("notification-filter:all"===i||"notification-filter:unread"===i)return this.filter=i.endsWith(":unread")?"unread":"all",void this.render();if("notification-retry"===i)return void this.dbEmit("retry");if(this.hasAttribute("error"))return;if("notification-read-all"===i){const t=this.itemData.filter(t=>t.unread).map(t=>t.id);t.length&&(this.restoreFocus=!0,this.dbEmit("read-all",{ids:t}))}const e=t.target.dataset.notificationId,n=this.itemData.find(t=>t.id===e);n&&(i===`notification-open:${n.id}`&&this.dbEmit("notification-open",{id:n.id}),i===`notification-read:${n.id}`&&n.unread&&(this.restoreFocus=!0,this.dbEmit("read",{id:n.id})))}),this.render()}attributeChangedCallback(){this.isConnected&&this.render()}blocked(){return this.hasAttribute("disabled")||this.hasAttribute("loading")||this.hasAttribute("pending")}render(){const t="designbase-wc-notification-inbox";this.classList.add(t),this.setAttribute("aria-busy",String(this.hasAttribute("loading")||this.hasAttribute("pending")));const a=this.contains(document.activeElement),s=i("h3",`${t}__title`,this.getAttribute("label")||o("notification.title"));s.tabIndex=-1,s.dataset.action="notification-heading";const r=i("div",`${t}__controls`,"");r.setAttribute("aria-label",o("notification.filters"));for(const t of["all","unread"]){const i=e(`notification-filter:${t}`,o(`notification.${t}`),this.blocked());i.setAttribute("aria-pressed",String(this.filter===t)),i.setAttribute("variant",this.filter===t?"primary":"tertiary"),r.append(i)}const c=e("notification-read-all",o("notification.readAll"),this.blocked()||this.hasAttribute("error")||!this.itemData.some(t=>t.unread));c.setAttribute("variant","tertiary"),r.append(c);const d=[s,r],l=this.getAttribute("error");if(l){const n=i("p",`${t}__message`,l);n.setAttribute("role","alert"),d.push(n,e("notification-retry",o("notification.retry"),this.blocked()))}if(this.hasAttribute("loading")){const e=i("p",`${t}__message`,o("loading"));e.setAttribute("role","status"),d.push(e)}else{const n=this.itemData.filter(t=>"all"===this.filter||t.unread);if(n.length){const a=i("ul",`${t}__list`,"");for(const s of n){const n=i("li",`${t}__item`,"");n.dataset.unread=String(s.unread);const r=i("div",`${t}__meta`,"");s.unread&&r.append(i("span",`${t}__unread`,o("notification.unread"))),s.categoryLabel&&r.append(i("span","",s.categoryLabel)),r.append(i("span","",s.dateLabel));const c=e(`notification-open:${s.id}`,s.title,this.blocked()||!!l);if(c.dataset.notificationId=s.id,c.classList.add(`${t}__open`),c.setAttribute("variant","ghost"),n.append(r,c,i("p",`${t}__description`,s.description)),s.unread){const t=e(`notification-read:${s.id}`,o("notification.markRead"),this.blocked()||!!l);t.dataset.notificationId=s.id,t.setAttribute("variant","tertiary"),n.append(t)}a.append(n)}d.push(a)}else{const e=i("p",`${t}__empty`,o("unread"===this.filter?"notification.caughtUp":"notification.empty"));e.setAttribute("role","status"),d.push(e)}}const h=this.restoreFocus&&this.checkVisibility()&&(document.activeElement===document.body||this.contains(document.activeElement));if(n(this,...d),h||a&&!this.contains(document.activeElement)){const t=this.blocked()?"notification-heading":`notification-filter:${this.filter}`;this.querySelector(`[data-action="${t}"]`)?.focus()}this.restoreFocus=!1}}customElements.get("db-notification-inbox")||customElements.define("db-notification-inbox",DbNotificationInbox);export{DbNotificationInbox};
|
|
@@ -2,7 +2,7 @@ import './db-button.js';
|
|
|
2
2
|
import './db-input.js';
|
|
3
3
|
import './db-otp-input.js';
|
|
4
4
|
import './db-select.js';
|
|
5
|
-
import { PHONE_VERIFY_SIZES } from '
|
|
5
|
+
import { PHONE_VERIFY_SIZES } from '../ui-contracts/dist/components.d.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* ui-wc — db-phone-verify (수동 작성, 자동 동기화 대상 아님)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { DbElement } from '../core/base-element.js';
|
|
2
|
+
import './db-button.js';
|
|
3
|
+
|
|
4
|
+
interface DbPlanFeature {
|
|
5
|
+
id: string;
|
|
6
|
+
label: string;
|
|
7
|
+
allowed: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** Presentation of server-supplied entitlements. Never grants access or changes subscriptions. */
|
|
10
|
+
declare class DbPlanOverview extends DbElement {
|
|
11
|
+
private featureData;
|
|
12
|
+
static get observedAttributes(): string[];
|
|
13
|
+
get features(): DbPlanFeature[];
|
|
14
|
+
set features(value: DbPlanFeature[]);
|
|
15
|
+
connectedCallback(): void;
|
|
16
|
+
attributeChangedCallback(): void;
|
|
17
|
+
private render;
|
|
18
|
+
}
|
|
19
|
+
declare global {
|
|
20
|
+
interface HTMLElementTagNameMap {
|
|
21
|
+
'db-plan-overview': DbPlanOverview;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { DbPlanOverview };
|
|
26
|
+
export type { DbPlanFeature };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DbElement as t}from"../core/base-element.js";import{textNode as e,creditAction as a,replaceView as i,creditNumber as s,creditText as r}from"../core/credit-ui.js";import{t as n}from"../core/i18n.js";import"./db-button.js";class DbPlanOverview extends t{constructor(){super(...arguments),this.featureData=[]}static get observedAttributes(){return["name","price-label","period-label","used","limit","unit","label","manage-label","loading","error","disabled"]}get features(){return this.featureData.map(t=>({...t}))}set features(t){const e=new Set;this.featureData=Array.isArray(t)?t.filter(t=>!(!t||"string"!=typeof t.id||!t.id||e.has(t.id)||"string"!=typeof t.label||"boolean"!=typeof t.allowed)&&(e.add(t.id),!0)).map(t=>({...t})):[],this.isConnected&&this.render()}connectedCallback(){this.upgradeProperties(["features"]),this.cleanups.listen(this,"db-click",t=>{if(!(t.target instanceof HTMLElement))return;if(this.hasAttribute("loading")||this.hasAttribute("disabled"))return;const e=t.target.dataset.action;"retry"===e&&this.dbEmit("retry"),"manage"!==e||this.hasAttribute("error")||this.dbEmit("manage")}),this.render()}attributeChangedCallback(){this.isConnected&&this.render()}render(){const t="designbase-wc-plan-overview";this.classList.add(t);const l=this.hasAttribute("loading"),o=this.getAttribute("error");this.setAttribute("aria-busy",String(l));const d=e("div",`${t}__header`,"");d.append(e("h3",`${t}__label`,this.getAttribute("label")||n("plan.current")));const u=[d];if(l||o){const s=e("p",`${t}__message`,l?n("loading"):o||"");return s.setAttribute("role",l?"status":"alert"),u.push(s),l||u.push(a("retry",n("plan.retry"),this.hasAttribute("disabled"))),void i(this,...u)}const b=e("strong",`${t}__name`,this.getAttribute("name")||"—"),p=e("p",`${t}__price`,this.getAttribute("price-label")||"");this.hasAttribute("period-label")&&p.append(e("span","",` / ${this.getAttribute("period-label")}`)),u.push(b,p);const h=s(this.getAttribute("used")),c=s(this.getAttribute("limit")),g=e("div",`${t}__usage`,"");if(g.append(e("span","",`${n("plan.usage")} ${r(h)} / ${r(c)} ${this.getAttribute("unit")||n("credits.unit")}`)),null!==h&&null!==c&&c>0){const t=document.createElement("progress");t.max=c,t.value=Math.min(h,c),t.setAttribute("aria-label",n("plan.usage")),g.append(t)}u.push(g);const m=e("ul",`${t}__features`,"");for(const a of this.featureData){const i=e("li","","");i.dataset.allowed=String(a.allowed),i.append(e("span","",a.label),e("span",`${t}__permission`,n(a.allowed?"plan.allowed":"plan.locked"))),m.append(i)}u.push(m),this.hasAttribute("manage-label")&&u.push(a("manage",this.getAttribute("manage-label")||n("plan.manage"),this.hasAttribute("disabled"))),i(this,...u)}}customElements.get("db-plan-overview")||customElements.define("db-plan-overview",DbPlanOverview);export{DbPlanOverview};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{POPOVER_PLACEMENTS as e,POPOVER_TRIGGERS as t}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbPopover extends HTMLElement{constructor(){super(...arguments),this.onDocMouseDown=null,this.onDocKeyDown=null,this.onExternalTriggerClick=null,this.handleTriggerClick=e=>{"click"===this.resolvedTrigger()&&(e.preventDefault(),e.stopPropagation(),this.setOpen(!this.isOpen()))},this.handleTriggerMouseEnter=()=>{"hover"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerMouseLeave=()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()},this.handleTriggerFocus=()=>{"focus"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerBlur=()=>{"focus"===this.resolvedTrigger()&&this.scheduleClose()},this.handleReposition=()=>{this.isOpen()&&(this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.repositionRaf=requestAnimationFrame(()=>{this.positionPanel(),this.repositionRaf=void 0}))}}static get observedAttributes(){return["open","placement","position","title","content","size","variant","trigger","delay","hide-delay","always-show","disabled","max-width","show-arrow","close-on-outside-click","close-on-escape","trigger-id"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(e){e?this.setAttribute("open",""):this.removeAttribute("open")}connectedCallback(){this.classList.add("designbase-wc-popover-host"),this.hasAttribute("placement")||this.hasAttribute("position")||this.setAttribute("placement","top"),this.render(),this.childObserver=new MutationObserver(()=>this.render()),this.childObserver.observe(this,{childList:!0}),this.bindExternalTrigger(),this.attachGlobalListeners(),this.syncOpenFromAttributes()}disconnectedCallback(){this.childObserver?.disconnect(),this.clearTimers(),this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.unbindExternalTrigger(),this.detachGlobalListeners(),this.removePanel()}attributeChangedCallback(e){this.isConnected&&("trigger-id"===e&&(this.unbindExternalTrigger(),this.bindExternalTrigger()),"open"!==e&&"always-show"!==e&&"disabled"!==e?("content"===e&&this.bodyEl&&(this.bodyEl.textContent=this.getAttribute("content")||""),this.isOpen()&&(this.updatePanelMetadata(),requestAnimationFrame(()=>this.positionPanel()))):this.syncOpenFromAttributes())}resolvedPlacement(){const t=this.getAttribute("position")||this.getAttribute("placement")||"top";return e.includes(t)?t:"top"}resolvedTrigger(){const e=this.getAttribute("trigger")||"click";return t.includes(e)?e:"click"}isControlled(){return this.hasAttribute("open")}isOpen(){return!this.hasAttribute("disabled")&&(!!this.hasAttribute("always-show")||(this.isControlled()?"false"!==this.getAttribute("open"):this.panel?.classList.contains("designbase-wc-popover--visible")??!1))}setOpen(e){this.hasAttribute("disabled")||this.hasAttribute("always-show")||(this.isControlled()?e?this.setAttribute("open",""):this.removeAttribute("open"):e?this.showPanel():this.hidePanel(),this.dispatchEvent(new CustomEvent("db-open-change",{bubbles:!0,composed:!0,detail:{open:e}})),e||this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0})))}syncOpenFromAttributes(){this.hasAttribute("always-show")?this.showPanel():this.isControlled()&&("false"!==this.getAttribute("open")?this.showPanel():this.hidePanel())}clearTimers(){this.showTimer&&clearTimeout(this.showTimer),this.hideTimer&&clearTimeout(this.hideTimer),this.showTimer=void 0,this.hideTimer=void 0}groupOf(e){return e.startsWith("top")?"top":e.startsWith("bottom")?"bottom":e.startsWith("left")?"left":"right"}collectTriggerChildren(){const isInternalNode=e=>e.hasAttribute("data-wc-internal")||e===this.triggerWrap,e=Array.from(this.children).filter(e=>!isInternalNode(e));return e.length>0?e:Array.from(this.triggerWrap?.children||[])}ensureTriggerWrap(){this.triggerWrap||(this.triggerWrap=document.createElement("span"),this.triggerWrap.className="designbase-wc-popover__trigger",this.triggerWrap.setAttribute("data-wc-internal",""),this.triggerWrap.tabIndex=0,this.triggerWrap.addEventListener("click",this.handleTriggerClick),this.triggerWrap.addEventListener("mouseenter",this.handleTriggerMouseEnter),this.triggerWrap.addEventListener("mouseleave",this.handleTriggerMouseLeave),this.triggerWrap.addEventListener("focus",this.handleTriggerFocus),this.triggerWrap.addEventListener("blur",this.handleTriggerBlur))}mountTriggerChildren(e){this.triggerWrap&&e.forEach(e=>{e.parentElement!==this.triggerWrap&&this.triggerWrap.append(e)})}collectBodyChildren(){return Array.from(this.querySelectorAll('[slot="content"]'))}bindExternalTrigger(){const e=this.getAttribute("trigger-id");e&&(this.triggerEl=document.getElementById(e),this.triggerEl&&(this.onExternalTriggerClick=()=>{"click"===this.resolvedTrigger()&&this.setOpen(!this.isOpen())},this.triggerEl.addEventListener("click",this.onExternalTriggerClick)))}unbindExternalTrigger(){this.triggerEl&&this.onExternalTriggerClick&&this.triggerEl.removeEventListener("click",this.onExternalTriggerClick),this.triggerEl=null,this.onExternalTriggerClick=null}attachGlobalListeners(){this.onDocMouseDown=e=>{if(!this.isOpen()||"false"===this.getAttribute("close-on-outside-click"))return;const t=e.target;this.panel?.contains(t)||this.triggerWrap?.contains(t)||this.triggerEl?.contains(t)||this.setOpen(!1)},this.onDocKeyDown=e=>{"Escape"===e.key&&this.isOpen()&&"false"!==this.getAttribute("close-on-escape")&&this.setOpen(!1)},document.addEventListener("mousedown",this.onDocMouseDown),document.addEventListener("keydown",this.onDocKeyDown)}detachGlobalListeners(){this.onDocMouseDown&&document.removeEventListener("mousedown",this.onDocMouseDown),this.onDocKeyDown&&document.removeEventListener("keydown",this.onDocKeyDown),this.onDocMouseDown=null,this.onDocKeyDown=null}scheduleOpen(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("delay")||0)):0;this.showTimer=setTimeout(()=>this.showPanel(),e)}scheduleClose(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("hide-delay")||80)):0;this.hideTimer=setTimeout(()=>this.setOpen(!1),e)}getTriggerRect(){const e=this.triggerEl||this.triggerWrap;return e?.getBoundingClientRect()}flipPlacementIfNeeded(e,t,i){const s=window.innerHeight,r=window.innerWidth,o=this.groupOf(e),n=t.top-i.height-8>=8,a=t.bottom+8+i.height<=s-8,h=t.left-i.width-8>=8,l=t.right+8+i.width<=r-8;return"top"===o&&!n&&a?e.replace(/^top/,"bottom"):"bottom"===o&&!a&&n?e.replace(/^bottom/,"top"):"left"===o&&!h&&l?e.replace(/^left/,"right"):"right"===o&&!l&&h?e.replace(/^right/,"left"):e}applyCoords(e,t,i){let s=0,r=0,o=0,n=0;const a=i.height,h=i.width,l=16;switch(e){case"top":s=t.top-i.height-8,r=t.left+t.width/2-i.width/2,o=a-5,n=h/2-5;break;case"top-start":s=t.top-i.height-8,r=t.left,o=a-5,n=11;break;case"top-end":s=t.top-i.height-8,r=t.right-i.width,o=a-5,n=h-l-5;break;case"bottom":s=t.bottom+8,r=t.left+t.width/2-i.width/2,o=-5,n=h/2-5;break;case"bottom-start":s=t.bottom+8,r=t.left,o=-5,n=11;break;case"bottom-end":s=t.bottom+8,r=t.right-i.width,o=-5,n=h-l-5;break;case"left":s=t.top+t.height/2-i.height/2,r=t.left-i.width-8,o=a/2-5,n=h-5;break;case"left-start":s=t.top,r=t.left-i.width-8,o=11,n=h-5;break;case"left-end":s=t.bottom-i.height,r=t.left-i.width-8,o=a-l-5,n=h-5;break;case"right":s=t.top+t.height/2-i.height/2,r=t.right+8,o=a/2-5,n=-5;break;case"right-start":s=t.top,r=t.right+8,o=11,n=-5;break;case"right-end":s=t.bottom-i.height,r=t.right+8,o=a-l-5,n=-5}const d=window.innerWidth,c=window.innerHeight;return r<8&&(r=8),r+i.width>d-8&&(r=d-i.width-8),s<8&&(s=8),s+i.height>c-8&&(s=c-i.height-8),{top:s,left:r,aTop:o,aLeft:n,placement:e}}positionPanel(){if(!this.panel)return;const t=this.getTriggerRect();if(!t)return;const i=Number(this.getAttribute("max-width")||300);this.panel.style.maxWidth=`${i}px`,this.panel.offsetHeight;const s=this.panel.getBoundingClientRect(),r=this.resolvedPlacement(),o=this.flipPlacementIfNeeded(r,t,s),{top:n,left:a,aTop:h,aLeft:l}=this.applyCoords(o,t,s);this.panel.style.top=`${n}px`,this.panel.style.left=`${a}px`,this.panel.dataset.placementGroup=this.groupOf(o),e.forEach(e=>{this.panel.classList.toggle(`designbase-wc-popover--${e}`,e===o)}),this.arrowEl&&(this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${o}`,this.arrowEl.style.top=`${h}px`,this.arrowEl.style.left=`${l}px`)}revealPanel(){this.panel&&(this.panel.classList.remove("designbase-wc-popover--visible"),this.positionPanel(),this.panel.offsetHeight,this.positionPanel(),this.panel.classList.add("designbase-wc-popover--visible"))}updatePanelMetadata(){if(!this.panel)return;const e=this.getAttribute("size")||"m",t=this.getAttribute("variant")||"default",i=this.resolvedPlacement();this.panel.className=["designbase-wc-popover",`designbase-wc-popover--${e}`,`designbase-wc-popover--${t}`,`designbase-wc-popover--${i}`,this.isOpen()?"designbase-wc-popover--visible":"",this.hasAttribute("disabled")?"designbase-wc-popover--disabled":""].filter(Boolean).join(" ")}ensurePanel(){if(this.panel)return;const e=document.createElement("div");e.className="designbase-wc-popover",e.setAttribute("data-wc-internal",""),e.setAttribute("role","dialog"),e.setAttribute("aria-modal","false"),e.style.position="fixed",e.style.zIndex="9999";const t=document.createElement("div");t.className="designbase-wc-popover__content";const i=document.createElement("div");i.className="designbase-wc-popover__header";const s=document.createElement("h3");s.className="designbase-wc-popover__title";const r=document.createElement("db-button");r.className="designbase-wc-popover__close-button",r.setAttribute("variant","ghost"),r.setAttribute("size","s"),r.setAttribute("icon-only",""),r.setAttribute("start-icon","close"),r.setAttribute("aria-label","팝오버 닫기"),r.addEventListener("db-click",e=>{e.stopPropagation(),this.setOpen(!1)}),i.append(s,r),this.bodyEl=document.createElement("div"),this.bodyEl.className="designbase-wc-popover__body",t.append(i,this.bodyEl),e.append(t),"false"!==this.getAttribute("show-arrow")&&(this.arrowEl=document.createElement("div"),this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${this.resolvedPlacement()}`,e.append(this.arrowEl)),this.panel=e,this.panel.querySelector(".designbase-wc-popover__title").textContent=this.getAttribute("title")||"",this.panel.querySelector(".designbase-wc-popover__title").hidden=!this.getAttribute("title"),document.body.append(e),e.addEventListener("mouseenter",()=>{"hover"===this.resolvedTrigger()&&this.clearTimers()}),e.addEventListener("mouseleave",()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()})}showPanel(){if(this.hasAttribute("disabled"))return;this.ensurePanel(),this.updatePanelMetadata();const e=this.collectBodyChildren();e.length>0?this.bodyEl.replaceChildren(...e.map(e=>e.cloneNode(!0))):this.bodyEl.textContent=this.getAttribute("content")||"";const t=this.panel.querySelector(".designbase-wc-popover__title");t.textContent=this.getAttribute("title")||"",t.hidden=!this.getAttribute("title"),requestAnimationFrame(()=>{this.revealPanel(),window.addEventListener("scroll",this.handleReposition,{capture:!0,passive:!0}),window.addEventListener("resize",this.handleReposition)})}hidePanel(){this.panel?.classList.remove("designbase-wc-popover--visible"),window.removeEventListener("scroll",this.handleReposition,!0),window.removeEventListener("resize",this.handleReposition),this.hasAttribute("always-show")||this.removePanel()}removePanel(){this.panel?.remove(),this.panel=void 0,this.bodyEl=void 0,this.arrowEl=void 0}render(){this.ensureTriggerWrap();const e=this.collectTriggerChildren();this.mountTriggerChildren(e);const t=Boolean(this.getAttribute("trigger-id"));this.triggerWrap&&(e.length>0||!t?this.triggerWrap.parentElement!==this&&this.append(this.triggerWrap):this.triggerWrap.parentElement===this&&this.triggerWrap.remove()),this.hasAttribute("always-show")&&this.showPanel()}}customElements.get("db-popover")||customElements.define("db-popover",DbPopover);export{DbPopover};
|
|
1
|
+
import{POPOVER_PLACEMENTS as e,POPOVER_TRIGGERS as t}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbPopover extends HTMLElement{constructor(){super(...arguments),this.onDocMouseDown=null,this.onDocKeyDown=null,this.onExternalTriggerClick=null,this.handleTriggerClick=e=>{"click"===this.resolvedTrigger()&&(e.preventDefault(),e.stopPropagation(),this.setOpen(!this.isOpen()))},this.handleTriggerMouseEnter=()=>{"hover"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerMouseLeave=()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()},this.handleTriggerFocus=()=>{"focus"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerBlur=()=>{"focus"===this.resolvedTrigger()&&this.scheduleClose()},this.handleReposition=()=>{this.isOpen()&&(this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.repositionRaf=requestAnimationFrame(()=>{this.positionPanel(),this.repositionRaf=void 0}))}}static get observedAttributes(){return["open","placement","position","title","content","size","variant","trigger","delay","hide-delay","always-show","disabled","max-width","show-arrow","close-on-outside-click","close-on-escape","trigger-id"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(e){e?this.setAttribute("open",""):this.removeAttribute("open")}connectedCallback(){this.classList.add("designbase-wc-popover-host"),this.hasAttribute("placement")||this.hasAttribute("position")||this.setAttribute("placement","top"),this.render(),this.childObserver=new MutationObserver(()=>this.render()),this.childObserver.observe(this,{childList:!0}),this.bindExternalTrigger(),this.attachGlobalListeners(),this.syncOpenFromAttributes()}disconnectedCallback(){this.childObserver?.disconnect(),this.clearTimers(),this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.unbindExternalTrigger(),this.detachGlobalListeners(),this.removePanel()}attributeChangedCallback(e){this.isConnected&&("trigger-id"===e&&(this.unbindExternalTrigger(),this.bindExternalTrigger()),"open"!==e&&"always-show"!==e&&"disabled"!==e?("content"===e&&this.bodyEl&&(this.bodyEl.textContent=this.getAttribute("content")||""),this.isOpen()&&(this.updatePanelMetadata(),requestAnimationFrame(()=>this.positionPanel()))):this.syncOpenFromAttributes())}resolvedPlacement(){const t=this.getAttribute("position")||this.getAttribute("placement")||"top";return e.includes(t)?t:"top"}resolvedTrigger(){const e=this.getAttribute("trigger")||"click";return t.includes(e)?e:"click"}isControlled(){return this.hasAttribute("open")}isOpen(){return!this.hasAttribute("disabled")&&(!!this.hasAttribute("always-show")||(this.isControlled()?"false"!==this.getAttribute("open"):this.panel?.classList.contains("designbase-wc-popover--visible")??!1))}setOpen(e){this.hasAttribute("disabled")||this.hasAttribute("always-show")||(this.isControlled()?e?this.setAttribute("open",""):this.removeAttribute("open"):e?this.showPanel():this.hidePanel(),this.dispatchEvent(new CustomEvent("db-open-change",{bubbles:!0,composed:!0,detail:{open:e}})),e||this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0})))}syncOpenFromAttributes(){this.hasAttribute("always-show")?this.showPanel():this.isControlled()&&("false"!==this.getAttribute("open")?this.showPanel():this.hidePanel())}clearTimers(){this.showTimer&&clearTimeout(this.showTimer),this.hideTimer&&clearTimeout(this.hideTimer),this.showTimer=void 0,this.hideTimer=void 0}groupOf(e){return e.startsWith("top")?"top":e.startsWith("bottom")?"bottom":e.startsWith("left")?"left":"right"}collectTriggerChildren(){const isInternalNode=e=>e.hasAttribute("data-wc-internal")||"content"===e.getAttribute("slot")||e===this.triggerWrap,e=Array.from(this.children).filter(e=>!isInternalNode(e));return e.length>0?e:Array.from(this.triggerWrap?.children||[]).filter(e=>"content"!==e.getAttribute("slot"))}ensureTriggerWrap(){this.triggerWrap||(this.triggerWrap=document.createElement("span"),this.triggerWrap.className="designbase-wc-popover__trigger",this.triggerWrap.setAttribute("data-wc-internal",""),this.triggerWrap.tabIndex=this.hasAttribute("trigger-id")?-1:0,this.triggerWrap.addEventListener("click",this.handleTriggerClick),this.triggerWrap.addEventListener("mouseenter",this.handleTriggerMouseEnter),this.triggerWrap.addEventListener("mouseleave",this.handleTriggerMouseLeave),this.triggerWrap.addEventListener("focus",this.handleTriggerFocus),this.triggerWrap.addEventListener("blur",this.handleTriggerBlur))}mountTriggerChildren(e){this.triggerWrap&&e.forEach(e=>{e.parentElement!==this.triggerWrap&&this.triggerWrap.append(e)})}collectBodyChildren(){return[...Array.from(this.querySelectorAll(':scope > [slot="content"]')),...Array.from(this.bodyEl?.querySelectorAll(':scope > [slot="content"]')||[])]}bindExternalTrigger(){const e=this.getAttribute("trigger-id");e&&(this.triggerEl=document.getElementById(e),this.triggerEl&&(this.onExternalTriggerClick=()=>{"click"===this.resolvedTrigger()&&this.setOpen(!this.isOpen())},this.triggerEl.addEventListener("click",this.onExternalTriggerClick)))}unbindExternalTrigger(){this.triggerEl&&this.onExternalTriggerClick&&this.triggerEl.removeEventListener("click",this.onExternalTriggerClick),this.triggerEl=null,this.onExternalTriggerClick=null}attachGlobalListeners(){this.onDocMouseDown=e=>{if(!this.isOpen()||"false"===this.getAttribute("close-on-outside-click"))return;const t=e.target;this.panel?.contains(t)||this.triggerWrap?.contains(t)||this.triggerEl?.contains(t)||this.setOpen(!1)},this.onDocKeyDown=e=>{"Escape"===e.key&&this.isOpen()&&"false"!==this.getAttribute("close-on-escape")&&this.setOpen(!1)},document.addEventListener("mousedown",this.onDocMouseDown),document.addEventListener("keydown",this.onDocKeyDown)}detachGlobalListeners(){this.onDocMouseDown&&document.removeEventListener("mousedown",this.onDocMouseDown),this.onDocKeyDown&&document.removeEventListener("keydown",this.onDocKeyDown),this.onDocMouseDown=null,this.onDocKeyDown=null}scheduleOpen(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("delay")||0)):0;this.showTimer=setTimeout(()=>this.showPanel(),e)}scheduleClose(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("hide-delay")||80)):0;this.hideTimer=setTimeout(()=>this.setOpen(!1),e)}getTriggerRect(){const e=this.triggerEl||this.triggerWrap;return e?.getBoundingClientRect()}flipPlacementIfNeeded(e,t,i){const s=window.innerHeight,r=window.innerWidth,o=this.groupOf(e),n=t.top-i.height-8>=8,a=t.bottom+8+i.height<=s-8,h=t.left-i.width-8>=8,l=t.right+8+i.width<=r-8;return"top"===o&&!n&&a?e.replace(/^top/,"bottom"):"bottom"===o&&!a&&n?e.replace(/^bottom/,"top"):"left"===o&&!h&&l?e.replace(/^left/,"right"):"right"===o&&!l&&h?e.replace(/^right/,"left"):e}applyCoords(e,t,i){let s=0,r=0,o=0,n=0;const a=i.height,h=i.width,l=16;switch(e){case"top":s=t.top-i.height-8,r=t.left+t.width/2-i.width/2,o=a-5,n=h/2-5;break;case"top-start":s=t.top-i.height-8,r=t.left,o=a-5,n=11;break;case"top-end":s=t.top-i.height-8,r=t.right-i.width,o=a-5,n=h-l-5;break;case"bottom":s=t.bottom+8,r=t.left+t.width/2-i.width/2,o=-5,n=h/2-5;break;case"bottom-start":s=t.bottom+8,r=t.left,o=-5,n=11;break;case"bottom-end":s=t.bottom+8,r=t.right-i.width,o=-5,n=h-l-5;break;case"left":s=t.top+t.height/2-i.height/2,r=t.left-i.width-8,o=a/2-5,n=h-5;break;case"left-start":s=t.top,r=t.left-i.width-8,o=11,n=h-5;break;case"left-end":s=t.bottom-i.height,r=t.left-i.width-8,o=a-l-5,n=h-5;break;case"right":s=t.top+t.height/2-i.height/2,r=t.right+8,o=a/2-5,n=-5;break;case"right-start":s=t.top,r=t.right+8,o=11,n=-5;break;case"right-end":s=t.bottom-i.height,r=t.right+8,o=a-l-5,n=-5}const d=window.innerWidth,c=window.innerHeight;return r<8&&(r=8),r+i.width>d-8&&(r=d-i.width-8),s<8&&(s=8),s+i.height>c-8&&(s=c-i.height-8),{top:s,left:r,aTop:o,aLeft:n,placement:e}}positionPanel(){if(!this.panel)return;const t=this.getTriggerRect();if(!t)return;const i=Number(this.getAttribute("max-width")||300);this.panel.style.maxWidth=`${i}px`,this.panel.offsetHeight;const s=this.panel.getBoundingClientRect(),r=this.resolvedPlacement(),o=this.flipPlacementIfNeeded(r,t,s),{top:n,left:a,aTop:h,aLeft:l}=this.applyCoords(o,t,s);this.panel.style.top=`${n}px`,this.panel.style.left=`${a}px`,this.panel.dataset.placementGroup=this.groupOf(o),e.forEach(e=>{this.panel.classList.toggle(`designbase-wc-popover--${e}`,e===o)}),this.arrowEl&&(this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${o}`,this.arrowEl.style.top=`${h}px`,this.arrowEl.style.left=`${l}px`)}revealPanel(){this.panel&&(this.panel.classList.remove("designbase-wc-popover--visible"),this.positionPanel(),this.panel.offsetHeight,this.positionPanel(),this.panel.classList.add("designbase-wc-popover--visible"))}updatePanelMetadata(){if(!this.panel)return;const e=this.getAttribute("size")||"m",t=this.getAttribute("variant")||"default",i=this.resolvedPlacement();this.panel.className=["designbase-wc-popover",`designbase-wc-popover--${e}`,`designbase-wc-popover--${t}`,`designbase-wc-popover--${i}`,this.isOpen()?"designbase-wc-popover--visible":"",this.hasAttribute("disabled")?"designbase-wc-popover--disabled":""].filter(Boolean).join(" ")}ensurePanel(){if(this.panel)return;const e=document.createElement("div");e.className="designbase-wc-popover",e.setAttribute("data-wc-internal",""),e.setAttribute("role","dialog"),e.setAttribute("aria-modal","false"),e.style.position="fixed",e.style.zIndex="9999";const t=document.createElement("div");t.className="designbase-wc-popover__content";const i=document.createElement("div");i.className="designbase-wc-popover__header";const s=document.createElement("h3");s.className="designbase-wc-popover__title";const r=document.createElement("db-button");r.className="designbase-wc-popover__close-button",r.setAttribute("variant","ghost"),r.setAttribute("size","s"),r.setAttribute("icon-only",""),r.setAttribute("start-icon","close"),r.setAttribute("aria-label","팝오버 닫기"),r.addEventListener("db-click",e=>{e.stopPropagation(),this.setOpen(!1)}),i.append(s,r),this.bodyEl=document.createElement("div"),this.bodyEl.className="designbase-wc-popover__body",t.append(i,this.bodyEl),e.append(t),"false"!==this.getAttribute("show-arrow")&&(this.arrowEl=document.createElement("div"),this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${this.resolvedPlacement()}`,e.append(this.arrowEl)),this.panel=e,this.panel.querySelector(".designbase-wc-popover__title").textContent=this.getAttribute("title")||"",this.panel.querySelector(".designbase-wc-popover__title").hidden=!this.getAttribute("title"),document.body.append(e),e.addEventListener("mouseenter",()=>{"hover"===this.resolvedTrigger()&&this.clearTimers()}),e.addEventListener("mouseleave",()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()})}showPanel(){if(this.hasAttribute("disabled"))return;this.ensurePanel(),this.updatePanelMetadata();const e=this.collectBodyChildren();e.length>0?this.bodyEl.replaceChildren(...e):this.bodyEl.textContent=this.getAttribute("content")||"";const t=this.panel.querySelector(".designbase-wc-popover__title");t.textContent=this.getAttribute("title")||"",t.hidden=!this.getAttribute("title"),requestAnimationFrame(()=>{this.revealPanel(),window.addEventListener("scroll",this.handleReposition,{capture:!0,passive:!0}),window.addEventListener("resize",this.handleReposition)})}hidePanel(){this.panel?.classList.remove("designbase-wc-popover--visible"),window.removeEventListener("scroll",this.handleReposition,!0),window.removeEventListener("resize",this.handleReposition),this.hasAttribute("always-show")||this.removePanel()}removePanel(){this.bodyEl?.querySelectorAll(':scope > [slot="content"]').forEach(e=>this.append(e)),this.panel?.remove(),this.panel=void 0,this.bodyEl=void 0,this.arrowEl=void 0}render(){this.ensureTriggerWrap();const e=this.collectTriggerChildren();this.mountTriggerChildren(e);const t=Boolean(this.getAttribute("trigger-id"));this.triggerWrap&&(e.length>0||!t?this.triggerWrap.parentElement!==this&&this.append(this.triggerWrap):this.triggerWrap.parentElement===this&&this.triggerWrap.remove()),this.hasAttribute("always-show")&&this.showPanel()}}customElements.get("db-popover")||customElements.define("db-popover",DbPopover);export{DbPopover};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ProgressiveBlurPosition, ProgressiveBlurSize } from '../ui-contracts/dist/components.d.js';
|
|
2
|
+
|
|
3
|
+
declare class DbProgressiveBlur extends HTMLElement {
|
|
4
|
+
static get observedAttributes(): string[];
|
|
5
|
+
private built;
|
|
6
|
+
private topPanel?;
|
|
7
|
+
private bottomPanel?;
|
|
8
|
+
private mainPanel?;
|
|
9
|
+
get position(): ProgressiveBlurPosition;
|
|
10
|
+
set position(value: ProgressiveBlurPosition);
|
|
11
|
+
get size(): ProgressiveBlurSize;
|
|
12
|
+
set size(value: ProgressiveBlurSize);
|
|
13
|
+
get height(): string;
|
|
14
|
+
set height(value: string);
|
|
15
|
+
get width(): string;
|
|
16
|
+
set width(value: string);
|
|
17
|
+
get tint(): string;
|
|
18
|
+
set tint(value: string);
|
|
19
|
+
get blurLevels(): number[];
|
|
20
|
+
set blurLevels(value: number[]);
|
|
21
|
+
connectedCallback(): void;
|
|
22
|
+
disconnectedCallback(): void;
|
|
23
|
+
attributeChangedCallback(): void;
|
|
24
|
+
private build;
|
|
25
|
+
private createEdgePanel;
|
|
26
|
+
private renderLayers;
|
|
27
|
+
private sync;
|
|
28
|
+
}
|
|
29
|
+
declare global {
|
|
30
|
+
interface HTMLElementTagNameMap {
|
|
31
|
+
'db-progressive-blur': DbProgressiveBlur;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { DbProgressiveBlur };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{coerceToContract as t}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{PROGRESSIVE_BLUR_POSITIONS as e,PROGRESSIVE_BLUR_SIZES as s}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const i="designbase-wc-progressive-blur",r=[.5,1,2,4,8,16,32,64];class DbProgressiveBlur extends HTMLElement{constructor(){super(...arguments),this.built=!1}static get observedAttributes(){return["position","height","width","size","blur-levels","tint"]}get position(){return t(this.getAttribute("position"),e,"bottom")}set position(t){this.setAttribute("position",t)}get size(){return t(this.getAttribute("size"),s,"m")}set size(t){this.setAttribute("size",t)}get height(){return this.getAttribute("height")||""}set height(t){this.setAttribute("height",t)}get width(){return this.getAttribute("width")||""}set width(t){this.setAttribute("width",t)}get tint(){return this.getAttribute("tint")||""}set tint(t){this.setAttribute("tint",t)}get blurLevels(){const t=this.getAttribute("blur-levels");if(!t)return r;try{if(t.startsWith("[")){const e=JSON.parse(t);if(Array.isArray(e)&&e.every(t=>"number"==typeof t))return e}const e=t.split(",").map(t=>parseFloat(t.trim())).filter(t=>Number.isFinite(t)&&t>=0);return e.length?e:r}catch{return r}}set blurLevels(t){this.setAttribute("blur-levels",JSON.stringify(t))}connectedCallback(){this.setAttribute("aria-hidden","true"),this.built||(this.build(),this.built=!0),this.sync()}disconnectedCallback(){}attributeChangedCallback(){this.built&&this.sync()}build(){this.classList.add(i)}createEdgePanel(t,e){const s=document.createElement("div");s.className=`${i}__edge ${i}__edge--${t}`;const r=e.length;if(e.forEach((e,n)=>{const o=document.createElement("div");o.className=`${i}__layer`;const a=`${e}px`;o.style.backdropFilter=`blur(${a})`,o.style.setProperty("-webkit-backdrop-filter",`blur(${a})`);const h=Math.max(0,Math.round(n/r*100)),l=Math.min(100,Math.round((n+1.5)/r*100)),u=`linear-gradient(to ${t}, rgba(0,0,0,0) ${h}%, rgba(0,0,0,1) ${l}%)`;o.style.maskImage=u,o.style.setProperty("-webkit-mask-image",u),s.appendChild(o)}),this.tint){const e=document.createElement("div");e.className=`${i}__tint`,e.style.background=`linear-gradient(to ${t}, transparent 0%, ${this.tint} 100%)`,s.appendChild(e)}return s}renderLayers(){this.replaceChildren();const t=this.position,e=this.blurLevels;"both"===t?(this.topPanel=this.createEdgePanel("top",e),this.bottomPanel=this.createEdgePanel("bottom",e),this.append(this.topPanel,this.bottomPanel)):(this.mainPanel=this.createEdgePanel(t,e),this.append(this.mainPanel))}sync(){e.forEach(t=>this.classList.remove(`${i}--${t}`)),s.forEach(t=>this.classList.remove(`${i}--${t}`)),this.classList.add(`${i}--${this.position}`),this.classList.add(`${i}--${this.size}`);const t=this.height;t?this.style.setProperty("--progressive-blur-height",t):this.style.removeProperty("--progressive-blur-height");const r=this.width;r?this.style.setProperty("--progressive-blur-width",r):this.style.removeProperty("--progressive-blur-width"),this.renderLayers()}}customElements.get("db-progressive-blur")||customElements.define("db-progressive-blur",DbProgressiveBlur);export{DbProgressiveBlur};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { DbPaperCard } from './paper-card.js';
|
|
2
|
+
|
|
3
|
+
interface DbReceiptItem {
|
|
4
|
+
name: string;
|
|
5
|
+
quantity: number;
|
|
6
|
+
unitAmount: number;
|
|
7
|
+
}
|
|
8
|
+
interface DbReceiptLabels {
|
|
9
|
+
quantity: string;
|
|
10
|
+
subtotal: string;
|
|
11
|
+
discount: string;
|
|
12
|
+
tax: string;
|
|
13
|
+
total: string;
|
|
14
|
+
payment: string;
|
|
15
|
+
empty: string;
|
|
16
|
+
invalid: string;
|
|
17
|
+
}
|
|
18
|
+
/** Integer minor-unit amounts: KRW 3900 = ₩3,900; USD 3900 = $39.00. */
|
|
19
|
+
declare class DbReceipt extends DbPaperCard {
|
|
20
|
+
static get observedAttributes(): string[];
|
|
21
|
+
private data;
|
|
22
|
+
private customLabels;
|
|
23
|
+
protected upgradeNames(): string[];
|
|
24
|
+
get items(): DbReceiptItem[];
|
|
25
|
+
set items(value: DbReceiptItem[]);
|
|
26
|
+
get labels(): DbReceiptLabels;
|
|
27
|
+
set labels(value: Partial<DbReceiptLabels>);
|
|
28
|
+
protected render(): void;
|
|
29
|
+
}
|
|
30
|
+
declare global {
|
|
31
|
+
interface HTMLElementTagNameMap {
|
|
32
|
+
'db-receipt': DbReceipt;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export { DbReceipt };
|
|
37
|
+
export type { DbReceiptItem, DbReceiptLabels };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DbPaperCard as t,paperJson as e,paperNode as a,paperDetails as r}from"./paper-card.js";const i={quantity:"수량",subtotal:"소계",discount:"할인",tax:"세금",total:"합계",payment:"결제수단",empty:"표시할 품목이 없습니다.",invalid:"품목과 금액 정보를 확인해주세요."},minor=t=>"number"==typeof t&&Number.isSafeInteger(t)&&t>=0;class DbReceipt extends t{constructor(){super(...arguments),this.data=void 0,this.customLabels={}}static get observedAttributes(){return["variant","code-image-src","code-alt","merchant","merchant-detail","reference","issued-at","items","currency","locale","discount-amount","tax-amount","payment-method","note","edge","action-label","disabled"]}upgradeNames(){return["items","labels"]}get items(){const t=this.data??e(this.attr("items"));return Array.isArray(t)?t.map(t=>({...t})):[]}set items(t){this.data=null==t?void 0:Array.isArray(t)?t.map(t=>({...t})):t,this.isConnected&&this.render()}get labels(){return{...i,...this.customLabels}}set labels(t){this.customLabels={};for(const e of Object.keys(i))"string"==typeof t?.[e]&&(this.customLabels[e]=t[e]);this.isConnected&&this.render()}render(){const t="compact"===this.getAttribute("variant");this.dataset.variant=t?"compact":"default";const e=this.labels,i=a("section","db-paper__main");i.append(a("h3","db-paper__title",this.attr("merchant")||"영수증")),this.attr("merchant-detail")&&i.append(a("p","db-paper__description",this.attr("merchant-detail")));const s=a("div","db-paper__receipt-meta");let n;this.attr("issued-at")&&s.append(a("span","",this.attr("issued-at"))),!t&&this.attr("reference")&&s.append(a("span","",this.attr("reference"))),i.append(s);try{n=new Intl.NumberFormat(this.attr("locale")||"ko-KR",{style:"currency",currency:this.attr("currency")||"KRW"})}catch{n=new Intl.NumberFormat("ko-KR",{style:"currency",currency:"KRW"})}const p=n.resolvedOptions().maximumFractionDigits||0,o=BigInt(10**p),c=new Intl.NumberFormat(n.resolvedOptions().locale,{useGrouping:!1,minimumIntegerDigits:Math.max(1,p),maximumFractionDigits:0}),money=t=>{const e=BigInt(t);return n.formatToParts(e/o).map(t=>"fraction"===t.type?c.format(e%o):t.value).join("")};let d=this.data;if(void 0===d)try{d=this.hasAttribute("items")?JSON.parse(this.attr("items")):[]}catch{d=null}const u=Array.isArray(d)?d:[];let m=Array.isArray(d),l=0;for(const t of u){if(!t||"string"!=typeof t.name||!Number.isSafeInteger(t.quantity)||t.quantity<=0||!minor(t.unitAmount)||!Number.isSafeInteger(t.quantity*t.unitAmount)){m=!1;break}if(l+=t.quantity*t.unitAmount,!Number.isSafeInteger(l)){m=!1;break}}const amount=t=>this.hasAttribute(t)&&""===this.attr(t).trim()?NaN:Number(this.getAttribute(t)??0),b=amount("discount-amount"),h=amount("tax-amount");m=m&&minor(b)&&minor(h)&&b<=l&&Number.isSafeInteger(l-b+h);const y=a("div","db-paper__receipt-items");if(m)if(u.length)for(const t of u){const r=a("div","db-paper__receipt-item"),i=a("div","");i.append(a("strong","",t.name),a("span","db-paper__label",`${e.quantity} ${t.quantity} × ${money(t.unitAmount)}`)),r.append(i,a("span","",money(t.unitAmount*t.quantity))),y.append(r)}else y.append(a("p","db-paper__note",e.empty));else{const t=a("p","db-paper__error",e.invalid);t.setAttribute("role","alert"),y.append(t)}i.append(y);const f=a("div","db-paper__stub"),g=t?i:f;if(m&&(!t||b||h)){const t=[{label:e.subtotal,value:money(l)}];b&&t.push({label:e.discount,value:"−"+money(b)}),h&&t.push({label:e.tax,value:money(h)}),g.append(r(t))}const _=a("div","db-paper__receipt-total");_.append(a("strong","",e.total),a("strong","db-paper__amount",m?money(l-b+h):"—")),g.append(_),this.attr("payment-method")&&g.append(r([{label:e.payment,value:this.attr("payment-method")}])),this.attr("note")&&g.append(a("p","db-paper__note",this.attr("note"))),(t||this.attr("code-image-src"))&&f.append(this.code(this.attr("reference")));const v=this.action(this.attr("reference"));v&&(v.toggleAttribute("disabled",!m||this.hasAttribute("disabled")),f.append(v)),this.replace(i,f)}}customElements.get("db-receipt")||customElements.define("db-receipt",DbReceipt);export{DbReceipt};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getDbComponentIconSize as e,createDbIcon as t}from"./db-icons.js";import{SEARCH_BAR_SIZES as s,SEARCH_BAR_RECENT_LAYOUTS as a}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbSearchBar extends HTMLElement{constructor(){super(...arguments),this.recentSearches=[],this.isFocused=!1,this.currentSuggestion=0,this.scrollParents=[]}static get observedAttributes(){return["value","default-value","placeholder","size","appearance","disabled","readonly","full-width","show-shortcut","shortcut-label","enable-recent-searches","recent-searches-key","recent-searches-layout","suggested-searches","suggestion-rolling-interval","categories","selected-category","search-results","empty-state-message"]}getResolvedSize(){const e=this.getAttribute("size")||"m";return s.includes(e)?e:"m"}getIconPx(){return e(this.getResolvedSize())}syncIcons(){const e=this.getIconPx();this.querySelector(".designbase-wc-search-bar__search-icon")?.replaceChildren(t("search",e)),this.clearButton?.replaceChildren(t("close",e))}hasInputValue(){return Boolean((this.input?.value??this.getAttribute("value")??"").trim())}get value(){return this.input?.value??this.getAttribute("value")??""}set value(e){this.setAttribute("value",e),this.input&&(this.input.value=e)}connectedCallback(){this.loadRecentSearches(),this.render(),this.bindGlobalShortcut()}disconnectedCallback(){this.clearSuggestionInterval(),this.unbindGlobalShortcut(),this.detachDropdownPortal(),this.blurTimer&&clearTimeout(this.blurTimer)}attributeChangedCallback(e){if(this.isConnected)return"value"===e&&this.input?(this.input.value=this.getAttribute("value")||"",this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"disabled"===e||"readonly"===e||"placeholder"===e||"show-shortcut"===e||"shortcut-label"===e||"selected-category"===e||"search-results"===e||"empty-state-message"===e||"suggested-searches"===e?(this.syncAttributes(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"enable-recent-searches"===e||"recent-searches-key"===e?(this.loadRecentSearches(),void this.updateDropdown()):void("categories"!==e&&"recent-searches-layout"!==e?this.render():this.updateDropdown())}focus(){this.input?.focus()}parseJsonArray(e){try{const t=JSON.parse(this.getAttribute(e)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}getRecentSearchesKey(){return this.getAttribute("recent-searches-key")||"searchbar-recent-searches"}loadRecentSearches(){if(this.hasAttribute("enable-recent-searches"))try{const e=localStorage.getItem(this.getRecentSearchesKey());this.recentSearches=e?JSON.parse(e):[],Array.isArray(this.recentSearches)||(this.recentSearches=[])}catch{this.recentSearches=[]}else this.recentSearches=[]}saveRecentSearches(){try{localStorage.setItem(this.getRecentSearchesKey(),JSON.stringify(this.recentSearches))}catch{}}clearSuggestionInterval(){this.suggestionInterval&&(clearInterval(this.suggestionInterval),this.suggestionInterval=void 0)}syncSuggestionRolling(){this.clearSuggestionInterval();const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=Number(this.getAttribute("suggestion-rolling-interval")||5e3);e.length>0&&!t&&(this.suggestionInterval=setInterval(()=>{this.currentSuggestion=(this.currentSuggestion+1)%e.length,this.syncPlaceholder(),this.updateDropdown()},s))}syncPlaceholder(){if(!this.input)return;const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=this.getAttribute("placeholder")||"검색...";e.length>0&&!t?this.input.placeholder=e[this.currentSuggestion]||s:this.input.placeholder=s}syncValueState(){const e=this.hasInputValue();this.classList.toggle("designbase-wc-search-bar--has-value",e),this.clearButton&&(this.clearButton.hidden=!e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.shortcutBadge&&(this.shortcutBadge.hidden=!this.hasAttribute("show-shortcut")||e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.syncIcons()}syncAttributes(){const e=this.getAttribute("size")||"m",t=this.hasAttribute("disabled"),a=this.hasAttribute("readonly"),n=this.hasAttribute("show-shortcut");this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${s.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",t&&"designbase-wc-search-bar--disabled",a&&"designbase-wc-search-bar--readonly",this.hasAttribute("full-width")&&"designbase-wc-search-bar--full-width",Boolean(this.hasInputValue())&&"designbase-wc-search-bar--has-value"].filter(Boolean).join(" "),this.input&&(this.input.disabled=t,this.input.readOnly=a),this.shortcutBadge&&(this.shortcutBadge.hidden=!n||this.hasInputValue()||t||a,this.shortcutBadge.textContent=this.getAttribute("shortcut-label")||"⌘K"),this.syncValueState()}bindGlobalShortcut(){this.unbindGlobalShortcut(),!this.hasAttribute("show-shortcut")||this.hasAttribute("disabled")||this.hasAttribute("readonly")||(this.globalKeyHandler=e=>{const t=e.metaKey||e.ctrlKey;let s="k";const a=(this.getAttribute("shortcut-label")||"⌘K").slice(-1).toLowerCase();a&&(s=a),t&&e.key.toLowerCase()===s&&(e.preventDefault(),this.focus())},window.addEventListener("keydown",this.globalKeyHandler))}unbindGlobalShortcut(){this.globalKeyHandler&&(window.removeEventListener("keydown",this.globalKeyHandler),this.globalKeyHandler=void 0)}positionDropdown(){if(!this.dropdown||this.dropdown.hidden)return;const e=this.getBoundingClientRect(),t=this.input?.getBoundingClientRect(),s=t??e;this.dropdown.style.top=`${s.bottom+4}px`,this.dropdown.style.left=`${e.left}px`,this.dropdown.style.width=`${e.width}px`,this.dropdown.style.right="auto"}bindRepositionListeners(){if(this.repositionHandler)return;this.repositionHandler=()=>{requestAnimationFrame(()=>this.positionDropdown())},window.addEventListener("scroll",this.repositionHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.repositionHandler),this.scrollParents=[];let e=this.parentElement;for(;e&&e!==document.body;){const t=getComputedStyle(e),s=/(auto|scroll|overlay)/.test(t.overflowY),a=/(auto|scroll|overlay)/.test(t.overflow);(s||a)&&e.scrollHeight>e.clientHeight&&(e.addEventListener("scroll",this.repositionHandler,{passive:!0}),this.scrollParents.push(e)),e=e.parentElement}}unbindRepositionListeners(){this.repositionHandler&&(window.removeEventListener("scroll",this.repositionHandler,!0),window.removeEventListener("resize",this.repositionHandler),this.scrollParents.forEach(e=>e.removeEventListener("scroll",this.repositionHandler)),this.scrollParents=[],this.repositionHandler=void 0)}attachDropdownPortal(){this.dropdown&&!this.dropdown.hidden&&(this.dropdown.classList.add("designbase-wc-search-bar__dropdown--portal"),this.dropdown.parentElement!==document.body&&document.body.append(this.dropdown),requestAnimationFrame(()=>this.positionDropdown()),this.repositionHandler||this.bindRepositionListeners())}detachDropdownPortal(){this.unbindRepositionListeners(),this.dropdown&&(this.dropdown.classList.remove("designbase-wc-search-bar__dropdown--portal"),this.dropdown.style.top="",this.dropdown.style.left="",this.dropdown.style.width="",this.dropdown.style.right="",this.dropdown.parentElement===document.body&&this.isConnected&&this.append(this.dropdown))}shouldShowDropdown(){const e=this.hasInputValue(),t=this.parseJsonArray("categories"),s=this.parseJsonArray("suggested-searches"),a=this.getAttribute("search-results"),n=this.getAttribute("empty-state-message");return this.isFocused&&(t.length>0||this.hasAttribute("enable-recent-searches")&&this.recentSearches.length>0&&!e||s.length>0&&!e||null!==a&&e||Boolean(n)&&!e&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===s.length)}formatSearchResult(e){if("string"==typeof e||"number"==typeof e)return String(e);if(e&&"object"==typeof e){const t=e;if("string"==typeof t.title)return t.title;if("string"==typeof t.label)return t.label}return String(e)}handleSearch(e){const t=(e??this.value).trim();t&&(this.dispatchEvent(new CustomEvent("db-search",{detail:{value:t},bubbles:!0,composed:!0})),this.hasAttribute("enable-recent-searches")&&(this.recentSearches=[t,...this.recentSearches.filter(e=>e!==t)].slice(0,10),this.saveRecentSearches(),this.updateDropdown()))}updateDropdown(){if(!this.dropdown)return;const s=this.shouldShowDropdown();if(this.dropdown.hidden=!s,this.classList.toggle("designbase-wc-search-bar--dropdown-open",s),!s)return this.dropdown.replaceChildren(),void this.detachDropdownPortal();this.dropdown.replaceChildren();const n=this.hasInputValue(),r=this.parseJsonArray("categories"),i=this.parseJsonArray("suggested-searches"),o=this.getAttribute("selected-category")||"",c=this.parseJsonArray("search-results"),h=this.getAttribute("empty-state-message"),d=a.includes(this.getAttribute("recent-searches-layout")||"vertical")&&this.getAttribute("recent-searches-layout")||"vertical";if(r.length>0){const e=document.createElement("div");e.className="designbase-wc-search-bar__categories",r.forEach(t=>{const s=document.createElement("db-chip");s.setAttribute("label",t),s.setAttribute("size","s"),s.setAttribute("variant",t===o?"primary":"default"),s.setAttribute("clickable",""),s.addEventListener("mousedown",e=>{e.preventDefault(),this.setAttribute("selected-category",t),this.dispatchEvent(new CustomEvent("db-category-change",{detail:{category:t},bubbles:!0,composed:!0})),this.updateDropdown()}),e.append(s)}),this.dropdown.append(e)}if(n&&this.hasAttribute("search-results")){const e=document.createElement("div");if(e.className="designbase-wc-search-bar__results",c.length>0){const t=document.createElement("ul");t.className="designbase-wc-search-bar__results-list",c.forEach((e,s)=>{const a=document.createElement("li");a.className="designbase-wc-search-bar__result-item",a.textContent=this.formatSearchResult(e),a.addEventListener("mousedown",t=>{t.preventDefault(),this.isFocused=!1,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-search-result-click",{detail:{result:e,index:s},bubbles:!0,composed:!0}))}),t.append(a)}),e.append(t)}else{const t=document.createElement("div");t.className="designbase-wc-search-bar__results-empty",t.textContent="검색 결과가 없습니다.",e.append(t)}return this.dropdown.append(e),void this.attachDropdownPortal()}if(this.hasAttribute("enable-recent-searches")&&!n&&this.recentSearches.length>0){const s=document.createElement("div");s.className=`designbase-wc-search-bar__recent-searches designbase-wc-search-bar__recent-searches--${d}`;const a=document.createElement("div");a.className="designbase-wc-search-bar__recent-header";const n=document.createElement("span");n.className="designbase-wc-search-bar__recent-title",n.textContent="최근 검색어";const r=document.createElement("button");r.type="button",r.className="designbase-wc-search-bar__clear-all-button",r.setAttribute("aria-label","모든 최근 검색어 삭제"),r.textContent="전체 삭제",r.addEventListener("mousedown",e=>{e.preventDefault(),this.recentSearches=[];try{localStorage.removeItem(this.getRecentSearchesKey())}catch{}this.updateDropdown()}),a.append(n,r);const i=document.createElement("div");i.className="designbase-wc-search-bar__recent-list",this.recentSearches.forEach(s=>{const a=document.createElement("div");a.className="designbase-wc-search-bar__recent-item";const n=document.createElement("button");n.type="button",n.className="designbase-wc-search-bar__recent-search-button",n.textContent=s,n.addEventListener("mousedown",e=>{if(e.preventDefault(),!this.input)return;this.input.value=s,this.setAttribute("value",s),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(s);const t={value:s};this.dispatchEvent(new CustomEvent("db-input",{detail:t,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:t,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()});const r=document.createElement("button");r.type="button",r.className="designbase-wc-search-bar__recent-remove-button",r.setAttribute("aria-label",`${s} 삭제`),r.append(t("close",e("s"))),r.addEventListener("mousedown",e=>{e.preventDefault(),this.recentSearches=this.recentSearches.filter(e=>e!==s),this.saveRecentSearches(),this.updateDropdown()}),a.append(n,r),i.append(a)}),s.append(a,i),this.dropdown.append(s)}if(i.length>0&&!n){const e=document.createElement("div");e.className="designbase-wc-search-bar__suggestions";const t=document.createElement("div");t.className="designbase-wc-search-bar__suggestions-header";const s=document.createElement("span");s.className="designbase-wc-search-bar__suggestions-title",s.textContent="추천 검색어",t.append(s);const a=document.createElement("div");a.className="designbase-wc-search-bar__suggestions-list",i.forEach((e,t)=>{const s=document.createElement("button");s.type="button",s.className=["designbase-wc-search-bar__suggestion-item",t===this.currentSuggestion&&"designbase-wc-search-bar__suggestion-item--active"].filter(Boolean).join(" "),s.textContent=e,s.addEventListener("mousedown",t=>{if(t.preventDefault(),!this.input)return;this.clearSuggestionInterval(),this.input.value=e,this.setAttribute("value",e),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(e);const s={value:e};this.dispatchEvent(new CustomEvent("db-input",{detail:s,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:s,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()}),a.append(s)}),e.append(t,a),this.dropdown.append(e)}if(h&&!n&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===i.length){const e=document.createElement("div");e.className="designbase-wc-search-bar__empty-state",e.textContent=h,this.dropdown.append(e)}this.attachDropdownPortal()}render(){const e=this.getAttribute("size")||"m",a=this.hasAttribute("disabled"),n=this.hasAttribute("readonly"),r=this.hasAttribute("full-width"),i=this.hasAttribute("show-shortcut"),o=this.getAttribute("value")??this.getAttribute("default-value")??"",c=Boolean(o.trim()),h=this.getIconPx();this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${s.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",a&&"designbase-wc-search-bar--disabled",n&&"designbase-wc-search-bar--readonly",r&&"designbase-wc-search-bar--full-width",c&&"designbase-wc-search-bar--has-value",this.shouldShowDropdown()&&"designbase-wc-search-bar--dropdown-open"].filter(Boolean).join(" "),this.setAttribute("role","search"),this.clearSuggestionInterval(),this.detachDropdownPortal(),this.replaceChildren();const d=document.createElement("div");d.className="designbase-wc-search-bar__container";const l=document.createElement("div");l.className="designbase-wc-search-bar__search-icon",l.setAttribute("aria-hidden","true"),l.append(t("search",h));const u=document.createElement("input");if(u.type="text",u.className="designbase-wc-search-bar__input",u.value=o,u.disabled=a,u.readOnly=n,u.setAttribute("aria-label","검색어 입력"),this.input=u,i){const t=document.createElement("db-badge");t.className="designbase-wc-search-bar__shortcut-badge",t.setAttribute("size","l"===e?"m":"s"),t.setAttribute("variant","secondary"),t.setAttribute("type","text"),t.setAttribute("aria-hidden","true"),t.textContent=this.getAttribute("shortcut-label")||"⌘K",t.hidden=c||a||n,this.shortcutBadge=t,d.append(l,u,t)}else d.append(l,u);const b=document.createElement("button");b.type="button",b.className="designbase-wc-search-bar__clear-button",b.setAttribute("aria-label","검색어 지우기"),b.hidden=!c||a||n,b.append(t("close",h)),this.clearButton=b,d.append(b);const p=document.createElement("div");p.className="designbase-wc-search-bar__dropdown",p.hidden=!0,p.addEventListener("mousedown",e=>{e.preventDefault()}),this.dropdown=p,u.addEventListener("input",()=>{this.setAttribute("value",u.value),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling();const e={value:u.value};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),u.addEventListener("keydown",e=>{"Enter"===e.key&&this.handleSearch()}),u.addEventListener("focus",()=>{this.isFocused=!0,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-focus",{bubbles:!0,composed:!0}))}),u.addEventListener("blur",()=>{this.isFocused=!1,this.blurTimer&&clearTimeout(this.blurTimer),this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-blur",{bubbles:!0,composed:!0}))}),b.addEventListener("click",()=>{u.value="",this.setAttribute("value",""),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling(),u.focus(),this.dispatchEvent(new CustomEvent("db-clear",{bubbles:!0,composed:!0}));const e={value:""};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),this.append(d,p),this.syncIcons(),this.syncPlaceholder(),this.syncSuggestionRolling(),this.bindGlobalShortcut(),this.updateDropdown()}}customElements.get("db-search-bar")||customElements.define("db-search-bar",DbSearchBar);export{DbSearchBar};
|
|
1
|
+
import{getDbComponentIconSize as e,createDbIcon as t}from"./db-icons.js";import{SEARCH_BAR_SIZES as s,SEARCH_BAR_RECENT_LAYOUTS as a}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbSearchBar extends HTMLElement{constructor(){super(...arguments),this.recentSearches=[],this.isFocused=!1,this.currentSuggestion=0,this.scrollParents=[]}static get observedAttributes(){return["value","default-value","placeholder","size","appearance","disabled","readonly","full-width","show-shortcut","shortcut-label","enable-recent-searches","recent-searches-key","recent-searches-layout","suggested-searches","suggestion-rolling-interval","categories","selected-category","search-results","empty-state-message"]}getResolvedSize(){const e=this.getAttribute("size")||"m";return s.includes(e)?e:"m"}getIconPx(){return e(this.getResolvedSize())}syncIcons(){const e=this.getIconPx();this.querySelector(".designbase-wc-search-bar__search-icon")?.replaceChildren(t("search",e)),this.clearButton?.replaceChildren(t("close",e))}hasInputValue(){return Boolean((this.input?.value??this.getAttribute("value")??"").trim())}get value(){return this.input?.value??this.getAttribute("value")??""}set value(e){this.setAttribute("value",e),this.input&&(this.input.value=e)}connectedCallback(){this.loadRecentSearches(),this.render(),this.bindGlobalShortcut()}disconnectedCallback(){this.clearSuggestionInterval(),this.unbindGlobalShortcut(),this.detachDropdownPortal(),this.blurTimer&&clearTimeout(this.blurTimer)}attributeChangedCallback(e){if(this.isConnected)return"value"===e&&this.input?(this.input.value=this.getAttribute("value")||"",this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"disabled"===e||"readonly"===e||"placeholder"===e||"show-shortcut"===e||"shortcut-label"===e||"selected-category"===e||"search-results"===e||"empty-state-message"===e||"suggested-searches"===e?(this.syncAttributes(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"enable-recent-searches"===e||"recent-searches-key"===e?(this.loadRecentSearches(),void this.updateDropdown()):void("categories"!==e&&"recent-searches-layout"!==e?this.render():this.updateDropdown())}focus(){this.input?.focus()}parseJsonArray(e){try{const t=JSON.parse(this.getAttribute(e)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}getRecentSearchesKey(){return this.getAttribute("recent-searches-key")||"searchbar-recent-searches"}loadRecentSearches(){if(this.hasAttribute("enable-recent-searches"))try{const e=localStorage.getItem(this.getRecentSearchesKey());this.recentSearches=e?JSON.parse(e):[],Array.isArray(this.recentSearches)||(this.recentSearches=[])}catch{this.recentSearches=[]}else this.recentSearches=[]}saveRecentSearches(){try{localStorage.setItem(this.getRecentSearchesKey(),JSON.stringify(this.recentSearches))}catch{}}clearSuggestionInterval(){this.suggestionInterval&&(clearInterval(this.suggestionInterval),this.suggestionInterval=void 0)}syncSuggestionRolling(){this.clearSuggestionInterval();const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=Number(this.getAttribute("suggestion-rolling-interval")||5e3);e.length>0&&!t&&(this.suggestionInterval=setInterval(()=>{this.currentSuggestion=(this.currentSuggestion+1)%e.length,this.syncPlaceholder(),this.updateDropdown()},s))}syncPlaceholder(){if(!this.input)return;const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=this.getAttribute("placeholder")||"검색...";e.length>0&&!t?this.input.placeholder=e[this.currentSuggestion]||s:this.input.placeholder=s}syncValueState(){const e=this.hasInputValue();this.classList.toggle("designbase-wc-search-bar--has-value",e),this.clearButton&&(this.clearButton.hidden=!e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.shortcutBadge&&(this.shortcutBadge.hidden=!this.hasAttribute("show-shortcut")||e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.syncIcons()}syncAttributes(){const e=this.getAttribute("size")||"m",t=this.hasAttribute("disabled"),a=this.hasAttribute("readonly"),n=this.hasAttribute("show-shortcut");this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${s.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",t&&"designbase-wc-search-bar--disabled",a&&"designbase-wc-search-bar--readonly",this.hasAttribute("full-width")&&"designbase-wc-search-bar--full-width",Boolean(this.hasInputValue())&&"designbase-wc-search-bar--has-value"].filter(Boolean).join(" "),this.input&&(this.input.disabled=t,this.input.readOnly=a),this.shortcutBadge&&(this.shortcutBadge.hidden=!n||this.hasInputValue()||t||a,this.shortcutBadge.textContent=this.getAttribute("shortcut-label")||"⌘K"),this.syncValueState()}bindGlobalShortcut(){this.unbindGlobalShortcut(),!this.hasAttribute("show-shortcut")||this.hasAttribute("disabled")||this.hasAttribute("readonly")||(this.globalKeyHandler=e=>{if(e.defaultPrevented||e.isComposing||!this.getClientRects().length)return;const t=e.metaKey||e.ctrlKey;let s="k";const a=(this.getAttribute("shortcut-label")||"⌘K").slice(-1).toLowerCase();a&&(s=a),t&&e.key.toLowerCase()===s&&(e.preventDefault(),this.focus())},window.addEventListener("keydown",this.globalKeyHandler))}unbindGlobalShortcut(){this.globalKeyHandler&&(window.removeEventListener("keydown",this.globalKeyHandler),this.globalKeyHandler=void 0)}positionDropdown(){if(!this.dropdown||this.dropdown.hidden)return;const e=this.getBoundingClientRect(),t=this.input?.getBoundingClientRect(),s=t??e;this.dropdown.style.top=`${s.bottom+4}px`,this.dropdown.style.left=`${e.left}px`,this.dropdown.style.width=`${e.width}px`,this.dropdown.style.right="auto"}bindRepositionListeners(){if(this.repositionHandler)return;this.repositionHandler=()=>{requestAnimationFrame(()=>this.positionDropdown())},window.addEventListener("scroll",this.repositionHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.repositionHandler),this.scrollParents=[];let e=this.parentElement;for(;e&&e!==document.body;){const t=getComputedStyle(e),s=/(auto|scroll|overlay)/.test(t.overflowY),a=/(auto|scroll|overlay)/.test(t.overflow);(s||a)&&e.scrollHeight>e.clientHeight&&(e.addEventListener("scroll",this.repositionHandler,{passive:!0}),this.scrollParents.push(e)),e=e.parentElement}}unbindRepositionListeners(){this.repositionHandler&&(window.removeEventListener("scroll",this.repositionHandler,!0),window.removeEventListener("resize",this.repositionHandler),this.scrollParents.forEach(e=>e.removeEventListener("scroll",this.repositionHandler)),this.scrollParents=[],this.repositionHandler=void 0)}attachDropdownPortal(){this.dropdown&&!this.dropdown.hidden&&(this.dropdown.classList.add("designbase-wc-search-bar__dropdown--portal"),this.dropdown.parentElement!==document.body&&document.body.append(this.dropdown),requestAnimationFrame(()=>this.positionDropdown()),this.repositionHandler||this.bindRepositionListeners())}detachDropdownPortal(){this.unbindRepositionListeners(),this.dropdown&&(this.dropdown.classList.remove("designbase-wc-search-bar__dropdown--portal"),this.dropdown.style.top="",this.dropdown.style.left="",this.dropdown.style.width="",this.dropdown.style.right="",this.dropdown.parentElement===document.body&&this.isConnected&&this.append(this.dropdown))}shouldShowDropdown(){const e=this.hasInputValue(),t=this.parseJsonArray("categories"),s=this.parseJsonArray("suggested-searches"),a=this.getAttribute("search-results"),n=this.getAttribute("empty-state-message");return this.isFocused&&(t.length>0||this.hasAttribute("enable-recent-searches")&&this.recentSearches.length>0&&!e||s.length>0&&!e||null!==a&&e||Boolean(n)&&!e&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===s.length)}formatSearchResult(e){if("string"==typeof e||"number"==typeof e)return String(e);if(e&&"object"==typeof e){const t=e;if("string"==typeof t.title)return t.title;if("string"==typeof t.label)return t.label}return String(e)}handleSearch(e){const t=(e??this.value).trim();t&&(this.dispatchEvent(new CustomEvent("db-search",{detail:{value:t},bubbles:!0,composed:!0})),this.hasAttribute("enable-recent-searches")&&(this.recentSearches=[t,...this.recentSearches.filter(e=>e!==t)].slice(0,10),this.saveRecentSearches(),this.updateDropdown()))}updateDropdown(){if(!this.dropdown)return;const s=this.shouldShowDropdown();if(this.dropdown.hidden=!s,this.classList.toggle("designbase-wc-search-bar--dropdown-open",s),!s)return this.dropdown.replaceChildren(),void this.detachDropdownPortal();this.dropdown.replaceChildren();const n=this.hasInputValue(),r=this.parseJsonArray("categories"),i=this.parseJsonArray("suggested-searches"),o=this.getAttribute("selected-category")||"",c=this.parseJsonArray("search-results"),h=this.getAttribute("empty-state-message"),d=a.includes(this.getAttribute("recent-searches-layout")||"vertical")&&this.getAttribute("recent-searches-layout")||"vertical";if(r.length>0){const e=document.createElement("div");e.className="designbase-wc-search-bar__categories",r.forEach(t=>{const s=document.createElement("db-chip");s.setAttribute("label",t),s.setAttribute("size","s"),s.setAttribute("variant",t===o?"primary":"default"),s.setAttribute("clickable",""),s.addEventListener("mousedown",e=>{e.preventDefault(),this.setAttribute("selected-category",t),this.dispatchEvent(new CustomEvent("db-category-change",{detail:{category:t},bubbles:!0,composed:!0})),this.updateDropdown()}),e.append(s)}),this.dropdown.append(e)}if(n&&this.hasAttribute("search-results")){const e=document.createElement("div");if(e.className="designbase-wc-search-bar__results",c.length>0){const t=document.createElement("ul");t.className="designbase-wc-search-bar__results-list",c.forEach((e,s)=>{const a=document.createElement("li");a.className="designbase-wc-search-bar__result-item",a.textContent=this.formatSearchResult(e),a.addEventListener("mousedown",t=>{t.preventDefault(),this.isFocused=!1,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-search-result-click",{detail:{result:e,index:s},bubbles:!0,composed:!0}))}),t.append(a)}),e.append(t)}else{const t=document.createElement("div");t.className="designbase-wc-search-bar__results-empty",t.textContent="검색 결과가 없습니다.",e.append(t)}return this.dropdown.append(e),void this.attachDropdownPortal()}if(this.hasAttribute("enable-recent-searches")&&!n&&this.recentSearches.length>0){const s=document.createElement("div");s.className=`designbase-wc-search-bar__recent-searches designbase-wc-search-bar__recent-searches--${d}`;const a=document.createElement("div");a.className="designbase-wc-search-bar__recent-header";const n=document.createElement("span");n.className="designbase-wc-search-bar__recent-title",n.textContent="최근 검색어";const r=document.createElement("button");r.type="button",r.className="designbase-wc-search-bar__clear-all-button",r.setAttribute("aria-label","모든 최근 검색어 삭제"),r.textContent="전체 삭제",r.addEventListener("mousedown",e=>{e.preventDefault(),this.recentSearches=[];try{localStorage.removeItem(this.getRecentSearchesKey())}catch{}this.updateDropdown()}),a.append(n,r);const i=document.createElement("div");i.className="designbase-wc-search-bar__recent-list",this.recentSearches.forEach(s=>{const a=document.createElement("div");a.className="designbase-wc-search-bar__recent-item";const n=document.createElement("button");n.type="button",n.className="designbase-wc-search-bar__recent-search-button",n.textContent=s,n.addEventListener("mousedown",e=>{if(e.preventDefault(),!this.input)return;this.input.value=s,this.setAttribute("value",s),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(s);const t={value:s};this.dispatchEvent(new CustomEvent("db-input",{detail:t,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:t,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()});const r=document.createElement("button");r.type="button",r.className="designbase-wc-search-bar__recent-remove-button",r.setAttribute("aria-label",`${s} 삭제`),r.append(t("close",e("s"))),r.addEventListener("mousedown",e=>{e.preventDefault(),this.recentSearches=this.recentSearches.filter(e=>e!==s),this.saveRecentSearches(),this.updateDropdown()}),a.append(n,r),i.append(a)}),s.append(a,i),this.dropdown.append(s)}if(i.length>0&&!n){const e=document.createElement("div");e.className="designbase-wc-search-bar__suggestions";const t=document.createElement("div");t.className="designbase-wc-search-bar__suggestions-header";const s=document.createElement("span");s.className="designbase-wc-search-bar__suggestions-title",s.textContent="추천 검색어",t.append(s);const a=document.createElement("div");a.className="designbase-wc-search-bar__suggestions-list",i.forEach((e,t)=>{const s=document.createElement("button");s.type="button",s.className=["designbase-wc-search-bar__suggestion-item",t===this.currentSuggestion&&"designbase-wc-search-bar__suggestion-item--active"].filter(Boolean).join(" "),s.textContent=e,s.addEventListener("mousedown",t=>{if(t.preventDefault(),!this.input)return;this.clearSuggestionInterval(),this.input.value=e,this.setAttribute("value",e),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(e);const s={value:e};this.dispatchEvent(new CustomEvent("db-input",{detail:s,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:s,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()}),a.append(s)}),e.append(t,a),this.dropdown.append(e)}if(h&&!n&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===i.length){const e=document.createElement("div");e.className="designbase-wc-search-bar__empty-state",e.textContent=h,this.dropdown.append(e)}this.attachDropdownPortal()}render(){const e=this.getAttribute("size")||"m",a=this.hasAttribute("disabled"),n=this.hasAttribute("readonly"),r=this.hasAttribute("full-width"),i=this.hasAttribute("show-shortcut"),o=this.getAttribute("value")??this.getAttribute("default-value")??"",c=Boolean(o.trim()),h=this.getIconPx();this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${s.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",a&&"designbase-wc-search-bar--disabled",n&&"designbase-wc-search-bar--readonly",r&&"designbase-wc-search-bar--full-width",c&&"designbase-wc-search-bar--has-value",this.shouldShowDropdown()&&"designbase-wc-search-bar--dropdown-open"].filter(Boolean).join(" "),this.setAttribute("role","search"),this.clearSuggestionInterval(),this.detachDropdownPortal(),this.replaceChildren();const d=document.createElement("div");d.className="designbase-wc-search-bar__container";const l=document.createElement("div");l.className="designbase-wc-search-bar__search-icon",l.setAttribute("aria-hidden","true"),l.append(t("search",h));const u=document.createElement("input");if(u.type="text",u.className="designbase-wc-search-bar__input",u.value=o,u.disabled=a,u.readOnly=n,u.setAttribute("aria-label","검색어 입력"),this.input=u,i){const t=document.createElement("db-badge");t.className="designbase-wc-search-bar__shortcut-badge",t.setAttribute("size","l"===e?"m":"s"),t.setAttribute("variant","secondary"),t.setAttribute("type","text"),t.setAttribute("aria-hidden","true"),t.textContent=this.getAttribute("shortcut-label")||"⌘K",t.hidden=c||a||n,this.shortcutBadge=t,d.append(l,u,t)}else d.append(l,u);const b=document.createElement("button");b.type="button",b.className="designbase-wc-search-bar__clear-button",b.setAttribute("aria-label","검색어 지우기"),b.hidden=!c||a||n,b.append(t("close",h)),this.clearButton=b,d.append(b);const p=document.createElement("div");p.className="designbase-wc-search-bar__dropdown",p.hidden=!0,p.addEventListener("mousedown",e=>{e.preventDefault()}),this.dropdown=p,u.addEventListener("input",()=>{this.setAttribute("value",u.value),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling();const e={value:u.value};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),u.addEventListener("keydown",e=>{"Enter"===e.key&&this.handleSearch()}),u.addEventListener("focus",()=>{this.isFocused=!0,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-focus",{bubbles:!0,composed:!0}))}),u.addEventListener("blur",()=>{this.isFocused=!1,this.blurTimer&&clearTimeout(this.blurTimer),this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-blur",{bubbles:!0,composed:!0}))}),b.addEventListener("click",()=>{u.value="",this.setAttribute("value",""),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling(),u.focus(),this.dispatchEvent(new CustomEvent("db-clear",{bubbles:!0,composed:!0}));const e={value:""};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),this.append(d,p),this.syncIcons(),this.syncPlaceholder(),this.syncSuggestionRolling(),this.bindGlobalShortcut(),this.updateDropdown()}}customElements.get("db-search-bar")||customElements.define("db-search-bar",DbSearchBar);export{DbSearchBar};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{createDbIcon as e}from"./db-icons.js";const t="designbase-wc-segment-control",i={bar:'<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="12" width="4" height="8"/><rect x="10" y="8" width="4" height="12"/><rect x="17" y="4" width="4" height="16"/></svg>',line:'<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 16 9 10 14 13 20 6"/></svg>',pie:'<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v10l8.66 5"/><circle cx="12" cy="12" r="10"/></svg>',donut:'<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3"/></svg>',radar:'<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 20 8 17 20 7 20 4 8"/></svg>'};class DbSegmentControl extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.indicatorEl=null,this.segmentButtons=[],this.focusedIndex=-1,this.boundKeyDown=e=>this.handleKeyDown(e),this.boundResize=()=>this.updateIndicator(),this.resizeObserver=null}static get observedAttributes(){return["options","value","default-value","size","variant","appearance","full-width","disabled"]}connectedCallback(){this.built||(this.built=!0),this.render(),this.addEventListener("keydown",this.boundKeyDown),window.addEventListener("resize",this.boundResize),this.resizeObserver=new ResizeObserver(()=>this.updateIndicator()),this.resizeObserver.observe(this)}disconnectedCallback(){this.removeEventListener("keydown",this.boundKeyDown),window.removeEventListener("resize",this.boundResize),this.resizeObserver?.disconnect(),this.resizeObserver=null}attributeChangedCallback(e){this.built&&("value"!==e?this.render():this.updateSelection())}get options(){return this.parseOptions(this.getAttribute("options"))}set options(e){const t="string"==typeof e?e:JSON.stringify(e);this.getAttribute("options")!==t&&this.setAttribute("options",t)}get value(){return this.getAttribute("value")||this.getAttribute("default-value")||this.options[0]?.value||""}set value(e){this.setAttribute("value",e)}parseOptions(e){if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}render(){const s=this.getAttribute("size")||"m",n=this.getAttribute("variant")||"default",r=this.getAttribute("appearance")||"default",a=this.hasAttribute("disabled"),o=this.options,l=this.value;this.className=[t,`${t}--${s}`,`${t}--${n}`,"pill"===r&&`${t}--appearance-pill`,"rounded"===r&&`${t}--appearance-rounded`,this.hasAttribute("full-width")&&`${t}--full-width`,a&&`${t}--disabled`].filter(Boolean).join(" "),this.setAttribute("role","tablist"),this.hasAttribute("aria-label")||this.setAttribute("aria-label","세그먼트 컨트롤"),this.replaceChildren(),this.segmentButtons=[],o.forEach((s,r)=>{const o=s.value===l,d=Boolean(a||s.disabled),h=document.createElement("button");if(h.type="button",h.className=[`${t}__segment`,o&&`${t}__segment--selected`,d&&`${t}__segment--disabled`].filter(Boolean).join(" "),h.setAttribute("role","tab"),h.setAttribute("aria-selected",String(o)),h.setAttribute("aria-disabled",String(d)),h.setAttribute("tabindex",o?"0":"-1"),h.disabled=d,s.icon&&(i[s.icon]||["desktop","tablet","mobile"].includes(s.icon))){const n=document.createElement("span");n.className=`${t}__segment-icon`,"desktop"===s.icon||"tablet"===s.icon||"mobile"===s.icon?n.append(e(s.icon,18)):n.innerHTML=i[s.icon],h.appendChild(n)}const u=document.createElement("span");u.className=`${t}__segment-label`,u.textContent=s.label,"icon-only"===n&&(h.setAttribute("aria-label",s.label),h.title=s.label,u.setAttribute("aria-label",s.label)),h.appendChild(u),h.addEventListener("click",()=>this.select(s.value)),h.addEventListener("focus",()=>{this.focusedIndex=r,h.classList.add(`${t}__segment--focused`)}),h.addEventListener("blur",()=>{this.focusedIndex=-1,h.classList.remove(`${t}__segment--focused`)}),this.appendChild(h),this.segmentButtons.push(h)}),this.indicatorEl=document.createElement("div"),this.indicatorEl.className=`${t}__indicator`,this.appendChild(this.indicatorEl),this.updateSelection()}updateSelection(){const e=this.options,i=this.value,s=e.findIndex(e=>e.value===i);this.segmentButtons.forEach((s,n)=>{const r=e[n],a=r?.value===i;s.classList.toggle(`${t}__segment--selected`,a),s.setAttribute("aria-selected",String(a)),s.setAttribute("tabindex",a?"0":"-1")}),this.indicatorEl&&e.length>0&&s>=0&&requestAnimationFrame(()=>this.updateIndicator())}updateIndicator(){const e=this.options.findIndex(e=>e.value===this.value),t=this.segmentButtons[e];this.indicatorEl&&t&&(this.indicatorEl.style.width=`${t.offsetWidth}px`,this.indicatorEl.style.transform=`translateX(${t.offsetLeft}px)`)}select(e){if(this.hasAttribute("disabled"))return;const t=this.options.find(t=>t.value===e);t&&!t.disabled&&(this.setAttribute("value",e),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:e},bubbles:!0,composed:!0})))}handleKeyDown(e){if(this.hasAttribute("disabled"))return;const t=this.options,i=this.focusedIndex>=0?this.focusedIndex:t.findIndex(e=>e.value===this.value);if(-1===i)return;let s=i;switch(e.key){case"ArrowLeft":e.preventDefault(),s=i>0?i-1:t.length-1;break;case"ArrowRight":e.preventDefault(),s=i<t.length-1?i+1:0;break;case"Home":e.preventDefault(),s=0;break;case"End":e.preventDefault(),s=t.length-1;break;case"Enter":case" ":return e.preventDefault(),void this.select(t[s]?.value??this.value);default:return}for(;s!==i;){const i=t[s];if(i&&!i.disabled){this.segmentButtons[s]?.focus();break}s="ArrowLeft"===e.key||"Home"===e.key?s>0?s-1:t.length-1:s<t.length-1?s+1:0}}}customElements.get("db-segment-control")||customElements.define("db-segment-control",DbSegmentControl);export{DbSegmentControl};
|