@designbasekorea/ui-wc 0.10.0 → 0.12.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 +19 -0
- package/LICENSE-WORLD-MAP.md +10 -0
- package/README.md +83 -0
- package/dist/esm/components/db-achievement-list.d.ts +2 -0
- package/dist/esm/components/db-achievement-list.js +1 -1
- package/dist/esm/components/db-activity-heatmap.d.ts +1 -0
- package/dist/esm/components/db-activity-heatmap.js +1 -1
- package/dist/esm/components/db-ad-banner.d.ts +2 -0
- package/dist/esm/components/db-ad-banner.js +1 -1
- package/dist/esm/components/db-ai-chat-list.d.ts +5 -1
- package/dist/esm/components/db-ai-chat-list.js +1 -1
- package/dist/esm/components/db-ai-chat.d.ts +2 -0
- package/dist/esm/components/db-ai-chat.js +1 -1
- package/dist/esm/components/db-ai-file-tree.js +1 -1
- package/dist/esm/components/db-alert.d.ts +1 -0
- package/dist/esm/components/db-alert.js +1 -1
- package/dist/esm/components/db-audio-player.d.ts +2 -0
- package/dist/esm/components/db-audio-player.js +1 -1
- package/dist/esm/components/db-avatar.d.ts +1 -0
- package/dist/esm/components/db-avatar.js +1 -1
- package/dist/esm/components/db-banner.d.ts +2 -0
- package/dist/esm/components/db-banner.js +1 -1
- package/dist/esm/components/db-button.d.ts +7 -1
- package/dist/esm/components/db-button.js +1 -1
- package/dist/esm/components/db-calendar.d.ts +5 -0
- package/dist/esm/components/db-calendar.js +1 -1
- package/dist/esm/components/db-card.d.ts +1 -0
- package/dist/esm/components/db-card.js +1 -1
- package/dist/esm/components/db-chat-composer.d.ts +3 -0
- package/dist/esm/components/db-chat-composer.js +1 -1
- package/dist/esm/components/db-chat-message.d.ts +2 -0
- package/dist/esm/components/db-chat-message.js +1 -1
- package/dist/esm/components/db-chat-room.d.ts +1 -0
- package/dist/esm/components/db-chat-room.js +1 -1
- package/dist/esm/components/db-chat-typing.d.ts +2 -0
- package/dist/esm/components/db-chat-typing.js +1 -1
- package/dist/esm/components/db-chat-widget.d.ts +9 -0
- package/dist/esm/components/db-chat-widget.js +1 -1
- package/dist/esm/components/db-chip.d.ts +2 -0
- package/dist/esm/components/db-chip.js +1 -1
- package/dist/esm/components/db-code-block.d.ts +1 -0
- package/dist/esm/components/db-code-block.js +1 -1
- package/dist/esm/components/db-color-picker.d.ts +4 -0
- package/dist/esm/components/db-color-picker.js +1 -1
- package/dist/esm/components/db-color-swatch.d.ts +3 -0
- package/dist/esm/components/db-color-swatch.js +1 -1
- package/dist/esm/components/db-cookie-banner.d.ts +3 -0
- package/dist/esm/components/db-cookie-banner.js +1 -1
- package/dist/esm/components/db-countdown.d.ts +2 -1
- package/dist/esm/components/db-countdown.js +1 -1
- package/dist/esm/components/db-date-picker.d.ts +3 -0
- package/dist/esm/components/db-date-picker.js +1 -1
- package/dist/esm/components/db-dropdown.d.ts +1 -0
- package/dist/esm/components/db-dropdown.js +1 -1
- package/dist/esm/components/db-dropzone.d.ts +2 -0
- package/dist/esm/components/db-dropzone.js +1 -1
- package/dist/esm/components/db-email-verify.d.ts +1 -0
- package/dist/esm/components/db-email-verify.js +1 -1
- package/dist/esm/components/db-file-uploader.d.ts +2 -0
- package/dist/esm/components/db-file-uploader.js +1 -1
- package/dist/esm/components/db-form.d.ts +2 -0
- package/dist/esm/components/db-form.js +1 -1
- package/dist/esm/components/db-gantt.d.ts +2 -0
- package/dist/esm/components/db-gantt.js +1 -1
- package/dist/esm/components/db-image-list.d.ts +3 -0
- package/dist/esm/components/db-image-list.js +1 -1
- package/dist/esm/components/db-image.d.ts +1 -0
- package/dist/esm/components/db-image.js +1 -1
- package/dist/esm/components/db-input-group.d.ts +30 -0
- package/dist/esm/components/db-input-group.js +1 -0
- package/dist/esm/components/db-input.d.ts +1 -0
- package/dist/esm/components/db-input.js +1 -1
- package/dist/esm/components/db-kanban.d.ts +3 -0
- package/dist/esm/components/db-kanban.js +1 -1
- package/dist/esm/components/db-lightbox.d.ts +2 -0
- package/dist/esm/components/db-lightbox.js +1 -1
- package/dist/esm/components/db-list.d.ts +2 -0
- package/dist/esm/components/db-list.js +1 -1
- package/dist/esm/components/db-markdown-editor.d.ts +2 -0
- package/dist/esm/components/db-markdown-editor.js +1 -1
- package/dist/esm/components/db-menu-item.js +1 -1
- package/dist/esm/components/db-navbar.d.ts +3 -0
- package/dist/esm/components/db-navbar.js +1 -1
- package/dist/esm/components/db-node.d.ts +1 -0
- package/dist/esm/components/db-node.js +1 -1
- package/dist/esm/components/db-onboarding-modal.d.ts +2 -0
- package/dist/esm/components/db-onboarding-modal.js +1 -1
- package/dist/esm/components/db-otp-input.d.ts +4 -1
- package/dist/esm/components/db-otp-input.js +1 -1
- package/dist/esm/components/db-page-header.js +1 -1
- package/dist/esm/components/db-popover.d.ts +1 -0
- package/dist/esm/components/db-popover.js +1 -1
- package/dist/esm/components/db-progress-step.d.ts +2 -0
- package/dist/esm/components/db-progress-step.js +1 -1
- package/dist/esm/components/db-range-slider.d.ts +1 -0
- package/dist/esm/components/db-range-slider.js +1 -1
- package/dist/esm/components/db-rating.d.ts +1 -0
- package/dist/esm/components/db-rating.js +1 -1
- package/dist/esm/components/db-search-bar.d.ts +2 -0
- package/dist/esm/components/db-search-bar.js +1 -1
- package/dist/esm/components/db-section-logo-cloud.js +1 -1
- package/dist/esm/components/db-selection-bar.d.ts +42 -0
- package/dist/esm/components/db-selection-bar.js +1 -0
- package/dist/esm/components/db-share.d.ts +5 -0
- package/dist/esm/components/db-share.js +1 -1
- package/dist/esm/components/db-sidebar.d.ts +3 -0
- package/dist/esm/components/db-sidebar.js +1 -1
- package/dist/esm/components/db-signature.d.ts +2 -0
- package/dist/esm/components/db-signature.js +1 -1
- package/dist/esm/components/db-spinner.d.ts +2 -0
- package/dist/esm/components/db-spinner.js +1 -1
- package/dist/esm/components/db-stepper.d.ts +2 -0
- package/dist/esm/components/db-stepper.js +1 -1
- package/dist/esm/components/db-table.d.ts +2 -0
- package/dist/esm/components/db-table.js +1 -1
- package/dist/esm/components/db-tabs.d.ts +1 -0
- package/dist/esm/components/db-tabs.js +1 -1
- package/dist/esm/components/db-ticket.js +1 -1
- package/dist/esm/components/db-time-picker.d.ts +2 -0
- package/dist/esm/components/db-time-picker.js +1 -1
- package/dist/esm/components/db-timeline.d.ts +4 -0
- package/dist/esm/components/db-timeline.js +1 -1
- package/dist/esm/components/db-toast.d.ts +2 -0
- package/dist/esm/components/db-toast.js +1 -1
- package/dist/esm/components/db-tool-layout.d.ts +92 -0
- package/dist/esm/components/db-tool-layout.js +1 -0
- package/dist/esm/components/db-tool-panel.d.ts +50 -0
- package/dist/esm/components/db-tool-panel.js +1 -0
- package/dist/esm/components/db-top-banner.d.ts +2 -0
- package/dist/esm/components/db-top-banner.js +1 -1
- package/dist/esm/components/db-video-player.d.ts +3 -0
- package/dist/esm/components/db-video-player.js +1 -1
- package/dist/esm/components/db-world-map.d.ts +60 -0
- package/dist/esm/components/db-world-map.js +1 -0
- package/dist/esm/components/db-youtube-player.d.ts +2 -0
- package/dist/esm/components/db-youtube-player.js +1 -1
- package/dist/esm/components/db-zoom-control.d.ts +52 -0
- package/dist/esm/components/db-zoom-control.js +1 -0
- package/dist/esm/components/input-validation.js +1 -1
- package/dist/esm/components/paper-card.d.ts +2 -0
- package/dist/esm/components/paper-card.js +1 -1
- package/dist/esm/core/i18n-copy.js +1 -1
- package/dist/esm/core/i18n-en.js +1 -1
- package/dist/esm/core/i18n.d.ts +34 -1
- package/dist/esm/core/i18n.js +1 -1
- package/dist/esm/helpers/world-countries.js +1 -0
- package/dist/esm/helpers/world-land.js +1 -0
- package/dist/esm/index.d.ts +7 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/node_modules/@designbasekorea/ui-contracts/dist/components.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.css +1 -1
- package/dist/index.d.ts +484 -6
- package/dist/index.esm.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +871 -71
- package/dist/react/index.esm.js +1 -1
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dbText as t}from"../core/i18n.js";import{hexToRgb as e,rgbToHsv as i,hsvToRgb as s,toHex as l,rgbToHsl as n,formatColor as o,normalizeHex as r,isHex as a,clamp as h}from"./color-picker-utils.js";import{getDbComponentIconSize as d,createDbIcon as p}from"./db-icons.js";import{rafThrottle as u}from"../core/dom.js";import{coerceToContract as c}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{COLOR_PICKER_SIZES as g,COLOR_PICKER_POSITIONS as m}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const E=g,b=["dropdown","modal"],v=["input","swatch"],y=m,I="#006FFF",w=e(I)??{r:0,g:111,b:255},A=i(w.r,w.g,w.b),C=JSON.stringify([{label:"HEX",value:"hex"},{label:"RGB",value:"rgb"},{label:"RGBA",value:"rgba"},{label:"HSL",value:"hsl"},{label:"HSLA",value:"hsla"}]);class DbColorPicker extends HTMLElement{constructor(){super(...arguments),this.h=A.h,this.s=A.s,this.v=A.v,this.a=100,this.open=!1,this.format="hex",this.colorInput=I,this.alphaInput="100",this.isCopied=!1,this.tempColor="",this.dragging=null,this.mounted=!1,this.copiedTimer=null,this.debounceTimer=null,this.lastEmittedHex="",this.suppressNextValueSync=!1,this.didMount=!1,this.triggerInputFocused=!1,this.panelInputFocused=!1,this.panelAlphaInputFocused=!1,this.handleEscape=t=>{"Escape"!==t.key||t.defaultPrevented||t.isComposing||!this.open||"dropdown"===this.getOption("type",b,"dropdown")&&(t.preventDefault(),this.close(),this.toggleBtn?.focus())},this.handleOutsideClick=t=>{if(!this.open||"dropdown"!==this.getOption("type",b,"dropdown"))return;const e=t.target;this.contains(e)||this.formatSelectEl?.contains(e)||(this.open=!1,this.update())},this.handleDocumentMouseMove=u(t=>{"area"===this.dragging&&(this.getBool("disabled")||this.getBool("readonly")||this.updateFromArea(t.clientX,t.clientY))}),this.handleDocumentMouseUp=()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))},this.handleModalCancel=()=>{const t=e(this.tempColor);if(t){const e=i(t.r,t.g,t.b);this.h=e.h,this.s=e.s,this.v=e.v}this.open=!1,this.update(),this.dispatchEvent(new CustomEvent("db-cancel",{bubbles:!0,composed:!0}))},this.handleModalApply=()=>{this.open=!1,this.actuallyEmit(),this.dispatchEvent(new CustomEvent("db-apply",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})),this.update()}}static get observedAttributes(){return["size","type","trigger","position","value","default-value","show-input","show-alpha","show-format-selector","show-copy-button","show-eyedropper","disabled","readonly","full-width","error","on-change-format","change-debounce-ms","emit-during-drag"]}connectedCallback(){this.mounted||this.mount(),this.syncFromValueAttr(!0),this.update(),document.addEventListener("mousedown",this.handleOutsideClick),document.addEventListener("mousemove",this.handleDocumentMouseMove),document.addEventListener("mouseup",this.handleDocumentMouseUp),document.addEventListener("keydown",this.handleEscape)}disconnectedCallback(){document.removeEventListener("mousedown",this.handleOutsideClick),document.removeEventListener("mousemove",this.handleDocumentMouseMove),document.removeEventListener("mouseup",this.handleDocumentMouseUp),document.removeEventListener("keydown",this.handleEscape),this.copiedTimer&&clearTimeout(this.copiedTimer),this.debounceTimer&&clearTimeout(this.debounceTimer)}attributeChangedCallback(t){this.mounted&&("value"!==t&&"default-value"!==t||this.syncFromValueAttr(!1),this.update())}getBool(t,e=!1){if(!this.hasAttribute(t))return e;const i=this.getAttribute(t);return""===i||"true"===i}getOption(t,e,i){return c(this.getAttribute(t),e,i)}getIconSize(){return d(this.getOption("size",E,"m"))}getRgb(){return s(this.h,this.s,this.v)}getHex(){const t=this.getRgb();return l(t.r,t.g,t.b)}getHsl(){const t=this.getRgb();return n(t.r,t.g,t.b)}getUiFormatted(){const t=this.getRgb(),e=this.getHex(),i=this.getHsl();return o(this.format,t,e,i,this.a)}getOutward(){return"hex"===("ui"===this.getAttribute("on-change-format")?"ui":"hex")?this.getHex():this.getUiFormatted()}syncFromValueAttr(t){const s=this.getAttribute("value")??(t?this.getAttribute("default-value"):null)??(t?I:null);if(null==s)return;const l=r(s);if(!a(l))return;if(!t&&this.suppressNextValueSync&&l===this.lastEmittedHex)return void(this.suppressNextValueSync=!1);const n=e(l);if(!n)return;const o=i(n.r,n.g,n.b);this.h=o.h,this.s=o.s,this.v=o.v,this.colorInput=l,this.lastEmittedHex=l}actuallyEmit(){const t=r(this.getHex()),e=this.hasAttribute("value")&&a(this.getAttribute("value")||"")?r(this.getAttribute("value")||""):null;e&&e===t||this.lastEmittedHex!==t&&(this.lastEmittedHex=t,this.suppressNextValueSync=!0,this.setAttribute("value",t),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})))}scheduleEmit(){const t=this.getBool("emit-during-drag",!0);if(this.dragging&&!t)return;const e=Number(this.getAttribute("change-debounce-ms")||"0");if(e>0)return this.debounceTimer&&clearTimeout(this.debounceTimer),void(this.debounceTimer=setTimeout(()=>this.actuallyEmit(),e));this.actuallyEmit()}onColorStateChanged(t=!1){this.didMount?(!t||this.getBool("emit-during-drag",!0),this.scheduleEmit()):this.didMount=!0}updateFromArea(t,e){const i=this.colorFieldEl;if(!i)return;const s=i.getBoundingClientRect(),l=h(t-s.left,0,s.width),n=h(e-s.top,0,s.height);this.s=l/s.width*100,this.v=100-n/s.height*100,this.updateVisuals(),this.onColorStateChanged()}getInputValue(t){return t?t.getAttribute("value")??"":""}setInputValue(t,e){t&&void 0!==e&&t.setAttribute("value",e)}getPanelControlSize(){return"s"===this.getOption("size",E,"m")?"s":"m"}commitColorInput(t){const s="trigger"===t?this.triggerInputEl?.value??"":this.getInputValue(this.panelValueInputEl),l=s.trim();if(/^#([0-9A-Fa-f]{6})$/.test(l)){const t=e(l),s=i(t.r,t.g,t.b);return this.h=s.h,this.s=s.s,this.v=s.v,this.colorInput=r(l),this.updateVisuals(),void this.onColorStateChanged()}let n=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(s);if(n){const t=h(parseInt(n[1],10),0,255),e=h(parseInt(n[2],10),0,255),s=h(parseInt(n[3],10),0,255),l=i(t,e,s);return this.h=l.h,this.s=l.s,this.v=l.v,this.colorInput=`rgb(${t}, ${e}, ${s})`,this.updateVisuals(),void this.onColorStateChanged()}if(n=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i.exec(l),n){const t=h(parseInt(n[1],10),0,255),e=h(parseInt(n[2],10),0,255),s=h(parseInt(n[3],10),0,255),l=parseFloat(n[4]),o=i(t,e,s);this.h=o.h,this.s=o.s,this.v=o.v,this.a=Math.round(100*l),this.alphaInput=String(this.a),this.colorInput=`rgba(${t}, ${e}, ${s}, ${l})`,this.updateVisuals(),this.onColorStateChanged()}}commitAlphaInput(){const t=Number(this.getInputValue(this.panelAlphaInputEl).trim()||this.alphaInput);if(!Number.isNaN(t)&&t>=0&&t<=100){const e=Math.round(t);this.a=e,this.alphaInput=String(e),this.updateVisuals(),this.onColorStateChanged()}else this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput)}async onCopy(){try{await navigator.clipboard.writeText(this.getUiFormatted()),this.isCopied=!0,this.updateCopyButtons(),this.copiedTimer&&clearTimeout(this.copiedTimer),this.copiedTimer=setTimeout(()=>{this.isCopied=!1,this.updateCopyButtons()},1600)}catch{}}async onEyedrop(){try{if("EyeDropper"in window){const t=new window.EyeDropper,{sRGBHex:s}=await t.open(),l=e(s);if(!l)return;const n=i(l.r,l.g,l.b);this.h=n.h,this.s=n.s,this.v=n.v,this.updateVisuals(),this.onColorStateChanged()}}catch{}}toggleOpen(){if(this.getBool("disabled")||this.getBool("readonly"))return;if("modal"===this.getOption("type",b,"dropdown"))return this.tempColor=this.getHex(),this.open=!0,void this.update();this.open=!this.open,this.update()}close(){this.open&&"dropdown"===this.getOption("type",b,"dropdown")&&(this.open=!1,this.update())}mount(){this.mounted=!0;const e=this.getIconSize();this.triggerEl=document.createElement("div"),this.triggerEl.className="designbase-wc-color-picker__trigger",this.triggerEl.addEventListener("click",()=>this.toggleOpen());const i=document.createElement("div");i.className="designbase-wc-color-picker__color-display",this.colorBoxEl=document.createElement("div"),this.colorBoxEl.className="designbase-wc-color-picker__color-box",i.append(this.colorBoxEl),this.triggerInputEl=document.createElement("input"),this.triggerInputEl.type="text",this.triggerInputEl.className="designbase-wc-color-picker__input",this.triggerInputEl.placeholder="#000000",this.triggerInputEl.addEventListener("click",t=>t.stopPropagation()),this.triggerInputEl.addEventListener("focus",()=>{this.triggerInputFocused=!0}),this.triggerInputEl.addEventListener("blur",()=>{this.triggerInputFocused=!1;const t="hex"===this.format?r(this.getUiFormatted()):this.getUiFormatted();this.triggerInputEl&&this.triggerInputEl.value!==t&&(this.triggerInputEl.value=t,this.colorInput=t)}),this.triggerInputEl.addEventListener("input",()=>{this.triggerInputEl&&(this.colorInput=this.triggerInputEl.value)}),this.triggerInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("trigger")});const s=document.createElement("div");s.className="designbase-wc-color-picker__trigger-actions",this.triggerCopyBtn=document.createElement("button"),this.triggerCopyBtn.type="button",this.triggerCopyBtn.className="designbase-wc-color-picker__copy-button-inline",this.triggerCopyBtn.setAttribute("aria-label","Copy color value"),this.triggerCopyBtn.addEventListener("click",t=>{t.stopPropagation(),this.onCopy()}),this.toggleBtn=document.createElement("button"),this.toggleBtn.type="button",this.toggleBtn.className="designbase-wc-color-picker__toggle",this.toggleBtn.setAttribute("aria-label","Toggle color picker"),this.toggleBtn.append(p("chevron-down",e)),s.append(this.triggerCopyBtn,this.toggleBtn),this.triggerEl.append(i,this.triggerInputEl,s),this.dropdownEl=document.createElement("div"),this.dropdownEl.className="designbase-wc-color-picker__dropdown",this.dropdownEl.addEventListener("click",t=>t.stopPropagation()),this.dropdownEl.hidden=!0;const l=document.createElement("div");l.className="designbase-wc-color-picker__selector";const n=document.createElement("div");n.className="designbase-wc-color-picker__color-area",this.colorFieldEl=document.createElement("div"),this.colorFieldEl.className="designbase-wc-color-picker__color-field",this.colorPointerEl=document.createElement("div"),this.colorPointerEl.className="designbase-wc-color-picker__color-pointer",this.colorFieldEl.append(this.colorPointerEl),this.colorFieldEl.addEventListener("mousedown",t=>{this.getBool("disabled")||this.getBool("readonly")||(t.preventDefault(),this.dragging="area",this.updateFromArea(t.clientX,t.clientY))}),this.colorFieldEl.addEventListener("touchstart",t=>{if(this.getBool("disabled")||this.getBool("readonly"))return;this.dragging="area";const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchmove",t=>{if("area"!==this.dragging)return;const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchend",()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))}),n.append(this.colorFieldEl);const o=document.createElement("div");o.className="designbase-wc-color-picker__controls",this.eyedropperBtnEl=document.createElement("db-button"),this.eyedropperBtnEl.setAttribute("variant","tertiary"),this.eyedropperBtnEl.setAttribute("size",this.getPanelControlSize()),this.eyedropperBtnEl.setAttribute("icon-only",""),this.eyedropperBtnEl.setAttribute("start-icon","eyedropper"),this.eyedropperBtnEl.setAttribute("aria-label","Eyedropper tool"),this.eyedropperBtnEl.addEventListener("click",()=>{this.onEyedrop()});const a=document.createElement("div");a.className="designbase-wc-color-picker__slider-container";const d=document.createElement("div");d.className="designbase-wc-color-picker__hue-slider",this.hueSliderEl=document.createElement("input"),this.hueSliderEl.type="range",this.hueSliderEl.min="0",this.hueSliderEl.max="360",this.hueSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--hue",this.hueSliderEl.addEventListener("input",()=>{this.h=parseFloat(this.hueSliderEl.value),this.updateVisuals(),this.onColorStateChanged()}),d.append(this.hueSliderEl),this.alphaSliderWrapEl=document.createElement("div"),this.alphaSliderWrapEl.className="designbase-wc-color-picker__alpha-slider",this.alphaSliderEl=document.createElement("input"),this.alphaSliderEl.type="range",this.alphaSliderEl.min="0",this.alphaSliderEl.max="100",this.alphaSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--alpha",this.alphaSliderEl.addEventListener("input",()=>{this.a=h(parseInt(this.alphaSliderEl.value,10),0,100),this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.updateVisuals(),this.onColorStateChanged()}),this.alphaSliderWrapEl.append(this.alphaSliderEl),a.append(d,this.alphaSliderWrapEl),o.append(this.eyedropperBtnEl,a);const u=document.createElement("div");u.className="designbase-wc-color-picker__value-display",this.formatSelectEl=document.createElement("db-select"),this.formatSelectEl.setAttribute("size","s"),this.formatSelectEl.setAttribute("position","top"),this.formatSelectEl.setAttribute("show-clear-button","false"),this.formatSelectEl.setAttribute("options",C),this.formatSelectEl.addEventListener("db-change",t=>{const e=t.detail,i=e?.value;i&&(this.format=i,this.updateVisuals())}),this.panelValueInputEl=document.createElement("db-input"),this.panelValueInputEl.classList.add("designbase-wc-color-picker__value-input"),this.panelValueInputEl.setAttribute("size","s"),this.panelValueInputEl.setAttribute("placeholder","#000000"),this.panelValueInputEl.addEventListener("db-focus",()=>{this.panelInputFocused=!0}),this.panelValueInputEl.addEventListener("db-blur",()=>{this.panelInputFocused=!1;const t="hex"===this.format?r(this.getUiFormatted()):this.getUiFormatted();this.getInputValue(this.panelValueInputEl)!==t&&(this.setInputValue(this.panelValueInputEl,t),this.colorInput=t)}),this.panelValueInputEl.addEventListener("db-input",t=>{const e=t.detail;void 0!==e?.value&&(this.colorInput=e.value)}),this.panelValueInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("panel")}),this.panelAlphaWrapEl=document.createElement("div"),this.panelAlphaWrapEl.className="designbase-wc-color-picker__alpha-input-wrap",this.panelAlphaInputEl=document.createElement("db-input"),this.panelAlphaInputEl.classList.add("designbase-wc-color-picker__alpha-input"),this.panelAlphaInputEl.setAttribute("size","s"),this.panelAlphaInputEl.setAttribute("placeholder","100"),this.panelAlphaInputEl.setAttribute("aria-label","Alpha percent"),this.panelAlphaInputEl.addEventListener("db-focus",()=>{this.panelAlphaInputFocused=!0}),this.panelAlphaInputEl.addEventListener("db-blur",()=>{this.panelAlphaInputFocused=!1,this.commitAlphaInput()}),this.panelAlphaInputEl.addEventListener("db-input",t=>{const e=t.detail,i=(e?.value??"").replace(/[^\d]/g,"").slice(0,3);i!==e?.value&&this.setInputValue(this.panelAlphaInputEl,i),this.alphaInput=i}),this.panelAlphaInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitAlphaInput()});const c=document.createElement("span");c.className="designbase-wc-color-picker__alpha-suffix",c.textContent="%",this.panelAlphaWrapEl.append(this.panelAlphaInputEl,c),this.panelCopyBtnEl=document.createElement("db-button"),this.panelCopyBtnEl.setAttribute("variant","tertiary"),this.panelCopyBtnEl.setAttribute("size","s"),this.panelCopyBtnEl.setAttribute("icon-only",""),this.panelCopyBtnEl.setAttribute("start-icon","copy"),this.panelCopyBtnEl.setAttribute("aria-label","Copy color value"),this.panelCopyBtnEl.addEventListener("click",()=>{this.onCopy()}),u.append(this.formatSelectEl,this.panelValueInputEl,this.panelAlphaWrapEl,this.panelCopyBtnEl),l.append(n,o,u),this.selectorEl=l,this.dropdownEl.append(l),this.modalEl=document.createElement("db-modal"),this.modalEl.setAttribute("size","s"),this.modalEl.setAttribute("title",t("색상 선택")),this.modalEl.setAttribute("close-on-escape","true"),this.modalEl.addEventListener("db-close",this.handleModalCancel),this.modalBodyEl=document.createElement("div"),this.modalBodyEl.className="designbase-wc-modal__body designbase-wc-color-picker__modal-body",this.modalBodyEl.setAttribute("data-modal-part","body");const g=document.createElement("div");g.className="designbase-wc-modal__footer",g.setAttribute("data-modal-part","footer");const m=document.createElement("db-button");m.setAttribute("variant","tertiary"),m.setAttribute("size","m"),m.textContent=t("취소"),m.addEventListener("click",this.handleModalCancel);const E=document.createElement("db-button");E.setAttribute("variant","primary"),E.setAttribute("size","m"),E.textContent=t("적용"),E.addEventListener("click",this.handleModalApply),g.append(m,E),this.modalEl.append(this.modalBodyEl,g),this.replaceChildren(this.triggerEl,this.dropdownEl,this.modalEl)}updateCopyButtons(){const t=this.getIconSize(),e=this.isCopied?"done":"copy";this.triggerCopyBtn&&this.triggerCopyBtn.replaceChildren(p(e,t)),this.panelCopyBtnEl&&this.panelCopyBtnEl.setAttribute("start-icon",e)}updateVisuals(){const t=this.getRgb(),e=this.getHex(),i=this.getBool("show-alpha",!0),s=this.getUiFormatted(),l="hex"===this.format?r(s):s;!this.triggerInputFocused&&this.triggerInputEl&&(this.triggerInputEl.value=l),!this.panelInputFocused&&this.panelValueInputEl&&this.setInputValue(this.panelValueInputEl,l),this.colorBoxEl&&(this.colorBoxEl.style.backgroundColor=i?`rgba(${t.r}, ${t.g}, ${t.b}, ${this.a/100})`:e),this.colorFieldEl&&(this.colorFieldEl.style.backgroundImage=`\n linear-gradient(to top, rgba(0,0,0,1), rgba(0,0,0,0)),\n linear-gradient(to right, #ffffff, hsl(${this.h}, 100%, 50%))\n `),this.colorPointerEl&&(this.colorPointerEl.style.left=`${this.s}%`,this.colorPointerEl.style.top=100-this.v+"%",this.colorPointerEl.style.backgroundColor=`rgb(${t.r}, ${t.g}, ${t.b})`),this.hueSliderEl&&(this.hueSliderEl.value=String(this.h),this.hueSliderEl.style.background="linear-gradient(to right,\n hsl(0,100%,50%),\n hsl(60,100%,50%),\n hsl(120,100%,50%),\n hsl(180,100%,50%),\n hsl(240,100%,50%),\n hsl(300,100%,50%),\n hsl(360,100%,50%))"),this.alphaSliderEl&&(this.alphaSliderEl.value=String(this.a),this.alphaSliderEl.style.backgroundImage=`\n linear-gradient(45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(-45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(-45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(to right, rgba(${t.r}, ${t.g}, ${t.b}, 0), rgba(${t.r}, ${t.g}, ${t.b}, 1))\n `,this.alphaSliderEl.style.backgroundSize="8px 8px,8px 8px,8px 8px,8px 8px,100% 100%",this.alphaSliderEl.style.backgroundPosition="0 0,0 4px,4px -4px,-4px 0,0 0",this.alphaSliderEl.style.backgroundColor="var(--db-surface-base)"),this.panelAlphaInputEl&&!this.panelAlphaInputFocused&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.formatSelectEl&&this.formatSelectEl.getAttribute("value")!==this.format&&this.formatSelectEl.setAttribute("value",this.format),this.colorInput=l}update(){if(!this.mounted)return;const t=this.getOption("size",E,"m"),e=this.getOption("type",b,"dropdown"),i=this.getOption("position",y,"bottom-start"),s=this.getBool("disabled"),l=this.getBool("readonly"),n=this.getBool("show-input",!0),o=this.getBool("show-alpha",!0),r=this.getBool("show-format-selector",!0),a=this.getBool("show-copy-button",!0),h=this.getBool("show-eyedropper",!0),d="undefined"!=typeof window&&"EyeDropper"in window,p=this.getOption("trigger",v,"input"),u="swatch"===p;if(this.className=["designbase-wc-color-picker",`designbase-wc-color-picker--${t}`,`designbase-wc-color-picker--${i}`,`designbase-wc-color-picker--trigger-${p}`,this.open&&"dropdown"===e&&"designbase-wc-color-picker--open",this.getBool("full-width")&&"designbase-wc-color-picker--full-width",this.getBool("error")&&"designbase-wc-color-picker--error",s&&"designbase-wc-color-picker--disabled",l&&"designbase-wc-color-picker--readonly",!n&&"designbase-wc-color-picker--no-input"].filter(Boolean).join(" "),this.triggerInputEl?.setAttribute("aria-invalid",String(this.getBool("error"))),this.triggerInputEl&&(this.triggerInputEl.hidden=u||!n,this.triggerInputEl.disabled=s,this.triggerInputEl.readOnly=l),this.triggerCopyBtn&&(this.triggerCopyBtn.hidden=u||!(n&&a),this.triggerCopyBtn.disabled=s),this.toggleBtn&&(this.toggleBtn.hidden=u,this.toggleBtn.disabled=s),this.dropdownEl&&(this.dropdownEl.className=`designbase-wc-color-picker__dropdown designbase-wc-color-picker__dropdown--${i}`,this.dropdownEl.hidden=!("dropdown"===e&&this.open)),this.alphaSliderWrapEl&&(this.alphaSliderWrapEl.hidden=!o),this.panelAlphaWrapEl&&(this.panelAlphaWrapEl.hidden=!o),this.formatSelectEl&&(this.formatSelectEl.hidden=!r),this.panelCopyBtnEl&&(this.panelCopyBtnEl.hidden=!a),this.eyedropperBtnEl&&(this.eyedropperBtnEl.hidden=!(h&&d)),this.selectorEl){const t="modal"===e?this.modalBodyEl:this.dropdownEl;t&&this.selectorEl.parentElement!==t&&t.append(this.selectorEl)}this.modalEl&&("modal"===e&&this.open?this.modalEl.setAttribute("open","true"):this.modalEl.removeAttribute("open")),this.updateCopyButtons(),this.updateVisuals()}}customElements.get("db-color-picker")||customElements.define("db-color-picker",DbColorPicker);export{DbColorPicker};
|
|
1
|
+
import{subscribeDbLocale as t,dbText as e}from"../core/i18n.js";import{hexToRgb as i,rgbToHsv as s,hsvToRgb as l,toHex as n,rgbToHsl as o,formatColor as a,normalizeHex as r,isHex as h,clamp as d}from"./color-picker-utils.js";import{getDbComponentIconSize as p,createDbIcon as u}from"./db-icons.js";import{rafThrottle as c}from"../core/dom.js";import{coerceToContract as g}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{COLOR_PICKER_SIZES as E,COLOR_PICKER_POSITIONS as m}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const b=E,v=["dropdown","modal"],y=["input","swatch"],I=m,w="#006FFF",A=i(w)??{r:0,g:111,b:255},C=s(A.r,A.g,A.b),B=JSON.stringify([{label:"HEX",value:"hex"},{label:"RGB",value:"rgb"},{label:"RGBA",value:"rgba"},{label:"HSL",value:"hsl"},{label:"HSLA",value:"hsla"}]);class DbColorPicker extends HTMLElement{constructor(){super(...arguments),this.h=C.h,this.s=C.s,this.v=C.v,this.a=100,this.open=!1,this.format="hex",this.colorInput=w,this.alphaInput="100",this.isCopied=!1,this.tempColor="",this.dragging=null,this.mounted=!1,this.copiedTimer=null,this.debounceTimer=null,this.lastEmittedHex="",this.suppressNextValueSync=!1,this.didMount=!1,this.triggerInputFocused=!1,this.panelInputFocused=!1,this.panelAlphaInputFocused=!1,this.handleEscape=t=>{"Escape"!==t.key||t.defaultPrevented||t.isComposing||!this.open||"dropdown"===this.getOption("type",v,"dropdown")&&(t.preventDefault(),this.close(),this.toggleBtn?.focus())},this.handleOutsideClick=t=>{if(!this.open||"dropdown"!==this.getOption("type",v,"dropdown"))return;const e=t.target;this.contains(e)||this.formatSelectEl?.contains(e)||(this.open=!1,this.update())},this.handleDocumentMouseMove=c(t=>{"area"===this.dragging&&(this.getBool("disabled")||this.getBool("readonly")||this.updateFromArea(t.clientX,t.clientY))}),this.handleDocumentMouseUp=()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))},this.handleModalCancel=()=>{const t=i(this.tempColor);if(t){const e=s(t.r,t.g,t.b);this.h=e.h,this.s=e.s,this.v=e.v}this.open=!1,this.update(),this.dispatchEvent(new CustomEvent("db-cancel",{bubbles:!0,composed:!0}))},this.handleModalApply=()=>{this.open=!1,this.actuallyEmit(),this.dispatchEvent(new CustomEvent("db-apply",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})),this.update()}}static get observedAttributes(){return["size","type","trigger","position","value","default-value","show-input","show-alpha","show-format-selector","show-copy-button","show-eyedropper","disabled","readonly","full-width","error","on-change-format","change-debounce-ms","emit-during-drag"]}connectedCallback(){this.mounted||this.mount(),this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>this.updateLocale()),this.updateLocale(),this.syncFromValueAttr(!0),this.update(),document.addEventListener("mousedown",this.handleOutsideClick),document.addEventListener("mousemove",this.handleDocumentMouseMove),document.addEventListener("mouseup",this.handleDocumentMouseUp),document.addEventListener("keydown",this.handleEscape)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,document.removeEventListener("mousedown",this.handleOutsideClick),document.removeEventListener("mousemove",this.handleDocumentMouseMove),document.removeEventListener("mouseup",this.handleDocumentMouseUp),document.removeEventListener("keydown",this.handleEscape),this.copiedTimer&&clearTimeout(this.copiedTimer),this.debounceTimer&&clearTimeout(this.debounceTimer)}updateLocale(){this.triggerCopyBtn?.setAttribute("aria-label",e("색상 값 복사")),this.toggleBtn?.setAttribute("aria-label",e("색상 선택기 열기 또는 닫기")),this.eyedropperBtnEl?.setAttribute("aria-label",e("스포이드 도구")),this.panelAlphaInputEl?.setAttribute("aria-label",e("불투명도 백분율")),this.panelCopyBtnEl?.setAttribute("aria-label",e("색상 값 복사")),this.modalEl?.setAttribute("title",e("색상 선택")),this.cancelButton&&(this.cancelButton.textContent=e("취소")),this.applyButton&&(this.applyButton.textContent=e("적용"))}attributeChangedCallback(t){this.mounted&&("value"!==t&&"default-value"!==t||this.syncFromValueAttr(!1),this.update())}getBool(t,e=!1){if(!this.hasAttribute(t))return e;const i=this.getAttribute(t);return""===i||"true"===i}getOption(t,e,i){return g(this.getAttribute(t),e,i)}getIconSize(){return p(this.getOption("size",b,"m"))}getRgb(){return l(this.h,this.s,this.v)}getHex(){const t=this.getRgb();return n(t.r,t.g,t.b)}getHsl(){const t=this.getRgb();return o(t.r,t.g,t.b)}getUiFormatted(){const t=this.getRgb(),e=this.getHex(),i=this.getHsl();return a(this.format,t,e,i,this.a)}getOutward(){return"hex"===("ui"===this.getAttribute("on-change-format")?"ui":"hex")?this.getHex():this.getUiFormatted()}syncFromValueAttr(t){const e=this.getAttribute("value")??(t?this.getAttribute("default-value"):null)??(t?w:null);if(null==e)return;const l=r(e);if(!h(l))return;if(!t&&this.suppressNextValueSync&&l===this.lastEmittedHex)return void(this.suppressNextValueSync=!1);const n=i(l);if(!n)return;const o=s(n.r,n.g,n.b);this.h=o.h,this.s=o.s,this.v=o.v,this.colorInput=l,this.lastEmittedHex=l}actuallyEmit(){const t=r(this.getHex()),e=this.hasAttribute("value")&&h(this.getAttribute("value")||"")?r(this.getAttribute("value")||""):null;e&&e===t||this.lastEmittedHex!==t&&(this.lastEmittedHex=t,this.suppressNextValueSync=!0,this.setAttribute("value",t),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})))}scheduleEmit(){const t=this.getBool("emit-during-drag",!0);if(this.dragging&&!t)return;const e=Number(this.getAttribute("change-debounce-ms")||"0");if(e>0)return this.debounceTimer&&clearTimeout(this.debounceTimer),void(this.debounceTimer=setTimeout(()=>this.actuallyEmit(),e));this.actuallyEmit()}onColorStateChanged(t=!1){this.didMount?(!t||this.getBool("emit-during-drag",!0),this.scheduleEmit()):this.didMount=!0}updateFromArea(t,e){const i=this.colorFieldEl;if(!i)return;const s=i.getBoundingClientRect(),l=d(t-s.left,0,s.width),n=d(e-s.top,0,s.height);this.s=l/s.width*100,this.v=100-n/s.height*100,this.updateVisuals(),this.onColorStateChanged()}getInputValue(t){return t?t.getAttribute("value")??"":""}setInputValue(t,e){t&&void 0!==e&&t.setAttribute("value",e)}getPanelControlSize(){return"s"===this.getOption("size",b,"m")?"s":"m"}commitColorInput(t){const e="trigger"===t?this.triggerInputEl?.value??"":this.getInputValue(this.panelValueInputEl),l=e.trim();if(/^#([0-9A-Fa-f]{6})$/.test(l)){const t=i(l),e=s(t.r,t.g,t.b);return this.h=e.h,this.s=e.s,this.v=e.v,this.colorInput=r(l),this.updateVisuals(),void this.onColorStateChanged()}let n=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(e);if(n){const t=d(parseInt(n[1],10),0,255),e=d(parseInt(n[2],10),0,255),i=d(parseInt(n[3],10),0,255),l=s(t,e,i);return this.h=l.h,this.s=l.s,this.v=l.v,this.colorInput=`rgb(${t}, ${e}, ${i})`,this.updateVisuals(),void this.onColorStateChanged()}if(n=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i.exec(l),n){const t=d(parseInt(n[1],10),0,255),e=d(parseInt(n[2],10),0,255),i=d(parseInt(n[3],10),0,255),l=parseFloat(n[4]),o=s(t,e,i);this.h=o.h,this.s=o.s,this.v=o.v,this.a=Math.round(100*l),this.alphaInput=String(this.a),this.colorInput=`rgba(${t}, ${e}, ${i}, ${l})`,this.updateVisuals(),this.onColorStateChanged()}}commitAlphaInput(){const t=Number(this.getInputValue(this.panelAlphaInputEl).trim()||this.alphaInput);if(!Number.isNaN(t)&&t>=0&&t<=100){const e=Math.round(t);this.a=e,this.alphaInput=String(e),this.updateVisuals(),this.onColorStateChanged()}else this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput)}async onCopy(){try{await navigator.clipboard.writeText(this.getUiFormatted()),this.isCopied=!0,this.updateCopyButtons(),this.copiedTimer&&clearTimeout(this.copiedTimer),this.copiedTimer=setTimeout(()=>{this.isCopied=!1,this.updateCopyButtons()},1600)}catch{}}async onEyedrop(){try{if("EyeDropper"in window){const t=new window.EyeDropper,{sRGBHex:e}=await t.open(),l=i(e);if(!l)return;const n=s(l.r,l.g,l.b);this.h=n.h,this.s=n.s,this.v=n.v,this.updateVisuals(),this.onColorStateChanged()}}catch{}}toggleOpen(){if(this.getBool("disabled")||this.getBool("readonly"))return;if("modal"===this.getOption("type",v,"dropdown"))return this.tempColor=this.getHex(),this.open=!0,void this.update();this.open=!this.open,this.update()}close(){this.open&&"dropdown"===this.getOption("type",v,"dropdown")&&(this.open=!1,this.update())}mount(){this.mounted=!0;const t=this.getIconSize();this.triggerEl=document.createElement("div"),this.triggerEl.className="designbase-wc-color-picker__trigger",this.triggerEl.addEventListener("click",()=>this.toggleOpen());const i=document.createElement("div");i.className="designbase-wc-color-picker__color-display",this.colorBoxEl=document.createElement("div"),this.colorBoxEl.className="designbase-wc-color-picker__color-box",i.append(this.colorBoxEl),this.triggerInputEl=document.createElement("input"),this.triggerInputEl.type="text",this.triggerInputEl.className="designbase-wc-color-picker__input",this.triggerInputEl.placeholder="#000000",this.triggerInputEl.addEventListener("click",t=>t.stopPropagation()),this.triggerInputEl.addEventListener("focus",()=>{this.triggerInputFocused=!0}),this.triggerInputEl.addEventListener("blur",()=>{this.triggerInputFocused=!1;const t="hex"===this.format?r(this.getUiFormatted()):this.getUiFormatted();this.triggerInputEl&&this.triggerInputEl.value!==t&&(this.triggerInputEl.value=t,this.colorInput=t)}),this.triggerInputEl.addEventListener("input",()=>{this.triggerInputEl&&(this.colorInput=this.triggerInputEl.value)}),this.triggerInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("trigger")});const s=document.createElement("div");s.className="designbase-wc-color-picker__trigger-actions",this.triggerCopyBtn=document.createElement("button"),this.triggerCopyBtn.type="button",this.triggerCopyBtn.className="designbase-wc-color-picker__copy-button-inline",this.triggerCopyBtn.setAttribute("aria-label","Copy color value"),this.triggerCopyBtn.addEventListener("click",t=>{t.stopPropagation(),this.onCopy()}),this.toggleBtn=document.createElement("button"),this.toggleBtn.type="button",this.toggleBtn.className="designbase-wc-color-picker__toggle",this.toggleBtn.setAttribute("aria-label","Toggle color picker"),this.toggleBtn.append(u("chevron-down",t)),s.append(this.triggerCopyBtn,this.toggleBtn),this.triggerEl.append(i,this.triggerInputEl,s),this.dropdownEl=document.createElement("div"),this.dropdownEl.className="designbase-wc-color-picker__dropdown",this.dropdownEl.addEventListener("click",t=>t.stopPropagation()),this.dropdownEl.hidden=!0;const l=document.createElement("div");l.className="designbase-wc-color-picker__selector";const n=document.createElement("div");n.className="designbase-wc-color-picker__color-area",this.colorFieldEl=document.createElement("div"),this.colorFieldEl.className="designbase-wc-color-picker__color-field",this.colorPointerEl=document.createElement("div"),this.colorPointerEl.className="designbase-wc-color-picker__color-pointer",this.colorFieldEl.append(this.colorPointerEl),this.colorFieldEl.addEventListener("mousedown",t=>{this.getBool("disabled")||this.getBool("readonly")||(t.preventDefault(),this.dragging="area",this.updateFromArea(t.clientX,t.clientY))}),this.colorFieldEl.addEventListener("touchstart",t=>{if(this.getBool("disabled")||this.getBool("readonly"))return;this.dragging="area";const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchmove",t=>{if("area"!==this.dragging)return;const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchend",()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))}),n.append(this.colorFieldEl);const o=document.createElement("div");o.className="designbase-wc-color-picker__controls",this.eyedropperBtnEl=document.createElement("db-button"),this.eyedropperBtnEl.setAttribute("variant","tertiary"),this.eyedropperBtnEl.setAttribute("size",this.getPanelControlSize()),this.eyedropperBtnEl.setAttribute("icon-only",""),this.eyedropperBtnEl.setAttribute("start-icon","eyedropper"),this.eyedropperBtnEl.setAttribute("aria-label","Eyedropper tool"),this.eyedropperBtnEl.addEventListener("click",()=>{this.onEyedrop()});const a=document.createElement("div");a.className="designbase-wc-color-picker__slider-container";const h=document.createElement("div");h.className="designbase-wc-color-picker__hue-slider",this.hueSliderEl=document.createElement("input"),this.hueSliderEl.type="range",this.hueSliderEl.min="0",this.hueSliderEl.max="360",this.hueSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--hue",this.hueSliderEl.addEventListener("input",()=>{this.h=parseFloat(this.hueSliderEl.value),this.updateVisuals(),this.onColorStateChanged()}),h.append(this.hueSliderEl),this.alphaSliderWrapEl=document.createElement("div"),this.alphaSliderWrapEl.className="designbase-wc-color-picker__alpha-slider",this.alphaSliderEl=document.createElement("input"),this.alphaSliderEl.type="range",this.alphaSliderEl.min="0",this.alphaSliderEl.max="100",this.alphaSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--alpha",this.alphaSliderEl.addEventListener("input",()=>{this.a=d(parseInt(this.alphaSliderEl.value,10),0,100),this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.updateVisuals(),this.onColorStateChanged()}),this.alphaSliderWrapEl.append(this.alphaSliderEl),a.append(h,this.alphaSliderWrapEl),o.append(this.eyedropperBtnEl,a);const p=document.createElement("div");p.className="designbase-wc-color-picker__value-display",this.formatSelectEl=document.createElement("db-select"),this.formatSelectEl.setAttribute("size","s"),this.formatSelectEl.setAttribute("position","top"),this.formatSelectEl.setAttribute("show-clear-button","false"),this.formatSelectEl.setAttribute("options",B),this.formatSelectEl.addEventListener("db-change",t=>{const e=t.detail,i=e?.value;i&&(this.format=i,this.updateVisuals())}),this.panelValueInputEl=document.createElement("db-input"),this.panelValueInputEl.classList.add("designbase-wc-color-picker__value-input"),this.panelValueInputEl.setAttribute("size","s"),this.panelValueInputEl.setAttribute("placeholder","#000000"),this.panelValueInputEl.addEventListener("db-focus",()=>{this.panelInputFocused=!0}),this.panelValueInputEl.addEventListener("db-blur",()=>{this.panelInputFocused=!1;const t="hex"===this.format?r(this.getUiFormatted()):this.getUiFormatted();this.getInputValue(this.panelValueInputEl)!==t&&(this.setInputValue(this.panelValueInputEl,t),this.colorInput=t)}),this.panelValueInputEl.addEventListener("db-input",t=>{const e=t.detail;void 0!==e?.value&&(this.colorInput=e.value)}),this.panelValueInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("panel")}),this.panelAlphaWrapEl=document.createElement("div"),this.panelAlphaWrapEl.className="designbase-wc-color-picker__alpha-input-wrap",this.panelAlphaInputEl=document.createElement("db-input"),this.panelAlphaInputEl.classList.add("designbase-wc-color-picker__alpha-input"),this.panelAlphaInputEl.setAttribute("size","s"),this.panelAlphaInputEl.setAttribute("placeholder","100"),this.panelAlphaInputEl.setAttribute("aria-label","Alpha percent"),this.panelAlphaInputEl.addEventListener("db-focus",()=>{this.panelAlphaInputFocused=!0}),this.panelAlphaInputEl.addEventListener("db-blur",()=>{this.panelAlphaInputFocused=!1,this.commitAlphaInput()}),this.panelAlphaInputEl.addEventListener("db-input",t=>{const e=t.detail,i=(e?.value??"").replace(/[^\d]/g,"").slice(0,3);i!==e?.value&&this.setInputValue(this.panelAlphaInputEl,i),this.alphaInput=i}),this.panelAlphaInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitAlphaInput()});const c=document.createElement("span");c.className="designbase-wc-color-picker__alpha-suffix",c.textContent="%",this.panelAlphaWrapEl.append(this.panelAlphaInputEl,c),this.panelCopyBtnEl=document.createElement("db-button"),this.panelCopyBtnEl.setAttribute("variant","tertiary"),this.panelCopyBtnEl.setAttribute("size","s"),this.panelCopyBtnEl.setAttribute("icon-only",""),this.panelCopyBtnEl.setAttribute("start-icon","copy"),this.panelCopyBtnEl.setAttribute("aria-label","Copy color value"),this.panelCopyBtnEl.addEventListener("click",()=>{this.onCopy()}),p.append(this.formatSelectEl,this.panelValueInputEl,this.panelAlphaWrapEl,this.panelCopyBtnEl),l.append(n,o,p),this.selectorEl=l,this.dropdownEl.append(l),this.modalEl=document.createElement("db-modal"),this.modalEl.setAttribute("size","s"),this.modalEl.setAttribute("title",e("색상 선택")),this.modalEl.setAttribute("close-on-escape","true"),this.modalEl.addEventListener("db-close",this.handleModalCancel),this.modalBodyEl=document.createElement("div"),this.modalBodyEl.className="designbase-wc-modal__body designbase-wc-color-picker__modal-body",this.modalBodyEl.setAttribute("data-modal-part","body");const g=document.createElement("div");g.className="designbase-wc-modal__footer",g.setAttribute("data-modal-part","footer");const E=document.createElement("db-button");this.cancelButton=E,E.setAttribute("variant","tertiary"),E.setAttribute("size","m"),E.textContent=e("취소"),E.addEventListener("click",this.handleModalCancel);const m=document.createElement("db-button");this.applyButton=m,m.setAttribute("variant","primary"),m.setAttribute("size","m"),m.textContent=e("적용"),m.addEventListener("click",this.handleModalApply),g.append(E,m),this.modalEl.append(this.modalBodyEl,g),this.replaceChildren(this.triggerEl,this.dropdownEl,this.modalEl)}updateCopyButtons(){const t=this.getIconSize(),e=this.isCopied?"done":"copy";this.triggerCopyBtn&&this.triggerCopyBtn.replaceChildren(u(e,t)),this.panelCopyBtnEl&&this.panelCopyBtnEl.setAttribute("start-icon",e)}updateVisuals(){const t=this.getRgb(),e=this.getHex(),i=this.getBool("show-alpha",!0),s=this.getUiFormatted(),l="hex"===this.format?r(s):s;!this.triggerInputFocused&&this.triggerInputEl&&(this.triggerInputEl.value=l),!this.panelInputFocused&&this.panelValueInputEl&&this.setInputValue(this.panelValueInputEl,l),this.colorBoxEl&&(this.colorBoxEl.style.backgroundColor=i?`rgba(${t.r}, ${t.g}, ${t.b}, ${this.a/100})`:e),this.colorFieldEl&&(this.colorFieldEl.style.backgroundImage=`\n linear-gradient(to top, rgba(0,0,0,1), rgba(0,0,0,0)),\n linear-gradient(to right, #ffffff, hsl(${this.h}, 100%, 50%))\n `),this.colorPointerEl&&(this.colorPointerEl.style.left=`${this.s}%`,this.colorPointerEl.style.top=100-this.v+"%",this.colorPointerEl.style.backgroundColor=`rgb(${t.r}, ${t.g}, ${t.b})`),this.hueSliderEl&&(this.hueSliderEl.value=String(this.h),this.hueSliderEl.style.background="linear-gradient(to right,\n hsl(0,100%,50%),\n hsl(60,100%,50%),\n hsl(120,100%,50%),\n hsl(180,100%,50%),\n hsl(240,100%,50%),\n hsl(300,100%,50%),\n hsl(360,100%,50%))"),this.alphaSliderEl&&(this.alphaSliderEl.value=String(this.a),this.alphaSliderEl.style.backgroundImage=`\n linear-gradient(45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(-45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(-45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(to right, rgba(${t.r}, ${t.g}, ${t.b}, 0), rgba(${t.r}, ${t.g}, ${t.b}, 1))\n `,this.alphaSliderEl.style.backgroundSize="8px 8px,8px 8px,8px 8px,8px 8px,100% 100%",this.alphaSliderEl.style.backgroundPosition="0 0,0 4px,4px -4px,-4px 0,0 0",this.alphaSliderEl.style.backgroundColor="var(--db-surface-base)"),this.panelAlphaInputEl&&!this.panelAlphaInputFocused&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.formatSelectEl&&this.formatSelectEl.getAttribute("value")!==this.format&&this.formatSelectEl.setAttribute("value",this.format),this.colorInput=l}update(){if(!this.mounted)return;const t=this.getOption("size",b,"m"),e=this.getOption("type",v,"dropdown"),i=this.getOption("position",I,"bottom-start"),s=this.getBool("disabled"),l=this.getBool("readonly"),n=this.getBool("show-input",!0),o=this.getBool("show-alpha",!0),a=this.getBool("show-format-selector",!0),r=this.getBool("show-copy-button",!0),h=this.getBool("show-eyedropper",!0),d="undefined"!=typeof window&&"EyeDropper"in window,p=this.getOption("trigger",y,"input"),u="swatch"===p;if(this.className=["designbase-wc-color-picker",`designbase-wc-color-picker--${t}`,`designbase-wc-color-picker--${i}`,`designbase-wc-color-picker--trigger-${p}`,this.open&&"dropdown"===e&&"designbase-wc-color-picker--open",this.getBool("full-width")&&"designbase-wc-color-picker--full-width",this.getBool("error")&&"designbase-wc-color-picker--error",s&&"designbase-wc-color-picker--disabled",l&&"designbase-wc-color-picker--readonly",!n&&"designbase-wc-color-picker--no-input"].filter(Boolean).join(" "),this.triggerInputEl?.setAttribute("aria-invalid",String(this.getBool("error"))),this.triggerInputEl&&(this.triggerInputEl.hidden=u||!n,this.triggerInputEl.disabled=s,this.triggerInputEl.readOnly=l),this.triggerCopyBtn&&(this.triggerCopyBtn.hidden=u||!(n&&r),this.triggerCopyBtn.disabled=s),this.toggleBtn&&(this.toggleBtn.hidden=u,this.toggleBtn.disabled=s),this.dropdownEl&&(this.dropdownEl.className=`designbase-wc-color-picker__dropdown designbase-wc-color-picker__dropdown--${i}`,this.dropdownEl.hidden=!("dropdown"===e&&this.open)),this.alphaSliderWrapEl&&(this.alphaSliderWrapEl.hidden=!o),this.panelAlphaWrapEl&&(this.panelAlphaWrapEl.hidden=!o),this.formatSelectEl&&(this.formatSelectEl.hidden=!a),this.panelCopyBtnEl&&(this.panelCopyBtnEl.hidden=!r),this.eyedropperBtnEl&&(this.eyedropperBtnEl.hidden=!(h&&d)),this.selectorEl){const t="modal"===e?this.modalBodyEl:this.dropdownEl;t&&this.selectorEl.parentElement!==t&&t.append(this.selectorEl)}this.modalEl&&("modal"===e&&this.open?this.modalEl.setAttribute("open","true"):this.modalEl.removeAttribute("open")),this.updateCopyButtons(),this.updateVisuals()}}customElements.get("db-color-picker")||customElements.define("db-color-picker",DbColorPicker);export{DbColorPicker};
|
|
@@ -6,6 +6,7 @@ type DbColorSwatchItem = {
|
|
|
6
6
|
name?: string;
|
|
7
7
|
};
|
|
8
8
|
declare class DbColorSwatch extends HTMLElement {
|
|
9
|
+
private unsubscribeLocale?;
|
|
9
10
|
private colors;
|
|
10
11
|
private selected;
|
|
11
12
|
private customValue;
|
|
@@ -18,6 +19,8 @@ declare class DbColorSwatch extends HTMLElement {
|
|
|
18
19
|
static get observedAttributes(): string[];
|
|
19
20
|
connectedCallback(): void;
|
|
20
21
|
disconnectedCallback(): void;
|
|
22
|
+
private displayName;
|
|
23
|
+
private updateLocale;
|
|
21
24
|
private handleOutsideMouseDown;
|
|
22
25
|
attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
|
|
23
26
|
get value(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeHex as
|
|
1
|
+
import{normalizeHex as e,isHex as t}from"./color-picker-utils.js";import{subscribeDbLocale as s,dbText as i}from"../core/i18n.js";import{coerceToContract as o}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{COLOR_SWATCH_SIZES as a}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const l=["rounded","circle"],c=a,r=["dropdown","modal"],n=[{value:"#1A1B25",name:"Dark"},{value:"#FFFFFF",name:"White"},{value:"#EF4444",name:"Red"},{value:"#F59E0B",name:"Orange"},{value:"#22C55E",name:"Green"},{value:"#3B82F6",name:"Blue"},{value:"#8B5CF6",name:"Purple"},{value:"#EC4899",name:"Pink"}],u={Dark:"어두운 색",White:"흰색",Red:"빨강",Orange:"주황",Green:"초록",Blue:"파랑",Purple:"보라",Pink:"분홍"};class DbColorSwatch extends HTMLElement{constructor(){super(...arguments),this.colors=n,this.selected="",this.customValue="",this.mounted=!1,this.handleOutsideMouseDown=e=>{if(!this.customWrapEl)return;const t=this.customPickerEl;if(!t||"function"!=typeof t.close)return;e.composedPath().includes(this.customWrapEl)||t.close()}}static get observedAttributes(){return["colors","value","default-value","shape","size","show-name","allow-custom","custom-type","disabled"]}connectedCallback(){this.mounted||(this.parseColors(),this.selected=e(this.getAttribute("value")??this.getAttribute("default-value")??""),this.mounted=!0),this.render(),this.unsubscribeLocale?.(),this.unsubscribeLocale=s(()=>this.updateLocale()),document.addEventListener("mousedown",this.handleOutsideMouseDown,!0)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,document.removeEventListener("mousedown",this.handleOutsideMouseDown,!0)}displayName(e){return this.colors===n&&e.name&&u[e.name]?i(u[e.name]):e.name||e.value}updateLocale(){this.presetsEl?.querySelectorAll(".designbase-wc-color-swatch__item").forEach((e,t)=>{const s=this.colors[t];if(!s)return;const i=this.displayName(s);e.setAttribute("aria-label",i);const o=e.querySelector(".designbase-wc-color-swatch__tip");o&&(o.textContent=i)}),this.customPickerEl?.setAttribute("aria-label",i("사용자 지정 색상")),this.customTipEl&&(this.customTipEl.textContent=i("사용자 지정"))}attributeChangedCallback(t,s,i){this.mounted&&s!==i&&("colors"===t&&this.parseColors(),"value"===t&&(this.selected=e(i??"")),this.render())}get value(){return this.selected}set value(t){this.selected=e(t),this.mounted&&this.render()}getOption(e,t,s){return o(this.getAttribute(e),t,s)}getBool(e,t=!1){if(!this.hasAttribute(e))return t;const s=this.getAttribute(e);return""===s||"true"===s}parseColors(){const s=this.getAttribute("colors");if(s)try{const i=JSON.parse(s);if(!Array.isArray(i))return void(this.colors=n);this.colors=i.map(e=>"string"==typeof e?{value:e}:{value:e?.value??"",name:e?.name}).filter(e=>t(e.value)).map(t=>({value:e(t.value),name:t.name})),0===this.colors.length&&(this.colors=n)}catch{this.colors=n}else this.colors=n}isCustomSelected(){if(!this.selected)return!1;return!this.colors.some(e=>e.value.toUpperCase()===this.selected.toUpperCase())}emitChange(e,t){this.dispatchEvent(new CustomEvent("db-change",{detail:{value:e,name:t??""},bubbles:!0,composed:!0}))}selectPreset(e){this.getBool("disabled")||(this.selected=e.value,this.setAttribute("value",this.selected),this.render(),this.emitChange(e.value,e.name))}render(){const e=this.getOption("shape",l,"rounded"),t=this.getOption("size",c,"m"),s=this.getBool("disabled"),i=this.getBool("show-name",!0),o=this.getBool("allow-custom",!0);this.className=["designbase-wc-color-swatch",`designbase-wc-color-swatch--${e}`,`designbase-wc-color-swatch--${t}`,s&&"designbase-wc-color-swatch--disabled"].filter(Boolean).join(" "),this.gridEl||(this.gridEl=document.createElement("div"),this.gridEl.className="designbase-wc-color-swatch__grid",this.presetsEl=document.createElement("div"),this.presetsEl.className="designbase-wc-color-swatch__presets",this.gridEl.append(this.presetsEl)),this.gridEl.parentElement!==this&&this.append(this.gridEl);const a=this.isCustomSelected();this.presetsEl.replaceChildren(...this.colors.map(e=>{const t=!a&&this.selected.toUpperCase()===e.value.toUpperCase();return this.buildSwatch(e,t,i,s)})),o?(this.ensureCustom(),this.updateCustom(t,a,i,s),this.customWrapEl&&this.customWrapEl.parentElement!==this.gridEl&&this.gridEl.append(this.customWrapEl)):this.customWrapEl?.parentElement&&this.customWrapEl.remove()}buildSwatch(e,t,s,i){const o=document.createElement("button");o.type="button",o.className=["designbase-wc-color-swatch__item",t&&"designbase-wc-color-swatch__item--selected"].filter(Boolean).join(" "),o.disabled=i,o.style.setProperty("--db-swatch-color",e.value),o.setAttribute("aria-label",this.displayName(e)),o.setAttribute("aria-pressed",String(t));const a=document.createElement("span");if(a.className="designbase-wc-color-swatch__chip",o.append(a),s){const t=document.createElement("span");t.className="designbase-wc-color-swatch__tip",t.textContent=this.displayName(e),o.append(t)}return o.addEventListener("click",()=>this.selectPreset(e)),o}ensureCustom(){this.customWrapEl||(this.customWrapEl=document.createElement("div"),this.customWrapEl.className="designbase-wc-color-swatch__custom",this.customPickerEl=document.createElement("db-color-picker"),this.customPickerEl.setAttribute("trigger","swatch"),this.customPickerEl.setAttribute("show-input","false"),this.customPickerEl.setAttribute("show-copy-button","false"),this.customPickerEl.setAttribute("aria-label",i("사용자 지정 색상")),this.customPickerEl.addEventListener("db-change",s=>{s.stopPropagation();const i=s.detail,o=e(i?.value??"");t(o)&&(this.customValue=o,this.selected=o,this.setAttribute("value",o),this.render(),this.emitChange(o,"Custom"))}),this.customTipEl=document.createElement("span"),this.customTipEl.className="designbase-wc-color-swatch__tip",this.customTipEl.textContent=i("사용자 지정"),this.customWrapEl.append(this.customPickerEl,this.customTipEl))}updateCustom(e,t,s,i){this.customWrapEl&&this.customPickerEl&&(this.customWrapEl.classList.toggle("designbase-wc-color-swatch__custom--selected",t),this.customTipEl&&(this.customTipEl.hidden=!s),this.customPickerEl.setAttribute("size",e),this.customPickerEl.setAttribute("type",this.getOption("custom-type",r,"dropdown")),this.customValue&&this.customPickerEl.setAttribute("value",this.customValue),i?this.customPickerEl.setAttribute("disabled",""):this.customPickerEl.removeAttribute("disabled"))}}customElements.get("db-color-swatch")||customElements.define("db-color-swatch",DbColorSwatch);export{DbColorSwatch};
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
declare class DbCookieBanner extends HTMLElement {
|
|
2
|
+
private unsubscribeLocale?;
|
|
2
3
|
static get observedAttributes(): string[];
|
|
3
4
|
connectedCallback(): void;
|
|
5
|
+
disconnectedCallback(): void;
|
|
6
|
+
private syncLocale;
|
|
4
7
|
attributeChangedCallback(): void;
|
|
5
8
|
private isEnabled;
|
|
6
9
|
private createButton;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sanitizeHref as e}from"../core/safe-url.js";class DbCookieBanner extends HTMLElement{static get observedAttributes(){return["title","description","policy-label","policy-href","accept-label","reject-label","settings-label","show-reject","show-settings","fixed","dismissed"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}isEnabled(e,t){const
|
|
1
|
+
import{sanitizeHref as e}from"../core/safe-url.js";import{subscribeDbLocale as t,dbText as i}from"../core/i18n.js";class DbCookieBanner extends HTMLElement{static get observedAttributes(){return["title","description","policy-label","policy-href","accept-label","reject-label","settings-label","show-reject","show-settings","fixed","dismissed"]}connectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>this.syncLocale()),this.render()}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0}syncLocale(){if(this.hasAttribute("dismissed"))return;const e=this.getAttribute("title")||i("쿠키 사용 안내"),t=this.querySelector(".designbase-wc-cookie-banner__title");t&&(t.textContent=e),this.setAttribute("aria-label",e);const s=this.querySelector(".designbase-wc-cookie-banner__description");s?.firstChild&&(s.firstChild.textContent=this.getAttribute("description")||i("더 나은 서비스 제공을 위해 쿠키를 사용합니다. 계속 이용하시면 쿠키 사용에 동의하는 것으로 간주됩니다."));const n=this.querySelector(".designbase-wc-cookie-banner__policy");n&&(n.textContent=this.getAttribute("policy-label")||i("쿠키 정책"));for(const[e,t]of[["settings","설정"],["reject","필수만 허용"],["accept","모두 허용"]]){const s=this.querySelector(`[data-cookie-action="${e}"]`);s&&(s.textContent=this.getAttribute(`${e}-label`)||i(t))}}attributeChangedCallback(){this.render()}isEnabled(e,t){const i=this.getAttribute(e);return null===i?t:"false"!==i}createButton(e,t,i,s){const n=document.createElement("db-button");return n.setAttribute("variant",t),n.setAttribute("size","s"),n.dataset.cookieAction=i.slice(3),n.textContent=e,n.addEventListener("db-click",()=>{this.dispatchEvent(new CustomEvent(i,{bubbles:!0,composed:!0})),s&&(this.setAttribute("dismissed",""),this.render())}),n}render(){if(this.hasAttribute("dismissed"))return this.replaceChildren(),this.className="designbase-wc-cookie-banner designbase-wc-cookie-banner--dismissed",this.style.display="none",void this.removeAttribute("role");this.style.display="";const t=this.getAttribute("title")||i("쿠키 사용 안내"),s=this.getAttribute("description")||i("더 나은 서비스 제공을 위해 쿠키를 사용합니다. 계속 이용하시면 쿠키 사용에 동의하는 것으로 간주됩니다."),n=this.getAttribute("policy-label")||i("쿠키 정책"),c=this.getAttribute("policy-href")||"",o=this.getAttribute("accept-label")||i("모두 허용"),a=this.getAttribute("reject-label")||i("필수만 허용"),r=this.getAttribute("settings-label")||i("설정"),l=this.isEnabled("show-reject",!0),b=this.isEnabled("show-settings",!1),d=this.isEnabled("fixed",!0);this.className=["designbase-wc-cookie-banner",d&&"designbase-wc-cookie-banner--fixed"].filter(Boolean).join(" "),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","false"),this.setAttribute("aria-label",t),this.setAttribute("aria-live","polite");const h=document.createElement("div");h.className="designbase-wc-cookie-banner__inner";const u=document.createElement("div");if(u.className="designbase-wc-cookie-banner__copy",t){const e=document.createElement("p");e.className="designbase-wc-cookie-banner__title",e.textContent=t,u.append(e)}const p=document.createElement("p");p.className="designbase-wc-cookie-banner__description",p.append(document.createTextNode(s));const m=e(c,"");if(m){p.append(document.createTextNode(" "));const e=document.createElement("a");e.className="designbase-wc-cookie-banner__policy",e.href=m,e.target="_blank",e.rel="noopener noreferrer",e.textContent=n,e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("db-policy",{bubbles:!0,composed:!0}))}),p.append(e)}u.append(p);const g=document.createElement("div");g.className="designbase-wc-cookie-banner__actions",b&&g.append(this.createButton(r,"ghost","db-settings",!1)),l&&g.append(this.createButton(a,"tertiary","db-reject",!0)),g.append(this.createButton(o,"primary","db-accept",!0)),h.append(u,g),this.replaceChildren(h)}}customElements.get("db-cookie-banner")||customElements.define("db-cookie-banner",DbCookieBanner);export{DbCookieBanner};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
declare class DbCountdown extends HTMLElement {
|
|
2
2
|
private timer;
|
|
3
3
|
private targetTime;
|
|
4
|
+
private unsubscribeLocale?;
|
|
4
5
|
static get observedAttributes(): string[];
|
|
5
6
|
connectedCallback(): void;
|
|
6
7
|
disconnectedCallback(): void;
|
|
7
|
-
attributeChangedCallback(): void;
|
|
8
|
+
attributeChangedCallback(name: string): void;
|
|
8
9
|
private boolAttr;
|
|
9
10
|
private optionAttr;
|
|
10
11
|
private setupTargetTime;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{subscribeDbLocale as t,t as e}from"../core/i18n.js";import{coerceToContract as s}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{COUNTDOWN_SIZES as o,COUNTDOWN_VARIANTS as n}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const i=o,a=n;class DbCountdown extends HTMLElement{constructor(){super(...arguments),this.timer=null,this.targetTime=Date.now()}static get observedAttributes(){return["end-date","duration","size","variant","show-days","show-hours","show-minutes","show-seconds","show-labels","label-days","label-hours","label-minutes","label-seconds"]}connectedCallback(){this.setupTargetTime(),this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>this.render()),this.start()}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.stop()}attributeChangedCallback(t){"end-date"!==t&&"duration"!==t||(this.setupTargetTime(),!this.isConnected)?this.render():this.start()}boolAttr(t,e=!1){if(!this.hasAttribute(t))return e;const s=this.getAttribute(t);return""===s||"true"===s}optionAttr(t,e,o){return s(this.getAttribute(t),e,o)}setupTargetTime(){const t=this.getAttribute("end-date"),e=Number(this.getAttribute("duration"));if(t){const e=new Date(t).getTime();return void(this.targetTime=Number.isFinite(e)?e:Date.now())}Number.isFinite(e)&&e>0?this.targetTime=Date.now()+1e3*e:this.targetTime=Date.now()}getRemaining(){const t=this.targetTime-Date.now();return t<=0?{days:0,hours:0,minutes:0,seconds:0,total:0}:{days:Math.floor(t/864e5),hours:Math.floor(t/36e5%24),minutes:Math.floor(t/6e4%60),seconds:Math.floor(t/1e3%60),total:t}}stop(){null!==this.timer&&(window.clearInterval(this.timer),this.timer=null)}start(){this.stop(),this.render(),this.timer=window.setInterval(()=>{const t=this.getRemaining();this.render(),this.dispatchEvent(new CustomEvent("db-tick",{detail:t,bubbles:!0,composed:!0})),t.total<=0&&(this.stop(),this.dispatchEvent(new CustomEvent("db-complete",{bubbles:!0,composed:!0})))},1e3)}two(t){return String(t).padStart(2,"0")}render(){const t=this.optionAttr("size",i,"m"),s=this.optionAttr("variant",a,"default"),o=this.boolAttr("show-labels",!0),n=this.getRemaining();this.className=["designbase-wc-countdown",`designbase-wc-countdown--${t}`,`designbase-wc-countdown--${s}`,o&&"designbase-wc-countdown--with-labels",n.total<=0&&"designbase-wc-countdown--expired"].filter(Boolean).join(" ");const r={days:this.getAttribute("label-days")||e("countdown.days"),hours:this.getAttribute("label-hours")||e("countdown.hours"),minutes:this.getAttribute("label-minutes")||e("countdown.minutes"),seconds:this.getAttribute("label-seconds")||e("countdown.seconds")},d=[{key:"days",value:n.days,show:this.boolAttr("show-days",!0)},{key:"hours",value:n.hours,show:this.boolAttr("show-hours",!0)},{key:"minutes",value:n.minutes,show:this.boolAttr("show-minutes",!0)},{key:"seconds",value:n.seconds,show:this.boolAttr("show-seconds",!0)}].filter(t=>t.show),u=[];for(let t=0;t<d.length;t+=1){const e=d[t],n=document.createElement("div");n.className="designbase-wc-countdown__unit";const i=document.createElement("div");if(i.className="designbase-wc-countdown__value",i.textContent=this.two(e.value),n.append(i),o){const t=document.createElement("div");t.className="designbase-wc-countdown__label",t.textContent=r[e.key],n.append(t)}if(u.push(n),t<d.length-1&&"minimal"!==s){const t=document.createElement("div");t.className="designbase-wc-countdown__separator",t.textContent=":",u.push(t)}}this.replaceChildren(...u)}}customElements.get("db-countdown")||customElements.define("db-countdown",DbCountdown);export{DbCountdown};
|
|
@@ -19,9 +19,12 @@ declare class DbDatePicker extends HTMLElement {
|
|
|
19
19
|
private tempValue?;
|
|
20
20
|
private activePresetId;
|
|
21
21
|
private inputText;
|
|
22
|
+
private unsubscribeLocale?;
|
|
23
|
+
private lastLocale;
|
|
22
24
|
private boundDocumentMouseDown;
|
|
23
25
|
connectedCallback(): void;
|
|
24
26
|
disconnectedCallback(): void;
|
|
27
|
+
private syncLocale;
|
|
25
28
|
/** 열린 달력은 Escape 로 닫히고 포커스는 트리거로 돌아간다 (A11Y-ESCAPE) */
|
|
26
29
|
private handleDocumentKeyDown;
|
|
27
30
|
private boundDocumentKeyDown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dbText as t}from"../core/i18n.js";import{createDbIcon as e,getDbComponentIconSize as i}from"./db-icons.js";import"./db-button.js";import"./db-modal.js";import{resolveDateLocale as s,startOfDay as n,parseISODate as a,DEFAULT_DATE_PICKER_PRESETS as r,formatDisplayDate as l,toISODate as d,detectActivePresetId as o,addMonths as h,generateWeekdays as u,generateCalendarGrid as c,formatPanelInputDate as p}from"./date-picker-utils.js";import{DATE_PICKER_SIZES as m,DATE_PICKER_VARIANTS as g}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const b="designbase-wc-date-picker",isRangeValue=t=>Boolean(t)&&"object"==typeof t&&!Array.isArray(t)&&"start"in t&&"end"in t;class DbDatePicker extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.isOpen=!1,this.currentMonth=new Date,this.viewStartMonth=new Date,this.rangeStart=null,this.hoveredDate=null,this.activePresetId="custom",this.inputText="",this.boundDocumentMouseDown=t=>this.handleDocumentMouseDown(t),this.handleDocumentKeyDown=t=>{"Escape"===t.key&&this.isOpen&&(t.preventDefault(),this.closePicker(),this.inputEl?.focus())},this.boundDocumentKeyDown=t=>this.handleDocumentKeyDown(t)}static get observedAttributes(){return["mode","layout","type","inline","value","default-value","min-date","max-date","size","variant","disabled","readonly","label","full-width","error","locale","start-of-week","show-outside-days","dropdown-position","open","events"]}connectedCallback(){this.built||this.build(),this.readInitialValue(),this.render(),document.addEventListener("mousedown",this.boundDocumentMouseDown),document.addEventListener("keydown",this.boundDocumentKeyDown)}disconnectedCallback(){document.removeEventListener("mousedown",this.boundDocumentMouseDown),document.removeEventListener("keydown",this.boundDocumentKeyDown)}attributeChangedCallback(t){if(this.built){if("value"===t&&(this.readAttributeValue(),this.syncInputText()),"open"===t)return this.isOpen=this.hasAttribute("open"),void this.render();this.render()}}get value(){return this.getAttribute("value")||""}set value(t){t?this.setAttribute("value",t):this.removeAttribute("value")}get mode(){const t=this.getAttribute("mode")||"single";return"range"===t?"range":"multiple"===t?"multiple":"single"}set mode(t){this.setAttribute("mode",t)}get isPanelLayout(){return"panel"===this.getAttribute("layout")}get effectiveMode(){return this.isPanelLayout?"range":this.mode}get inline(){return this.hasAttribute("inline")}set inline(t){this.toggleAttribute("inline",Boolean(t))}get type(){return"modal"===this.getAttribute("type")?"modal":"dropdown"}get locale(){return s(this.getAttribute("locale"))}set locale(t){this.setAttribute("locale",t||"")}get startOfWeek(){return"monday"===this.getAttribute("start-of-week")?"monday":"sunday"}get showOutsideDays(){return"false"!==this.getAttribute("show-outside-days")}get usesPendingValue(){return this.isPanelLayout||"modal"===this.type}get today(){return n(new Date)}get minDate(){return a(this.getAttribute("min-date"))}get maxDate(){return a(this.getAttribute("max-date"))}get presets(){return this.isPanelLayout?r.map(e=>({...e,label:t(e.label)})):[]}get events(){const t=this.getAttribute("events");if(!t)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}build(){this.built=!0,this.labelEl=document.createElement("label"),this.labelEl.className=`${b}__label`,this.triggerEl=document.createElement("div"),this.triggerEl.className=`${b}__trigger`;const e=document.createElement("button");e.type="button",e.className=`${b}__icon-display`,e.setAttribute("aria-label",t("날짜 선택 열기")),e.addEventListener("click",()=>this.toggleOpen()),this.inputEl=document.createElement("input"),this.inputEl.type="text",this.inputEl.className=`${b}__input`,this.inputEl.setAttribute("aria-label",t("날짜 입력")),this.inputEl.addEventListener("click",()=>this.openPicker()),this.inputEl.addEventListener("blur",()=>this.handleInputBlur()),this.inputEl.addEventListener("input",()=>{this.inputText=this.inputEl?.value||""});const i=document.createElement("button");i.type="button",i.className=`${b}__toggle`,i.setAttribute("aria-label",t("날짜 선택 열기")),i.addEventListener("click",()=>this.toggleOpen()),this.triggerEl.append(e,this.inputEl,i),this.dropdownEl=document.createElement("div"),this.dropdownEl.className=`${b}__dropdown`,this.dropdownEl.setAttribute("role","dialog"),this.dropdownEl.setAttribute("aria-modal","false"),this.calendarHost=document.createElement("div"),this.dropdownEl.appendChild(this.calendarHost)}readInitialValue(){const t=this.getAttribute("value")??this.getAttribute("default-value");if(t&&(this.selectedValue=this.parseValue(t)),this.tempValue=this.selectedValue,this.syncInputText(),isRangeValue(this.selectedValue)){const t=a(this.selectedValue.start);t&&(this.viewStartMonth=new Date(t))}else if("string"==typeof this.selectedValue){const t=a(this.selectedValue);t&&(this.currentMonth=new Date(t))}}readAttributeValue(){const t=this.getAttribute("value");if(!t)return this.selectedValue=void 0,void(this.tempValue=void 0);this.selectedValue=this.parseValue(t),this.isOpen&&this.usesPendingValue||(this.tempValue=this.selectedValue)}parseValue(t){if(t){if("multiple"===this.effectiveMode||t.trim().startsWith("["))try{const e=JSON.parse(t);if(Array.isArray(e))return e.filter(t=>Boolean(a(t)))}catch{return}if("range"===this.effectiveMode||t.trim().startsWith("{"))try{const e=JSON.parse(t);if(e?.start&&e?.end)return{start:e.start,end:e.end}}catch{return}return a(t)?t:void 0}}serializeValue(t){return t?"string"==typeof t?t:JSON.stringify(t):""}formatDisplay(t){if(!t)return"";if("string"==typeof t){const e=a(t);return e?l(e,this.locale):""}if(Array.isArray(t))return t.map(t=>a(t)).filter(Boolean).map(t=>l(t,this.locale)).join(", ");const e=a(t.start),i=a(t.end);return e&&i?t.start===t.end?l(e,this.locale):`${l(e,this.locale)} ~ ${l(i,this.locale)}`:""}syncInputText(){this.inputText=this.formatDisplay(this.selectedValue),this.inputEl&&(this.inputEl.value=this.inputText)}getWorkingValue(){return"range"===this.effectiveMode&&this.rangeStart?this.tempValue??this.selectedValue:this.usesPendingValue&&(this.isOpen||this.inline)?this.tempValue:this.selectedValue}presetContext(){return{today:this.today,startOfWeek:this.startOfWeek,minDate:this.minDate??void 0,maxDate:this.maxDate??void 0}}isDateValid(t){return!(this.minDate&&t<this.minDate)&&!(this.maxDate&&t>this.maxDate)}emitChange(t){const e=this.serializeValue(t);e?this.setAttribute("value",e):this.removeAttribute("value"),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:t??null},bubbles:!0,composed:!0}))}applyValue(t,e=!this.usesPendingValue){if(e)return this.selectedValue=t,this.tempValue=t,this.syncInputText(),void this.emitChange(t);this.tempValue=t,this.renderCalendar()}handleDateClick(t){if(this.disabled||this.readonly||!this.isDateValid(t))return;this.isPanelLayout&&(this.activePresetId="custom");const e=this.getWorkingValue();if("single"===this.effectiveMode){const e=d(t);return this.applyValue(e,!this.usesPendingValue),this.inline||this.isPanelLayout||this.closePicker(),void this.render()}if("multiple"===this.effectiveMode){const i=d(t),s=Array.isArray(e)?e:[],n=s.includes(i)?s.filter(t=>t!==i):[...s,i];return this.applyValue(n,!this.usesPendingValue),void this.render()}if(!this.rangeStart)return this.rangeStart=t,this.applyValue({start:d(t),end:d(t)},!1),void this.renderCalendar();const i=this.rangeStart,s=t,n=i>s?{start:d(s),end:d(i)}:{start:d(i),end:d(s)};this.rangeStart=null,this.applyValue(n,!0),this.inline||this.isPanelLayout||this.closePicker(),this.render()}handlePresetSelect(t){if(this.activePresetId=t.id,this.rangeStart=null,"custom"===t.id)return void this.renderCalendar();const e=t.getRange(this.presetContext());if(!e)return;const i={start:d(e.start),end:d(e.end)};this.viewStartMonth=new Date(e.start),this.applyValue(i,!this.usesPendingValue),this.render()}handlePendingApply(){this.selectedValue=this.tempValue,this.syncInputText(),this.emitChange(this.tempValue),this.rangeStart=null,this.closePicker(),this.render()}handlePendingCancel(){this.tempValue=this.selectedValue,this.rangeStart=null,this.activePresetId=o(isRangeValue(this.selectedValue)?{start:a(this.selectedValue.start),end:a(this.selectedValue.end)}:void 0,this.presets,this.presetContext()),this.closePicker(),this.render()}handleInputBlur(){if(!this.inputEl)return;const t=this.inputEl.value.trim();if(t.match(/^(\d{4})-(\d{2})-(\d{2})$/)){const e=a(t);if(e&&this.isDateValid(e)){const t=d(e);return this.applyValue(t,!0),void this.render()}}this.syncInputText()}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Boolean(t))}get readonly(){return this.hasAttribute("readonly")}set readonly(t){this.toggleAttribute("readonly",Boolean(t))}openPicker(){this.disabled||this.readonly||(this.isOpen=!0,this.usesPendingValue&&(this.tempValue=this.selectedValue,this.activePresetId=o(isRangeValue(this.selectedValue)?{start:a(this.selectedValue.start),end:a(this.selectedValue.end)}:void 0,this.presets,this.presetContext())),this.render())}closePicker(){this.isOpen=!1,this.rangeStart=null,this.hoveredDate=null,this.render()}toggleOpen(){this.isOpen?this.closePicker():this.openPicker()}handleDocumentMouseDown(t){this.isOpen&&!this.inline&&(this.contains(t.target)||(this.usesPendingValue&&(this.tempValue=this.selectedValue),this.closePicker()))}isDateSelected(t){const e=d(t),i=this.getWorkingValue();return"single"===this.effectiveMode?"string"==typeof i&&i===e:"multiple"===this.effectiveMode?Array.isArray(i)&&i.includes(e):!(!this.rangeStart||d(this.rangeStart)!==e)||!!isRangeValue(i)&&(i.start===e||i.end===e)}isInRange(t){if("range"!==this.effectiveMode)return!1;let e=null,i=null;if(this.rangeStart)e=this.rangeStart,i=this.hoveredDate;else{const t=this.getWorkingValue();isRangeValue(t)&&(e=a(t.start),i=a(t.end))}if(!e)return!1;const s=d(t),n=d(e),r=i?d(i):n;return s>=n&&s<=r}renderDateCell(t,e){const i=t.getMonth()===e.getMonth()&&t.getFullYear()===e.getFullYear(),s=t.toDateString()===this.today.toDateString(),n=this.isDateSelected(t),r=this.isInRange(t),l=0===t.getDay()||6===t.getDay(),d=this.events.filter(e=>{const i=a(e.date);return!!i&&i.toDateString()===t.toDateString()}),o=this.getWorkingValue(),h=isRangeValue(o)?a(o.end)?.toDateString():void 0,u=isRangeValue(o)?a(o.start)?.toDateString():void 0,c=document.createElement("button");c.type="button",c.className=[`${b}__date`,!i&&this.showOutsideDays&&`${b}__date--outside`,s&&`${b}__date--today`,n&&`${b}__date--selected`,r&&!n&&`${b}__date--in-range`,"range"===this.effectiveMode&&(this.rangeStart?.toDateString()===t.toDateString()||u===t.toDateString())&&`${b}__date--range-start`,"range"===this.effectiveMode&&h===t.toDateString()&&`${b}__date--range-end`,l&&`${b}__date--weekend`,!this.isDateValid(t)&&`${b}__date--disabled`,d.length>0&&`${b}__date--has-events`].filter(Boolean).join(" "),c.disabled=!this.isDateValid(t)||this.disabled||this.readonly,c.addEventListener("click",()=>this.handleDateClick(t));const p=document.createElement("span");if(p.className=`${b}__date-number`,p.textContent=String(t.getDate()),c.appendChild(p),d.length>0){const t=document.createElement("div");t.className=`${b}__events`,d.slice(0,3).forEach(e=>{const i=document.createElement("div");i.className=`${b}__event ${b}__event--${e.type||"dot"}`,e.color&&(i.style.backgroundColor=e.color),e.label&&(i.title=e.label),t.appendChild(i)}),c.appendChild(t)}return c}renderSingleMonth(s,n={}){const{showPrev:a=!1,showNext:r=!1}=n,l=this.getAttribute("size")||"m",d=i(l),o=document.createElement("div");o.className=`${b}__month`;const p=document.createElement("div");if(p.className=`${b}__header`,a){const i=document.createElement("button");i.type="button",i.className=`${b}__nav-button`,i.setAttribute("aria-label",t("이전 달")),i.disabled=this.disabled||this.readonly,i.appendChild(e("chevron-left",d)),i.addEventListener("click",()=>{this.isPanelLayout?this.viewStartMonth=h(this.viewStartMonth,-1):this.currentMonth=h(this.currentMonth,-1),this.renderCalendar()}),p.appendChild(i)}else{const t=document.createElement("span");t.className=`${b}__nav-spacer`,t.setAttribute("aria-hidden","true"),p.appendChild(t)}const m=document.createElement("div");if(m.className=`${b}__current-month`,m.textContent=s.toLocaleDateString(this.locale,{year:"numeric",month:"long"}),p.appendChild(m),r){const i=document.createElement("button");i.type="button",i.className=`${b}__nav-button`,i.setAttribute("aria-label",t("다음 달")),i.disabled=this.disabled||this.readonly,i.appendChild(e("chevron-right",d)),i.addEventListener("click",()=>{this.isPanelLayout?this.viewStartMonth=h(this.viewStartMonth,1):this.currentMonth=h(this.currentMonth,1),this.renderCalendar()}),p.appendChild(i)}else{const t=document.createElement("span");t.className=`${b}__nav-spacer`,t.setAttribute("aria-hidden","true"),p.appendChild(t)}o.appendChild(p);const g=document.createElement("div");g.className=`${b}__weekdays`,u(this.startOfWeek,this.locale).forEach(t=>{const e=document.createElement("div");e.className=`${b}__weekday`,e.textContent=t,g.appendChild(e)}),o.appendChild(g);const v=document.createElement("div");v.className=`${b}__grid`;const y=this.isPanelLayout;return c(s,this.startOfWeek,y).forEach((t,e)=>{if(!t){const t=document.createElement("span");return t.className=`${b}__date ${b}__date--empty`,t.setAttribute("aria-hidden","true"),t.dataset.index=String(e),void v.appendChild(t)}const i=t.getMonth()===s.getMonth()&&t.getFullYear()===s.getFullYear();if(!this.showOutsideDays&&!i){const t=document.createElement("span");return t.className=`${b}__date ${b}__date--empty`,t.setAttribute("aria-hidden","true"),t.dataset.index=String(e),void v.appendChild(t)}v.appendChild(this.renderDateCell(t,s))}),o.appendChild(v),o}renderDefaultCalendar(){const e=document.createElement("div");e.className=`${b}__selector`;const i=this.isPanelLayout?this.viewStartMonth:this.currentMonth;if(e.appendChild(this.renderSingleMonth(i,{showPrev:!0,showNext:!0})),!this.isPanelLayout){const i=document.createElement("div");i.className=`${b}__footer`;const s=document.createElement("button");s.type="button",s.className=`${b}__today-button`,s.textContent=t("오늘"),s.disabled=this.disabled||this.readonly,s.addEventListener("click",()=>{const t=new Date;this.isPanelLayout?this.viewStartMonth=t:this.currentMonth=t,this.renderCalendar()}),i.appendChild(s),e.appendChild(i)}return e}renderPanelCalendar(){const e=document.createElement("div");e.className=`${b}__panel`;const i=document.createElement("div");i.className=`${b}__presets`,i.setAttribute("role","listbox"),i.setAttribute("aria-label",t("기간 프리셋")),this.presets.forEach(t=>{const e=document.createElement("button");e.type="button",e.className=[`${b}__preset`,this.activePresetId===t.id&&`${b}__preset--active`].filter(Boolean).join(" "),e.setAttribute("role","option"),e.setAttribute("aria-selected",String(this.activePresetId===t.id)),e.textContent=t.label,e.addEventListener("click",()=>this.handlePresetSelect(t)),i.appendChild(e)}),e.appendChild(i);const s=document.createElement("div");s.className=`${b}__panel-main`;const n=document.createElement("div");n.className=`${b}__months ${b}__months--count-2`,[0,1].forEach(t=>{const e=h(this.viewStartMonth,t);n.appendChild(this.renderSingleMonth(e,{showPrev:0===t,showNext:1===t}))}),s.appendChild(n);const r=document.createElement("div");r.className=`${b}__panel-footer`;const l=isRangeValue(this.tempValue)?this.tempValue:void 0,d=document.createElement("div");d.className=`${b}__range-display`;const o=document.createElement("span");o.className=`${b}__range-text`,o.textContent=l?.start&&a(l.start)?p(a(l.start),this.locale):"시작일";const u=document.createElement("span");u.className=`${b}__range-separator`,u.textContent="–";const c=document.createElement("span");c.className=`${b}__range-text`,c.textContent=l?.end&&a(l.end)?p(a(l.end),this.locale):"종료일",d.append(o,u,c),r.appendChild(d);const m=document.createElement("div");m.className=`${b}__panel-actions`;const g=document.createElement("db-button");g.setAttribute("variant","secondary"),g.setAttribute("size","m"),g.textContent=t("취소"),g.addEventListener("click",()=>this.handlePendingCancel());const v=document.createElement("db-button");return v.setAttribute("variant","primary"),v.setAttribute("size","m"),v.textContent=t("적용"),v.addEventListener("click",()=>this.handlePendingApply()),m.append(g,v),r.appendChild(m),s.appendChild(r),e.appendChild(s),e}renderCalendar(){this.calendarHost&&(this.calendarHost.replaceChildren(),this.calendarHost.appendChild(this.isPanelLayout?this.renderPanelCalendar():this.renderDefaultCalendar()))}render(){const s=m.includes(this.getAttribute("size")||"m")&&this.getAttribute("size")||"m",n=g.includes(this.getAttribute("variant")||"default")&&this.getAttribute("variant")||"default",a=this.getAttribute("dropdown-position")||"bottom-start",r=i(s);if(this.className=[b,this.inline?`${b}--size-${s}`:`${b}--${s}`,`${b}--variant-${n}`,this.hasAttribute("full-width")&&`${b}--full-width`,this.disabled&&`${b}--disabled`,this.readonly&&`${b}--readonly`,this.isOpen&&`${b}--open`,this.hasAttribute("error")&&`${b}--error`,this.isPanelLayout&&`${b}--panel`].filter(Boolean).join(" "),this.inputEl?.setAttribute("aria-invalid",String(this.hasAttribute("error"))),this.replaceChildren(),this.inline)return this.calendarHost=document.createElement("div"),this.appendChild(this.calendarHost),void this.renderCalendar();if(!(this.labelEl&&this.triggerEl&&this.inputEl&&this.dropdownEl))return;const l=this.getAttribute("label")||"";this.labelEl.textContent=l,this.labelEl.hidden=!l,this.inputEl.value=this.inputText,this.inputEl.placeholder=this.isPanelLayout?"기간을 선택하세요":"날짜를 선택하세요",this.inputEl.disabled=this.disabled,this.inputEl.readOnly=this.readonly;const d=this.triggerEl.querySelector(`.${b}__icon-display`);d&&(d.innerHTML="",d.appendChild(e("calendar",r)),d.disabled=this.disabled);const o=this.triggerEl.querySelector(`.${b}__toggle`);if(o&&(o.innerHTML="",o.appendChild(e("chevron-down",r)),o.disabled=this.disabled),this.dropdownEl.className=[`${b}__dropdown`,`${b}__dropdown--${a}`,this.isPanelLayout&&`${b}__dropdown--panel`].filter(Boolean).join(" "),this.dropdownEl.hidden=!this.isOpen||"modal"===this.type,this.calendarHost=document.createElement("div"),this.dropdownEl.replaceChildren(this.calendarHost),this.renderCalendar(),this.append(this.labelEl,this.triggerEl),this.isOpen&&"dropdown"===this.type&&this.appendChild(this.dropdownEl),this.isOpen&&"modal"===this.type){const e=document.createElement("db-modal");e.setAttribute("open","true"),e.setAttribute("title",this.isPanelLayout?"기간 선택":"날짜 선택"),e.setAttribute("size",this.isPanelLayout?"l":"s"),e.addEventListener("db-close",()=>this.handlePendingCancel());const i=document.createElement("div");if(this.calendarHost=i,this.renderCalendar(),e.append(i),this.usesPendingValue){const i=document.createElement("div");i.className=`${b}__modal-footer`;const s=document.createElement("db-button");s.setAttribute("variant","secondary"),s.setAttribute("size","m"),s.textContent=t("취소"),s.addEventListener("click",()=>this.handlePendingCancel());const n=document.createElement("db-button");n.setAttribute("variant","primary"),n.setAttribute("size","m"),n.textContent=t("적용"),n.addEventListener("click",()=>this.handlePendingApply()),i.append(s,n),e.append(i)}this.appendChild(e)}}}customElements.get("db-date-picker")||customElements.define("db-date-picker",DbDatePicker);export{DbDatePicker};
|
|
1
|
+
import{subscribeDbLocale as t,dbText as e}from"../core/i18n.js";import{createDbIcon as i,getDbComponentIconSize as s}from"./db-icons.js";import"./db-button.js";import"./db-modal.js";import{resolveDateLocale as n,startOfDay as a,parseISODate as r,DEFAULT_DATE_PICKER_PRESETS as l,formatDisplayDate as d,toISODate as o,detectActivePresetId as h,addMonths as u,generateWeekdays as c,generateCalendarGrid as p,formatPanelInputDate as m}from"./date-picker-utils.js";import{DATE_PICKER_SIZES as b,DATE_PICKER_VARIANTS as g}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const v="designbase-wc-date-picker",isRangeValue=t=>Boolean(t)&&"object"==typeof t&&!Array.isArray(t)&&"start"in t&&"end"in t;class DbDatePicker extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.isOpen=!1,this.currentMonth=new Date,this.viewStartMonth=new Date,this.rangeStart=null,this.hoveredDate=null,this.activePresetId="custom",this.inputText="",this.lastLocale="",this.boundDocumentMouseDown=t=>this.handleDocumentMouseDown(t),this.handleDocumentKeyDown=t=>{"Escape"===t.key&&this.isOpen&&(t.preventDefault(),this.closePicker(),this.inputEl?.focus())},this.boundDocumentKeyDown=t=>this.handleDocumentKeyDown(t)}static get observedAttributes(){return["mode","layout","type","inline","value","default-value","min-date","max-date","size","variant","disabled","readonly","label","full-width","error","locale","start-of-week","show-outside-days","dropdown-position","open","events"]}connectedCallback(){this.built||this.build(),this.readInitialValue(),this.lastLocale=this.locale,this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>this.syncLocale()),this.render(),document.addEventListener("mousedown",this.boundDocumentMouseDown),document.addEventListener("keydown",this.boundDocumentKeyDown)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,document.removeEventListener("mousedown",this.boundDocumentMouseDown),document.removeEventListener("keydown",this.boundDocumentKeyDown)}syncLocale(){const t=this.formatDisplay(this.selectedValue,this.lastLocale||this.locale);this.lastLocale=this.locale,this.inputEl&&document.activeElement!==this.inputEl&&this.inputText===t&&this.syncInputText(),this.inputEl&&(this.inputEl.placeholder=e(this.isPanelLayout?"기간을 선택하세요":"날짜를 선택하세요"),this.inputEl.setAttribute("aria-label",e("날짜 입력"))),this.triggerEl?.querySelectorAll(`.${v}__icon-display, .${v}__toggle`).forEach(t=>t.setAttribute("aria-label",e("날짜 선택 열기")));const i=this.querySelector("db-modal");i&&i.setAttribute("title",e(this.isPanelLayout?"기간 선택":"날짜 선택"));const s=this.querySelectorAll(`.${v}__modal-footer db-button`);s[0]&&(s[0].textContent=e("취소")),s[1]&&(s[1].textContent=e("적용"));const n=document.activeElement,a=(this.calendarHost?Array.from(this.calendarHost.querySelectorAll("button, db-button")):[]).findIndex(t=>t===n||t.contains(n));this.renderCalendar(),a>=0&&this.calendarHost?.querySelectorAll("button, db-button")[a]?.focus({preventScroll:!0})}attributeChangedCallback(t){if(this.built){if("locale"===t){const t=this.formatDisplay(this.selectedValue,this.lastLocale||this.locale);this.lastLocale=this.locale,this.inputText===t&&document.activeElement!==this.inputEl&&this.syncInputText()}if("value"===t&&(this.readAttributeValue(),this.syncInputText()),"open"===t)return this.isOpen=this.hasAttribute("open"),void this.render();this.render()}}get value(){return this.getAttribute("value")||""}set value(t){t?this.setAttribute("value",t):this.removeAttribute("value")}get mode(){const t=this.getAttribute("mode")||"single";return"range"===t?"range":"multiple"===t?"multiple":"single"}set mode(t){this.setAttribute("mode",t)}get isPanelLayout(){return"panel"===this.getAttribute("layout")}get effectiveMode(){return this.isPanelLayout?"range":this.mode}get inline(){return this.hasAttribute("inline")}set inline(t){this.toggleAttribute("inline",Boolean(t))}get type(){return"modal"===this.getAttribute("type")?"modal":"dropdown"}get locale(){return n(this.getAttribute("locale"))}set locale(t){this.setAttribute("locale",t||"")}get startOfWeek(){return"monday"===this.getAttribute("start-of-week")?"monday":"sunday"}get showOutsideDays(){return"false"!==this.getAttribute("show-outside-days")}get usesPendingValue(){return this.isPanelLayout||"modal"===this.type}get today(){return a(new Date)}get minDate(){return r(this.getAttribute("min-date"))}get maxDate(){return r(this.getAttribute("max-date"))}get presets(){return this.isPanelLayout?l.map(t=>({...t,label:e(t.label)})):[]}get events(){const t=this.getAttribute("events");if(!t)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}build(){this.built=!0,this.labelEl=document.createElement("label"),this.labelEl.className=`${v}__label`,this.triggerEl=document.createElement("div"),this.triggerEl.className=`${v}__trigger`;const t=document.createElement("button");t.type="button",t.className=`${v}__icon-display`,t.setAttribute("aria-label",e("날짜 선택 열기")),t.addEventListener("click",()=>this.toggleOpen()),this.inputEl=document.createElement("input"),this.inputEl.type="text",this.inputEl.className=`${v}__input`,this.inputEl.setAttribute("aria-label",e("날짜 입력")),this.inputEl.addEventListener("click",()=>this.openPicker()),this.inputEl.addEventListener("blur",()=>this.handleInputBlur()),this.inputEl.addEventListener("input",()=>{this.inputText=this.inputEl?.value||""});const i=document.createElement("button");i.type="button",i.className=`${v}__toggle`,i.setAttribute("aria-label",e("날짜 선택 열기")),i.addEventListener("click",()=>this.toggleOpen()),this.triggerEl.append(t,this.inputEl,i),this.dropdownEl=document.createElement("div"),this.dropdownEl.className=`${v}__dropdown`,this.dropdownEl.setAttribute("role","dialog"),this.dropdownEl.setAttribute("aria-modal","false"),this.calendarHost=document.createElement("div"),this.dropdownEl.appendChild(this.calendarHost)}readInitialValue(){const t=this.getAttribute("value")??this.getAttribute("default-value");if(t&&(this.selectedValue=this.parseValue(t)),this.tempValue=this.selectedValue,this.syncInputText(),isRangeValue(this.selectedValue)){const t=r(this.selectedValue.start);t&&(this.viewStartMonth=new Date(t))}else if("string"==typeof this.selectedValue){const t=r(this.selectedValue);t&&(this.currentMonth=new Date(t))}}readAttributeValue(){const t=this.getAttribute("value");if(!t)return this.selectedValue=void 0,void(this.tempValue=void 0);this.selectedValue=this.parseValue(t),this.isOpen&&this.usesPendingValue||(this.tempValue=this.selectedValue)}parseValue(t){if(t){if("multiple"===this.effectiveMode||t.trim().startsWith("["))try{const e=JSON.parse(t);if(Array.isArray(e))return e.filter(t=>Boolean(r(t)))}catch{return}if("range"===this.effectiveMode||t.trim().startsWith("{"))try{const e=JSON.parse(t);if(e?.start&&e?.end)return{start:e.start,end:e.end}}catch{return}return r(t)?t:void 0}}serializeValue(t){return t?"string"==typeof t?t:JSON.stringify(t):""}formatDisplay(t,e=this.locale){if(!t)return"";if("string"==typeof t){const i=r(t);return i?d(i,e):""}if(Array.isArray(t))return t.map(t=>r(t)).filter(Boolean).map(t=>d(t,e)).join(", ");const i=r(t.start),s=r(t.end);return i&&s?t.start===t.end?d(i,e):`${d(i,e)} ~ ${d(s,e)}`:""}syncInputText(){this.inputText=this.formatDisplay(this.selectedValue),this.inputEl&&(this.inputEl.value=this.inputText)}getWorkingValue(){return"range"===this.effectiveMode&&this.rangeStart?this.tempValue??this.selectedValue:this.usesPendingValue&&(this.isOpen||this.inline)?this.tempValue:this.selectedValue}presetContext(){return{today:this.today,startOfWeek:this.startOfWeek,minDate:this.minDate??void 0,maxDate:this.maxDate??void 0}}isDateValid(t){return!(this.minDate&&t<this.minDate)&&!(this.maxDate&&t>this.maxDate)}emitChange(t){const e=this.serializeValue(t);e?this.setAttribute("value",e):this.removeAttribute("value"),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:t??null},bubbles:!0,composed:!0}))}applyValue(t,e=!this.usesPendingValue){if(e)return this.selectedValue=t,this.tempValue=t,this.syncInputText(),void this.emitChange(t);this.tempValue=t,this.renderCalendar()}handleDateClick(t){if(this.disabled||this.readonly||!this.isDateValid(t))return;this.isPanelLayout&&(this.activePresetId="custom");const e=this.getWorkingValue();if("single"===this.effectiveMode){const e=o(t);return this.applyValue(e,!this.usesPendingValue),this.inline||this.isPanelLayout||this.closePicker(),void this.render()}if("multiple"===this.effectiveMode){const i=o(t),s=Array.isArray(e)?e:[],n=s.includes(i)?s.filter(t=>t!==i):[...s,i];return this.applyValue(n,!this.usesPendingValue),void this.render()}if(!this.rangeStart)return this.rangeStart=t,this.applyValue({start:o(t),end:o(t)},!1),void this.renderCalendar();const i=this.rangeStart,s=t,n=i>s?{start:o(s),end:o(i)}:{start:o(i),end:o(s)};this.rangeStart=null,this.applyValue(n,!0),this.inline||this.isPanelLayout||this.closePicker(),this.render()}handlePresetSelect(t){if(this.activePresetId=t.id,this.rangeStart=null,"custom"===t.id)return void this.renderCalendar();const e=t.getRange(this.presetContext());if(!e)return;const i={start:o(e.start),end:o(e.end)};this.viewStartMonth=new Date(e.start),this.applyValue(i,!this.usesPendingValue),this.render()}handlePendingApply(){this.selectedValue=this.tempValue,this.syncInputText(),this.emitChange(this.tempValue),this.rangeStart=null,this.closePicker(),this.render()}handlePendingCancel(){this.tempValue=this.selectedValue,this.rangeStart=null,this.activePresetId=h(isRangeValue(this.selectedValue)?{start:r(this.selectedValue.start),end:r(this.selectedValue.end)}:void 0,this.presets,this.presetContext()),this.closePicker(),this.render()}handleInputBlur(){if(!this.inputEl)return;const t=this.inputEl.value.trim();if(t.match(/^(\d{4})-(\d{2})-(\d{2})$/)){const e=r(t);if(e&&this.isDateValid(e)){const t=o(e);return this.applyValue(t,!0),void this.render()}}this.syncInputText()}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Boolean(t))}get readonly(){return this.hasAttribute("readonly")}set readonly(t){this.toggleAttribute("readonly",Boolean(t))}openPicker(){this.disabled||this.readonly||(this.isOpen=!0,this.usesPendingValue&&(this.tempValue=this.selectedValue,this.activePresetId=h(isRangeValue(this.selectedValue)?{start:r(this.selectedValue.start),end:r(this.selectedValue.end)}:void 0,this.presets,this.presetContext())),this.render())}closePicker(){this.isOpen=!1,this.rangeStart=null,this.hoveredDate=null,this.render()}toggleOpen(){this.isOpen?this.closePicker():this.openPicker()}handleDocumentMouseDown(t){this.isOpen&&!this.inline&&(this.contains(t.target)||(this.usesPendingValue&&(this.tempValue=this.selectedValue),this.closePicker()))}isDateSelected(t){const e=o(t),i=this.getWorkingValue();return"single"===this.effectiveMode?"string"==typeof i&&i===e:"multiple"===this.effectiveMode?Array.isArray(i)&&i.includes(e):!(!this.rangeStart||o(this.rangeStart)!==e)||!!isRangeValue(i)&&(i.start===e||i.end===e)}isInRange(t){if("range"!==this.effectiveMode)return!1;let e=null,i=null;if(this.rangeStart)e=this.rangeStart,i=this.hoveredDate;else{const t=this.getWorkingValue();isRangeValue(t)&&(e=r(t.start),i=r(t.end))}if(!e)return!1;const s=o(t),n=o(e),a=i?o(i):n;return s>=n&&s<=a}renderDateCell(t,e){const i=t.getMonth()===e.getMonth()&&t.getFullYear()===e.getFullYear(),s=t.toDateString()===this.today.toDateString(),n=this.isDateSelected(t),a=this.isInRange(t),l=0===t.getDay()||6===t.getDay(),d=this.events.filter(e=>{const i=r(e.date);return!!i&&i.toDateString()===t.toDateString()}),o=this.getWorkingValue(),h=isRangeValue(o)?r(o.end)?.toDateString():void 0,u=isRangeValue(o)?r(o.start)?.toDateString():void 0,c=document.createElement("button");c.type="button",c.className=[`${v}__date`,!i&&this.showOutsideDays&&`${v}__date--outside`,s&&`${v}__date--today`,n&&`${v}__date--selected`,a&&!n&&`${v}__date--in-range`,"range"===this.effectiveMode&&(this.rangeStart?.toDateString()===t.toDateString()||u===t.toDateString())&&`${v}__date--range-start`,"range"===this.effectiveMode&&h===t.toDateString()&&`${v}__date--range-end`,l&&`${v}__date--weekend`,!this.isDateValid(t)&&`${v}__date--disabled`,d.length>0&&`${v}__date--has-events`].filter(Boolean).join(" "),c.disabled=!this.isDateValid(t)||this.disabled||this.readonly,c.addEventListener("click",()=>this.handleDateClick(t));const p=document.createElement("span");if(p.className=`${v}__date-number`,p.textContent=String(t.getDate()),c.appendChild(p),d.length>0){const t=document.createElement("div");t.className=`${v}__events`,d.slice(0,3).forEach(e=>{const i=document.createElement("div");i.className=`${v}__event ${v}__event--${e.type||"dot"}`,e.color&&(i.style.backgroundColor=e.color),e.label&&(i.title=e.label),t.appendChild(i)}),c.appendChild(t)}return c}renderSingleMonth(t,n={}){const{showPrev:a=!1,showNext:r=!1}=n,l=this.getAttribute("size")||"m",d=s(l),o=document.createElement("div");o.className=`${v}__month`;const h=document.createElement("div");if(h.className=`${v}__header`,a){const t=document.createElement("button");t.type="button",t.className=`${v}__nav-button`,t.setAttribute("aria-label",e("이전 달")),t.disabled=this.disabled||this.readonly,t.appendChild(i("chevron-left",d)),t.addEventListener("click",()=>{this.isPanelLayout?this.viewStartMonth=u(this.viewStartMonth,-1):this.currentMonth=u(this.currentMonth,-1),this.renderCalendar()}),h.appendChild(t)}else{const t=document.createElement("span");t.className=`${v}__nav-spacer`,t.setAttribute("aria-hidden","true"),h.appendChild(t)}const m=document.createElement("div");if(m.className=`${v}__current-month`,m.textContent=t.toLocaleDateString(this.locale,{year:"numeric",month:"long"}),h.appendChild(m),r){const t=document.createElement("button");t.type="button",t.className=`${v}__nav-button`,t.setAttribute("aria-label",e("다음 달")),t.disabled=this.disabled||this.readonly,t.appendChild(i("chevron-right",d)),t.addEventListener("click",()=>{this.isPanelLayout?this.viewStartMonth=u(this.viewStartMonth,1):this.currentMonth=u(this.currentMonth,1),this.renderCalendar()}),h.appendChild(t)}else{const t=document.createElement("span");t.className=`${v}__nav-spacer`,t.setAttribute("aria-hidden","true"),h.appendChild(t)}o.appendChild(h);const b=document.createElement("div");b.className=`${v}__weekdays`,c(this.startOfWeek,this.locale).forEach(t=>{const e=document.createElement("div");e.className=`${v}__weekday`,e.textContent=t,b.appendChild(e)}),o.appendChild(b);const g=document.createElement("div");g.className=`${v}__grid`;const y=this.isPanelLayout;return p(t,this.startOfWeek,y).forEach((e,i)=>{if(!e){const t=document.createElement("span");return t.className=`${v}__date ${v}__date--empty`,t.setAttribute("aria-hidden","true"),t.dataset.index=String(i),void g.appendChild(t)}const s=e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear();if(!this.showOutsideDays&&!s){const t=document.createElement("span");return t.className=`${v}__date ${v}__date--empty`,t.setAttribute("aria-hidden","true"),t.dataset.index=String(i),void g.appendChild(t)}g.appendChild(this.renderDateCell(e,t))}),o.appendChild(g),o}renderDefaultCalendar(){const t=document.createElement("div");t.className=`${v}__selector`;const i=this.isPanelLayout?this.viewStartMonth:this.currentMonth;if(t.appendChild(this.renderSingleMonth(i,{showPrev:!0,showNext:!0})),!this.isPanelLayout){const i=document.createElement("div");i.className=`${v}__footer`;const s=document.createElement("button");s.type="button",s.className=`${v}__today-button`,s.textContent=e("오늘"),s.disabled=this.disabled||this.readonly,s.addEventListener("click",()=>{const t=new Date;this.isPanelLayout?this.viewStartMonth=t:this.currentMonth=t,this.renderCalendar()}),i.appendChild(s),t.appendChild(i)}return t}renderPanelCalendar(){const t=document.createElement("div");t.className=`${v}__panel`;const i=document.createElement("div");i.className=`${v}__presets`,i.setAttribute("role","listbox"),i.setAttribute("aria-label",e("기간 프리셋")),this.presets.forEach(t=>{const e=document.createElement("button");e.type="button",e.className=[`${v}__preset`,this.activePresetId===t.id&&`${v}__preset--active`].filter(Boolean).join(" "),e.setAttribute("role","option"),e.setAttribute("aria-selected",String(this.activePresetId===t.id)),e.textContent=t.label,e.addEventListener("click",()=>this.handlePresetSelect(t)),i.appendChild(e)}),t.appendChild(i);const s=document.createElement("div");s.className=`${v}__panel-main`;const n=document.createElement("div");n.className=`${v}__months ${v}__months--count-2`,[0,1].forEach(t=>{const e=u(this.viewStartMonth,t);n.appendChild(this.renderSingleMonth(e,{showPrev:0===t,showNext:1===t}))}),s.appendChild(n);const a=document.createElement("div");a.className=`${v}__panel-footer`;const l=isRangeValue(this.tempValue)?this.tempValue:void 0,d=document.createElement("div");d.className=`${v}__range-display`;const o=document.createElement("span");o.className=`${v}__range-text`,o.textContent=l?.start&&r(l.start)?m(r(l.start),this.locale):e("시작일");const h=document.createElement("span");h.className=`${v}__range-separator`,h.textContent="–";const c=document.createElement("span");c.className=`${v}__range-text`,c.textContent=l?.end&&r(l.end)?m(r(l.end),this.locale):e("종료일"),d.append(o,h,c),a.appendChild(d);const p=document.createElement("div");p.className=`${v}__panel-actions`;const b=document.createElement("db-button");b.setAttribute("variant","secondary"),b.setAttribute("size","m"),b.textContent=e("취소"),b.addEventListener("click",()=>this.handlePendingCancel());const g=document.createElement("db-button");return g.setAttribute("variant","primary"),g.setAttribute("size","m"),g.textContent=e("적용"),g.addEventListener("click",()=>this.handlePendingApply()),p.append(b,g),a.appendChild(p),s.appendChild(a),t.appendChild(s),t}renderCalendar(){this.calendarHost&&(this.calendarHost.replaceChildren(),this.calendarHost.appendChild(this.isPanelLayout?this.renderPanelCalendar():this.renderDefaultCalendar()))}render(){const t=b.includes(this.getAttribute("size")||"m")&&this.getAttribute("size")||"m",n=g.includes(this.getAttribute("variant")||"default")&&this.getAttribute("variant")||"default",a=this.getAttribute("dropdown-position")||"bottom-start",r=s(t);if(this.className=[v,this.inline?`${v}--size-${t}`:`${v}--${t}`,`${v}--variant-${n}`,this.hasAttribute("full-width")&&`${v}--full-width`,this.disabled&&`${v}--disabled`,this.readonly&&`${v}--readonly`,this.isOpen&&`${v}--open`,this.hasAttribute("error")&&`${v}--error`,this.isPanelLayout&&`${v}--panel`].filter(Boolean).join(" "),this.inputEl?.setAttribute("aria-invalid",String(this.hasAttribute("error"))),this.replaceChildren(),this.inline)return this.calendarHost=document.createElement("div"),this.appendChild(this.calendarHost),void this.renderCalendar();if(!(this.labelEl&&this.triggerEl&&this.inputEl&&this.dropdownEl))return;const l=this.getAttribute("label")||"";this.labelEl.textContent=l,this.labelEl.hidden=!l,this.inputEl.value=this.inputText,this.inputEl.placeholder=e(this.isPanelLayout?"기간을 선택하세요":"날짜를 선택하세요"),this.inputEl.disabled=this.disabled,this.inputEl.readOnly=this.readonly;const d=this.triggerEl.querySelector(`.${v}__icon-display`);d&&(d.innerHTML="",d.appendChild(i("calendar",r)),d.disabled=this.disabled);const o=this.triggerEl.querySelector(`.${v}__toggle`);if(o&&(o.innerHTML="",o.appendChild(i("chevron-down",r)),o.disabled=this.disabled),this.dropdownEl.className=[`${v}__dropdown`,`${v}__dropdown--${a}`,this.isPanelLayout&&`${v}__dropdown--panel`].filter(Boolean).join(" "),this.dropdownEl.hidden=!this.isOpen||"modal"===this.type,this.calendarHost=document.createElement("div"),this.dropdownEl.replaceChildren(this.calendarHost),this.renderCalendar(),this.append(this.labelEl,this.triggerEl),this.isOpen&&"dropdown"===this.type&&this.appendChild(this.dropdownEl),this.isOpen&&"modal"===this.type){const t=document.createElement("db-modal");t.setAttribute("open","true"),t.setAttribute("title",e(this.isPanelLayout?"기간 선택":"날짜 선택")),t.setAttribute("size",this.isPanelLayout?"l":"s"),t.addEventListener("db-close",()=>this.handlePendingCancel());const i=document.createElement("div");if(this.calendarHost=i,this.renderCalendar(),t.append(i),this.usesPendingValue){const i=document.createElement("div");i.className=`${v}__modal-footer`;const s=document.createElement("db-button");s.setAttribute("variant","secondary"),s.setAttribute("size","m"),s.textContent=e("취소"),s.addEventListener("click",()=>this.handlePendingCancel());const n=document.createElement("db-button");n.setAttribute("variant","primary"),n.setAttribute("size","m"),n.textContent=e("적용"),n.addEventListener("click",()=>this.handlePendingApply()),i.append(s,n),t.append(i)}this.appendChild(t)}}}customElements.get("db-date-picker")||customElements.define("db-date-picker",DbDatePicker);export{DbDatePicker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setHostClasses as e}from"../core/host-class.js";import{isDbIconName as t,createDbIcon as i}from"./db-icons.js";import{DROPDOWN_SIZES as r,DROPDOWN_PLACEMENTS as s,DROPDOWN_TRIGGER_VARIANTS as n}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbDropdown extends HTMLElement{constructor(){super(...arguments),this.focusedIndex=-1,this.onTriggerActivate=null,this.lastTriggerSignature="",this.handleTriggerKeyDown=e=>{if(!this.menu?.contains(e.target))return"Enter"!==e.key&&" "!==e.key&&"ArrowDown"!==e.key||this.open?void("Escape"===e.key&&this.open&&(e.preventDefault(),this.open=!1,this.render())):(e.preventDefault(),this.open=!0,requestAnimationFrame(()=>this.focusItem(0)),void this.render())},this.handleDocumentKeyDown=e=>{if(!this.open)return;if("Escape"===e.key)return e.preventDefault(),this.open=!1,this.render(),void this.triggerWrap?.querySelector("[aria-haspopup]")?.focus();if(this.menu?.querySelector(':scope > [slot="content"]'))return;const t=this.enabledItems();if(!t.length)return;const i=t.findIndex(e=>this.parsedItems.indexOf(e)===this.focusedIndex);switch(e.key){case"ArrowDown":e.preventDefault(),this.focusItem(i<0?0:this.parsedItems.indexOf(t[(i+1)%t.length]));break;case"ArrowUp":e.preventDefault(),this.focusItem(i<0?0:this.parsedItems.indexOf(t[(i-1+t.length)%t.length]));break;case"Home":e.preventDefault(),this.focusItem(this.parsedItems.indexOf(t[0]));break;case"End":e.preventDefault(),this.focusItem(this.parsedItems.indexOf(t[t.length-1]));break;case"Enter":case" ":{e.preventDefault();const t=this.parsedItems[this.focusedIndex];!t||t.divider||t.disabled||this.selectItem(t);break}}},this.handleDocumentMouseDown=e=>{this.open&&(this.contains(e.target)||(this.open=!1,this.render()))}}static get observedAttributes(){return["options","items","placeholder","label","value","size","placement","full-width","disabled","open","trigger-variant","trigger-icon","icon-only","show-chevron"]}get showChevron(){return"false"!==this.getAttribute("show-chevron")}set showChevron(e){this.setAttribute("show-chevron",String(e))}get parsedItems(){const e=this.getAttribute("items");if(e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return(this.getAttribute("options")||"").split(",").map(e=>e.trim()).filter(Boolean).map((e,t)=>({id:`option-${t}`,label:e}))}get options(){return this.parsedItems.map(e=>e.label||e.id)}set options(e){this.setAttribute("options",Array.isArray(e)?e.join(","):e)}get items(){return this.parsedItems}set items(e){this.setAttribute("items","string"==typeof e?e:JSON.stringify(e))}get value(){return this.getAttribute("value")||""}set value(e){e?this.setAttribute("value",e):this.removeAttribute("value")}get open(){return this.hasAttribute("open")}set open(e){const t=this.open;this.toggleAttribute("open",e),t!==e&&this.dispatchEvent(new CustomEvent("db-open",{detail:{open:e},bubbles:!0,composed:!0}))}get disabled(){return this.hasAttribute("disabled")}set disabled(e){this.toggleAttribute("disabled",e)}get size(){return this.getAttribute("size")||"m"}set size(e){this.setAttribute("size",e)}get placement(){return this.getAttribute("placement")||"bottom-left"}set placement(e){this.setAttribute("placement",e)}get placeholder(){return this.getAttribute("placeholder")||""}set placeholder(e){e?this.setAttribute("placeholder",e):this.removeAttribute("placeholder")}get label(){return this.getAttribute("label")||""}set label(e){e?this.setAttribute("label",e):this.removeAttribute("label")}get fullWidth(){return this.hasAttribute("full-width")}set fullWidth(e){this.toggleAttribute("full-width",e)}connectedCallback(){requestAnimationFrame(()=>this.render()),document.addEventListener("mousedown",this.handleDocumentMouseDown),document.addEventListener("keydown",this.handleDocumentKeyDown)}disconnectedCallback(){document.removeEventListener("mousedown",this.handleDocumentMouseDown),document.removeEventListener("keydown",this.handleDocumentKeyDown),this.unbindTrigger()}attributeChangedCallback(e){this.isConnected&&("open"!==e||this.open||(this.focusedIndex=-1),this.render())}resolvedSize(){return r.includes(this.size)?this.size:"m"}resolvedPlacement(){return s.includes(this.placement)?this.placement:"bottom-left"}menuItemIconSize(){const e=this.resolvedSize();return"s"===e?14:"l"===e?18:16}triggerLabel(){return this.label?this.label:this.placeholder?this.placeholder:this.value?this.value:"메뉴"}enabledItems(){return this.parsedItems.filter(e=>!e.disabled&&!e.divider)}collectTriggerChildren(){const isInternalNode=e=>"content"===e.getAttribute("slot")||e.hasAttribute("data-wc-internal")||e===this.triggerWrap||e===this.menu||e===this.defaultTrigger,e=Array.from(this.children).filter(e=>!isInternalNode(e));return e.length>0?e:Array.from(this.triggerWrap?.children||[]).filter(e=>!isInternalNode(e))}hasCustomTrigger(){return this.collectTriggerChildren().length>0}bindTrigger(){this.triggerWrap&&(this.unbindTrigger(),this.onTriggerActivate=e=>{this.disabled||this.menu?.contains(e.target)||(e.preventDefault(),e.stopPropagation(),this.toggleOpen())},this.triggerWrap.addEventListener("click",this.onTriggerActivate),this.triggerWrap.addEventListener("keydown",this.handleTriggerKeyDown))}unbindTrigger(){this.triggerWrap&&this.onTriggerActivate&&this.triggerWrap.removeEventListener("click",this.onTriggerActivate),this.triggerWrap&&this.triggerWrap.removeEventListener("keydown",this.handleTriggerKeyDown),this.onTriggerActivate=null}toggleOpen(){this.disabled||(this.open=!this.open,this.open&&requestAnimationFrame(()=>this.focusItem(0)),this.render())}triggerSignature(){return[this.resolvedSize(),this.getAttribute("trigger-variant")||"tertiary",this.hasAttribute("icon-only")?"1":"0",this.getAttribute("trigger-icon")||"",this.fullWidth?"1":"0",this.showChevron?"1":"0"].join("|")}renderDefaultTrigger(){const e=this.resolvedSize(),i=this.getAttribute("trigger-variant")||"tertiary",r=n.includes(i)?i:"tertiary",s=this.hasAttribute("icon-only"),o=this.getAttribute("trigger-icon"),a=document.createElement("db-button");if(a.setAttribute("type","button"),a.setAttribute("variant",r),a.setAttribute("size",e),a.className="designbase-wc-dropdown__trigger",a.setAttribute("aria-haspopup","menu"),a.setAttribute("aria-label",this.triggerLabel()),this.fullWidth&&a.setAttribute("full-width",""),s)a.setAttribute("icon-only",""),a.setAttribute("start-icon",o&&t(o)?o:"edit"),a.removeAttribute("end-icon");else{a.removeAttribute("icon-only"),o&&t(o)?a.setAttribute("start-icon",o):a.removeAttribute("start-icon");const e=document.createElement("span");e.className="designbase-wc-dropdown__trigger-label",e.textContent=this.triggerLabel(),a.append(e),this.showChevron&&a.setAttribute("end-icon","chevron-down")}return a}syncDefaultTriggerState(e){e.setAttribute("aria-expanded",String(this.open)),e.setAttribute("aria-label",this.triggerLabel()),e.classList.toggle("designbase-wc-dropdown__trigger--open",this.open),this.disabled?e.setAttribute("disabled",""):e.removeAttribute("disabled");const t=e.querySelector(".designbase-wc-dropdown__trigger-label");t&&(t.textContent=this.triggerLabel())}ensureStructure(){this.triggerWrap||(this.triggerWrap=document.createElement("div"),this.triggerWrap.className="designbase-wc-dropdown__trigger-wrap",this.triggerWrap.setAttribute("data-wc-internal","")),this.menu||(this.menu=document.createElement("div"),this.menu.className="designbase-wc-dropdown__menu",this.menu.setAttribute("data-wc-internal",""),this.menu.setAttribute("role","menu"));const e=this.triggerWrap,t=this.menu;e&&t&&(this.contains(e)||this.append(e),e.contains(t)||e.append(t),Array.from(this.children).forEach(i=>{i===e||i.hasAttribute("data-wc-internal")||("content"===i.getAttribute("slot")?t.append(i):e.insertBefore(i,t))}))}renderTrigger(){const e=this.triggerWrap,t=this.menu;if(!e||!t)return;const i=this.collectTriggerChildren();if(i.length>0){this.defaultTrigger?.remove(),this.defaultTrigger=void 0;Array.from(e.children).filter(e=>e!==t&&e!==this.defaultTrigger).forEach(e=>e.remove()),i.forEach(i=>{i.setAttribute("aria-haspopup","menu"),i.setAttribute("aria-expanded",String(this.open)),i.classList.toggle("designbase-wc-dropdown__trigger--open",this.open),e.insertBefore(i,t)})}else{Array.from(e.children).filter(e=>e!==t&&e!==this.defaultTrigger).forEach(e=>e.remove()),this.defaultTrigger&&this.triggerSignature()===this.lastTriggerSignature||(this.defaultTrigger?.remove(),this.defaultTrigger=this.renderDefaultTrigger(),this.lastTriggerSignature=this.triggerSignature(),e.insertBefore(this.defaultTrigger,t)),this.defaultTrigger&&this.syncDefaultTriggerState(this.defaultTrigger)}this.bindTrigger()}renderMenu(){const e=this.resolvedPlacement();this.menu.className=`designbase-wc-dropdown__menu designbase-wc-dropdown__menu--${e}${this.open?" designbase-wc-dropdown__menu--open":""}`,this.menu.setAttribute("aria-hidden",String(!this.open)),this.menu.setAttribute("aria-label",this.triggerLabel());const t=this.menu.querySelector(':scope > [slot="content"]');if(this.menu.setAttribute("role",t?"dialog":"menu"),t)return this.menu.inert=!this.open,this.menu.setAttribute("aria-modal","false"),this.menu.classList.add("designbase-wc-dropdown__menu--custom"),void this.triggerWrap?.querySelector("[aria-haspopup]")?.setAttribute("aria-haspopup","dialog");this.menu.inert=!1,this.menu.removeAttribute("aria-modal"),this.menu.replaceChildren();const r=this.menuItemIconSize();this.parsedItems.forEach((e,t)=>{if(e.divider){const e=document.createElement("div");return e.className="designbase-wc-dropdown__divider",e.setAttribute("role","separator"),void this.menu?.append(e)}e.id||e.label||String(t);const s=e.label||e.id,n=Boolean(e.disabled||this.disabled),o=this.focusedIndex===t,a=document.createElement("button");if(a.type="button",a.className=["designbase-wc-dropdown__item",n&&"designbase-wc-dropdown__item--disabled",o&&"designbase-wc-dropdown__item--focused"].filter(Boolean).join(" "),a.setAttribute("role","menuitem"),a.disabled=n,a.tabIndex=o?0:-1,a.dataset.index=String(t),e.icon){const t=i(e.icon,r);t.classList.add("designbase-wc-dropdown__item-icon"),a.append(t)}const d=document.createElement("span");d.className="designbase-wc-dropdown__item-label",d.textContent=s,a.append(d),a.addEventListener("click",t=>{t.stopPropagation(),this.selectItem(e)}),this.menu?.append(a)})}render(){const t=this.resolvedSize();e(this,["designbase-wc-dropdown",`designbase-wc-dropdown--${t}`,this.open&&"designbase-wc-dropdown--open",this.fullWidth&&"designbase-wc-dropdown--full-width",this.disabled&&"designbase-wc-dropdown--disabled"]),this.ensureStructure(),this.renderTrigger(),this.renderMenu()}selectItem(e){e.disabled||e.divider||(this.open=!1,this.focusedIndex=-1,this.dispatchEvent(new CustomEvent("db-change",{detail:{value:e.label||e.id,id:e.id,item:e},bubbles:!0,composed:!0})),this.render(),this.triggerWrap?.querySelector("[aria-haspopup]")?.focus())}focusItem(e){if(this.menu?.querySelector(':scope > [slot="content"]'))return void this.menu.querySelector('input:not([disabled]), button:not([disabled]), [tabindex="0"]')?.focus();const t=this.enabledItems();if(!t.length)return;const i=t[Math.max(0,Math.min(e,t.length-1))],r=this.parsedItems.indexOf(i);this.focusedIndex=r;Array.from(this.menu?.querySelectorAll(".designbase-wc-dropdown__item")||[]).forEach(e=>{const t=Number(e.dataset.index)===r;e.classList.toggle("designbase-wc-dropdown__item--focused",t),e.tabIndex=t?0:-1,t&&e.focus()})}}customElements.get("db-dropdown")||customElements.define("db-dropdown",DbDropdown);export{DbDropdown};
|
|
1
|
+
import{subscribeDbLocale as e,dbText as t}from"../core/i18n.js";import{setHostClasses as i}from"../core/host-class.js";import{isDbIconName as r,createDbIcon as s}from"./db-icons.js";import{DROPDOWN_SIZES as n,DROPDOWN_PLACEMENTS as o,DROPDOWN_TRIGGER_VARIANTS as a}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbDropdown extends HTMLElement{constructor(){super(...arguments),this.focusedIndex=-1,this.onTriggerActivate=null,this.lastTriggerSignature="",this.handleTriggerKeyDown=e=>{if(!this.menu?.contains(e.target))return"Enter"!==e.key&&" "!==e.key&&"ArrowDown"!==e.key||this.open?void("Escape"===e.key&&this.open&&(e.preventDefault(),this.open=!1,this.render())):(e.preventDefault(),this.open=!0,requestAnimationFrame(()=>this.focusItem(0)),void this.render())},this.handleDocumentKeyDown=e=>{if(!this.open)return;if("Escape"===e.key)return e.preventDefault(),this.open=!1,this.render(),void this.triggerWrap?.querySelector("[aria-haspopup]")?.focus();if(this.menu?.querySelector(':scope > [slot="content"]'))return;const t=this.enabledItems();if(!t.length)return;const i=t.findIndex(e=>this.parsedItems.indexOf(e)===this.focusedIndex);switch(e.key){case"ArrowDown":e.preventDefault(),this.focusItem(i<0?0:this.parsedItems.indexOf(t[(i+1)%t.length]));break;case"ArrowUp":e.preventDefault(),this.focusItem(i<0?0:this.parsedItems.indexOf(t[(i-1+t.length)%t.length]));break;case"Home":e.preventDefault(),this.focusItem(this.parsedItems.indexOf(t[0]));break;case"End":e.preventDefault(),this.focusItem(this.parsedItems.indexOf(t[t.length-1]));break;case"Enter":case" ":{e.preventDefault();const t=this.parsedItems[this.focusedIndex];!t||t.divider||t.disabled||this.selectItem(t);break}}},this.handleDocumentMouseDown=e=>{this.open&&(this.contains(e.target)||(this.open=!1,this.render()))}}static get observedAttributes(){return["options","items","placeholder","label","value","size","placement","full-width","disabled","open","trigger-variant","trigger-icon","icon-only","show-chevron"]}get showChevron(){return"false"!==this.getAttribute("show-chevron")}set showChevron(e){this.setAttribute("show-chevron",String(e))}get parsedItems(){const e=this.getAttribute("items");if(e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return(this.getAttribute("options")||"").split(",").map(e=>e.trim()).filter(Boolean).map((e,t)=>({id:`option-${t}`,label:e}))}get options(){return this.parsedItems.map(e=>e.label||e.id)}set options(e){this.setAttribute("options",Array.isArray(e)?e.join(","):e)}get items(){return this.parsedItems}set items(e){this.setAttribute("items","string"==typeof e?e:JSON.stringify(e))}get value(){return this.getAttribute("value")||""}set value(e){e?this.setAttribute("value",e):this.removeAttribute("value")}get open(){return this.hasAttribute("open")}set open(e){const t=this.open;this.toggleAttribute("open",e),t!==e&&this.dispatchEvent(new CustomEvent("db-open",{detail:{open:e},bubbles:!0,composed:!0}))}get disabled(){return this.hasAttribute("disabled")}set disabled(e){this.toggleAttribute("disabled",e)}get size(){return this.getAttribute("size")||"m"}set size(e){this.setAttribute("size",e)}get placement(){return this.getAttribute("placement")||"bottom-left"}set placement(e){this.setAttribute("placement",e)}get placeholder(){return this.getAttribute("placeholder")||""}set placeholder(e){e?this.setAttribute("placeholder",e):this.removeAttribute("placeholder")}get label(){return this.getAttribute("label")||""}set label(e){e?this.setAttribute("label",e):this.removeAttribute("label")}get fullWidth(){return this.hasAttribute("full-width")}set fullWidth(e){this.toggleAttribute("full-width",e)}connectedCallback(){requestAnimationFrame(()=>this.render()),this.unsubscribeLocale?.(),this.unsubscribeLocale=e(()=>{this.defaultTrigger&&this.syncDefaultTriggerState(this.defaultTrigger),this.menu?.setAttribute("aria-label",this.triggerLabel())}),document.addEventListener("mousedown",this.handleDocumentMouseDown),document.addEventListener("keydown",this.handleDocumentKeyDown)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,document.removeEventListener("mousedown",this.handleDocumentMouseDown),document.removeEventListener("keydown",this.handleDocumentKeyDown),this.unbindTrigger()}attributeChangedCallback(e){this.isConnected&&("open"!==e||this.open||(this.focusedIndex=-1),this.render())}resolvedSize(){return n.includes(this.size)?this.size:"m"}resolvedPlacement(){return o.includes(this.placement)?this.placement:"bottom-left"}menuItemIconSize(){const e=this.resolvedSize();return"s"===e?14:"l"===e?18:16}triggerLabel(){return this.label?this.label:this.placeholder?this.placeholder:this.value?this.value:t("메뉴")}enabledItems(){return this.parsedItems.filter(e=>!e.disabled&&!e.divider)}collectTriggerChildren(){const isInternalNode=e=>"content"===e.getAttribute("slot")||e.hasAttribute("data-wc-internal")||e===this.triggerWrap||e===this.menu||e===this.defaultTrigger,e=Array.from(this.children).filter(e=>!isInternalNode(e));return e.length>0?e:Array.from(this.triggerWrap?.children||[]).filter(e=>!isInternalNode(e))}hasCustomTrigger(){return this.collectTriggerChildren().length>0}bindTrigger(){this.triggerWrap&&(this.unbindTrigger(),this.onTriggerActivate=e=>{this.disabled||this.menu?.contains(e.target)||(e.preventDefault(),e.stopPropagation(),this.toggleOpen())},this.triggerWrap.addEventListener("click",this.onTriggerActivate),this.triggerWrap.addEventListener("keydown",this.handleTriggerKeyDown))}unbindTrigger(){this.triggerWrap&&this.onTriggerActivate&&this.triggerWrap.removeEventListener("click",this.onTriggerActivate),this.triggerWrap&&this.triggerWrap.removeEventListener("keydown",this.handleTriggerKeyDown),this.onTriggerActivate=null}toggleOpen(){this.disabled||(this.open=!this.open,this.open&&requestAnimationFrame(()=>this.focusItem(0)),this.render())}triggerSignature(){return[this.resolvedSize(),this.getAttribute("trigger-variant")||"tertiary",this.hasAttribute("icon-only")?"1":"0",this.getAttribute("trigger-icon")||"",this.fullWidth?"1":"0",this.showChevron?"1":"0"].join("|")}renderDefaultTrigger(){const e=this.resolvedSize(),t=this.getAttribute("trigger-variant")||"tertiary",i=a.includes(t)?t:"tertiary",s=this.hasAttribute("icon-only"),n=this.getAttribute("trigger-icon"),o=document.createElement("db-button");if(o.setAttribute("type","button"),o.setAttribute("variant",i),o.setAttribute("size",e),o.className="designbase-wc-dropdown__trigger",o.setAttribute("aria-haspopup","menu"),o.setAttribute("aria-label",this.triggerLabel()),this.fullWidth&&o.setAttribute("full-width",""),s)o.setAttribute("icon-only",""),o.setAttribute("start-icon",n&&r(n)?n:"edit"),o.removeAttribute("end-icon");else{o.removeAttribute("icon-only"),n&&r(n)?o.setAttribute("start-icon",n):o.removeAttribute("start-icon");const e=document.createElement("span");e.className="designbase-wc-dropdown__trigger-label",e.textContent=this.triggerLabel(),o.append(e),this.showChevron&&o.setAttribute("end-icon","chevron-down")}return o}syncDefaultTriggerState(e){e.setAttribute("aria-expanded",String(this.open)),e.setAttribute("aria-label",this.triggerLabel()),e.classList.toggle("designbase-wc-dropdown__trigger--open",this.open),this.disabled?e.setAttribute("disabled",""):e.removeAttribute("disabled");const t=e.querySelector(".designbase-wc-dropdown__trigger-label");t&&(t.textContent=this.triggerLabel())}ensureStructure(){this.triggerWrap||(this.triggerWrap=document.createElement("div"),this.triggerWrap.className="designbase-wc-dropdown__trigger-wrap",this.triggerWrap.setAttribute("data-wc-internal","")),this.menu||(this.menu=document.createElement("div"),this.menu.className="designbase-wc-dropdown__menu",this.menu.setAttribute("data-wc-internal",""),this.menu.setAttribute("role","menu"));const e=this.triggerWrap,t=this.menu;e&&t&&(this.contains(e)||this.append(e),e.contains(t)||e.append(t),Array.from(this.children).forEach(i=>{i===e||i.hasAttribute("data-wc-internal")||("content"===i.getAttribute("slot")?t.append(i):e.insertBefore(i,t))}))}renderTrigger(){const e=this.triggerWrap,t=this.menu;if(!e||!t)return;const i=this.collectTriggerChildren();if(i.length>0){this.defaultTrigger?.remove(),this.defaultTrigger=void 0;Array.from(e.children).filter(e=>e!==t&&e!==this.defaultTrigger).forEach(e=>e.remove()),i.forEach(i=>{i.setAttribute("aria-haspopup","menu"),i.setAttribute("aria-expanded",String(this.open)),i.classList.toggle("designbase-wc-dropdown__trigger--open",this.open),e.insertBefore(i,t)})}else{Array.from(e.children).filter(e=>e!==t&&e!==this.defaultTrigger).forEach(e=>e.remove()),this.defaultTrigger&&this.triggerSignature()===this.lastTriggerSignature||(this.defaultTrigger?.remove(),this.defaultTrigger=this.renderDefaultTrigger(),this.lastTriggerSignature=this.triggerSignature(),e.insertBefore(this.defaultTrigger,t)),this.defaultTrigger&&this.syncDefaultTriggerState(this.defaultTrigger)}this.bindTrigger()}renderMenu(){const e=this.resolvedPlacement();this.menu.className=`designbase-wc-dropdown__menu designbase-wc-dropdown__menu--${e}${this.open?" designbase-wc-dropdown__menu--open":""}`,this.menu.setAttribute("aria-hidden",String(!this.open)),this.menu.setAttribute("aria-label",this.triggerLabel());const t=this.menu.querySelector(':scope > [slot="content"]');if(this.menu.setAttribute("role",t?"dialog":"menu"),t)return this.menu.inert=!this.open,this.menu.setAttribute("aria-modal","false"),this.menu.classList.add("designbase-wc-dropdown__menu--custom"),void this.triggerWrap?.querySelector("[aria-haspopup]")?.setAttribute("aria-haspopup","dialog");this.menu.inert=!1,this.menu.removeAttribute("aria-modal"),this.menu.replaceChildren();const i=this.menuItemIconSize();this.parsedItems.forEach((e,t)=>{if(e.divider){const e=document.createElement("div");return e.className="designbase-wc-dropdown__divider",e.setAttribute("role","separator"),void this.menu?.append(e)}e.id||e.label||String(t);const r=e.label||e.id,n=Boolean(e.disabled||this.disabled),o=this.focusedIndex===t,a=document.createElement("button");if(a.type="button",a.className=["designbase-wc-dropdown__item",n&&"designbase-wc-dropdown__item--disabled",o&&"designbase-wc-dropdown__item--focused"].filter(Boolean).join(" "),a.setAttribute("role","menuitem"),a.disabled=n,a.tabIndex=o?0:-1,a.dataset.index=String(t),e.icon){const t=s(e.icon,i);t.classList.add("designbase-wc-dropdown__item-icon"),a.append(t)}const d=document.createElement("span");d.className="designbase-wc-dropdown__item-label",d.textContent=r,a.append(d),a.addEventListener("click",t=>{t.stopPropagation(),this.selectItem(e)}),this.menu?.append(a)})}render(){const e=this.resolvedSize();i(this,["designbase-wc-dropdown",`designbase-wc-dropdown--${e}`,this.open&&"designbase-wc-dropdown--open",this.fullWidth&&"designbase-wc-dropdown--full-width",this.disabled&&"designbase-wc-dropdown--disabled"]),this.ensureStructure(),this.renderTrigger(),this.renderMenu()}selectItem(e){e.disabled||e.divider||(this.open=!1,this.focusedIndex=-1,this.dispatchEvent(new CustomEvent("db-change",{detail:{value:e.label||e.id,id:e.id,item:e},bubbles:!0,composed:!0})),this.render(),this.triggerWrap?.querySelector("[aria-haspopup]")?.focus())}focusItem(e){if(this.menu?.querySelector(':scope > [slot="content"]'))return void this.menu.querySelector('input:not([disabled]), button:not([disabled]), [tabindex="0"]')?.focus();const t=this.enabledItems();if(!t.length)return;const i=t[Math.max(0,Math.min(e,t.length-1))],r=this.parsedItems.indexOf(i);this.focusedIndex=r;Array.from(this.menu?.querySelectorAll(".designbase-wc-dropdown__item")||[]).forEach(e=>{const t=Number(e.dataset.index)===r;e.classList.toggle("designbase-wc-dropdown__item--focused",t),e.tabIndex=t?0:-1,t&&e.focus()})}}customElements.get("db-dropdown")||customElements.define("db-dropdown",DbDropdown);export{DbDropdown};
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
declare class DbDropzone extends HTMLElement {
|
|
2
2
|
static get observedAttributes(): string[];
|
|
3
|
+
private unsubscribeLocale?;
|
|
3
4
|
private fileInput?;
|
|
4
5
|
private internalDragOver;
|
|
5
6
|
connectedCallback(): void;
|
|
6
7
|
disconnectedCallback(): void;
|
|
7
8
|
attributeChangedCallback(): void;
|
|
9
|
+
private syncLocale;
|
|
8
10
|
private ensureInput;
|
|
9
11
|
private isDisabled;
|
|
10
12
|
private isDragOver;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{subscribeDbLocale as e,t}from"../core/i18n.js";import{createDbIcon as i}from"./db-icons.js";import{DROPZONE_SIZES as s,DROPZONE_VARIANTS as n}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbDropzone extends HTMLElement{constructor(){super(...arguments),this.internalDragOver=!1,this.handleFileInputChange=()=>{this.emitFiles(this.fileInput?.files??null),this.fileInput&&(this.fileInput.value="")},this.handleDragOver=e=>{e.preventDefault(),e.stopPropagation(),this.isDisabled()||(this.internalDragOver=!0,this.syncClasses(),this.dispatchEvent(new CustomEvent("db-drag-over",{bubbles:!0,composed:!0,detail:{event:e}})))},this.handleDragLeave=e=>{e.preventDefault(),e.stopPropagation(),this.isDisabled()||(this.internalDragOver=!1,this.syncClasses(),this.dispatchEvent(new CustomEvent("db-drag-leave",{bubbles:!0,composed:!0,detail:{event:e}})))},this.handleDrop=e=>{e.preventDefault(),e.stopPropagation(),this.isDisabled()||(this.internalDragOver=!1,this.syncClasses(),this.emitFiles(e.dataTransfer?.files??null),this.dispatchEvent(new CustomEvent("db-drop",{bubbles:!0,composed:!0,detail:{event:e}})))},this.handleClick=e=>{this.isDisabled()||e.target.closest(".designbase-wc-dropzone__button")||(this.fileInput?.click(),this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0,detail:{event:e}})))}}static get observedAttributes(){return["locale","size","variant","show-icon","icon","image","title","description","button-text","show-button","accept","max-size","multiple","drag-over","disabled","readonly"]}connectedCallback(){this.ensureInput(),this.sync(),this.unsubscribeLocale?.(),this.unsubscribeLocale=e(()=>this.syncLocale()),this.addEventListener("dragover",this.handleDragOver),this.addEventListener("dragleave",this.handleDragLeave),this.addEventListener("drop",this.handleDrop),this.addEventListener("click",this.handleClick)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.removeEventListener("dragover",this.handleDragOver),this.removeEventListener("dragleave",this.handleDragLeave),this.removeEventListener("drop",this.handleDrop),this.removeEventListener("click",this.handleClick)}attributeChangedCallback(){this.isConnected&&this.sync()}syncLocale(){const e=this.querySelector(":scope > .designbase-wc-dropzone__content[data-wc-internal]");if(!e)return;const i=e.querySelector(".designbase-wc-dropzone__title"),s=e.querySelector(".designbase-wc-dropzone__description"),n=e.querySelector(".designbase-wc-dropzone__button"),a=e.querySelector("img");i&&!this.getAttribute("title")&&(i.textContent=t("upload.title")),s&&!this.getAttribute("description")&&(s.textContent=this.getDescriptionText()),n&&!this.getAttribute("button-text")&&(n.textContent=t("upload.choose")),a&&(a.alt=t("upload.illustration"))}ensureInput(){this.fileInput||(this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.style.display="none",this.fileInput.setAttribute("data-wc-internal",""),this.fileInput.addEventListener("change",this.handleFileInputChange),this.append(this.fileInput))}isDisabled(){return this.hasAttribute("disabled")||this.hasAttribute("readonly")}isDragOver(){return this.hasAttribute("drag-over")?"false"!==this.getAttribute("drag-over"):this.internalDragOver}validateFile(e){const t=this.getAttribute("accept");if(t){const i=t.split(",").map(e=>e.trim()),s=e.type,n=`.${e.name.split(".").pop()?.toLowerCase()}`;if(!i.some(e=>e.startsWith(".")?n===e.toLowerCase():s===e||s.startsWith(e.replace("*",""))))return!1}const i=Number(this.getAttribute("max-size")||0);return!(i>0&&e.size>i)}emitFiles(e){if(!e||0===e.length)return;const t=Array.from(e).filter(e=>this.validateFile(e));t.length&&this.dispatchEvent(new CustomEvent("db-file-select",{bubbles:!0,composed:!0,detail:{files:t}}))}getDescriptionText(){const e=this.getAttribute("description");if(e)return e;const i=(this.getAttribute("accept")||"").split(",").filter(Boolean).map(e=>{const t=e.trim();return t.startsWith(".")?t.toUpperCase():t.includes("*")?t.replace("*","").toUpperCase():t});let s=i.length?i.join(", "):t("upload.allFormats");const n=Number(this.getAttribute("max-size")||0);if(n>0){const e=1024,i=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(n)/Math.log(e)),r=`${parseFloat((n/e**a).toFixed(2))} ${i[a]}`;s+=t("upload.maximum").replace("{size}",r)}return s}collectChildren(){return Array.from(this.children).filter(e=>e!==this.fileInput&&!e.hasAttribute("data-wc-internal"))}syncClasses(){const e=this.getAttribute("size")||"m",t=this.getAttribute("variant")||"default",i=s.includes(e)?e:"m",a=n.includes(t)?t:"default";this.className=["designbase-wc-dropzone",`designbase-wc-dropzone--size-${i}`,`designbase-wc-dropzone--variant-${a}`,this.isDragOver()&&"designbase-wc-dropzone--drag-over",this.hasAttribute("disabled")&&"designbase-wc-dropzone--disabled",this.hasAttribute("readonly")&&"designbase-wc-dropzone--readonly"].filter(Boolean).join(" ")}sync(){this.ensureInput(),this.syncClasses();const e=this.getAttribute("accept"),n=this.hasAttribute("multiple");this.fileInput&&(e?this.fileInput.setAttribute("accept",e):this.fileInput.removeAttribute("accept"),this.fileInput.toggleAttribute("multiple",n),this.fileInput.disabled=this.isDisabled());const a=this.collectChildren(),r=this.querySelector(":scope > .designbase-wc-dropzone__content[data-wc-internal]");if(a.length)return void r?.remove();let o=r;o||(o=document.createElement("div"),o.className="designbase-wc-dropzone__content",o.setAttribute("data-wc-internal",""),this.append(o)),o.replaceChildren();const l=this.getAttribute("size")||"m",d=s.includes(l)?l:"m",c=this.getAttribute("image"),h="false"!==this.getAttribute("show-icon"),u=this.getAttribute("icon")||"gallery",p=this.getAttribute("title")||t("upload.title"),b=this.getDescriptionText(),g=this.hasAttribute("show-button"),m=this.getAttribute("button-text")||t("upload.choose");if(c){const e=document.createElement("div");e.className="designbase-wc-dropzone__image";const i=document.createElement("img");i.src=c,i.alt=t("upload.illustration"),e.append(i),o.append(e)}else if(h){const e=document.createElement("div");e.className="designbase-wc-dropzone__icon";const t="s"===d?32:"l"===d?56:48;e.append(i(u,t)),o.append(e)}if(p){const e=document.createElement("div");e.className="designbase-wc-dropzone__title",e.textContent=p,o.append(e)}if(b){const e=document.createElement("div");e.className="designbase-wc-dropzone__description",e.textContent=b,o.append(e)}if(g){const e=document.createElement("button");e.type="button",e.className="designbase-wc-dropzone__button",e.textContent=m,e.disabled=this.isDisabled(),e.addEventListener("click",e=>{e.stopPropagation(),this.isDisabled()||this.fileInput?.click()}),o.append(e)}}}customElements.get("db-dropzone")||customElements.define("db-dropzone",DbDropzone);export{DbDropzone};
|
|
@@ -8,6 +8,7 @@ type Step = 'email' | 'code' | 'sent' | 'verified';
|
|
|
8
8
|
declare class DbEmailVerify extends HTMLElement {
|
|
9
9
|
static get observedAttributes(): string[];
|
|
10
10
|
private built;
|
|
11
|
+
private unsubscribeLocale?;
|
|
11
12
|
private timerId;
|
|
12
13
|
/** 인증번호 유효 시간(초) — code 모드에서만 쓴다 */
|
|
13
14
|
private remaining;
|