@designbasekorea/ui-wc 0.10.0 → 0.11.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 +12 -0
- package/LICENSE-WORLD-MAP.md +10 -0
- package/README.md +58 -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-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 +31 -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 +6 -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 +442 -6
- package/dist/index.esm.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +837 -71
- package/dist/react/index.esm.js +1 -1
- package/package.json +4 -3
|
@@ -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;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dbFormat as t,dbText as e}from"../core/i18n.js";import{createDbIcon as i}from"./db-icons.js";import"./db-button.js";import"./db-input.js";import"./db-otp-input.js";import{coerceToContract as s}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{EMAIL_VERIFY_SIZES as n}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";function el(t,e){const i=document.createElement(t);return e&&(i.className=e),i}function textButton(t,e){const i=el("button",t);return i.type="button",i.addEventListener("click",()=>{i.disabled||e()}),i}class DbEmailVerify extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.timerId=null,this.remaining=0,this.cooldownLeft=0,this.expired=!1}static get observedAttributes(){return["mode","email","code","step","size","disabled","error","error-message","countdown","resend-cooldown","eyebrow","title","description","send-label","resend-label","verify-label","confirm-label","done-label","code-length","closable","manual","sending","verifying","auto-submit"]}get mode(){return"confirm"===this.getAttribute("mode")?"confirm":"code"}set mode(t){this.setAttribute("mode",t)}get size(){return s(this.getAttribute("size"),n,"m")}set size(t){this.setAttribute("size",t)}get step(){const t=this.getAttribute("step");return"code"===t||"sent"===t||"verified"===t?t:"email"}set step(t){this.setAttribute("step",t)}get email(){return this.getAttribute("email")||""}set email(t){this.setAttribute("email",t)}get countdown(){const t=Number(this.getAttribute("countdown")||180);return Number.isFinite(t)&&t>0?t:180}set countdown(t){this.setAttribute("countdown",String(t))}get resendCooldown(){const t=this.getAttribute("resend-cooldown"),e=Number(t??30);return Number.isFinite(e)&&e>=0?e:30}set resendCooldown(t){this.setAttribute("resend-cooldown",String(t))}connectedCallback(){this.build(),this.sync(),this.startTimersForStep()}disconnectedCallback(){this.clearTimer()}attributeChangedCallback(t,e,i){this.built&&("step"!==t&&"mode"!==t||e===i||this.startTimersForStep(),this.sync())}startCodeStep(){"code"!==this.mode&&(this.mode="code"),"code"===this.step?this.startTimers():this.step="code",requestAnimationFrame(()=>this.otpInput?.focus?.())}restartCountdown(){"code"!==this.step&&"sent"!==this.step||this.startTimers()}markSent(){this.step="sent"}markVerified(){this.step="verified"}editEmail(){this.removeAttribute("code"),this.step="email",requestAnimationFrame(()=>this.emailInput?.focus?.())}startTimersForStep(){const t=this.step;"code"===this.mode&&"code"===t||"confirm"===this.mode&&"sent"===t?this.startTimers():this.clearTimer()}clearTimer(){this.timerId&&clearInterval(this.timerId),this.timerId=null,this.remaining=0,this.cooldownLeft=0,this.expired=!1}startTimers(){this.clearTimer();const t="code"===this.mode;this.remaining=t?this.countdown:0,this.cooldownLeft=t?Math.min(this.resendCooldown,this.countdown):this.resendCooldown,this.renderTimer(),this.remaining<=0&&this.cooldownLeft<=0||(this.timerId=setInterval(()=>{this.cooldownLeft>0&&(this.cooldownLeft-=1),this.remaining>0&&(this.remaining-=1,this.remaining<=0&&(this.expired=!0,this.cooldownLeft=0,this.dispatchEvent(new CustomEvent("db-countdown-complete",{bubbles:!0,composed:!0})))),this.renderTimer(),this.remaining<=0&&this.cooldownLeft<=0&&this.timerId&&(clearInterval(this.timerId),this.timerId=null)},1e3))}renderTimer(){if(!this.built)return;const i=Math.max(0,Math.floor(this.remaining/60)),s=Math.max(0,this.remaining%60);this.timerEl.textContent=`${String(i).padStart(2,"0")}:${String(s).padStart(2,"0")}`,this.timerEl.setAttribute("aria-label",t("남은 시간 {0}분 {1}초",[i,s])),this.timerEl.classList.toggle("designbase-wc-email-verify__timer--expired",this.expired),this.expiredEl.hidden=!this.expired;const n=this.hasAttribute("disabled"),r=this.cooldownLeft>0,o=this.getAttribute("resend-label")||e("재전송"),l=r?t("재전송 ({0}초)",[this.cooldownLeft]):o;for(const t of[this.codeResendBtn,this.sentResendBtn])t.textContent=l,t.disabled=r||n;this.syncVerifyDisabled()}syncVerifyDisabled(){const t=Number(this.getAttribute("code-length")||6);this.verifyBtn.toggleAttribute("disabled",this.hasAttribute("disabled")||"code"!==this.step||this.expired||(this.getAttribute("code")||"").length!==t)}emit(t,e={}){this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}handleResend(){this.emit("db-resend",{email:this.email,mode:this.mode}),this.hasAttribute("manual")||(this.removeAttribute("code"),this.startTimers())}handleChangeEmail(){this.emit("db-change-email",{email:this.email}),this.hasAttribute("manual")||this.editEmail()}build(){if(this.built)return;this.built=!0;const t="designbase-wc-email-verify";this.replaceChildren();const s=el("div",`${t}__shell`);this.closeBtn=el("button",`${t}__close`),this.closeBtn.type="button",this.closeBtn.setAttribute("aria-label",e("닫기")),this.closeBtn.append(i("close",18)),this.closeBtn.addEventListener("click",()=>this.emit("db-close")),this.headerEl=el("div",`${t}__header`),this.eyebrowEl=el("span",`${t}__eyebrow`),this.titleEl=el("h3",`${t}__title`),this.descEl=el("p",`${t}__description`),this.headerEl.append(this.eyebrowEl,this.titleEl,this.descEl),this.emailRow=el("div",`${t}__email-row`),this.emailInput=document.createElement("db-input"),this.emailInput.setAttribute("type","email"),this.emailInput.setAttribute("placeholder","name@example.com"),this.emailInput.setAttribute("autocomplete","email"),this.emailInput.setAttribute("full-width",""),this.emailInput.setAttribute("start-icon","mail"),this.emailInput.addEventListener("db-input",t=>{t.stopPropagation();const e=String(t.detail?.value??this.emailInput.value??"");this.setAttribute("email",e),this.emit("db-email-change",{email:e})}),this.emailInput.addEventListener("keydown",t=>{"Enter"===t.key&&this.requestSend()}),this.sendBtn=document.createElement("db-button"),this.sendBtn.setAttribute("variant","primary"),this.sendBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.requestSend()}),this.emailRow.append(this.emailInput,this.sendBtn),this.codeBlock=el("div",`${t}__code`);const n=el("div",`${t}__code-head`),r=el("span",`${t}__code-label`);r.dataset.role="code-label",this.timerEl=el("span",`${t}__timer`),this.timerEl.setAttribute("role","timer"),n.append(r,this.timerEl),this.otpInput=document.createElement("db-otp-input"),this.otpInput.setAttribute("full-width",""),this.otpInput.addEventListener("db-change",t=>{t.stopPropagation();const e=String(t.detail?.value||"");this.setAttribute("code",e),this.emit("db-code-change",{code:e})}),this.otpInput.addEventListener("db-complete",t=>{t.stopPropagation();const e=String(t.detail?.value||"");this.emit("db-code-complete",{code:e,email:this.email}),this.hasAttribute("auto-submit")&&this.requestVerify()}),this.expiredEl=el("p",`${t}__expired`),this.expiredEl.setAttribute("role","alert"),this.expiredEl.hidden=!0,this.verifyBtn=document.createElement("db-button"),this.verifyBtn.setAttribute("variant","primary"),this.verifyBtn.setAttribute("full-width",""),this.verifyBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.requestVerify()}),this.codeResendBtn=textButton(`${t}__link`,()=>this.handleResend()),this.codeChangeBtn=textButton(`${t}__link ${t}__link--muted`,()=>this.handleChangeEmail());const o=this.buildFooter(this.codeResendBtn,this.codeChangeBtn);this.codeBlock.append(n,this.otpInput,this.expiredEl,this.verifyBtn,o),this.sentBlock=el("div",`${t}__result`);const l=el("div",`${t}__result-icon`);l.append(i("mail",36));const d=el("h3",`${t}__result-title`);d.dataset.role="sent-title",this.sentDescEl=el("p",`${t}__result-desc`),this.confirmBtn=document.createElement("db-button"),this.confirmBtn.setAttribute("variant","primary"),this.confirmBtn.setAttribute("full-width",""),this.confirmBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.emit("db-confirm",{email:this.email})}),this.sentResendBtn=textButton(`${t}__link`,()=>this.handleResend()),this.sentChangeBtn=textButton(`${t}__link ${t}__link--muted`,()=>this.handleChangeEmail());const h=this.buildFooter(this.sentResendBtn,this.sentChangeBtn);this.sentBlock.append(l,d,this.sentDescEl,this.confirmBtn,h),this.verifiedBlock=el("div",`${t}__result ${t}__result--success`);const a=el("div",`${t}__result-icon`);a.append(i("circle-checked",36));const c=el("h3",`${t}__result-title`);c.dataset.role="verified-title",this.verifiedDescEl=el("p",`${t}__result-desc`),this.doneBtn=document.createElement("db-button"),this.doneBtn.setAttribute("variant","primary"),this.doneBtn.setAttribute("full-width",""),this.doneBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.emit("db-done",{email:this.email})}),this.verifiedBlock.append(a,c,this.verifiedDescEl,this.doneBtn),this.errorEl=el("p",`${t}__error`),this.errorEl.setAttribute("role","alert"),this.errorEl.hidden=!0,s.append(this.closeBtn,this.headerEl,this.emailRow,this.errorEl,this.codeBlock,this.sentBlock,this.verifiedBlock),this.append(s)}buildFooter(t,e){const i="designbase-wc-email-verify",s=el("div",`${i}__footer`),n=el("span",`${i}__footer-resend`),r=el("span",`${i}__footer-hint`);return r.dataset.role="resend-hint",n.append(r,t),s.append(n,e),s}sync(){const t="designbase-wc-email-verify",i=this.size,s=this.mode,n=this.step,r=this.hasAttribute("disabled"),o=this.getAttribute("code-length")||"6",l=this.email,d=l||"your@email.com",h="confirm"===s&&"code"===n?"email":"code"===s&&"sent"===n?"code":n,a="sent"===h||"verified"===h;this.className=[t,`${t}--${i}`,`${t}--mode-${s}`,`${t}--step-${h}`,this.hasAttribute("closable")&&`${t}--closable`,r&&`${t}--disabled`,this.hasAttribute("error")&&`${t}--error`].filter(Boolean).join(" "),this.emailInput.toggleAttribute("error",this.hasAttribute("error")&&"email"===h),this.closeBtn.hidden=!this.hasAttribute("closable"),this.headerEl.hidden=a;const c=this.getAttribute("eyebrow")||"";this.eyebrowEl.textContent=c,this.eyebrowEl.hidden=!c,"code"===h?(this.titleEl.textContent=e("인증번호를 입력해 주세요"),this.setTextWithEmail(this.descEl,"{0} 주소로 {1}자리 인증번호를 보냈어요.",d,[o])):(this.titleEl.textContent=this.getAttribute("title")||e("이메일 인증"),this.descEl.textContent=this.getAttribute("description")||e("confirm"===s?"인증받을 이메일 주소를 입력해 주세요. 입력한 주소로 인증 링크를 보내 드려요.":"인증받을 이메일 주소를 입력해 주세요. 입력한 주소로 인증번호를 보내 드려요.")),this.emailRow.hidden="email"!==h,this.emailInput.setAttribute("label",e("이메일 주소")),this.emailInput.value=l,this.emailInput.setAttribute("size",i),this.emailInput.toggleAttribute("disabled",r),this.sendBtn.setAttribute("size",i),this.sendBtn.textContent=this.getAttribute("send-label")||e("confirm"===s?"인증 메일 보내기":"인증번호 받기"),this.sendBtn.toggleAttribute("disabled",r||!this.isEmailValid()),this.sendBtn.toggleAttribute("loading",this.hasAttribute("sending")),this.codeBlock.hidden="code"!==h;this.querySelector('[data-role="code-label"]').textContent=e("인증번호"),this.otpInput.setAttribute("length",o),this.otpInput.setAttribute("size",i),this.otpInput.setAttribute("value",this.getAttribute("code")||""),this.otpInput.toggleAttribute("disabled",r||"code"!==h||this.expired),this.otpInput.toggleAttribute("error",this.hasAttribute("error")&&"code"===h),this.expiredEl.textContent=e("인증 시간이 만료되었어요. 인증번호를 다시 받아 주세요."),this.verifyBtn.setAttribute("size",i),this.verifyBtn.textContent=this.getAttribute("verify-label")||e("인증하기"),this.verifyBtn.toggleAttribute("loading",this.hasAttribute("verifying")),this.sentBlock.hidden="sent"!==h,this.querySelector('[data-role="sent-title"]').textContent=e("메일함을 확인해 주세요"),this.setTextWithEmail(this.sentDescEl,"{0} 주소로 인증 링크를 보냈어요. 메일의 링크를 누르면 인증이 완료돼요.",d),this.confirmBtn.setAttribute("size",i),this.confirmBtn.textContent=this.getAttribute("confirm-label")||e("확인"),this.verifiedBlock.hidden="verified"!==h,this.querySelector('[data-role="verified-title"]').textContent=e("이메일 인증 완료"),this.setTextWithEmail(this.verifiedDescEl,"{0} 주소가 인증되었어요.",d),this.doneBtn.setAttribute("size",i),this.doneBtn.textContent=this.getAttribute("done-label")||e("확인"),this.querySelectorAll('[data-role="resend-hint"]').forEach(t=>{t.textContent=e("메일을 받지 못하셨나요?")});for(const t of[this.codeChangeBtn,this.sentChangeBtn])t.textContent=e("이메일 변경"),t.disabled=r;const m=this.getAttribute("error-message")||"";this.errorEl.textContent=m,this.errorEl.hidden=!this.hasAttribute("error")||!m||a;const u="code"===h?this.otpInput:this.emailRow;this.errorEl.previousElementSibling!==u&&u.after(this.errorEl),this.renderTimer()}isEmailValid(){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email.trim())}requestSend(){("email"===this.step||"confirm"===this.mode&&"code"===this.step)&&(this.hasAttribute("disabled")||this.hasAttribute("sending")||!this.isEmailValid()||(this.emit("db-send-code",{email:this.email,mode:this.mode}),this.hasAttribute("manual")||("confirm"===this.mode?this.markSent():this.startCodeStep())))}requestVerify(){const t=(this.getAttribute("code")||this.otpInput.value).replace(/\D/g,""),e=Number(this.getAttribute("code-length")||6);"code"!==this.step||this.expired||t.length!==e||this.hasAttribute("disabled")||this.emit("db-verify",{email:this.email,code:t})}setTextWithEmail(t,i,s,n=[]){const r=e(i).replace(/\{(\d+)\}/g,(t,e)=>"0"===e?t:String(n[Number(e)-1]??"")),[o,l=""]=r.split("{0}"),d=document.createElement("strong");d.textContent=s,t.replaceChildren(document.createTextNode(o),d,document.createTextNode(l))}}customElements.get("db-email-verify")||customElements.define("db-email-verify",DbEmailVerify);export{DbEmailVerify};
|
|
1
|
+
import{subscribeDbLocale as t,dbText as e,dbFormat as i}from"../core/i18n.js";import{createDbIcon as s}from"./db-icons.js";import"./db-button.js";import"./db-input.js";import"./db-otp-input.js";import{coerceToContract as n}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{EMAIL_VERIFY_SIZES as r}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";function el(t,e){const i=document.createElement(t);return e&&(i.className=e),i}function textButton(t,e){const i=el("button",t);return i.type="button",i.addEventListener("click",()=>{i.disabled||e()}),i}class DbEmailVerify extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.timerId=null,this.remaining=0,this.cooldownLeft=0,this.expired=!1}static get observedAttributes(){return["mode","email","code","step","size","disabled","error","error-message","countdown","resend-cooldown","eyebrow","title","description","send-label","resend-label","verify-label","confirm-label","done-label","code-length","closable","manual","sending","verifying","auto-submit"]}get mode(){return"confirm"===this.getAttribute("mode")?"confirm":"code"}set mode(t){this.setAttribute("mode",t)}get size(){return n(this.getAttribute("size"),r,"m")}set size(t){this.setAttribute("size",t)}get step(){const t=this.getAttribute("step");return"code"===t||"sent"===t||"verified"===t?t:"email"}set step(t){this.setAttribute("step",t)}get email(){return this.getAttribute("email")||""}set email(t){this.setAttribute("email",t)}get countdown(){const t=Number(this.getAttribute("countdown")||180);return Number.isFinite(t)&&t>0?t:180}set countdown(t){this.setAttribute("countdown",String(t))}get resendCooldown(){const t=this.getAttribute("resend-cooldown"),e=Number(t??30);return Number.isFinite(e)&&e>=0?e:30}set resendCooldown(t){this.setAttribute("resend-cooldown",String(t))}connectedCallback(){this.build(),this.sync(),this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>{this.closeBtn.setAttribute("aria-label",e("닫기")),this.sync()}),this.startTimersForStep()}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.clearTimer()}attributeChangedCallback(t,e,i){this.built&&("step"!==t&&"mode"!==t||e===i||this.startTimersForStep(),this.sync())}startCodeStep(){"code"!==this.mode&&(this.mode="code"),"code"===this.step?this.startTimers():this.step="code",requestAnimationFrame(()=>this.otpInput?.focus?.())}restartCountdown(){"code"!==this.step&&"sent"!==this.step||this.startTimers()}markSent(){this.step="sent"}markVerified(){this.step="verified"}editEmail(){this.removeAttribute("code"),this.step="email",requestAnimationFrame(()=>this.emailInput?.focus?.())}startTimersForStep(){const t=this.step;"code"===this.mode&&"code"===t||"confirm"===this.mode&&"sent"===t?this.startTimers():this.clearTimer()}clearTimer(){this.timerId&&clearInterval(this.timerId),this.timerId=null,this.remaining=0,this.cooldownLeft=0,this.expired=!1}startTimers(){this.clearTimer();const t="code"===this.mode;this.remaining=t?this.countdown:0,this.cooldownLeft=t?Math.min(this.resendCooldown,this.countdown):this.resendCooldown,this.renderTimer(),this.remaining<=0&&this.cooldownLeft<=0||(this.timerId=setInterval(()=>{this.cooldownLeft>0&&(this.cooldownLeft-=1),this.remaining>0&&(this.remaining-=1,this.remaining<=0&&(this.expired=!0,this.cooldownLeft=0,this.dispatchEvent(new CustomEvent("db-countdown-complete",{bubbles:!0,composed:!0})))),this.renderTimer(),this.remaining<=0&&this.cooldownLeft<=0&&this.timerId&&(clearInterval(this.timerId),this.timerId=null)},1e3))}renderTimer(){if(!this.built)return;const t=Math.max(0,Math.floor(this.remaining/60)),s=Math.max(0,this.remaining%60);this.timerEl.textContent=`${String(t).padStart(2,"0")}:${String(s).padStart(2,"0")}`,this.timerEl.setAttribute("aria-label",i("남은 시간 {0}분 {1}초",[t,s])),this.timerEl.classList.toggle("designbase-wc-email-verify__timer--expired",this.expired),this.expiredEl.hidden=!this.expired;const n=this.hasAttribute("disabled"),r=this.cooldownLeft>0,o=this.getAttribute("resend-label")||e("재전송"),l=r?i("재전송 ({0}초)",[this.cooldownLeft]):o;for(const t of[this.codeResendBtn,this.sentResendBtn])t.textContent=l,t.disabled=r||n;this.syncVerifyDisabled()}syncVerifyDisabled(){const t=Number(this.getAttribute("code-length")||6);this.verifyBtn.toggleAttribute("disabled",this.hasAttribute("disabled")||"code"!==this.step||this.expired||(this.getAttribute("code")||"").length!==t)}emit(t,e={}){this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}handleResend(){this.emit("db-resend",{email:this.email,mode:this.mode}),this.hasAttribute("manual")||(this.removeAttribute("code"),this.startTimers())}handleChangeEmail(){this.emit("db-change-email",{email:this.email}),this.hasAttribute("manual")||this.editEmail()}build(){if(this.built)return;this.built=!0;const t="designbase-wc-email-verify";this.replaceChildren();const i=el("div",`${t}__shell`);this.closeBtn=el("button",`${t}__close`),this.closeBtn.type="button",this.closeBtn.setAttribute("aria-label",e("닫기")),this.closeBtn.append(s("close",18)),this.closeBtn.addEventListener("click",()=>this.emit("db-close")),this.headerEl=el("div",`${t}__header`),this.eyebrowEl=el("span",`${t}__eyebrow`),this.titleEl=el("h3",`${t}__title`),this.descEl=el("p",`${t}__description`),this.headerEl.append(this.eyebrowEl,this.titleEl,this.descEl),this.emailRow=el("div",`${t}__email-row`),this.emailInput=document.createElement("db-input"),this.emailInput.setAttribute("type","email"),this.emailInput.setAttribute("placeholder","name@example.com"),this.emailInput.setAttribute("autocomplete","email"),this.emailInput.setAttribute("full-width",""),this.emailInput.setAttribute("start-icon","mail"),this.emailInput.addEventListener("db-input",t=>{t.stopPropagation();const e=String(t.detail?.value??this.emailInput.value??"");this.setAttribute("email",e),this.emit("db-email-change",{email:e})}),this.emailInput.addEventListener("keydown",t=>{"Enter"===t.key&&this.requestSend()}),this.sendBtn=document.createElement("db-button"),this.sendBtn.setAttribute("variant","primary"),this.sendBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.requestSend()}),this.emailRow.append(this.emailInput,this.sendBtn),this.codeBlock=el("div",`${t}__code`);const n=el("div",`${t}__code-head`),r=el("span",`${t}__code-label`);r.dataset.role="code-label",this.timerEl=el("span",`${t}__timer`),this.timerEl.setAttribute("role","timer"),n.append(r,this.timerEl),this.otpInput=document.createElement("db-otp-input"),this.otpInput.setAttribute("full-width",""),this.otpInput.addEventListener("db-change",t=>{t.stopPropagation();const e=String(t.detail?.value||"");this.setAttribute("code",e),this.emit("db-code-change",{code:e})}),this.otpInput.addEventListener("db-complete",t=>{t.stopPropagation();const e=String(t.detail?.value||"");this.emit("db-code-complete",{code:e,email:this.email}),this.hasAttribute("auto-submit")&&this.requestVerify()}),this.expiredEl=el("p",`${t}__expired`),this.expiredEl.setAttribute("role","alert"),this.expiredEl.hidden=!0,this.verifyBtn=document.createElement("db-button"),this.verifyBtn.setAttribute("variant","primary"),this.verifyBtn.setAttribute("full-width",""),this.verifyBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.requestVerify()}),this.codeResendBtn=textButton(`${t}__link`,()=>this.handleResend()),this.codeChangeBtn=textButton(`${t}__link ${t}__link--muted`,()=>this.handleChangeEmail());const o=this.buildFooter(this.codeResendBtn,this.codeChangeBtn);this.codeBlock.append(n,this.otpInput,this.expiredEl,this.verifyBtn,o),this.sentBlock=el("div",`${t}__result`);const l=el("div",`${t}__result-icon`);l.append(s("mail",36));const h=el("h3",`${t}__result-title`);h.dataset.role="sent-title",this.sentDescEl=el("p",`${t}__result-desc`),this.confirmBtn=document.createElement("db-button"),this.confirmBtn.setAttribute("variant","primary"),this.confirmBtn.setAttribute("full-width",""),this.confirmBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.emit("db-confirm",{email:this.email})}),this.sentResendBtn=textButton(`${t}__link`,()=>this.handleResend()),this.sentChangeBtn=textButton(`${t}__link ${t}__link--muted`,()=>this.handleChangeEmail());const d=this.buildFooter(this.sentResendBtn,this.sentChangeBtn);this.sentBlock.append(l,h,this.sentDescEl,this.confirmBtn,d),this.verifiedBlock=el("div",`${t}__result ${t}__result--success`);const a=el("div",`${t}__result-icon`);a.append(s("circle-checked",36));const c=el("h3",`${t}__result-title`);c.dataset.role="verified-title",this.verifiedDescEl=el("p",`${t}__result-desc`),this.doneBtn=document.createElement("db-button"),this.doneBtn.setAttribute("variant","primary"),this.doneBtn.setAttribute("full-width",""),this.doneBtn.addEventListener("db-click",t=>{t.stopPropagation(),this.emit("db-done",{email:this.email})}),this.verifiedBlock.append(a,c,this.verifiedDescEl,this.doneBtn),this.errorEl=el("p",`${t}__error`),this.errorEl.setAttribute("role","alert"),this.errorEl.hidden=!0,i.append(this.closeBtn,this.headerEl,this.emailRow,this.errorEl,this.codeBlock,this.sentBlock,this.verifiedBlock),this.append(i)}buildFooter(t,e){const i="designbase-wc-email-verify",s=el("div",`${i}__footer`),n=el("span",`${i}__footer-resend`),r=el("span",`${i}__footer-hint`);return r.dataset.role="resend-hint",n.append(r,t),s.append(n,e),s}sync(){const t="designbase-wc-email-verify",i=this.size,s=this.mode,n=this.step,r=this.hasAttribute("disabled"),o=this.getAttribute("code-length")||"6",l=this.email,h=l||"your@email.com",d="confirm"===s&&"code"===n?"email":"code"===s&&"sent"===n?"code":n,a="sent"===d||"verified"===d;this.className=[t,`${t}--${i}`,`${t}--mode-${s}`,`${t}--step-${d}`,this.hasAttribute("closable")&&`${t}--closable`,r&&`${t}--disabled`,this.hasAttribute("error")&&`${t}--error`].filter(Boolean).join(" "),this.emailInput.toggleAttribute("error",this.hasAttribute("error")&&"email"===d),this.closeBtn.hidden=!this.hasAttribute("closable"),this.headerEl.hidden=a;const c=this.getAttribute("eyebrow")||"";this.eyebrowEl.textContent=c,this.eyebrowEl.hidden=!c,"code"===d?(this.titleEl.textContent=e("인증번호를 입력해 주세요"),this.setTextWithEmail(this.descEl,"{0} 주소로 {1}자리 인증번호를 보냈어요.",h,[o])):(this.titleEl.textContent=this.getAttribute("title")||e("이메일 인증"),this.descEl.textContent=this.getAttribute("description")||e("confirm"===s?"인증받을 이메일 주소를 입력해 주세요. 입력한 주소로 인증 링크를 보내 드려요.":"인증받을 이메일 주소를 입력해 주세요. 입력한 주소로 인증번호를 보내 드려요.")),this.emailRow.hidden="email"!==d,this.emailInput.setAttribute("label",e("이메일 주소")),this.emailInput.value=l,this.emailInput.setAttribute("size",i),this.emailInput.toggleAttribute("disabled",r),this.sendBtn.setAttribute("size",i),this.sendBtn.textContent=this.getAttribute("send-label")||e("confirm"===s?"인증 메일 보내기":"인증번호 받기"),this.sendBtn.toggleAttribute("disabled",r||!this.isEmailValid()),this.sendBtn.toggleAttribute("loading",this.hasAttribute("sending")),this.codeBlock.hidden="code"!==d;this.querySelector('[data-role="code-label"]').textContent=e("인증번호"),this.otpInput.setAttribute("length",o),this.otpInput.setAttribute("size",i),this.otpInput.setAttribute("value",this.getAttribute("code")||""),this.otpInput.toggleAttribute("disabled",r||"code"!==d||this.expired),this.otpInput.toggleAttribute("error",this.hasAttribute("error")&&"code"===d),this.expiredEl.textContent=e("인증 시간이 만료되었어요. 인증번호를 다시 받아 주세요."),this.verifyBtn.setAttribute("size",i),this.verifyBtn.textContent=this.getAttribute("verify-label")||e("인증하기"),this.verifyBtn.toggleAttribute("loading",this.hasAttribute("verifying")),this.sentBlock.hidden="sent"!==d,this.querySelector('[data-role="sent-title"]').textContent=e("메일함을 확인해 주세요"),this.setTextWithEmail(this.sentDescEl,"{0} 주소로 인증 링크를 보냈어요. 메일의 링크를 누르면 인증이 완료돼요.",h),this.confirmBtn.setAttribute("size",i),this.confirmBtn.textContent=this.getAttribute("confirm-label")||e("확인"),this.verifiedBlock.hidden="verified"!==d,this.querySelector('[data-role="verified-title"]').textContent=e("이메일 인증 완료"),this.setTextWithEmail(this.verifiedDescEl,"{0} 주소가 인증되었어요.",h),this.doneBtn.setAttribute("size",i),this.doneBtn.textContent=this.getAttribute("done-label")||e("확인"),this.querySelectorAll('[data-role="resend-hint"]').forEach(t=>{t.textContent=e("메일을 받지 못하셨나요?")});for(const t of[this.codeChangeBtn,this.sentChangeBtn])t.textContent=e("이메일 변경"),t.disabled=r;const m=this.getAttribute("error-message")||"";this.errorEl.textContent=m,this.errorEl.hidden=!this.hasAttribute("error")||!m||a;const u="code"===d?this.otpInput:this.emailRow;this.errorEl.previousElementSibling!==u&&u.after(this.errorEl),this.renderTimer()}isEmailValid(){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email.trim())}requestSend(){("email"===this.step||"confirm"===this.mode&&"code"===this.step)&&(this.hasAttribute("disabled")||this.hasAttribute("sending")||!this.isEmailValid()||(this.emit("db-send-code",{email:this.email,mode:this.mode}),this.hasAttribute("manual")||("confirm"===this.mode?this.markSent():this.startCodeStep())))}requestVerify(){const t=(this.getAttribute("code")||this.otpInput.value).replace(/\D/g,""),e=Number(this.getAttribute("code-length")||6);"code"!==this.step||this.expired||t.length!==e||this.hasAttribute("disabled")||this.emit("db-verify",{email:this.email,code:t})}setTextWithEmail(t,i,s,n=[]){const r=e(i).replace(/\{(\d+)\}/g,(t,e)=>"0"===e?t:String(n[Number(e)-1]??"")),[o,l=""]=r.split("{0}"),h=document.createElement("strong");h.textContent=s,t.replaceChildren(document.createTextNode(o),h,document.createTextNode(l))}}customElements.get("db-email-verify")||customElements.define("db-email-verify",DbEmailVerify);export{DbEmailVerify};
|
|
@@ -8,12 +8,14 @@ type UploadFile = {
|
|
|
8
8
|
uploadedAt?: Date;
|
|
9
9
|
};
|
|
10
10
|
declare class DbFileUploader extends HTMLElement {
|
|
11
|
+
private unsubscribeLocale?;
|
|
11
12
|
static get observedAttributes(): string[];
|
|
12
13
|
private dropzone?;
|
|
13
14
|
private uploadedFiles;
|
|
14
15
|
private uploadIntervals;
|
|
15
16
|
connectedCallback(): void;
|
|
16
17
|
disconnectedCallback(): void;
|
|
18
|
+
private syncLocale;
|
|
17
19
|
attributeChangedCallback(): void;
|
|
18
20
|
private isDisabled;
|
|
19
21
|
private ensureDropzone;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{subscribeDbLocale as e,t}from"../core/i18n.js";import{createDbIcon as s}from"./db-icons.js";import{FILE_UPLOADER_SIZES as i,FILE_UPLOADER_VARIANTS as l}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbFileUploader extends HTMLElement{constructor(){super(...arguments),this.uploadedFiles=[],this.uploadIntervals=new Map,this.handleFileSelect=e=>{if(this.isDisabled())return;const t=e.detail,s=t?.files??[];if(!s.length)return;const i=s.map(e=>({file:e,id:`${Date.now()}-${Math.random()}`,status:"pending",progress:0}));this.hasAttribute("multiple")?this.uploadedFiles=[...this.uploadedFiles,...i]:this.uploadedFiles=i,this.dispatchEvent(new CustomEvent("db-upload",{bubbles:!0,composed:!0,detail:{files:i}})),this.simulateUpload(i),this.renderFileList()},this.handleRemove=e=>{if(this.isDisabled())return;const t=this.uploadIntervals.get(e);t&&(clearInterval(t),this.uploadIntervals.delete(e)),this.uploadedFiles=this.uploadedFiles.filter(t=>t.id!==e),this.dispatchEvent(new CustomEvent("db-remove",{bubbles:!0,composed:!0,detail:{fileId:e}})),this.renderFileList()},this.handleRetry=e=>{if(this.isDisabled())return;const t=this.uploadedFiles.find(t=>t.id===e);t&&(this.updateFile(e,{status:"pending",progress:0,error:void 0}),this.dispatchEvent(new CustomEvent("db-retry",{bubbles:!0,composed:!0,detail:{fileId:e}})),this.simulateUpload([t]),this.renderFileList())}}static get observedAttributes(){return["locale","size","variant","accept","max-size","multiple","show-file-list","show-progress","disabled","readonly"]}connectedCallback(){this.ensureDropzone(),this.sync(),this.unsubscribeLocale?.(),this.unsubscribeLocale=e(()=>this.syncLocale()),this.dropzone?.addEventListener("db-file-select",this.handleFileSelect)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.dropzone?.removeEventListener("db-file-select",this.handleFileSelect),this.uploadIntervals.forEach(e=>clearInterval(e)),this.uploadIntervals.clear()}syncLocale(){const e=this.querySelector(":scope > .designbase-wc-file-uploader__file-list .designbase-wc-file-uploader__file-list-title");e&&(e.textContent=t("upload.files").replace("{count}",String(this.uploadedFiles.length))),this.querySelectorAll(":scope > .designbase-wc-file-uploader__file-list .designbase-wc-file-uploader__retry-button").forEach(e=>{e.textContent=t("upload.retry")}),this.querySelectorAll(":scope > .designbase-wc-file-uploader__file-list .designbase-wc-file-uploader__remove-button").forEach(e=>{e.textContent=t("upload.remove")})}attributeChangedCallback(){this.isConnected&&this.sync()}isDisabled(){return this.hasAttribute("disabled")||this.hasAttribute("readonly")}ensureDropzone(){this.dropzone||(this.dropzone=document.createElement("db-dropzone"),this.dropzone.setAttribute("data-wc-internal",""),this.prepend(this.dropzone))}formatFileSize(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/1024**t).toFixed(2))} ${["Bytes","KB","MB","GB"][t]}`}simulateUpload(e){e.forEach((e,t)=>{this.updateFile(e.id,{status:"uploading",progress:0});let s=0;const i=setInterval(()=>{if(s+=20*Math.random(),s>=100)return s=100,clearInterval(i),this.uploadIntervals.delete(e.id),this.updateFile(e.id,{status:"success",progress:100}),void this.renderFileList();this.updateFile(e.id,{progress:s}),this.renderFileList()},100+50*t);this.uploadIntervals.set(e.id,i)})}updateFile(e,t){this.uploadedFiles=this.uploadedFiles.map(s=>s.id===e?{...s,...t}:s)}sync(){if(this.ensureDropzone(),!this.dropzone)return;const e=this.getAttribute("size")||"m",t=this.getAttribute("variant")||"default",s=i.includes(e)?e:"m",a=l.includes(t)?t:"default";this.className=["designbase-wc-file-uploader",`designbase-wc-file-uploader--size-${s}`,`designbase-wc-file-uploader--variant-${a}`,this.hasAttribute("disabled")&&"designbase-wc-file-uploader--disabled",this.hasAttribute("readonly")&&"designbase-wc-file-uploader--readonly"].filter(Boolean).join(" "),this.dropzone.setAttribute("size",s),this.dropzone.setAttribute("variant",a),this.getAttribute("accept")?this.dropzone.setAttribute("accept",this.getAttribute("accept")):this.dropzone.removeAttribute("accept"),this.getAttribute("max-size")?this.dropzone.setAttribute("max-size",this.getAttribute("max-size")):this.dropzone.removeAttribute("max-size"),this.dropzone.toggleAttribute("multiple",this.hasAttribute("multiple")),this.dropzone.toggleAttribute("disabled",this.hasAttribute("disabled")),this.dropzone.toggleAttribute("readonly",this.hasAttribute("readonly")),this.renderFileList()}renderStatusIcon(e){if("uploading"===e){const e=document.createElement("db-spinner");return e.setAttribute("type","circular"),e.setAttribute("size","s"),e}return s("success"===e?"done":"error"===e?"error-filled":"gallery",20)}renderFileList(){const e=!this.hasAttribute("show-file-list")||"false"!==this.getAttribute("show-file-list"),s=!this.hasAttribute("show-progress")||"false"!==this.getAttribute("show-progress");if(this.querySelector(":scope > .designbase-wc-file-uploader__file-list")?.remove(),!e||!this.uploadedFiles.length)return;const i=document.createElement("div");i.className="designbase-wc-file-uploader__file-list";const l=document.createElement("div");l.className="designbase-wc-file-uploader__file-list-title",l.textContent=t("upload.files").replace("{count}",String(this.uploadedFiles.length)),i.append(l);const a=document.createElement("div");a.className="designbase-wc-file-uploader__file-items",this.uploadedFiles.forEach(e=>{const i=document.createElement("div");i.className=`designbase-wc-file-uploader__file-item designbase-wc-file-uploader__file-item--${e.status}`;const l=document.createElement("div");l.className="designbase-wc-file-uploader__file-info";const r=document.createElement("div");r.className="designbase-wc-file-uploader__file-icon",r.append(this.renderStatusIcon(e.status));const d=document.createElement("div");d.className="designbase-wc-file-uploader__file-details";const o=document.createElement("div");o.className="designbase-wc-file-uploader__file-name",o.textContent=e.file.name;const n=document.createElement("div");if(n.className="designbase-wc-file-uploader__file-size",n.textContent=this.formatFileSize(e.file.size),d.append(o,n),e.error){const t=document.createElement("div");t.className="designbase-wc-file-uploader__file-error",t.textContent=e.error,d.append(t)}if(l.append(r,d),i.append(l),s&&"uploading"===e.status){const t=document.createElement("div");t.className="designbase-wc-file-uploader__progress";const s=document.createElement("db-progressbar");s.setAttribute("value",String(Math.round(e.progress||0))),s.setAttribute("size","s"),s.setAttribute("variant","primary"),s.setAttribute("bar-style","solid"),s.setAttribute("show-label",""),s.setAttribute("label-position","inside"),s.setAttribute("full-width",""),t.append(s),i.append(t)}const u=document.createElement("div");if(u.className="designbase-wc-file-uploader__file-actions","error"===e.status){const s=document.createElement("button");s.type="button",s.className="designbase-wc-file-uploader__retry-button",s.textContent=t("upload.retry"),s.disabled=this.isDisabled(),s.addEventListener("click",()=>this.handleRetry(e.id)),u.append(s)}const c=document.createElement("button");c.type="button",c.className="designbase-wc-file-uploader__remove-button",c.textContent=t("upload.remove"),c.disabled=this.isDisabled(),c.addEventListener("click",()=>this.handleRemove(e.id)),u.append(c),i.append(u),a.append(i)}),i.append(a),this.append(i)}}customElements.get("db-file-uploader")||customElements.define("db-file-uploader",DbFileUploader);export{DbFileUploader};
|
|
@@ -49,6 +49,7 @@ interface DbFormFieldData {
|
|
|
49
49
|
declare class DbForm extends HTMLElement {
|
|
50
50
|
static get observedAttributes(): string[];
|
|
51
51
|
private built;
|
|
52
|
+
private unsubscribeLocale?;
|
|
52
53
|
private formEl;
|
|
53
54
|
private headerEl;
|
|
54
55
|
private fieldsEl;
|
|
@@ -63,6 +64,7 @@ declare class DbForm extends HTMLElement {
|
|
|
63
64
|
private boundSubmit;
|
|
64
65
|
private boundReset;
|
|
65
66
|
connectedCallback(): void;
|
|
67
|
+
disconnectedCallback(): void;
|
|
66
68
|
attributeChangedCallback(name: string): void;
|
|
67
69
|
get fields(): DbFormFieldData[];
|
|
68
70
|
set fields(value: DbFormFieldData[] | string);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./db-input.js";import"./db-textarea.js";import"./db-select.js";import"./db-checkbox.js";import"./db-radio.js";import"./db-button.js";const e="designbase-wc-form";class DbForm extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.formEl=null,this.headerEl=null,this.fieldsEl=null,this.actionsEl=null,this.submitBtn=null,this.resetBtn=null,this.values={},this.errors={},this.touched={},this.initialValues={},this.fieldWrappers=new Map,this.boundSubmit=e=>this.handleSubmit(e),this.boundReset=e=>this.handleReset(e)}static get observedAttributes(){return["fields","columns","size","variant","title","description","submit-text","reset-text","show-reset","submit-loading","submit-disabled","initial-values"]}connectedCallback(){this.built||(this.buildShell(),this.built=!0),this.bootstrapValues(),this.syncAll()}attributeChangedCallback(e){this.built&&("initial-values"===e&&this.bootstrapValues(),"fields"===e&&this.bootstrapValues(),this.syncAll())}get fields(){return this.parseFields(this.getAttribute("fields"))}set fields(e){this.setAttribute("fields","string"==typeof e?e:JSON.stringify(e))}parseFields(e){if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}parseInitialValues(){const e=this.getAttribute("initial-values");if(!e)return{};try{const t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}bootstrapValues(){this.initialValues=this.parseInitialValues();const e={...this.initialValues};this.fields.forEach(t=>{void 0===e[t.name]&&(void 0===t.value?void 0===t.defaultValue?"checkbox"===t.type&&t.checkboxGroup?e[t.name]=[]:"checkbox"!==t.type?e[t.name]="":e[t.name]=!1:e[t.name]=t.defaultValue:e[t.name]=t.value)}),this.values=e}buildShell(){this.formEl=document.createElement("form"),this.formEl.className=`${e}__native`,this.formEl.noValidate=!0,this.formEl.addEventListener("submit",this.boundSubmit),this.headerEl=document.createElement("div"),this.headerEl.className=`${e}__header`,this.fieldsEl=document.createElement("div"),this.fieldsEl.className=`${e}__fields`,this.actionsEl=document.createElement("div"),this.actionsEl.className=`${e}__actions`,this.submitBtn=document.createElement("db-button"),this.submitBtn.setAttribute("type","submit"),this.submitBtn.setAttribute("variant","primary"),this.resetBtn=document.createElement("db-button"),this.resetBtn.setAttribute("type","button"),this.resetBtn.setAttribute("variant","secondary"),this.resetBtn.addEventListener("click",this.boundReset),this.actionsEl.append(this.submitBtn,this.resetBtn),this.formEl.append(this.fieldsEl,this.actionsEl),this.append(this.headerEl,this.formEl)}syncAll(){this.syncClasses(),this.syncHeader(),this.renderFields(),this.syncActions()}syncClasses(){const t=this.getAttribute("columns")||"1",i=this.getAttribute("size")||"m",s=this.getAttribute("variant")||"default";this.className=[e,`${e}--columns-${t}`,`${e}--${i}`,`${e}--${s}`,this.hasAttribute("submit-loading")&&`${e}--loading`].filter(Boolean).join(" ")}syncHeader(){if(!this.headerEl)return;const t=this.getAttribute("title")||"",i=this.getAttribute("description")||"";if(this.headerEl.innerHTML="",t||i){if(this.headerEl.hidden=!1,t){const i=document.createElement("h3");i.className=`${e}__title`,i.textContent=t,this.headerEl.appendChild(i)}if(i){const t=document.createElement("p");t.className=`${e}__description`,t.textContent=i,this.headerEl.appendChild(t)}}else this.headerEl.hidden=!0}syncActions(){const e=this.getAttribute("submit-text")||"제출",t=this.getAttribute("reset-text")||"리셋",i=this.hasAttribute("show-reset");this.submitBtn&&(this.submitBtn.textContent=e,this.hasAttribute("submit-loading")?this.submitBtn.setAttribute("loading",""):this.submitBtn.removeAttribute("loading"),this.hasAttribute("submit-disabled")?this.submitBtn.setAttribute("disabled",""):this.submitBtn.removeAttribute("disabled")),this.resetBtn&&(this.resetBtn.textContent=t,this.resetBtn.hidden=!i)}renderFields(){if(!this.fieldsEl)return;const t=this.getAttribute("size")||"m";this.fieldsEl.innerHTML="",this.fieldWrappers.clear(),this.fields.forEach(i=>{const s=document.createElement("div");if(s.className=`${e}__field-wrapper ${e}__field-wrapper--${i.type||"text"}`,s.dataset.field=i.name,i.label&&("checkbox"!==i.type||i.checkboxGroup)){const t=document.createElement("label");if(t.className=`${e}__label`,t.htmlFor=`db-form-${i.name}`,t.textContent=i.label,i.required||i.validation?.required){const i=document.createElement("span");i.className=`${e}__required`,i.textContent="*",i.setAttribute("aria-hidden","true"),t.appendChild(i)}s.appendChild(t)}s.appendChild(this.createFieldControl(i,t)),this.fieldsEl.appendChild(s),this.fieldWrappers.set(i.name,s),this.refreshFieldState(i.name)})}refreshFieldState(t){const i=this.fields.find(e=>e.name===t),s=this.fieldWrappers.get(t);if(!i||!s)return;const r=Boolean(this.touched[t]&&this.errors[t]);s.classList.toggle(`${e}__field-wrapper--error`,r),s.querySelector(`.${e}__error`)?.remove(),s.querySelector(`.${e}__help`)?.remove();const a=s.querySelector(`.${e}__field, db-input, db-textarea, db-select, db-checkbox`);a&&(r?(a.setAttribute("error",""),a.setAttribute("error-message",this.errors[t])):(a.removeAttribute("error"),a.removeAttribute("error-message")));const n=a&&["DB-INPUT","DB-TEXTAREA","DB-SELECT"].includes(a.tagName);if(!r||!n){if(r){const i=document.createElement("div");return i.className=`${e}__error`,i.textContent=this.errors[t],void s.appendChild(i)}if(i.helpText){const t=document.createElement("div");t.className=`${e}__help`,t.textContent=i.helpText,s.appendChild(t)}}}refreshAllFieldStates(){this.fields.forEach(e=>this.refreshFieldState(e.name))}createFieldControl(t,i){const s=t.type||"text",r=this.values[t.name],a=Boolean(this.touched[t.name]&&this.errors[t.name]),n=a?this.errors[t.name]:"";if("textarea"===s){const s=document.createElement("db-textarea");return s.className=`${e}__field`,s.setAttribute("name",t.name),s.id=`db-form-${t.name}`,s.setAttribute("size",i),s.setAttribute("full-width",""),t.placeholder&&s.setAttribute("placeholder",t.placeholder),void 0!==r&&s.setAttribute("value",String(r)),t.disabled&&s.setAttribute("disabled",""),t.readOnly&&s.setAttribute("readonly",""),t.required&&s.setAttribute("required",""),t.maxLength&&s.setAttribute("max-length",String(t.maxLength)),a&&(s.setAttribute("error",""),s.setAttribute("error-message",n)),s.addEventListener("db-change",e=>{const i=e.detail;this.handleFieldChange(t,i.value)}),s.addEventListener("db-input",e=>{const i=e.detail;this.handleFieldChange(t,i.value,!1)}),s}if("select"===s){const s=document.createElement("db-select");return s.className=`${e}__field`,s.setAttribute("name",t.name),s.id=`db-form-${t.name}`,s.setAttribute("size",i),s.setAttribute("full-width",""),t.placeholder&&s.setAttribute("placeholder",t.placeholder),t.options&&s.setAttribute("options",JSON.stringify(t.options)),t.multiple&&s.setAttribute("multiple",""),t.disabled&&s.setAttribute("disabled",""),t.readOnly&&s.setAttribute("readonly",""),t.required&&s.setAttribute("required",""),void 0!==r&&s.setAttribute("value",Array.isArray(r)?JSON.stringify(r):String(r)),a&&(s.setAttribute("error",""),s.setAttribute("error-message",n)),s.addEventListener("db-change",e=>{const i=e.detail;this.handleFieldChange(t,i.value)}),s}if("radio"===s&&t.radioGroup){const s=document.createElement("div");return s.className=`${e}__radio-group`,s.setAttribute("role","radiogroup"),(t.options||[]).forEach(e=>{const a=document.createElement("db-radio");a.setAttribute("name",t.name),a.setAttribute("value",e.value),a.setAttribute("size",i),r===e.value&&a.setAttribute("checked",""),(t.disabled||e.disabled)&&a.setAttribute("disabled",""),a.textContent=e.label,a.addEventListener("db-change",i=>{i.detail.checked&&this.handleFieldChange(t,e.value)}),s.appendChild(a)}),s}if("checkbox"===s&&t.checkboxGroup){const s=document.createElement("div");s.className=`${e}__checkbox-group`;const a=Array.isArray(r)?r:[];return(t.options||[]).forEach(e=>{const r=document.createElement("db-checkbox");r.setAttribute("name",t.name),r.setAttribute("value",e.value),r.setAttribute("size",i),a.includes(e.value)&&r.setAttribute("checked",""),(t.disabled||e.disabled)&&r.setAttribute("disabled",""),r.textContent=e.label,r.addEventListener("db-change",i=>{const s=i.detail,r=Array.isArray(this.values[t.name])?[...this.values[t.name]]:[],a=s.checked?[...new Set([...r,e.value])]:r.filter(t=>t!==e.value);this.handleFieldChange(t,a)}),s.appendChild(r)}),s}if("checkbox"===s){const s=document.createElement("db-checkbox");return s.className=`${e}__field`,s.setAttribute("name",t.name),s.id=`db-form-${t.name}`,s.setAttribute("size",i),r&&s.setAttribute("checked",""),t.disabled&&s.setAttribute("disabled",""),t.readOnly&&s.setAttribute("readonly",""),t.required&&s.setAttribute("required",""),s.textContent=t.label||"",s.addEventListener("db-change",e=>{const i=e.detail;this.handleFieldChange(t,i.checked)}),s}const l=document.createElement("db-input");return l.className=`${e}__field`,l.setAttribute("name",t.name),l.id=`db-form-${t.name}`,l.setAttribute("type",s),l.setAttribute("size",i),l.setAttribute("full-width",""),t.placeholder&&l.setAttribute("placeholder",t.placeholder),void 0!==r&&!1!==r&&l.setAttribute("value",String(r)),t.disabled&&l.setAttribute("disabled",""),t.readOnly&&l.setAttribute("readonly",""),t.required&&l.setAttribute("required",""),void 0!==t.min&&l.setAttribute("min",String(t.min)),void 0!==t.max&&l.setAttribute("max",String(t.max)),void 0!==t.minLength&&l.setAttribute("minlength",String(t.minLength)),void 0!==t.maxLength&&l.setAttribute("maxlength",String(t.maxLength)),t.pattern&&l.setAttribute("pattern",t.pattern),a&&(l.setAttribute("error",""),l.setAttribute("error-message",n)),l.addEventListener("db-change",e=>{const i=e.detail;this.handleFieldChange(t,i.value)}),l.addEventListener("db-input",e=>{const i=e.detail;this.handleFieldChange(t,i.value,!1)}),l}handleFieldChange(e,t,i=!0){this.values[e.name]=t,i&&(this.touched[e.name]=!0);const s=this.validateField(e,t);this.errors[e.name]=s||"",this.refreshFieldState(e.name),this.dispatchEvent(new CustomEvent("db-change",{bubbles:!0,composed:!0,detail:{values:{...this.values}}}))}validateField(e,t){const i=e.validation||{};if((i.required??e.required)&&(null==t||""===t||!1===t||Array.isArray(t)&&0===t.length))return e.errorMessage||`${e.label||e.name}은(는) 필수입니다.`;if(void 0!==i.min&&Number(t)<i.min)return e.errorMessage||`최소값은 ${i.min}입니다.`;if(void 0!==i.max&&Number(t)>i.max)return e.errorMessage||`최대값은 ${i.max}입니다.`;if(void 0!==i.minLength&&String(t).length<i.minLength)return e.errorMessage||`최소 ${i.minLength}자 이상 입력해주세요.`;if(void 0!==i.maxLength&&String(t).length>i.maxLength)return e.errorMessage||`최대 ${i.maxLength}자까지 입력 가능합니다.`;const s=i.pattern||e.pattern;if(s&&String(t))try{if(!new RegExp(s).test(String(t)))return e.errorMessage||"올바른 형식으로 입력해주세요."}catch{}}validateForm(){let e=!0;return this.fields.forEach(t=>{const i=this.validateField(t,this.values[t.name]);i?(this.errors[t.name]=i,e=!1):this.errors[t.name]=""}),e}handleSubmit(e){e.preventDefault(),this.fields.forEach(e=>{this.touched[e.name]=!0}),this.validateForm()?this.dispatchEvent(new CustomEvent("db-submit",{bubbles:!0,composed:!0,detail:{values:{...this.values}}})):this.refreshAllFieldStates()}handleReset(e){e.preventDefault(),this.values={...this.initialValues},this.bootstrapValues(),this.errors={},this.touched={},this.renderFields(),this.dispatchEvent(new CustomEvent("db-reset",{bubbles:!0,composed:!0,detail:{values:{...this.values}}})),this.dispatchEvent(new CustomEvent("db-change",{bubbles:!0,composed:!0,detail:{values:{...this.values}}}))}}customElements.get("db-form")||customElements.define("db-form",DbForm);export{DbForm};
|
|
1
|
+
import"./db-input.js";import"./db-textarea.js";import"./db-select.js";import"./db-checkbox.js";import"./db-radio.js";import"./db-button.js";import{subscribeDbLocale as e,dbText as t,dbFormat as i}from"../core/i18n.js";const s="designbase-wc-form";class DbForm extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.formEl=null,this.headerEl=null,this.fieldsEl=null,this.actionsEl=null,this.submitBtn=null,this.resetBtn=null,this.values={},this.errors={},this.touched={},this.initialValues={},this.fieldWrappers=new Map,this.boundSubmit=e=>this.handleSubmit(e),this.boundReset=e=>this.handleReset(e)}static get observedAttributes(){return["fields","columns","size","variant","title","description","submit-text","reset-text","show-reset","submit-loading","submit-disabled","initial-values"]}connectedCallback(){this.built||(this.buildShell(),this.built=!0),this.bootstrapValues(),this.unsubscribeLocale?.(),this.unsubscribeLocale=e(()=>{this.syncActions();for(const e of this.fields)this.errors[e.name]&&(this.errors[e.name]=this.validateField(e,this.values[e.name])||"",this.refreshFieldState(e.name))}),this.syncAll()}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0}attributeChangedCallback(e){this.built&&("initial-values"===e&&this.bootstrapValues(),"fields"===e&&this.bootstrapValues(),this.syncAll())}get fields(){return this.parseFields(this.getAttribute("fields"))}set fields(e){this.setAttribute("fields","string"==typeof e?e:JSON.stringify(e))}parseFields(e){if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}parseInitialValues(){const e=this.getAttribute("initial-values");if(!e)return{};try{const t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}bootstrapValues(){this.initialValues=this.parseInitialValues();const e={...this.initialValues};this.fields.forEach(t=>{void 0===e[t.name]&&(void 0===t.value?void 0===t.defaultValue?"checkbox"===t.type&&t.checkboxGroup?e[t.name]=[]:"checkbox"!==t.type?e[t.name]="":e[t.name]=!1:e[t.name]=t.defaultValue:e[t.name]=t.value)}),this.values=e}buildShell(){this.formEl=document.createElement("form"),this.formEl.className=`${s}__native`,this.formEl.noValidate=!0,this.formEl.addEventListener("submit",this.boundSubmit),this.headerEl=document.createElement("div"),this.headerEl.className=`${s}__header`,this.fieldsEl=document.createElement("div"),this.fieldsEl.className=`${s}__fields`,this.actionsEl=document.createElement("div"),this.actionsEl.className=`${s}__actions`,this.submitBtn=document.createElement("db-button"),this.submitBtn.setAttribute("type","submit"),this.submitBtn.setAttribute("variant","primary"),this.resetBtn=document.createElement("db-button"),this.resetBtn.setAttribute("type","button"),this.resetBtn.setAttribute("variant","secondary"),this.resetBtn.addEventListener("click",this.boundReset),this.actionsEl.append(this.submitBtn,this.resetBtn),this.formEl.append(this.fieldsEl,this.actionsEl),this.append(this.headerEl,this.formEl)}syncAll(){this.syncClasses(),this.syncHeader(),this.renderFields(),this.syncActions()}syncClasses(){const e=this.getAttribute("columns")||"1",t=this.getAttribute("size")||"m",i=this.getAttribute("variant")||"default";this.className=[s,`${s}--columns-${e}`,`${s}--${t}`,`${s}--${i}`,this.hasAttribute("submit-loading")&&`${s}--loading`].filter(Boolean).join(" ")}syncHeader(){if(!this.headerEl)return;const e=this.getAttribute("title")||"",t=this.getAttribute("description")||"";if(this.headerEl.innerHTML="",e||t){if(this.headerEl.hidden=!1,e){const t=document.createElement("h3");t.className=`${s}__title`,t.textContent=e,this.headerEl.appendChild(t)}if(t){const e=document.createElement("p");e.className=`${s}__description`,e.textContent=t,this.headerEl.appendChild(e)}}else this.headerEl.hidden=!0}syncActions(){const e=this.getAttribute("submit-text")||t("제출"),i=this.getAttribute("reset-text")||t("리셋"),s=this.hasAttribute("show-reset");this.submitBtn&&(this.submitBtn.textContent=e,this.hasAttribute("submit-loading")?this.submitBtn.setAttribute("loading",""):this.submitBtn.removeAttribute("loading"),this.hasAttribute("submit-disabled")?this.submitBtn.setAttribute("disabled",""):this.submitBtn.removeAttribute("disabled")),this.resetBtn&&(this.resetBtn.textContent=i,this.resetBtn.hidden=!s)}renderFields(){if(!this.fieldsEl)return;const e=this.getAttribute("size")||"m";this.fieldsEl.innerHTML="",this.fieldWrappers.clear(),this.fields.forEach(t=>{const i=document.createElement("div");if(i.className=`${s}__field-wrapper ${s}__field-wrapper--${t.type||"text"}`,i.dataset.field=t.name,t.label&&("checkbox"!==t.type||t.checkboxGroup)){const e=document.createElement("label");if(e.className=`${s}__label`,e.htmlFor=`db-form-${t.name}`,e.textContent=t.label,t.required||t.validation?.required){const t=document.createElement("span");t.className=`${s}__required`,t.textContent="*",t.setAttribute("aria-hidden","true"),e.appendChild(t)}i.appendChild(e)}i.appendChild(this.createFieldControl(t,e)),this.fieldsEl.appendChild(i),this.fieldWrappers.set(t.name,i),this.refreshFieldState(t.name)})}refreshFieldState(e){const t=this.fields.find(t=>t.name===e),i=this.fieldWrappers.get(e);if(!t||!i)return;const r=Boolean(this.touched[e]&&this.errors[e]);i.classList.toggle(`${s}__field-wrapper--error`,r),i.querySelector(`.${s}__error`)?.remove(),i.querySelector(`.${s}__help`)?.remove();const a=i.querySelector(`.${s}__field, db-input, db-textarea, db-select, db-checkbox`);a&&(r?(a.setAttribute("error",""),a.setAttribute("error-message",this.errors[e])):(a.removeAttribute("error"),a.removeAttribute("error-message")));const n=a&&["DB-INPUT","DB-TEXTAREA","DB-SELECT"].includes(a.tagName);if(!r||!n){if(r){const t=document.createElement("div");return t.className=`${s}__error`,t.textContent=this.errors[e],void i.appendChild(t)}if(t.helpText){const e=document.createElement("div");e.className=`${s}__help`,e.textContent=t.helpText,i.appendChild(e)}}}refreshAllFieldStates(){this.fields.forEach(e=>this.refreshFieldState(e.name))}createFieldControl(e,t){const i=e.type||"text",r=this.values[e.name],a=Boolean(this.touched[e.name]&&this.errors[e.name]),n=a?this.errors[e.name]:"";if("textarea"===i){const i=document.createElement("db-textarea");return i.className=`${s}__field`,i.setAttribute("name",e.name),i.id=`db-form-${e.name}`,i.setAttribute("size",t),i.setAttribute("full-width",""),e.placeholder&&i.setAttribute("placeholder",e.placeholder),void 0!==r&&i.setAttribute("value",String(r)),e.disabled&&i.setAttribute("disabled",""),e.readOnly&&i.setAttribute("readonly",""),e.required&&i.setAttribute("required",""),e.maxLength&&i.setAttribute("max-length",String(e.maxLength)),a&&(i.setAttribute("error",""),i.setAttribute("error-message",n)),i.addEventListener("db-change",t=>{const i=t.detail;this.handleFieldChange(e,i.value)}),i.addEventListener("db-input",t=>{const i=t.detail;this.handleFieldChange(e,i.value,!1)}),i}if("select"===i){const i=document.createElement("db-select");return i.className=`${s}__field`,i.setAttribute("name",e.name),i.id=`db-form-${e.name}`,i.setAttribute("size",t),i.setAttribute("full-width",""),e.placeholder&&i.setAttribute("placeholder",e.placeholder),e.options&&i.setAttribute("options",JSON.stringify(e.options)),e.multiple&&i.setAttribute("multiple",""),e.disabled&&i.setAttribute("disabled",""),e.readOnly&&i.setAttribute("readonly",""),e.required&&i.setAttribute("required",""),void 0!==r&&i.setAttribute("value",Array.isArray(r)?JSON.stringify(r):String(r)),a&&(i.setAttribute("error",""),i.setAttribute("error-message",n)),i.addEventListener("db-change",t=>{const i=t.detail;this.handleFieldChange(e,i.value)}),i}if("radio"===i&&e.radioGroup){const i=document.createElement("div");return i.className=`${s}__radio-group`,i.setAttribute("role","radiogroup"),(e.options||[]).forEach(s=>{const a=document.createElement("db-radio");a.setAttribute("name",e.name),a.setAttribute("value",s.value),a.setAttribute("size",t),r===s.value&&a.setAttribute("checked",""),(e.disabled||s.disabled)&&a.setAttribute("disabled",""),a.textContent=s.label,a.addEventListener("db-change",t=>{t.detail.checked&&this.handleFieldChange(e,s.value)}),i.appendChild(a)}),i}if("checkbox"===i&&e.checkboxGroup){const i=document.createElement("div");i.className=`${s}__checkbox-group`;const a=Array.isArray(r)?r:[];return(e.options||[]).forEach(s=>{const r=document.createElement("db-checkbox");r.setAttribute("name",e.name),r.setAttribute("value",s.value),r.setAttribute("size",t),a.includes(s.value)&&r.setAttribute("checked",""),(e.disabled||s.disabled)&&r.setAttribute("disabled",""),r.textContent=s.label,r.addEventListener("db-change",t=>{const i=t.detail,r=Array.isArray(this.values[e.name])?[...this.values[e.name]]:[],a=i.checked?[...new Set([...r,s.value])]:r.filter(e=>e!==s.value);this.handleFieldChange(e,a)}),i.appendChild(r)}),i}if("checkbox"===i){const i=document.createElement("db-checkbox");return i.className=`${s}__field`,i.setAttribute("name",e.name),i.id=`db-form-${e.name}`,i.setAttribute("size",t),r&&i.setAttribute("checked",""),e.disabled&&i.setAttribute("disabled",""),e.readOnly&&i.setAttribute("readonly",""),e.required&&i.setAttribute("required",""),i.textContent=e.label||"",i.addEventListener("db-change",t=>{const i=t.detail;this.handleFieldChange(e,i.checked)}),i}const l=document.createElement("db-input");return l.className=`${s}__field`,l.setAttribute("name",e.name),l.id=`db-form-${e.name}`,l.setAttribute("type",i),l.setAttribute("size",t),l.setAttribute("full-width",""),e.placeholder&&l.setAttribute("placeholder",e.placeholder),void 0!==r&&!1!==r&&l.setAttribute("value",String(r)),e.disabled&&l.setAttribute("disabled",""),e.readOnly&&l.setAttribute("readonly",""),e.required&&l.setAttribute("required",""),void 0!==e.min&&l.setAttribute("min",String(e.min)),void 0!==e.max&&l.setAttribute("max",String(e.max)),void 0!==e.minLength&&l.setAttribute("minlength",String(e.minLength)),void 0!==e.maxLength&&l.setAttribute("maxlength",String(e.maxLength)),e.pattern&&l.setAttribute("pattern",e.pattern),a&&(l.setAttribute("error",""),l.setAttribute("error-message",n)),l.addEventListener("db-change",t=>{const i=t.detail;this.handleFieldChange(e,i.value)}),l.addEventListener("db-input",t=>{const i=t.detail;this.handleFieldChange(e,i.value,!1)}),l}handleFieldChange(e,t,i=!0){this.values[e.name]=t,i&&(this.touched[e.name]=!0);const s=this.validateField(e,t);this.errors[e.name]=s||"",this.refreshFieldState(e.name),this.dispatchEvent(new CustomEvent("db-change",{bubbles:!0,composed:!0,detail:{values:{...this.values}}}))}validateField(e,s){const r=e.validation||{};if((r.required??e.required)&&(null==s||""===s||!1===s||Array.isArray(s)&&0===s.length))return e.errorMessage||i("{0}은(는) 필수입니다.",[e.label||e.name]);if(void 0!==r.min&&Number(s)<r.min)return e.errorMessage||i("최소값은 {0}입니다.",[r.min]);if(void 0!==r.max&&Number(s)>r.max)return e.errorMessage||i("최대값은 {0}입니다.",[r.max]);if(void 0!==r.minLength&&String(s).length<r.minLength)return e.errorMessage||i("최소 {0}자 이상 입력해주세요.",[r.minLength]);if(void 0!==r.maxLength&&String(s).length>r.maxLength)return e.errorMessage||i("최대 {0}자까지 입력 가능합니다.",[r.maxLength]);const a=r.pattern||e.pattern;if(a&&String(s))try{if(!new RegExp(a).test(String(s)))return e.errorMessage||t("올바른 형식으로 입력해주세요.")}catch{}}validateForm(){let e=!0;return this.fields.forEach(t=>{const i=this.validateField(t,this.values[t.name]);i?(this.errors[t.name]=i,e=!1):this.errors[t.name]=""}),e}handleSubmit(e){e.preventDefault(),this.fields.forEach(e=>{this.touched[e.name]=!0}),this.validateForm()?this.dispatchEvent(new CustomEvent("db-submit",{bubbles:!0,composed:!0,detail:{values:{...this.values}}})):this.refreshAllFieldStates()}handleReset(e){e.preventDefault(),this.values={...this.initialValues},this.bootstrapValues(),this.errors={},this.touched={},this.renderFields(),this.dispatchEvent(new CustomEvent("db-reset",{bubbles:!0,composed:!0,detail:{values:{...this.values}}})),this.dispatchEvent(new CustomEvent("db-change",{bubbles:!0,composed:!0,detail:{values:{...this.values}}}))}}customElements.get("db-form")||customElements.define("db-form",DbForm);export{DbForm};
|
|
@@ -29,6 +29,7 @@ type DbGanttGroup = {
|
|
|
29
29
|
declare class DbGantt extends HTMLElement {
|
|
30
30
|
private collapsedGroups;
|
|
31
31
|
private dragState;
|
|
32
|
+
private unsubscribeLocale?;
|
|
32
33
|
private reorderState;
|
|
33
34
|
private reorderDropIndex;
|
|
34
35
|
private suppressRender;
|
|
@@ -43,6 +44,7 @@ declare class DbGantt extends HTMLElement {
|
|
|
43
44
|
connectedCallback(): void;
|
|
44
45
|
disconnectedCallback(): void;
|
|
45
46
|
attributeChangedCallback(): void;
|
|
47
|
+
private refreshLocale;
|
|
46
48
|
private parseJson;
|
|
47
49
|
private getBool;
|
|
48
50
|
private getNumber;
|