@designbasekorea/ui-wc 0.9.0 → 0.9.3
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 +31 -0
- package/README.md +18 -2
- package/dist/esm/components/date-picker-utils.js +1 -1
- package/dist/esm/components/db-accordion.js +1 -1
- package/dist/esm/components/db-achievement-list.js +1 -1
- package/dist/esm/components/db-achievement-modal.js +1 -1
- package/dist/esm/components/db-activity-heatmap.js +1 -1
- package/dist/esm/components/db-ad-banner.js +1 -1
- package/dist/esm/components/db-ai-chat-list.js +1 -1
- package/dist/esm/components/db-ai-chat.js +1 -1
- package/dist/esm/components/db-alert.d.ts +12 -0
- package/dist/esm/components/db-alert.js +1 -1
- package/dist/esm/components/db-app-badge.js +1 -1
- package/dist/esm/components/db-audio-player.js +1 -1
- package/dist/esm/components/db-backdrop.js +1 -1
- package/dist/esm/components/db-boarding-pass-stack.js +1 -1
- package/dist/esm/components/db-boarding-pass.js +1 -1
- package/dist/esm/components/db-bottom-navigation.js +1 -1
- package/dist/esm/components/db-bottom-sheet.js +1 -1
- package/dist/esm/components/db-breadcrumbs.js +1 -1
- package/dist/esm/components/db-calendar.js +1 -1
- package/dist/esm/components/db-card.js +1 -1
- package/dist/esm/components/db-carousel.d.ts +3 -3
- package/dist/esm/components/db-carousel.js +1 -1
- package/dist/esm/components/db-chat-composer.js +1 -1
- package/dist/esm/components/db-chat-room.js +1 -1
- package/dist/esm/components/db-chat-widget.js +1 -1
- package/dist/esm/components/db-chip.js +1 -1
- package/dist/esm/components/db-code-block.js +1 -1
- package/dist/esm/components/db-color-picker.js +1 -1
- package/dist/esm/components/db-confirm.js +1 -1
- package/dist/esm/components/db-context-bar.js +1 -1
- package/dist/esm/components/db-context-menu.js +1 -1
- package/dist/esm/components/db-credit-card.js +1 -1
- package/dist/esm/components/db-cursor-follower.js +1 -1
- package/dist/esm/components/db-date-picker.js +1 -1
- package/dist/esm/components/db-design-canvas.js +1 -1
- package/dist/esm/components/db-design-toolbar.js +1 -1
- package/dist/esm/components/db-download-progress.js +1 -1
- package/dist/esm/components/db-drawer.d.ts +1 -0
- package/dist/esm/components/db-drawer.js +1 -1
- package/dist/esm/components/db-dropdown.js +1 -1
- package/dist/esm/components/db-dropzone.js +1 -1
- package/dist/esm/components/db-email-verify.d.ts +0 -6
- package/dist/esm/components/db-email-verify.js +1 -1
- package/dist/esm/components/db-file-uploader.js +1 -1
- package/dist/esm/components/db-flight-status.js +1 -1
- package/dist/esm/components/db-footer.js +1 -1
- package/dist/esm/components/db-gantt.js +1 -1
- package/dist/esm/components/db-image-list.d.ts +2 -0
- package/dist/esm/components/db-image-list.js +1 -1
- package/dist/esm/components/db-indicator.js +1 -1
- package/dist/esm/components/db-input.js +1 -1
- package/dist/esm/components/db-kanban.js +1 -1
- package/dist/esm/components/db-lightbox.d.ts +4 -0
- package/dist/esm/components/db-lightbox.js +1 -1
- package/dist/esm/components/db-markdown-editor.js +1 -1
- package/dist/esm/components/db-marquee.d.ts +2 -10
- package/dist/esm/components/db-marquee.js +1 -1
- package/dist/esm/components/db-modal.js +1 -1
- package/dist/esm/components/db-navbar.js +1 -1
- package/dist/esm/components/db-node.js +1 -1
- package/dist/esm/components/db-onboarding-modal.js +1 -1
- package/dist/esm/components/db-otp-input.js +1 -1
- package/dist/esm/components/db-page-header.d.ts +8 -0
- package/dist/esm/components/db-page-header.js +1 -1
- package/dist/esm/components/db-pagination.js +1 -1
- package/dist/esm/components/db-phone-verify.js +1 -1
- package/dist/esm/components/db-popover.js +1 -1
- package/dist/esm/components/db-progress-step.js +1 -1
- package/dist/esm/components/db-receipt.js +1 -1
- package/dist/esm/components/db-resizable-panels.js +1 -1
- package/dist/esm/components/db-search-bar.js +1 -1
- package/dist/esm/components/db-section-testimonials.d.ts +1 -4
- package/dist/esm/components/db-section-testimonials.js +1 -1
- package/dist/esm/components/db-segment-control.d.ts +0 -4
- package/dist/esm/components/db-segment-control.js +1 -1
- package/dist/esm/components/db-select.js +1 -1
- package/dist/esm/components/db-share.js +1 -1
- package/dist/esm/components/db-sidebar.js +1 -1
- package/dist/esm/components/db-split-view.js +1 -1
- package/dist/esm/components/db-stepper.d.ts +0 -3
- package/dist/esm/components/db-stepper.js +1 -1
- package/dist/esm/components/db-table.js +1 -1
- package/dist/esm/components/db-testimonial.js +1 -1
- package/dist/esm/components/db-time-picker.js +1 -1
- package/dist/esm/components/db-tooltip.js +1 -1
- package/dist/esm/components/db-top-banner.js +1 -1
- package/dist/esm/components/db-tutorial.js +1 -1
- package/dist/esm/components/db-two-factor.d.ts +4 -10
- package/dist/esm/components/db-two-factor.js +1 -1
- package/dist/esm/components/db-video-player.js +1 -1
- package/dist/esm/components/db-voice-control.js +1 -1
- package/dist/esm/components/db-youtube-player.js +1 -1
- package/dist/esm/components/input-validation.js +1 -1
- package/dist/esm/components/paper-card.js +1 -1
- package/dist/esm/core/focus-trap.js +1 -1
- package/dist/esm/core/host-class.js +1 -0
- package/dist/esm/core/i18n-copy.js +1 -0
- package/dist/esm/core/i18n-en.js +1 -0
- package/dist/esm/core/i18n.d.ts +65 -1
- package/dist/esm/core/i18n.js +1 -1
- package/dist/esm/core/theme-scope.js +1 -0
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/node_modules/@designbasekorea/carousel/dist/chunks/chunk-AGE5BHQ4.js +1 -0
- package/dist/esm/node_modules/@designbasekorea/carousel/dist/chunks/chunk-GM4TCAP5.js +1 -0
- package/dist/esm/node_modules/@designbasekorea/carousel/dist/chunks/chunk-GSN4JZN7.js +1 -0
- package/dist/esm/node_modules/@designbasekorea/carousel/dist/chunks/chunk-VJJVQGV4.js +1 -0
- package/dist/esm/node_modules/@designbasekorea/carousel/dist/chunks/chunk-YWLMJGDH.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.css +1 -1
- package/dist/index.d.ts +100 -41
- package/dist/index.esm.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +12 -0
- package/dist/react/index.esm.js +1 -1
- package/package.json +5 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{lockScroll as
|
|
1
|
+
import{inheritThemeScope as t}from"../core/theme-scope.js";import{lockScroll as e,unlockScroll as s}from"../core/scroll-lock.js";const i=["fade","slide","zoom","none"];class DbBackdrop extends HTMLElement{constructor(){super(...arguments),this.scrollLocked=!1,this.keyHandler=null,this.handlePortalClick=t=>{t.target===this.portal&&"true"!==this.getAttribute("disable-backdrop-click")&&(this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0})))}}static get observedAttributes(){return["open","blur","opacity","blur-amount","animation","animation-duration","z-index","background-color","disable-backdrop-click","disable-escape-key-down"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}connectedCallback(){this.style.display="contents",this.syncOpenState()}disconnectedCallback(){this.detachListeners(),this.portal?.remove(),this.portal=void 0,this.releaseScrollLock()}attributeChangedCallback(){this.isConnected&&this.syncOpenState()}isOpen(){return this.open}syncOpenState(){this.isOpen()?this.render():(this.releaseScrollLock(),this.detachListeners(),this.portal?.remove())}collectChildren(){return Array.from(this.children).filter(t=>!t.hasAttribute("data-wc-internal"))}attachListeners(){this.keyHandler||(this.keyHandler=t=>{"Escape"===t.key&&"true"!==this.getAttribute("disable-escape-key-down")&&(this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0})))},document.addEventListener("keydown",this.keyHandler))}detachListeners(){this.keyHandler&&(document.removeEventListener("keydown",this.keyHandler),this.keyHandler=null)}render(){if(!this.isOpen())return void this.syncOpenState();const s=this.hasAttribute("blur"),r=this.getAttribute("opacity")||"0.5",o=this.getAttribute("blur-amount")||"4",a=i.includes(this.getAttribute("animation")||"fade")&&this.getAttribute("animation")||"fade",n=this.getAttribute("animation-duration")||"300",l=this.getAttribute("z-index")||"1000",c=this.getAttribute("background-color"),d=this.collectChildren();this.scrollLocked||(e(),this.scrollLocked=!0),this.attachListeners(),this.portal||(this.portal=document.createElement("div"),this.portal.setAttribute("data-wc-internal",""),this.portal.addEventListener("click",this.handlePortalClick)),this.portal.className=["designbase-wc-backdrop",`designbase-wc-backdrop--${a}`,"designbase-wc-backdrop--open",s?"designbase-wc-backdrop--blur":""].filter(Boolean).join(" "),this.portal.setAttribute("role","presentation"),this.portal.setAttribute("aria-hidden","false"),this.portal.style.setProperty("--backdrop-opacity",r),this.portal.style.setProperty("--backdrop-blur-amount",`${o}px`),this.portal.style.setProperty("--backdrop-animation-duration",`${n}ms`),this.portal.style.setProperty("--backdrop-z-index",l),c?this.portal.style.backgroundColor=c:this.portal.style.removeProperty("background-color"),this.portal.replaceChildren(...d),this.portal.isConnected||(t(this,this.portal),document.body.append(this.portal))}releaseScrollLock(){this.scrollLocked&&(this.scrollLocked=!1,s())}}customElements.get("db-backdrop")||customElements.define("db-backdrop",DbBackdrop);export{DbBackdrop};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{t as e}from"../core/i18n.js";import{DbElement as t}from"../core/base-element.js";import{paperNode as s,paperJson as i}from"./paper-card.js";import"./db-boarding-pass.js";let a=0;const r=["id","issuer","origin","destination","originName","destinationName","passenger","serviceNumber","date","boardingTime","departureTime","arrivalTime","terminal","gate","seat","travelClass","codeImageSrc"],sanitize=e=>Array.isArray(e)?e.filter(e=>e&&"object"==typeof e&&["id","issuer","origin","destination"].every(t=>"string"==typeof e[t])).map(e=>Object.fromEntries(r.filter(t=>"string"==typeof e[t]).map(t=>[t,e[t]]))):[];class DbBoardingPassStack extends t{constructor(){super(...arguments),this.instanceId="db-travel-wallet-"+ ++a,this.view=s("section","db-boarding-pass-stack__view")}static get observedAttributes(){return["passes","selected-index","label","action-label","disabled"]}get passes(){return sanitize(this.data??i(this.getAttribute("passes")))}set passes(e){this.data=null==e?void 0:sanitize(e),this.isConnected&&this.render()}get selectedIndex(){const e=Number(this.getAttribute("selected-index")||0);return Number.isFinite(e)?Math.max(0,Math.min(this.passes.length-1,Math.floor(e))):0}set selectedIndex(e){this.setAttribute("selected-index",String(e))}connectedCallback(){this.classList.add("db-boarding-pass-stack"),this.upgradeProperties(["passes","selectedIndex"]),this.view.parentNode||this.prepend(this.view),this.render()}attributeChangedCallback(){this.isConnected&&this.render()}select(e){if(this.hasAttribute("disabled"))return;this.selectedIndex=e,this.view.querySelector(`button[data-index="${this.selectedIndex}"]`)?.focus();const t=this.passes[this.selectedIndex];t&&this.dbEmit("change",{index:this.selectedIndex,pass:t})}render(){const t=this.passes,i=this.selectedIndex,a=this.view.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement;if(this.view.setAttribute("aria-label",this.getAttribute("label")||e("wallet.title")),!t.length)return void this.view.replaceChildren(s("p","db-boarding-pass-stack__empty",e("wallet.empty")));const n=s("div","db-boarding-pass-stack__tabs");n.setAttribute("role","tablist"),n.setAttribute("aria-label",e("wallet.journeys")),n.setAttribute("aria-orientation","vertical"),t.forEach((a,r)=>{const d=s("button","db-boarding-pass-stack__tab");d.type="button",d.dataset.index=String(r),d.id=`${this.instanceId}-tab-${r}`,d.setAttribute("aria-controls",`${this.instanceId}-panel`),d.setAttribute("role","tab"),d.setAttribute("aria-selected",String(r===i)),d.setAttribute("aria-label",`${a.origin} → ${a.destination}${a.seat?` · ${e("boardingPass.seat")} ${a.seat}`:""}`),d.tabIndex=r===i?0:-1,d.disabled=this.hasAttribute("disabled"),d.append(s("strong","",`${a.origin} → ${a.destination}`),s("span","",[a.issuer,a.date,a.seat&&`${e("boardingPass.seat")} ${a.seat}`].filter(Boolean).join(" · "))),d.addEventListener("click",()=>this.select(r)),d.addEventListener("keydown",e=>{let s=r;if("ArrowDown"===e.key||"ArrowRight"===e.key)s=(r+1)%t.length;else if("ArrowUp"===e.key||"ArrowLeft"===e.key)s=(r-1+t.length)%t.length;else if("Home"===e.key)s=0;else{if("End"!==e.key)return;s=t.length-1}e.preventDefault(),this.select(s)}),n.append(d)});const d=s("div","db-boarding-pass-stack__panel");d.id=`${this.instanceId}-panel`,d.setAttribute("role","tabpanel"),d.setAttribute("aria-labelledby",`${this.instanceId}-tab-${i}`),d.setAttribute("aria-label",`${t[i].origin} → ${t[i].destination} · ${e("boardingPass.title")}`);const o=document.createElement("db-boarding-pass"),l=t[i];for(const e of r)"id"!==e&&l[e]&&o.setAttribute(e.replace(/[A-Z]/g,e=>"-"+e.toLowerCase()),l[e]);o.setAttribute("reference",l.id),o.setAttribute("layout","vertical"),this.getAttribute("action-label")&&o.setAttribute("action-label",this.getAttribute("action-label")),o.toggleAttribute("disabled",this.hasAttribute("disabled")),d.append(o),this.view.replaceChildren(n,d),a&&this.view.querySelector(`button[data-index="${i}"]`)?.focus()}}customElements.get("db-boarding-pass-stack")||customElements.define("db-boarding-pass-stack",DbBoardingPassStack);export{DbBoardingPassStack};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DbPaperCard as
|
|
1
|
+
import{t as e}from"../core/i18n.js";import{DbPaperCard as t,paperNode as a,paperDetails as s}from"./paper-card.js";const r={origin:"출발",destination:"도착",passenger:"탑승객",service:"편명",date:"날짜",boarding:"탑승 시각",departure:"출발 시각",arrival:"도착 시각",terminal:"터미널",gate:"게이트",seat:"좌석",travelClass:"등급"};class DbBoardingPass extends t{constructor(){super(...arguments),this.customLabels={}}static get observedAttributes(){return["layout","issuer","origin","origin-name","destination","destination-name","passenger","service-number","date","boarding-time","departure-time","arrival-time","terminal","gate","seat","travel-class","reference","code-image-src","code-alt","note","action-label","disabled"]}upgradeNames(){return["labels"]}get labels(){return{...Object.fromEntries(Object.entries(r).map(([t,a])=>[t,e(`boardingPass.${t}`,a)])),...this.customLabels}}set labels(e){this.customLabels={};for(const t of Object.keys(r))"string"==typeof e?.[t]&&(this.customLabels[t]=e[t]);this.isConnected&&this.render()}render(){const t=this.labels,r=a("section","db-paper__main"),n=a("header","db-paper__pass-header");n.append(a("strong","db-paper__issuer",this.attr("issuer")||e("boardingPass.title")),a("span","",this.attr("service-number"))),r.append(n);const i=a("div","db-paper__route"),endpoint=(e,t)=>{const s=a("div","db-paper__endpoint");return s.append(a("span","db-paper__label",t),a("strong","db-paper__airport",this.attr(e)||"—")),this.attr(e+"-name")&&s.append(a("span","db-paper__city",this.attr(e+"-name"))),s};if(i.append(endpoint("origin",t.origin),a("span","db-paper__route-arrow","→"),endpoint("destination",t.destination)),r.append(i),this.attr("passenger")){const e=a("div","db-paper__passenger");e.append(a("span","db-paper__label",t.passenger),a("strong","",this.attr("passenger"))),r.append(e)}const p=[],add=(e,t)=>{this.attr(e)&&p.push({label:t,value:this.attr(e)})};add("date",t.date),add("travel-class",t.travelClass),add("boarding-time",t.boarding),add("departure-time",t.departure),add("arrival-time",t.arrival),p.length&&r.append(s(p));const o=a("div","db-paper__stub");o.append(this.code(this.attr("reference")));const d=[];for(const[e,a]of[["terminal",t.terminal],["gate",t.gate],["seat",t.seat]])this.attr(e)&&d.push({label:a,value:this.attr(e)});d.length&&o.append(s(d)),this.attr("note")&&o.append(a("p","db-paper__note",this.attr("note")));const l=this.action(this.attr("reference"));l&&o.append(l),this.replace(r,o)}}customElements.get("db-boarding-pass")||customElements.define("db-boarding-pass",DbBoardingPass);export{DbBoardingPass};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{dbText as t}from"../core/i18n.js";import{createDbIcon as e}from"./db-icons.js";import{BOTTOM_NAV_SIZES as i,BOTTOM_NAV_BACKGROUNDS as n}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbBottomNavigation extends HTMLElement{static get observedAttributes(){return["items","active-item-id","size","background-color","fixed"]}connectedCallback(){this.render()}attributeChangedCallback(){this.isConnected&&this.render()}get items(){return this.parseItems()}set items(t){this.setAttribute("items","string"==typeof t?t:JSON.stringify(t))}parseItems(){try{const t=JSON.parse(this.getAttribute("items")||"[]");return Array.isArray(t)?t:[]}catch{return[]}}iconSize(t){return"s"===t?20:"l"===t?28:24}syncHostClasses(){const t=this.getAttribute("size")||"m",e=i.includes(t)?t:"m",a=this.getAttribute("background-color")||"default",s=n.includes(a)?a:"default";this.className=["designbase-wc-bottom-navigation",`designbase-wc-bottom-navigation--${e}`,`designbase-wc-bottom-navigation--${s}`,"false"!==this.getAttribute("fixed")&&"designbase-wc-bottom-navigation--fixed"].filter(Boolean).join(" ")}render(){this.syncHostClasses(),this.setAttribute("role","navigation"),this.setAttribute("aria-label",t("하단 네비게이션"));const i=this.parseItems(),n=this.getAttribute("active-item-id")||"",a=this.getAttribute("size")||"m",s=this.iconSize(a);let o=this.querySelector(".designbase-wc-bottom-navigation__container");o?o.replaceChildren():(o=document.createElement("div"),o.className="designbase-wc-bottom-navigation__container",this.replaceChildren(o)),i.forEach(t=>{const i=n===t.id||Boolean(t.isActive),a=function resolveIcon(t){if(t)return t}(i&&t.activeIcon?t.activeIcon:t.icon),r=document.createElement("button");r.type="button",r.className=["designbase-wc-bottom-navigation__item",i&&"designbase-wc-bottom-navigation__item--active",t.disabled&&"designbase-wc-bottom-navigation__item--disabled"].filter(Boolean).join(" "),r.disabled=Boolean(t.disabled),r.setAttribute("aria-label",t.label),i&&r.setAttribute("aria-current","page");const c=document.createElement("div");c.className="designbase-wc-bottom-navigation__item-content";const d=document.createElement("div");if(d.className="designbase-wc-bottom-navigation__icon-wrapper",a){const t=e(a,s);t.classList.add("designbase-wc-bottom-navigation__icon"),d.append(t)}if(void 0!==t.badge&&""!==t.badge){const e=document.createElement("db-badge");e.className="designbase-wc-bottom-navigation__badge",e.setAttribute("size","s"),e.setAttribute("variant",function mapBadgeVariant(t){return"error"===t?"danger":"warning"===t?"warning":"success"===t?"success":"info"===t?"info":"primary"===t?"primary":"secondary"}(t.badgeColor)),e.setAttribute("type","number"),e.setAttribute("count",String(t.badge)),d.append(e)}const b=document.createElement("span");b.className="designbase-wc-bottom-navigation__label",b.textContent=t.label,c.append(d,b),r.append(c),r.addEventListener("click",()=>{t.disabled||this.dispatchEvent(new CustomEvent("db-item-click",{bubbles:!0,composed:!0,detail:{item:t}}))}),o.append(r)})}}customElements.get("db-bottom-navigation")||customElements.define("db-bottom-navigation",DbBottomNavigation);export{DbBottomNavigation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDbIcon as t}from"./db-icons.js";import{createFocusTrap as e}from"../core/focus-trap.js";import{unlockScroll as s,lockScroll as i}from"../core/scroll-lock.js";import{BOTTOM_SHEET_VARIANTS as r,BOTTOM_SHEET_ANIMATIONS as o}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const n={s:40,m:60,l:80,full:100};function resolveHeightPercent(t){if(!t)return n.m;const e=n[t];if(e)return Math.min(100,Math.max(20,e));const s=Number(t);return Number.isFinite(s)?Math.min(100,Math.max(20,s)):n.m}class DbBottomSheet extends HTMLElement{constructor(){super(...arguments),this.sheetHeightPercent=n.m,this.scrollLocked=!1,this.isDragging=!1,this.isVisible=!1,this.isMounted=!1,this.keyHandler=null,this.dragState={active:!1,pointerId:-1,startY:0,startHeight:n.m,lastY:0,lastTime:0},this.handlePointerDown=t=>{"true"!==this.getAttribute("disable-drag")&&0===t.button&&(t.preventDefault(),t.currentTarget.setPointerCapture(t.pointerId),this.dragState={active:!0,pointerId:t.pointerId,startY:t.clientY,startHeight:this.sheetHeightPercent,lastY:t.clientY,lastTime:Date.now()},this.isDragging=!0,this.syncActiveClasses())},this.handlePointerMove=t=>{const e=this.dragState;if(!e.active||t.pointerId!==e.pointerId)return;t.preventDefault(),e.lastY=t.clientY,e.lastTime=Date.now();const s=window.innerHeight||1,i=(e.startY-t.clientY)/s*100,r=this.getMaxHeightLimit(resolveHeightPercent(this.getAttribute("height")));this.sheetHeightPercent=Math.min(r,Math.max(20,e.startHeight+i)),this.applySheetDimensions()},this.handlePointerUp=t=>{const e=this.dragState;if(!e.active||t.pointerId!==e.pointerId)return;const s=t.currentTarget;s.hasPointerCapture(t.pointerId)&&s.releasePointerCapture(t.pointerId),this.finishDrag()}}static get observedAttributes(){return["open","title","subtitle","height","max-height","variant","disable-backdrop-click","disable-escape-key-down","disable-drag","show-close-button","animation","animation-duration","z-index","show-backdrop","backdrop-blur","backdrop-opacity","sticky-header","sticky-footer"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}shouldMountPortal(){return this.isOpenRequested()||this.isMounted}connectedCallback(){this.style.display="contents",this.childObserver=new MutationObserver(()=>{this.isOpenRequested()&&this.render()}),this.childObserver.observe(this,{childList:!0}),this.syncOpenState()}disconnectedCallback(){this.childObserver?.disconnect(),this.childObserver=void 0,this.clearTimers(),this.detachEscape(),this.root?.remove(),this.root=void 0,this.teardownOverlay()}teardownOverlay(){this.focusTrap?.deactivate(),this.focusTrap=void 0,this.scrollLocked&&(this.scrollLocked=!1,s())}attributeChangedCallback(t){this.isConnected&&("open"!==t?("height"===t&&this.isOpenRequested()&&(this.sheetHeightPercent=resolveHeightPercent(this.getAttribute("height"))),this.shouldMountPortal()&&(this.render(),this.isMounted&&this.syncActiveClasses())):this.syncOpenState())}isOpenRequested(){return this.open}clearTimers(){this.enterFrame&&(cancelAnimationFrame(this.enterFrame),this.enterFrame=void 0),this.exitTimer&&(clearTimeout(this.exitTimer),this.exitTimer=void 0)}scheduleEnterAnimation(){this.enterFrame&&cancelAnimationFrame(this.enterFrame),this.enterFrame=requestAnimationFrame(()=>{this.enterFrame=requestAnimationFrame(()=>{this.enterFrame=void 0,this.isOpenRequested()&&this.sheet&&(this.sheet.offsetHeight,this.isVisible=!0,this.syncActiveClasses())})})}getMaxHeightLimit(t){const e=Number(this.getAttribute("max-height")||0),s=t>=100;return Math.min(100,Math.max(t,e||(s?100:90)))}close(){this.open=!1,this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0}))}attachEscape(){this.keyHandler||(this.keyHandler=t=>{"Escape"===t.key&&"true"!==this.getAttribute("disable-escape-key-down")&&this.close()},document.addEventListener("keydown",this.keyHandler))}detachEscape(){this.keyHandler&&(document.removeEventListener("keydown",this.keyHandler),this.keyHandler=null)}collectSlotted(t){const e=Array.from(this.querySelectorAll(`:scope > [slot="${t}"]`));if(e.length)return e;if("header"===t){const t=this.sheet?.querySelector(".designbase-wc-bottom-sheet__header-main");return t?Array.from(t.children):[]}if("footer"===t){const t=this.sheet?.querySelector(".designbase-wc-bottom-sheet__footer");return t?Array.from(t.children):[]}return[]}collectContentNodes(){const t=Array.from(this.children).filter(t=>{const e=t.getAttribute("slot");return!e||"default"===e});return t.length?t:this.contentEl?Array.from(this.contentEl.children):[]}finishDrag(){const t=this.dragState;if(!t.active)return;t.active=!1,this.isDragging=!1;const e=t.lastY-t.startY,s=e/Math.max(1,Date.now()-t.lastTime),i=window.innerHeight||1,r=(t.startY-t.lastY)/i*100,o=this.getMaxHeightLimit(resolveHeightPercent(this.getAttribute("height"))),n=Math.min(o,Math.max(20,t.startHeight+r));n<=22||e>72||s>.6?this.close():(this.sheetHeightPercent=n,this.applySheetDimensions(),this.syncActiveClasses())}syncOpenState(){const t=this.isOpenRequested(),s=Number(this.getAttribute("animation-duration")||400);if(this.clearTimers(),t)return this.sheetHeightPercent=resolveHeightPercent(this.getAttribute("height")),this.render(),this.isMounted=!0,this.isVisible=!1,this.syncActiveClasses(),this.root&&!this.root.isConnected&&document.body.append(this.root),this.scheduleEnterAnimation(),this.scrollLocked||(i(),this.scrollLocked=!0),this.sheet&&!this.focusTrap&&(this.focusTrap=e(this.sheet),requestAnimationFrame(()=>this.focusTrap?.activate())),void this.attachEscape();this.isVisible=!1,this.syncActiveClasses(),this.exitTimer=setTimeout(()=>{this.exitTimer=void 0,this.detachContentToHost(),this.isMounted=!1,this.syncActiveClasses(),this.root?.remove(),this.teardownOverlay(),this.detachEscape()},s),this.detachEscape()}syncActiveClasses(){if(!this.sheet)return;const t=resolveHeightPercent(this.getAttribute("height")),e=this.getAttribute("variant")||"default",s=this.getAttribute("animation")||"slide",i=r.includes(e)?e:"default",n=o.includes(s)?s:"slide",a="false"!==this.getAttribute("show-backdrop"),h=this.hasAttribute("sticky-header"),c=this.hasAttribute("sticky-footer");this.sheet.className=["designbase-wc-bottom-sheet",`designbase-wc-bottom-sheet--${i}`,`designbase-wc-bottom-sheet--${n}`,this.isMounted&&this.isVisible&&"designbase-wc-bottom-sheet--open",this.isDragging&&"designbase-wc-bottom-sheet--dragging",h&&"designbase-wc-bottom-sheet--sticky-header",c&&"designbase-wc-bottom-sheet--sticky-footer",!a&&"designbase-wc-bottom-sheet--no-backdrop",(t>=100||this.sheetHeightPercent>=100)&&"designbase-wc-bottom-sheet--full"].filter(Boolean).join(" "),this.backdrop?.classList.toggle("designbase-wc-backdrop--open",this.isMounted&&this.isVisible)}applySheetDimensions(){if(!this.sheet)return;const t=this.getMaxHeightLimit(resolveHeightPercent(this.getAttribute("height")));this.sheet.style.height=`${this.sheetHeightPercent}vh`,this.sheet.style.maxHeight=`${t}vh`}detachContentToHost(){this.contentEl&&Array.from(this.contentEl.children).forEach(t=>this.append(t));const t=this.sheet?.querySelector(".designbase-wc-bottom-sheet__header-main");t&&Array.from(t.children).forEach(t=>{"bottom-sheet-title"!==t.id&&"bottom-sheet-subtitle"!==t.id&&this.append(t)});const e=this.sheet?.querySelector(".designbase-wc-bottom-sheet__footer");e&&Array.from(e.children).forEach(t=>this.append(t))}render(){if(!this.shouldMountPortal())return;const e=this.getAttribute("title"),s=this.getAttribute("subtitle"),i="false"!==this.getAttribute("show-close-button"),r="false"!==this.getAttribute("show-backdrop"),o=this.hasAttribute("backdrop-blur"),n=this.getAttribute("backdrop-opacity")||"0.5",a=this.getAttribute("animation-duration")||"400",h=this.getAttribute("z-index")||"1000",c=this.hasAttribute("sticky-header"),d=this.hasAttribute("sticky-footer"),l=this.collectSlotted("header"),b=this.collectSlotted("footer"),m=this.collectContentNodes();if(this.root||(this.root=document.createElement("div"),this.root.setAttribute("data-wc-internal",""),this.backdrop=document.createElement("div"),this.backdrop.className="designbase-wc-backdrop designbase-wc-backdrop--bottom-sheet",this.backdrop.setAttribute("role","presentation"),this.backdrop.addEventListener("click",t=>{t.target===this.backdrop&&"true"!==this.getAttribute("disable-backdrop-click")&&this.close()}),this.sheet=document.createElement("div"),this.sheet.setAttribute("role","dialog"),this.sheet.setAttribute("aria-modal","true"),this.grabBar=document.createElement("div"),this.grabBar.className="designbase-wc-bottom-sheet__grab-bar",this.grabBar.addEventListener("pointerdown",this.handlePointerDown),this.grabBar.addEventListener("pointermove",this.handlePointerMove),this.grabBar.addEventListener("pointerup",this.handlePointerUp),this.grabBar.addEventListener("pointercancel",this.handlePointerUp),this.contentEl=document.createElement("div"),this.contentEl.className="designbase-wc-bottom-sheet__content"),this.root.replaceChildren(),r&&this.backdrop&&(this.backdrop.className=["designbase-wc-backdrop","designbase-wc-backdrop--bottom-sheet",o&&"designbase-wc-backdrop--blur"].filter(Boolean).join(" "),this.backdrop.style.setProperty("--backdrop-opacity",n),this.backdrop.style.setProperty("--bottom-sheet-animation-duration",`${a}ms`),this.backdrop.style.zIndex=h,this.backdrop.setAttribute("aria-hidden",String(!this.isOpenRequested())),this.root.append(this.backdrop)),!this.sheet||!this.grabBar||!this.contentEl)return;this.sheet.style.zIndex=String(Number(h)+1),this.sheet.style.setProperty("--bottom-sheet-animation-duration",`${a}ms`),this.applySheetDimensions(),e?this.sheet.setAttribute("aria-labelledby","bottom-sheet-title"):this.sheet.removeAttribute("aria-labelledby"),s?this.sheet.setAttribute("aria-describedby","bottom-sheet-subtitle"):this.sheet.removeAttribute("aria-describedby"),this.sheet.replaceChildren();const u="true"===this.getAttribute("disable-drag");if(this.grabBar.className=["designbase-wc-bottom-sheet__grab-bar",!u&&"designbase-wc-bottom-sheet__grab-bar--draggable"].filter(Boolean).join(" "),this.grabBar.replaceChildren(),!u){const t=document.createElement("div");t.className="designbase-wc-bottom-sheet__handle",t.setAttribute("aria-hidden","true"),this.grabBar.append(t)}this.sheet.append(this.grabBar);if(Boolean(e||s||l.length||i)){const r=document.createElement("div");r.className=["designbase-wc-bottom-sheet__header",c&&"designbase-wc-bottom-sheet__header--sticky"].filter(Boolean).join(" ");const o=document.createElement("div");if(o.className="designbase-wc-bottom-sheet__header-main",l.length)l.forEach(t=>o.append(t));else{if(e){const t=document.createElement("h2");t.id="bottom-sheet-title",t.className="designbase-wc-bottom-sheet__title",t.textContent=e,o.append(t)}if(s){const t=document.createElement("p");t.id="bottom-sheet-subtitle",t.className="designbase-wc-bottom-sheet__subtitle",t.textContent=s,o.append(t)}}if(r.append(o),i){const e=document.createElement("button");e.type="button",e.className="designbase-wc-bottom-sheet__close-button",e.setAttribute("aria-label","닫기"),e.append(t("close",20)),e.addEventListener("click",()=>this.close()),r.append(e)}this.sheet.append(r)}if(this.contentEl.replaceChildren(...m),this.sheet.append(this.contentEl),b.length){const t=document.createElement("div");t.className=["designbase-wc-bottom-sheet__footer",d&&"designbase-wc-bottom-sheet__footer--sticky"].filter(Boolean).join(" "),b.forEach(e=>t.append(e)),this.sheet.append(t)}this.root.append(this.sheet),this.isMounted&&!this.root.isConnected&&document.body.append(this.root),this.syncActiveClasses()}}customElements.get("db-bottom-sheet")||customElements.define("db-bottom-sheet",DbBottomSheet);export{DbBottomSheet};
|
|
1
|
+
import{inheritThemeScope as t}from"../core/theme-scope.js";import{dbText as e}from"../core/i18n.js";import{createDbIcon as s}from"./db-icons.js";import{createFocusTrap as i}from"../core/focus-trap.js";import{unlockScroll as r,lockScroll as o}from"../core/scroll-lock.js";import{BOTTOM_SHEET_VARIANTS as n,BOTTOM_SHEET_ANIMATIONS as h}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const a={s:40,m:60,l:80,full:100};function resolveHeightPercent(t){if(!t)return a.m;const e=a[t];if(e)return Math.min(100,Math.max(20,e));const s=Number(t);return Number.isFinite(s)?Math.min(100,Math.max(20,s)):a.m}class DbBottomSheet extends HTMLElement{constructor(){super(...arguments),this.sheetHeightPercent=a.m,this.scrollLocked=!1,this.isDragging=!1,this.isVisible=!1,this.isMounted=!1,this.keyHandler=null,this.dragState={active:!1,pointerId:-1,startY:0,startHeight:a.m,lastY:0,lastTime:0},this.handlePointerDown=t=>{"true"!==this.getAttribute("disable-drag")&&0===t.button&&(t.preventDefault(),t.currentTarget.setPointerCapture(t.pointerId),this.dragState={active:!0,pointerId:t.pointerId,startY:t.clientY,startHeight:this.sheetHeightPercent,lastY:t.clientY,lastTime:Date.now()},this.isDragging=!0,this.syncActiveClasses())},this.handlePointerMove=t=>{const e=this.dragState;if(!e.active||t.pointerId!==e.pointerId)return;t.preventDefault(),e.lastY=t.clientY,e.lastTime=Date.now();const s=window.innerHeight||1,i=(e.startY-t.clientY)/s*100,r=this.getMaxHeightLimit(resolveHeightPercent(this.getAttribute("height")));this.sheetHeightPercent=Math.min(r,Math.max(20,e.startHeight+i)),this.applySheetDimensions()},this.handlePointerUp=t=>{const e=this.dragState;if(!e.active||t.pointerId!==e.pointerId)return;const s=t.currentTarget;s.hasPointerCapture(t.pointerId)&&s.releasePointerCapture(t.pointerId),this.finishDrag()}}static get observedAttributes(){return["open","title","subtitle","height","max-height","variant","disable-backdrop-click","disable-escape-key-down","disable-drag","show-close-button","animation","animation-duration","z-index","show-backdrop","backdrop-blur","backdrop-opacity","sticky-header","sticky-footer"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(t){t?this.setAttribute("open",""):this.removeAttribute("open")}shouldMountPortal(){return this.isOpenRequested()||this.isMounted}connectedCallback(){this.style.display="contents",this.childObserver=new MutationObserver(()=>{this.isOpenRequested()&&this.render()}),this.childObserver.observe(this,{childList:!0}),this.syncOpenState()}disconnectedCallback(){this.childObserver?.disconnect(),this.childObserver=void 0,this.clearTimers(),this.detachEscape(),this.root?.remove(),this.root=void 0,this.teardownOverlay()}teardownOverlay(){this.focusTrap?.deactivate(),this.focusTrap=void 0,this.scrollLocked&&(this.scrollLocked=!1,r())}attributeChangedCallback(t){this.isConnected&&("open"!==t?("height"===t&&this.isOpenRequested()&&(this.sheetHeightPercent=resolveHeightPercent(this.getAttribute("height"))),this.shouldMountPortal()&&(this.render(),this.isMounted&&this.syncActiveClasses())):this.syncOpenState())}isOpenRequested(){return this.open}clearTimers(){this.enterFrame&&(cancelAnimationFrame(this.enterFrame),this.enterFrame=void 0),this.exitTimer&&(clearTimeout(this.exitTimer),this.exitTimer=void 0)}scheduleEnterAnimation(){this.enterFrame&&cancelAnimationFrame(this.enterFrame),this.enterFrame=requestAnimationFrame(()=>{this.enterFrame=requestAnimationFrame(()=>{this.enterFrame=void 0,this.isOpenRequested()&&this.sheet&&(this.sheet.offsetHeight,this.isVisible=!0,this.syncActiveClasses())})})}getMaxHeightLimit(t){const e=Number(this.getAttribute("max-height")||0),s=t>=100;return Math.min(100,Math.max(t,e||(s?100:90)))}close(){this.open=!1,this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0}))}attachEscape(){this.keyHandler||(this.keyHandler=t=>{"Escape"===t.key&&"true"!==this.getAttribute("disable-escape-key-down")&&this.close()},document.addEventListener("keydown",this.keyHandler))}detachEscape(){this.keyHandler&&(document.removeEventListener("keydown",this.keyHandler),this.keyHandler=null)}collectSlotted(t){const e=Array.from(this.querySelectorAll(`:scope > [slot="${t}"]`));if(e.length)return e;if("header"===t){const t=this.sheet?.querySelector(".designbase-wc-bottom-sheet__header-main");return t?Array.from(t.children):[]}if("footer"===t){const t=this.sheet?.querySelector(".designbase-wc-bottom-sheet__footer");return t?Array.from(t.children):[]}return[]}collectContentNodes(){const t=Array.from(this.children).filter(t=>{const e=t.getAttribute("slot");return!e||"default"===e});return t.length?t:this.contentEl?Array.from(this.contentEl.children):[]}finishDrag(){const t=this.dragState;if(!t.active)return;t.active=!1,this.isDragging=!1;const e=t.lastY-t.startY,s=e/Math.max(1,Date.now()-t.lastTime),i=window.innerHeight||1,r=(t.startY-t.lastY)/i*100,o=this.getMaxHeightLimit(resolveHeightPercent(this.getAttribute("height"))),n=Math.min(o,Math.max(20,t.startHeight+r));n<=22||e>72||s>.6?this.close():(this.sheetHeightPercent=n,this.applySheetDimensions(),this.syncActiveClasses())}syncOpenState(){const e=this.isOpenRequested(),s=Number(this.getAttribute("animation-duration")||400);if(this.clearTimers(),e)return this.sheetHeightPercent=resolveHeightPercent(this.getAttribute("height")),this.render(),this.isMounted=!0,this.isVisible=!1,this.syncActiveClasses(),this.root&&!this.root.isConnected&&(t(this,this.root),document.body.append(this.root)),this.scheduleEnterAnimation(),this.scrollLocked||(o(),this.scrollLocked=!0),this.sheet&&!this.focusTrap&&(this.focusTrap=i(this.sheet),requestAnimationFrame(()=>this.focusTrap?.activate())),void this.attachEscape();this.isVisible=!1,this.syncActiveClasses(),this.exitTimer=setTimeout(()=>{this.exitTimer=void 0,this.detachContentToHost(),this.isMounted=!1,this.syncActiveClasses(),this.root?.remove(),this.teardownOverlay(),this.detachEscape()},s),this.detachEscape()}syncActiveClasses(){if(!this.sheet)return;const t=resolveHeightPercent(this.getAttribute("height")),e=this.getAttribute("variant")||"default",s=this.getAttribute("animation")||"slide",i=n.includes(e)?e:"default",r=h.includes(s)?s:"slide",o="false"!==this.getAttribute("show-backdrop"),a=this.hasAttribute("sticky-header"),c=this.hasAttribute("sticky-footer");this.sheet.className=["designbase-wc-bottom-sheet",`designbase-wc-bottom-sheet--${i}`,`designbase-wc-bottom-sheet--${r}`,this.isMounted&&this.isVisible&&"designbase-wc-bottom-sheet--open",this.isDragging&&"designbase-wc-bottom-sheet--dragging",a&&"designbase-wc-bottom-sheet--sticky-header",c&&"designbase-wc-bottom-sheet--sticky-footer",!o&&"designbase-wc-bottom-sheet--no-backdrop",(t>=100||this.sheetHeightPercent>=100)&&"designbase-wc-bottom-sheet--full"].filter(Boolean).join(" "),this.backdrop?.classList.toggle("designbase-wc-backdrop--open",this.isMounted&&this.isVisible)}applySheetDimensions(){if(!this.sheet)return;const t=this.getMaxHeightLimit(resolveHeightPercent(this.getAttribute("height")));this.sheet.style.height=`${this.sheetHeightPercent}vh`,this.sheet.style.maxHeight=`${t}vh`}detachContentToHost(){this.contentEl&&Array.from(this.contentEl.children).forEach(t=>this.append(t));const t=this.sheet?.querySelector(".designbase-wc-bottom-sheet__header-main");t&&Array.from(t.children).forEach(t=>{"bottom-sheet-title"!==t.id&&"bottom-sheet-subtitle"!==t.id&&this.append(t)});const e=this.sheet?.querySelector(".designbase-wc-bottom-sheet__footer");e&&Array.from(e.children).forEach(t=>this.append(t))}render(){if(!this.shouldMountPortal())return;const i=this.getAttribute("title"),r=this.getAttribute("subtitle"),o="false"!==this.getAttribute("show-close-button"),n="false"!==this.getAttribute("show-backdrop"),h=this.hasAttribute("backdrop-blur"),a=this.getAttribute("backdrop-opacity")||"0.5",c=this.getAttribute("animation-duration")||"400",d=this.getAttribute("z-index")||"1000",l=this.hasAttribute("sticky-header"),b=this.hasAttribute("sticky-footer"),m=this.collectSlotted("header"),u=this.collectSlotted("footer"),p=this.collectContentNodes();if(this.root||(this.root=document.createElement("div"),this.root.setAttribute("data-wc-internal",""),this.backdrop=document.createElement("div"),this.backdrop.className="designbase-wc-backdrop designbase-wc-backdrop--bottom-sheet",this.backdrop.setAttribute("role","presentation"),this.backdrop.addEventListener("click",t=>{t.target===this.backdrop&&"true"!==this.getAttribute("disable-backdrop-click")&&this.close()}),this.sheet=document.createElement("div"),this.sheet.setAttribute("role","dialog"),this.sheet.setAttribute("aria-modal","true"),this.grabBar=document.createElement("div"),this.grabBar.className="designbase-wc-bottom-sheet__grab-bar",this.grabBar.addEventListener("pointerdown",this.handlePointerDown),this.grabBar.addEventListener("pointermove",this.handlePointerMove),this.grabBar.addEventListener("pointerup",this.handlePointerUp),this.grabBar.addEventListener("pointercancel",this.handlePointerUp),this.contentEl=document.createElement("div"),this.contentEl.className="designbase-wc-bottom-sheet__content"),this.root.replaceChildren(),n&&this.backdrop&&(this.backdrop.className=["designbase-wc-backdrop","designbase-wc-backdrop--bottom-sheet",h&&"designbase-wc-backdrop--blur"].filter(Boolean).join(" "),this.backdrop.style.setProperty("--backdrop-opacity",a),this.backdrop.style.setProperty("--bottom-sheet-animation-duration",`${c}ms`),this.backdrop.style.zIndex=d,this.backdrop.setAttribute("aria-hidden",String(!this.isOpenRequested())),this.root.append(this.backdrop)),!this.sheet||!this.grabBar||!this.contentEl)return;this.sheet.style.zIndex=String(Number(d)+1),this.sheet.style.setProperty("--bottom-sheet-animation-duration",`${c}ms`),this.applySheetDimensions(),i?this.sheet.setAttribute("aria-labelledby","bottom-sheet-title"):this.sheet.removeAttribute("aria-labelledby"),r?this.sheet.setAttribute("aria-describedby","bottom-sheet-subtitle"):this.sheet.removeAttribute("aria-describedby"),this.sheet.replaceChildren();const g="true"===this.getAttribute("disable-drag");if(this.grabBar.className=["designbase-wc-bottom-sheet__grab-bar",!g&&"designbase-wc-bottom-sheet__grab-bar--draggable"].filter(Boolean).join(" "),this.grabBar.replaceChildren(),!g){const t=document.createElement("div");t.className="designbase-wc-bottom-sheet__handle",t.setAttribute("aria-hidden","true"),this.grabBar.append(t)}this.sheet.append(this.grabBar);if(Boolean(i||r||m.length||o)){const t=document.createElement("div");t.className=["designbase-wc-bottom-sheet__header",l&&"designbase-wc-bottom-sheet__header--sticky"].filter(Boolean).join(" ");const n=document.createElement("div");if(n.className="designbase-wc-bottom-sheet__header-main",m.length)m.forEach(t=>n.append(t));else{if(i){const t=document.createElement("h2");t.id="bottom-sheet-title",t.className="designbase-wc-bottom-sheet__title",t.textContent=i,n.append(t)}if(r){const t=document.createElement("p");t.id="bottom-sheet-subtitle",t.className="designbase-wc-bottom-sheet__subtitle",t.textContent=r,n.append(t)}}if(t.append(n),o){const i=document.createElement("button");i.type="button",i.className="designbase-wc-bottom-sheet__close-button",i.setAttribute("aria-label",e("닫기")),i.append(s("close",20)),i.addEventListener("click",()=>this.close()),t.append(i)}this.sheet.append(t)}if(this.contentEl.replaceChildren(...p),this.sheet.append(this.contentEl),u.length){const t=document.createElement("div");t.className=["designbase-wc-bottom-sheet__footer",b&&"designbase-wc-bottom-sheet__footer--sticky"].filter(Boolean).join(" "),u.forEach(e=>t.append(e)),this.sheet.append(t)}this.root.append(this.sheet),this.isMounted&&!this.root.isConnected&&(t(this,this.root),document.body.append(this.root)),this.syncActiveClasses()}}customElements.get("db-bottom-sheet")||customElements.define("db-bottom-sheet",DbBottomSheet);export{DbBottomSheet};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{dbText as e}from"../core/i18n.js";import{createDbIcon as t}from"./db-icons.js";import{sanitizeHref as n}from"../core/safe-url.js";import{coerceToContract as s}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{BREADCRUMBS_VARIANTS as a,BREADCRUMBS_SIZES as r}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const i={s:12,m:14,l:16};class DbBreadcrumbs extends HTMLElement{constructor(){super(...arguments),this.openMenuId=null,this.onDocumentMouseDown=null,this.onDocumentKeyDown=null}static get observedAttributes(){return["items","size","variant","breadcrumb-style","max-items","menu-dropdown","max-label-length"]}get items(){try{return JSON.parse(this.getAttribute("items")||"[]")}catch{return[]}}set items(e){this.setAttribute("items","string"==typeof e?e:JSON.stringify(e))}connectedCallback(){this.render()}disconnectedCallback(){this.removeGlobalListeners()}attributeChangedCallback(){this.isConnected&&(this.openMenuId=null,this.render())}get menuDropdown(){return this.hasAttribute("menu-dropdown")}get maxLabelLength(){const e=Number(this.getAttribute("max-label-length"));return Number.isFinite(e)&&e>0?e:12}get resolvedVariant(){return s(this.getAttribute("variant")||this.getAttribute("breadcrumb-style"),a,"default")}itemId(e,t){return e.id||`item-${t}`}menuItemId(e,t){return e.id||`menu-${t}`}visibleItems(){const e=this.items,t=Number(this.getAttribute("max-items")||0);if(!t||e.length<=t)return e;const n=e[0],s=e[e.length-1],a=e.slice(1,-1),r=t-2;if(r<=0)return[n,s];const i=Math.floor(a.length/2)-Math.floor(r/2);return[n,...a.slice(i,i+r),s]}shouldUseDropdown(e){return this.menuDropdown&&Boolean(e.menu?.length)}closeMenu(){this.openMenuId&&(this.openMenuId=null,this.removeGlobalListeners(),this.updateDropdownStates())}openMenu(e){this.openMenuId=e,this.addGlobalListeners(),this.updateDropdownStates()}toggleMenu(e){this.openMenuId===e?this.closeMenu():this.openMenu(e)}addGlobalListeners(){this.onDocumentMouseDown||(this.onDocumentMouseDown=e=>{this.contains(e.target)||this.closeMenu()},this.onDocumentKeyDown=e=>{"Escape"===e.key&&this.closeMenu()},document.addEventListener("mousedown",this.onDocumentMouseDown),document.addEventListener("keydown",this.onDocumentKeyDown))}removeGlobalListeners(){this.onDocumentMouseDown&&(document.removeEventListener("mousedown",this.onDocumentMouseDown),this.onDocumentMouseDown=null),this.onDocumentKeyDown&&(document.removeEventListener("keydown",this.onDocumentKeyDown),this.onDocumentKeyDown=null)}updateDropdownStates(){this.querySelectorAll("[data-breadcrumb-dropdown]").forEach(e=>{const t=e.dataset.breadcrumbDropdown||"",n=this.openMenuId===t;e.classList.toggle("designbase-wc-breadcrumbs__dropdown--open",n);const s=e.querySelector(".designbase-wc-breadcrumbs__trigger");s&&s.setAttribute("aria-expanded",String(n))})}createLabel(e){const t=function formatBreadcrumbLabel(e,t){return!t||e.length<=t?{text:e,full:e,truncated:!1}:{text:`${e.slice(0,t)}...`,full:e,truncated:!0}}(e,this.maxLabelLength),n=document.createElement("span");return n.className="designbase-wc-breadcrumbs__label",n.textContent=t.text,t.truncated&&n.setAttribute("title",t.full),n}createMenuItem(e,s,a){const r=e.href&&!e.disabled?document.createElement("a"):document.createElement("button");if(r.className=["designbase-wc-breadcrumbs__menu-item",e.active&&"designbase-wc-breadcrumbs__menu-item--active",e.disabled&&"designbase-wc-breadcrumbs__menu-item--disabled"].filter(Boolean).join(" "),r.setAttribute("role","menuitem"),r instanceof HTMLButtonElement?(r.type="button",r.disabled=Boolean(e.disabled)):r.href=n(e.href,"#"),e.icon){const n=document.createElement("span");n.className="designbase-wc-breadcrumbs__icon",n.append(t(e.icon,16)),r.append(n)}return r.append(this.createLabel(e.label)),r.addEventListener("click",t=>{e.disabled?t.preventDefault():(this.closeMenu(),this.dispatchEvent(new CustomEvent("db-menu-click",{detail:{menuItem:{...e,id:this.menuItemId(e,s)},parentItem:a},bubbles:!0,composed:!0})))}),r}createDropdownItem(e,n,s,a){const r=this.itemId(e,n),i=this.openMenuId===r,o=document.createElement("div");o.className=["designbase-wc-breadcrumbs__dropdown",i&&"designbase-wc-breadcrumbs__dropdown--open"].filter(Boolean).join(" "),o.dataset.breadcrumbDropdown=r;const d=document.createElement("button");if(d.type="button",d.className=["designbase-wc-breadcrumbs__trigger",(s||e.active)&&"designbase-wc-breadcrumbs__trigger--active",e.disabled&&"designbase-wc-breadcrumbs__trigger--disabled"].filter(Boolean).join(" "),d.setAttribute("aria-haspopup","menu"),d.setAttribute("aria-expanded",String(i)),d.disabled=Boolean(e.disabled),e.icon){const n=document.createElement("span");n.className="designbase-wc-breadcrumbs__icon",n.append(t(e.icon,16)),d.append(n)}d.append(this.createLabel(e.label));const c=document.createElement("span");c.className="designbase-wc-breadcrumbs__chevron",c.setAttribute("aria-hidden","true"),c.append(t("chevron-down",a)),d.append(c),d.addEventListener("click",t=>{t.stopPropagation(),e.disabled||this.toggleMenu(r)}),o.append(d);const u=document.createElement("div");return u.className="designbase-wc-breadcrumbs__menu",u.setAttribute("role","menu"),e.menu?.forEach((t,n)=>{u.append(this.createMenuItem(t,n,e))}),o.append(u),o}createStandardItem(e,s,a){const r=!e.href||a||e.disabled?document.createElement("span"):document.createElement("a");if(r.className=r instanceof HTMLAnchorElement?["designbase-wc-breadcrumbs__link",e.active&&"designbase-wc-breadcrumbs__link--active",e.disabled&&"designbase-wc-breadcrumbs__link--disabled"].filter(Boolean).join(" "):["designbase-wc-breadcrumbs__text",a&&"designbase-wc-breadcrumbs__text--active",e.disabled&&"designbase-wc-breadcrumbs__text--disabled"].filter(Boolean).join(" "),e.icon){const n=document.createElement("span");n.className="designbase-wc-breadcrumbs__icon",n.append(t(e.icon,16)),r.append(n)}return r.append(this.createLabel(e.label)),r instanceof HTMLAnchorElement&&(r.href=n(e.href,"#")),r.addEventListener("click",t=>{(e.disabled||e.active||a)&&t.preventDefault(),this.dispatchEvent(new CustomEvent("db-click",{detail:{item:e},bubbles:!0,composed:!0}))}),r}render(){const n=s(this.getAttribute("size"),r,"m"),a=this.resolvedVariant,o=this.visibleItems(),d=o.length<this.items.length,c=i[n]||14;this.className=["designbase-wc-breadcrumbs",`designbase-wc-breadcrumbs--${n}`,`designbase-wc-breadcrumbs--${a}`,d&&"designbase-wc-breadcrumbs--collapsed"].filter(Boolean).join(" "),this.setAttribute("role","navigation"),this.setAttribute("aria-label",e("브레드크럼 네비게이션")),this.replaceChildren();const u=document.createElement("ol");u.className="designbase-wc-breadcrumbs__list",o.forEach((e,n)=>{const s=n===o.length-1,a=document.createElement("li");if(a.className="designbase-wc-breadcrumbs__item",this.shouldUseDropdown(e)?a.append(this.createDropdownItem(e,n,s,c)):a.append(this.createStandardItem(e,n,s)),!s){const e=document.createElement("span");e.className="designbase-wc-breadcrumbs__separator",e.setAttribute("aria-hidden","true"),e.append(t("chevron-right",16)),a.append(e)}u.append(a)}),this.append(u)}}customElements.get("db-breadcrumbs")||customElements.define("db-breadcrumbs",DbBreadcrumbs);export{DbBreadcrumbs};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDbIcon as e,getDbComponentIconSize as t}from"./db-icons.js";import{parseISODate as a,toISODate as n}from"./date-picker-utils.js";import"./db-modal.js";import"./db-input.js";import"./db-select.js";import"./db-date-picker.js";import"./db-time-picker.js";import"./db-button.js";const s="designbase-wc-calendar",i=[{value:"meeting",label:"회의"},{value:"task",label:"업무"},{value:"reminder",label:"알림"},{value:"birthday",label:"생일"},{value:"holiday",label:"휴일"},{value:"custom",label:"기타"}],d=[{value:"#17a2b8",label:"청록"},{value:"#0d6efd",label:"파랑"},{value:"#198754",label:"초록"},{value:"#ffc107",label:"노랑"},{value:"#dc3545",label:"빨강"},{value:"#6f42c1",label:"보라"}];class DbCalendar extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.currentView="month",this.selectedDate=new Date,this._events=[],this.showEventModal=!1,this.selectedEvent=null,this.isEditing=!1,this.draggedEvent=null,this.dragOverDate=null,this.selectedDateRange={start:null,end:null},this.eventForm={title:"",description:"",startTime:"09:00",endTime:"10:00",type:"meeting",color:"#17a2b8",isAllDay:!1,location:""}}static get observedAttributes(){return["view","current-date","events","locale","show-weekends","highlight-today","show-outside-days"]}connectedCallback(){this.built||this.build(),this.readAttributes(),this.render()}attributeChangedCallback(){this.built&&(this.readAttributes(),this.render())}get locale(){return this.getAttribute("locale")||"ko-KR"}get showWeekends(){return"false"!==this.getAttribute("show-weekends")}get highlightToday(){return"false"!==this.getAttribute("highlight-today")}get showOutsideDays(){return"false"!==this.getAttribute("show-outside-days")}get events(){return this._events}set events(e){"string"!=typeof e?(this._events=Array.isArray(e)?e:[],this.setAttribute("events",JSON.stringify(this._events))):this.setAttribute("events",e)}build(){this.built=!0,this.headerEl=document.createElement("div"),this.headerEl.className=`${s}__header`,this.bodyEl=document.createElement("div"),this.bodyEl.className=`${s}__body`,this.modalEl=document.createElement("db-modal"),this.modalEl.setAttribute("size","m"),this.modalEl.addEventListener("db-close",()=>this.closeModal())}readAttributes(){this.currentView="month";const e=a(this.getAttribute("current-date"));e&&(this.selectedDate=e);const t=this.getAttribute("events");if(t)try{const e=JSON.parse(t);this._events=Array.isArray(e)?e:[]}catch{this._events=[]}else this._events=[]}isSameDate(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}eventsForDate(e){return this._events.filter(t=>{const n=a(t.date);return!!n&&this.isSameDate(n,e)})}emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}handleViewChange(e){this.currentView="month",this.emit("db-view-change",{view:e}),this.render()}shiftMonth(e){const t=new Date(this.selectedDate);t.setMonth(t.getMonth()+e),this.selectedDate=t,this.emit("db-month-change",{date:n(t)}),this.render()}shiftYear(e){const t=new Date(this.selectedDate);t.setFullYear(t.getFullYear()+e),this.selectedDate=t,this.emit("db-month-change",{date:n(t)}),this.render()}handleDateClick(e){this.selectedDate=e,this.emit("db-date-click",{date:n(e)}),!this.selectedDateRange.start||this.selectedDateRange.start&&this.selectedDateRange.end?this.selectedDateRange={start:e,end:null}:this.selectedDateRange.start&&!this.selectedDateRange.end&&(e<this.selectedDateRange.start?this.selectedDateRange={start:e,end:this.selectedDateRange.start}:this.selectedDateRange={start:this.selectedDateRange.start,end:e}),this.openAddModal(e)}handleDragStart(e,t){this.draggedEvent=e,t.dataTransfer?.setData("text/plain",e.id),t.dataTransfer?.setData("application/json",JSON.stringify(e)),t.dataTransfer&&(t.dataTransfer.effectAllowed="move")}handleDragOver(e,t){t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.dragOverDate=e,this.render()}handleDragLeave(e){const t=e.relatedTarget,a=e.currentTarget;a&&t&&a.contains(t)||(this.dragOverDate=null,this.render())}handleDrop(e,t){if(t.preventDefault(),!this.draggedEvent)return;const a={...this.draggedEvent,date:n(e)};this.emit("db-event-edit",{event:a}),this.draggedEvent=null,this.dragOverDate=null,this.render()}handleDragEnd(){this.draggedEvent=null,this.dragOverDate=null,this.render()}handleEventClick(e,t){t.stopPropagation(),this.selectedEvent=e,this.isEditing=!0;const n=a(e.date);n&&(this.selectedDate=n),this.eventForm={title:e.title,description:e.description||"",startTime:e.startTime||"09:00",endTime:e.endTime||"10:00",type:e.type,color:e.color||"#17a2b8",isAllDay:e.isAllDay||!1,location:e.location||""},this.emit("db-event-click",{event:e}),this.showEventModal=!0,this.render()}openAddModal(e){this.selectedDate=e,this.selectedEvent=null,this.isEditing=!1,this.eventForm={title:"",description:"",startTime:"09:00",endTime:"10:00",type:"meeting",color:"#17a2b8",isAllDay:!1,location:""},this.showEventModal=!0,this.render()}closeModal(){this.showEventModal=!1,this.selectedEvent=null,this.isEditing=!1,this.render()}saveEvent(){if(!this.eventForm.title.trim())return void window.alert("제목을 입력해주세요.");const e={title:this.eventForm.title.trim(),description:this.eventForm.description,date:n(this.selectedDate),startTime:this.eventForm.startTime,endTime:this.eventForm.endTime,type:this.eventForm.type,color:this.eventForm.color,isAllDay:this.eventForm.isAllDay,location:this.eventForm.location};if(this.isEditing&&this.selectedEvent){const t={...this.selectedEvent,...e};this.emit("db-event-edit",{event:t})}else this.emit("db-event-add",{event:e});this.closeModal()}deleteEvent(){this.selectedEvent&&window.confirm("정말로 이 일정을 삭제하시겠습니까?")&&(this.emit("db-event-delete",{eventId:this.selectedEvent.id}),this.closeModal())}renderHeader(){if(!this.headerEl)return;this.headerEl.replaceChildren();const a=document.createElement("div");a.className=`${s}__navigation`;const n=t("m"),i=document.createElement("button");i.type="button",i.className=`${s}__nav-button`,i.setAttribute("aria-label","이전"),i.appendChild(e("chevron-left",n)),i.addEventListener("click",()=>{this.shiftMonth(-1)});const d=document.createElement("div");d.className=`${s}__title`,d.textContent=this.selectedDate.toLocaleDateString(this.locale,{year:"numeric",month:"long"});const l=document.createElement("button");l.type="button",l.className=`${s}__nav-button`,l.setAttribute("aria-label","다음"),l.appendChild(e("chevron-right",n)),l.addEventListener("click",()=>{this.shiftMonth(1)}),a.append(i,d,l),this.headerEl.appendChild(a)}renderMonthView(){const e=document.createElement("div");e.className=`${s}__month-view`;const t=document.createElement("div");t.className=`${s}__weekdays`,["일","월","화","수","목","금","토"].forEach(e=>{const a=document.createElement("div");a.className=`${s}__weekday`,a.textContent=e,t.appendChild(a)}),e.appendChild(t);const a=document.createElement("div");a.className=`${s}__days`;const n=this.selectedDate.getFullYear(),i=this.selectedDate.getMonth(),d=new Date(n,i,1),l=new Date(d);l.setDate(l.getDate()-d.getDay());const r=new Date;for(let e=0;e<42;e+=1){const t=new Date(l);t.setDate(l.getDate()+e);const n=t.getMonth()===i;if(!this.showOutsideDays&&!n)continue;const d=0===t.getDay()||6===t.getDay();if(!this.showWeekends&&d)continue;const o=document.createElement("div"),c=this.selectedDateRange.start&&this.selectedDateRange.end&&t>=this.selectedDateRange.start&&t<=this.selectedDateRange.end,h=this.selectedDateRange.start&&t.toDateString()===this.selectedDateRange.start.toDateString(),m=this.selectedDateRange.end&&t.toDateString()===this.selectedDateRange.end.toDateString(),u=Boolean(c&&!h&&!m);o.className=[`${s}__day`,n&&`${s}__day--current-month`,this.highlightToday&&t.toDateString()===r.toDateString()&&`${s}__day--today`,this.isSameDate(t,this.selectedDate)&&`${s}__day--selected`,h&&`${s}__day--selected--start`,m&&`${s}__day--selected--end`,u&&`${s}__day--selected--middle`,!this.showWeekends&&d&&`${s}__day--weekend`].filter(Boolean).join(" "),o.addEventListener("click",()=>this.handleDateClick(t));const v=document.createElement("span");v.className=`${s}__day-number`,v.textContent=String(t.getDate()),o.appendChild(v);const p=this.eventsForDate(t);if(p.length){const e=document.createElement("div");if(e.className=`${s}__day-events`,p.slice(0,2).forEach(t=>{const a=document.createElement("div");a.className=[`${s}__event-bar`,`${s}__event-bar--${t.type}`].filter(Boolean).join(" "),t.color&&(a.style.backgroundColor=t.color),this.draggedEvent?.id===t.id&&a.classList.add(`${s}__event-bar--dragging`),a.title=t.title,a.draggable=!0;const n=document.createElement("span");n.className=`${s}__event-title`,n.textContent=t.title,a.appendChild(n),a.addEventListener("click",e=>this.handleEventClick(t,e)),a.addEventListener("dragstart",e=>this.handleDragStart(t,e)),a.addEventListener("dragend",()=>this.handleDragEnd()),e.appendChild(a)}),p.length>2){const t=document.createElement("div");t.className=`${s}__more-events`,t.textContent=`+${p.length-2} more`,e.appendChild(t)}o.appendChild(e)}const g=document.createElement("div");g.className=[`${s}__drop-zone`,this.dragOverDate&&this.isSameDate(this.dragOverDate,t)&&`${s}__drop-zone--active`].filter(Boolean).join(" "),g.addEventListener("dragover",e=>this.handleDragOver(t,e)),g.addEventListener("dragleave",e=>this.handleDragLeave(e)),g.addEventListener("drop",e=>this.handleDrop(t,e)),o.appendChild(g),a.appendChild(o)}return e.appendChild(a),e}renderYearView(){const e=document.createElement("div");e.className=`${s}__year-view`;const t=this.selectedDate.getFullYear();for(let n=0;n<12;n+=1){const i=new Date(t,n,1),d=this._events.filter(e=>{const s=a(e.date);return s&&s.getFullYear()===t&&s.getMonth()===n}),l=document.createElement("div");l.className=`${s}__year-month`,l.addEventListener("click",()=>{this.selectedDate=i,this.handleViewChange("month")});const r=document.createElement("h3");if(r.className=`${s}__year-month-title`,r.textContent=i.toLocaleDateString(this.locale,{month:"long"}),l.appendChild(r),d.length){const e=document.createElement("div");if(e.className=`${s}__year-month-events`,d.slice(0,4).forEach(t=>{const a=document.createElement("span");a.className=[`${s}__year-event`,`${s}__year-event--${t.type}`].join(" "),t.color&&(a.style.backgroundColor=t.color),e.appendChild(a)}),d.length>4){const t=document.createElement("span");t.className=`${s}__year-more-events`,t.textContent=`+${d.length-4} more`,e.appendChild(t)}l.appendChild(e)}e.appendChild(l)}return e}renderWeekView(){const e=document.createElement("div");e.className=`${s}__week-view`;const t=new Date,a=new Date(this.selectedDate);a.setDate(this.selectedDate.getDate()-this.selectedDate.getDay());const n=document.createElement("div");n.className=`${s}__week-header`;const i=document.createElement("div");i.className=`${s}__time-column-header`,n.appendChild(i);for(let e=0;e<7;e+=1){const i=new Date(a);i.setDate(a.getDate()+e);const d=document.createElement("div");d.className=[`${s}__week-day-header`,i.toDateString()===t.toDateString()&&`${s}__week-day-header--today`].filter(Boolean).join(" ");const l=document.createElement("span");l.className=`${s}__week-day-name`,l.textContent=i.toLocaleDateString(this.locale,{weekday:"short"});const r=document.createElement("span");r.className=`${s}__week-day-number`,r.textContent=String(i.getDate()),d.append(l,r),n.appendChild(d)}e.appendChild(n);const d=document.createElement("div");d.className=`${s}__week-grid`;const l=document.createElement("div");l.className=`${s}__week-time-column`;for(let e=6;e<=22;e+=1){const t=document.createElement("div");t.className=`${s}__time-slot`;const a=document.createElement("span");a.className=`${s}__time-label`,a.textContent=`${String(e).padStart(2,"0")}:00`,t.appendChild(a),l.appendChild(t)}d.appendChild(l);const r=document.createElement("div");r.className=`${s}__week-columns`;for(let e=0;e<7;e+=1){const t=new Date(a);t.setDate(a.getDate()+e);const n=document.createElement("div");n.className=`${s}__week-column`;for(let e=6;e<=22;e+=1){const a=document.createElement("div");a.className=`${s}__week-cell`,a.title=`${t.toLocaleDateString()} ${String(e).padStart(2,"0")}:00`,a.addEventListener("click",()=>{this.selectedDate=new Date(t),this.eventForm.startTime=`${String(e).padStart(2,"0")}:00`,this.eventForm.endTime=`${String(e+1).padStart(2,"0")}:00`,this.openAddModal(this.selectedDate)}),n.appendChild(a)}this.eventsForDate(t).forEach(e=>{if(!e.startTime)return;const[t,a]=e.startTime.split(":").map(Number),i=.8*(60*(t-6)+(a||0)),d=(e.endTime||e.startTime).split(":").map(Number),l=60*(d[0]||t)+(d[1]||0),r=60*t+(a||0),o=Math.max(20,48*(l-r)/60),c=document.createElement("div");c.className=[`${s}__week-event`,`${s}__week-event--${e.type}`].filter(Boolean).join(" "),c.textContent=e.title,c.title=e.title,c.style.backgroundColor=e.color||"#17a2b8",c.style.top=`${i}px`,c.style.height=`${o}px`,c.addEventListener("click",t=>this.handleEventClick(e,t)),n.appendChild(c)}),r.appendChild(n)}return d.appendChild(r),e.appendChild(d),e}renderModal(){if(!this.modalEl)return;if(this.modalEl.replaceChildren(),!this.showEventModal)return void this.modalEl.removeAttribute("open");this.modalEl.setAttribute("open","true"),this.modalEl.setAttribute("title",this.isEditing?"일정 편집":"새 일정 추가");const e=document.createElement("div");e.className=`${s}__event-form`;const t=document.createElement("db-input");t.setAttribute("label","제목 *"),t.setAttribute("placeholder","일정 제목을 입력하세요"),t.setAttribute("full-width",""),t.setAttribute("value",this.eventForm.title),t.addEventListener("db-input",e=>{this.eventForm.title=e.detail.value});const l=document.createElement("db-input");l.setAttribute("label","설명"),l.setAttribute("placeholder","일정 설명을 입력하세요"),l.setAttribute("full-width",""),l.setAttribute("value",this.eventForm.description),l.addEventListener("db-input",e=>{this.eventForm.description=e.detail.value});const r=document.createElement("db-date-picker");r.setAttribute("label","날짜"),r.setAttribute("full-width",""),r.setAttribute("value",n(this.selectedDate)),r.addEventListener("db-change",e=>{const t=a(e.detail.value);t&&(this.selectedDate=t)});const o=document.createElement("db-select");o.setAttribute("label","일정 타입"),o.setAttribute("full-width",""),o.setAttribute("options",JSON.stringify(i)),o.setAttribute("value",this.eventForm.type),o.addEventListener("db-change",e=>{this.eventForm.type=e.detail.value});const c=document.createElement("db-select");c.setAttribute("label","색상"),c.setAttribute("full-width",""),c.setAttribute("options",JSON.stringify(d)),c.setAttribute("value",this.eventForm.color),c.addEventListener("db-change",e=>{this.eventForm.color=e.detail.value});const h=document.createElement("db-time-picker");h.setAttribute("label","시작 시간"),h.setAttribute("full-width",""),h.setAttribute("value",this.eventForm.startTime),h.addEventListener("db-change",e=>{this.eventForm.startTime=e.detail.value});const m=document.createElement("db-time-picker");m.setAttribute("label","종료 시간"),m.setAttribute("full-width",""),m.setAttribute("value",this.eventForm.endTime),m.addEventListener("db-change",e=>{this.eventForm.endTime=e.detail.value}),e.append(t,l,r,o,c,h,m);const u=document.createElement("div");u.className="designbase-wc-modal__body",u.setAttribute("data-modal-part","body"),u.appendChild(e);const v=document.createElement("div");v.className="designbase-wc-modal__footer",v.setAttribute("data-modal-part","footer");const p=document.createElement("div");if(p.className=`${s}__modal-actions`,this.isEditing){const e=document.createElement("db-button");e.setAttribute("variant","destructive"),e.textContent="삭제",e.addEventListener("click",()=>this.deleteEvent()),p.appendChild(e)}const g=document.createElement("div");g.className=`${s}__modal-buttons`;const b=document.createElement("db-button");b.setAttribute("variant","secondary"),b.textContent="취소",b.addEventListener("click",()=>this.closeModal());const E=document.createElement("db-button");E.setAttribute("variant","primary"),E.textContent=this.isEditing?"수정":"저장",E.addEventListener("click",()=>this.saveEvent()),g.append(b,E),p.appendChild(g),v.appendChild(p),this.modalEl.append(u,v)}render(){this.className=s,this.replaceChildren(),this.headerEl&&this.bodyEl&&(this.renderHeader(),this.bodyEl.replaceChildren(),this.bodyEl.appendChild(this.renderMonthView()),this.append(this.headerEl,this.bodyEl),this.renderModal(),this.showEventModal&&this.modalEl&&this.appendChild(this.modalEl))}}customElements.get("db-calendar")||customElements.define("db-calendar",DbCalendar);export{DbCalendar};
|
|
1
|
+
import{dbText as e,getDbLocale as t}from"../core/i18n.js";import{createDbIcon as a,getDbComponentIconSize as n}from"./db-icons.js";import{parseISODate as s,toISODate as i}from"./date-picker-utils.js";import"./db-modal.js";import"./db-input.js";import"./db-select.js";import"./db-date-picker.js";import"./db-time-picker.js";import"./db-button.js";const d="designbase-wc-calendar";class DbCalendar extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.currentView="month",this.selectedDate=new Date,this._events=[],this.showEventModal=!1,this.selectedEvent=null,this.isEditing=!1,this.draggedEvent=null,this.dragOverDate=null,this.selectedDateRange={start:null,end:null},this.eventForm={title:"",description:"",startTime:"09:00",endTime:"10:00",type:"meeting",color:"#17a2b8",isAllDay:!1,location:""}}static get observedAttributes(){return["view","current-date","events","locale","show-weekends","highlight-today","show-outside-days"]}connectedCallback(){this.built||this.build(),this.readAttributes(),this.render()}attributeChangedCallback(){this.built&&(this.readAttributes(),this.render())}get locale(){return this.getAttribute("locale")||("ko"===t()?"ko-KR":"en-US")}get showWeekends(){return"false"!==this.getAttribute("show-weekends")}get highlightToday(){return"false"!==this.getAttribute("highlight-today")}get showOutsideDays(){return"false"!==this.getAttribute("show-outside-days")}get events(){return this._events}set events(e){"string"!=typeof e?(this._events=Array.isArray(e)?e:[],this.setAttribute("events",JSON.stringify(this._events))):this.setAttribute("events",e)}build(){this.built=!0,this.headerEl=document.createElement("div"),this.headerEl.className=`${d}__header`,this.bodyEl=document.createElement("div"),this.bodyEl.className=`${d}__body`,this.modalEl=document.createElement("db-modal"),this.modalEl.setAttribute("size","m"),this.modalEl.addEventListener("db-close",()=>this.closeModal())}readAttributes(){this.currentView="month";const e=s(this.getAttribute("current-date"));e&&(this.selectedDate=e);const t=this.getAttribute("events");if(t)try{const e=JSON.parse(t);this._events=Array.isArray(e)?e:[]}catch{this._events=[]}else this._events=[]}isSameDate(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}eventsForDate(e){return this._events.filter(t=>{const a=s(t.date);return!!a&&this.isSameDate(a,e)})}emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}handleViewChange(e){this.currentView="month",this.emit("db-view-change",{view:e}),this.render()}shiftMonth(e){const t=new Date(this.selectedDate);t.setMonth(t.getMonth()+e),this.selectedDate=t,this.emit("db-month-change",{date:i(t)}),this.render()}shiftYear(e){const t=new Date(this.selectedDate);t.setFullYear(t.getFullYear()+e),this.selectedDate=t,this.emit("db-month-change",{date:i(t)}),this.render()}handleDateClick(e){this.selectedDate=e,this.emit("db-date-click",{date:i(e)}),!this.selectedDateRange.start||this.selectedDateRange.start&&this.selectedDateRange.end?this.selectedDateRange={start:e,end:null}:this.selectedDateRange.start&&!this.selectedDateRange.end&&(e<this.selectedDateRange.start?this.selectedDateRange={start:e,end:this.selectedDateRange.start}:this.selectedDateRange={start:this.selectedDateRange.start,end:e}),this.openAddModal(e)}handleDragStart(e,t){this.draggedEvent=e,t.dataTransfer?.setData("text/plain",e.id),t.dataTransfer?.setData("application/json",JSON.stringify(e)),t.dataTransfer&&(t.dataTransfer.effectAllowed="move")}handleDragOver(e,t){t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.dragOverDate=e,this.render()}handleDragLeave(e){const t=e.relatedTarget,a=e.currentTarget;a&&t&&a.contains(t)||(this.dragOverDate=null,this.render())}handleDrop(e,t){if(t.preventDefault(),!this.draggedEvent)return;const a={...this.draggedEvent,date:i(e)};this.emit("db-event-edit",{event:a}),this.draggedEvent=null,this.dragOverDate=null,this.render()}handleDragEnd(){this.draggedEvent=null,this.dragOverDate=null,this.render()}handleEventClick(e,t){t.stopPropagation(),this.selectedEvent=e,this.isEditing=!0;const a=s(e.date);a&&(this.selectedDate=a),this.eventForm={title:e.title,description:e.description||"",startTime:e.startTime||"09:00",endTime:e.endTime||"10:00",type:e.type,color:e.color||"#17a2b8",isAllDay:e.isAllDay||!1,location:e.location||""},this.emit("db-event-click",{event:e}),this.showEventModal=!0,this.render()}openAddModal(e){this.selectedDate=e,this.selectedEvent=null,this.isEditing=!1,this.eventForm={title:"",description:"",startTime:"09:00",endTime:"10:00",type:"meeting",color:"#17a2b8",isAllDay:!1,location:""},this.showEventModal=!0,this.render()}closeModal(){this.showEventModal=!1,this.selectedEvent=null,this.isEditing=!1,this.render()}saveEvent(){if(!this.eventForm.title.trim())return void window.alert("제목을 입력해주세요.");const e={title:this.eventForm.title.trim(),description:this.eventForm.description,date:i(this.selectedDate),startTime:this.eventForm.startTime,endTime:this.eventForm.endTime,type:this.eventForm.type,color:this.eventForm.color,isAllDay:this.eventForm.isAllDay,location:this.eventForm.location};if(this.isEditing&&this.selectedEvent){const t={...this.selectedEvent,...e};this.emit("db-event-edit",{event:t})}else this.emit("db-event-add",{event:e});this.closeModal()}deleteEvent(){this.selectedEvent&&window.confirm("정말로 이 일정을 삭제하시겠습니까?")&&(this.emit("db-event-delete",{eventId:this.selectedEvent.id}),this.closeModal())}renderHeader(){if(!this.headerEl)return;this.headerEl.replaceChildren();const t=document.createElement("div");t.className=`${d}__navigation`;const s=n("m"),i=document.createElement("button");i.type="button",i.className=`${d}__nav-button`,i.setAttribute("aria-label",e("이전")),i.appendChild(a("chevron-left",s)),i.addEventListener("click",()=>{this.shiftMonth(-1)});const l=document.createElement("div");l.className=`${d}__title`,l.textContent=this.selectedDate.toLocaleDateString(this.locale,{year:"numeric",month:"long"});const r=document.createElement("button");r.type="button",r.className=`${d}__nav-button`,r.setAttribute("aria-label",e("다음")),r.appendChild(a("chevron-right",s)),r.addEventListener("click",()=>{this.shiftMonth(1)}),t.append(i,l,r),this.headerEl.appendChild(t)}renderMonthView(){const e=document.createElement("div");e.className=`${d}__month-view`;const t=document.createElement("div");t.className=`${d}__weekdays`,["일","월","화","수","목","금","토"].forEach(e=>{const a=document.createElement("div");a.className=`${d}__weekday`,a.textContent=e,t.appendChild(a)}),e.appendChild(t);const a=document.createElement("div");a.className=`${d}__days`;const n=this.selectedDate.getFullYear(),s=this.selectedDate.getMonth(),i=new Date(n,s,1),l=new Date(i);l.setDate(l.getDate()-i.getDay());const r=new Date;for(let e=0;e<42;e+=1){const t=new Date(l);t.setDate(l.getDate()+e);const n=t.getMonth()===s;if(!this.showOutsideDays&&!n)continue;const i=0===t.getDay()||6===t.getDay();if(!this.showWeekends&&i)continue;const o=document.createElement("div"),c=this.selectedDateRange.start&&this.selectedDateRange.end&&t>=this.selectedDateRange.start&&t<=this.selectedDateRange.end,h=this.selectedDateRange.start&&t.toDateString()===this.selectedDateRange.start.toDateString(),m=this.selectedDateRange.end&&t.toDateString()===this.selectedDateRange.end.toDateString(),u=Boolean(c&&!h&&!m);o.className=[`${d}__day`,n&&`${d}__day--current-month`,this.highlightToday&&t.toDateString()===r.toDateString()&&`${d}__day--today`,this.isSameDate(t,this.selectedDate)&&`${d}__day--selected`,h&&`${d}__day--selected--start`,m&&`${d}__day--selected--end`,u&&`${d}__day--selected--middle`,!this.showWeekends&&i&&`${d}__day--weekend`].filter(Boolean).join(" "),o.addEventListener("click",()=>this.handleDateClick(t));const v=document.createElement("span");v.className=`${d}__day-number`,v.textContent=String(t.getDate()),o.appendChild(v);const p=this.eventsForDate(t);if(p.length){const e=document.createElement("div");if(e.className=`${d}__day-events`,p.slice(0,2).forEach(t=>{const a=document.createElement("div");a.className=[`${d}__event-bar`,`${d}__event-bar--${t.type}`].filter(Boolean).join(" "),t.color&&(a.style.backgroundColor=t.color),this.draggedEvent?.id===t.id&&a.classList.add(`${d}__event-bar--dragging`),a.title=t.title,a.draggable=!0;const n=document.createElement("span");n.className=`${d}__event-title`,n.textContent=t.title,a.appendChild(n),a.addEventListener("click",e=>this.handleEventClick(t,e)),a.addEventListener("dragstart",e=>this.handleDragStart(t,e)),a.addEventListener("dragend",()=>this.handleDragEnd()),e.appendChild(a)}),p.length>2){const t=document.createElement("div");t.className=`${d}__more-events`,t.textContent=`+${p.length-2} more`,e.appendChild(t)}o.appendChild(e)}const g=document.createElement("div");g.className=[`${d}__drop-zone`,this.dragOverDate&&this.isSameDate(this.dragOverDate,t)&&`${d}__drop-zone--active`].filter(Boolean).join(" "),g.addEventListener("dragover",e=>this.handleDragOver(t,e)),g.addEventListener("dragleave",e=>this.handleDragLeave(e)),g.addEventListener("drop",e=>this.handleDrop(t,e)),o.appendChild(g),a.appendChild(o)}return e.appendChild(a),e}renderYearView(){const e=document.createElement("div");e.className=`${d}__year-view`;const t=this.selectedDate.getFullYear();for(let a=0;a<12;a+=1){const n=new Date(t,a,1),i=this._events.filter(e=>{const n=s(e.date);return n&&n.getFullYear()===t&&n.getMonth()===a}),l=document.createElement("div");l.className=`${d}__year-month`,l.addEventListener("click",()=>{this.selectedDate=n,this.handleViewChange("month")});const r=document.createElement("h3");if(r.className=`${d}__year-month-title`,r.textContent=n.toLocaleDateString(this.locale,{month:"long"}),l.appendChild(r),i.length){const e=document.createElement("div");if(e.className=`${d}__year-month-events`,i.slice(0,4).forEach(t=>{const a=document.createElement("span");a.className=[`${d}__year-event`,`${d}__year-event--${t.type}`].join(" "),t.color&&(a.style.backgroundColor=t.color),e.appendChild(a)}),i.length>4){const t=document.createElement("span");t.className=`${d}__year-more-events`,t.textContent=`+${i.length-4} more`,e.appendChild(t)}l.appendChild(e)}e.appendChild(l)}return e}renderWeekView(){const e=document.createElement("div");e.className=`${d}__week-view`;const t=new Date,a=new Date(this.selectedDate);a.setDate(this.selectedDate.getDate()-this.selectedDate.getDay());const n=document.createElement("div");n.className=`${d}__week-header`;const s=document.createElement("div");s.className=`${d}__time-column-header`,n.appendChild(s);for(let e=0;e<7;e+=1){const s=new Date(a);s.setDate(a.getDate()+e);const i=document.createElement("div");i.className=[`${d}__week-day-header`,s.toDateString()===t.toDateString()&&`${d}__week-day-header--today`].filter(Boolean).join(" ");const l=document.createElement("span");l.className=`${d}__week-day-name`,l.textContent=s.toLocaleDateString(this.locale,{weekday:"short"});const r=document.createElement("span");r.className=`${d}__week-day-number`,r.textContent=String(s.getDate()),i.append(l,r),n.appendChild(i)}e.appendChild(n);const i=document.createElement("div");i.className=`${d}__week-grid`;const l=document.createElement("div");l.className=`${d}__week-time-column`;for(let e=6;e<=22;e+=1){const t=document.createElement("div");t.className=`${d}__time-slot`;const a=document.createElement("span");a.className=`${d}__time-label`,a.textContent=`${String(e).padStart(2,"0")}:00`,t.appendChild(a),l.appendChild(t)}i.appendChild(l);const r=document.createElement("div");r.className=`${d}__week-columns`;for(let e=0;e<7;e+=1){const t=new Date(a);t.setDate(a.getDate()+e);const n=document.createElement("div");n.className=`${d}__week-column`;for(let e=6;e<=22;e+=1){const a=document.createElement("div");a.className=`${d}__week-cell`,a.title=`${t.toLocaleDateString()} ${String(e).padStart(2,"0")}:00`,a.addEventListener("click",()=>{this.selectedDate=new Date(t),this.eventForm.startTime=`${String(e).padStart(2,"0")}:00`,this.eventForm.endTime=`${String(e+1).padStart(2,"0")}:00`,this.openAddModal(this.selectedDate)}),n.appendChild(a)}this.eventsForDate(t).forEach(e=>{if(!e.startTime)return;const[t,a]=e.startTime.split(":").map(Number),s=.8*(60*(t-6)+(a||0)),i=(e.endTime||e.startTime).split(":").map(Number),l=60*(i[0]||t)+(i[1]||0),r=60*t+(a||0),o=Math.max(20,48*(l-r)/60),c=document.createElement("div");c.className=[`${d}__week-event`,`${d}__week-event--${e.type}`].filter(Boolean).join(" "),c.textContent=e.title,c.title=e.title,c.style.backgroundColor=e.color||"#17a2b8",c.style.top=`${s}px`,c.style.height=`${o}px`,c.addEventListener("click",t=>this.handleEventClick(e,t)),n.appendChild(c)}),r.appendChild(n)}return i.appendChild(r),e.appendChild(i),e}renderModal(){if(!this.modalEl)return;if(this.modalEl.replaceChildren(),!this.showEventModal)return void this.modalEl.removeAttribute("open");this.modalEl.setAttribute("open","true"),this.modalEl.setAttribute("title",this.isEditing?"일정 편집":"새 일정 추가");const t=document.createElement("div");t.className=`${d}__event-form`;const a=document.createElement("db-input");a.setAttribute("label","제목 *"),a.setAttribute("placeholder",e("일정 제목을 입력하세요")),a.setAttribute("full-width",""),a.setAttribute("value",this.eventForm.title),a.addEventListener("db-input",e=>{this.eventForm.title=e.detail.value});const n=document.createElement("db-input");n.setAttribute("label","설명"),n.setAttribute("placeholder",e("일정 설명을 입력하세요")),n.setAttribute("full-width",""),n.setAttribute("value",this.eventForm.description),n.addEventListener("db-input",e=>{this.eventForm.description=e.detail.value});const l=document.createElement("db-date-picker");l.setAttribute("label","날짜"),l.setAttribute("full-width",""),l.setAttribute("value",i(this.selectedDate)),l.addEventListener("db-change",e=>{const t=s(e.detail.value);t&&(this.selectedDate=t)});const r=document.createElement("db-select");r.setAttribute("label","일정 타입"),r.setAttribute("full-width",""),r.setAttribute("options",JSON.stringify([{value:"meeting",label:e("회의")},{value:"task",label:e("업무")},{value:"reminder",label:e("알림")},{value:"birthday",label:e("생일")},{value:"holiday",label:e("휴일")},{value:"custom",label:e("기타")}])),r.setAttribute("value",this.eventForm.type),r.addEventListener("db-change",e=>{this.eventForm.type=e.detail.value});const o=document.createElement("db-select");o.setAttribute("label","색상"),o.setAttribute("full-width",""),o.setAttribute("options",JSON.stringify([{value:"#17a2b8",label:e("청록")},{value:"#0d6efd",label:e("파랑")},{value:"#198754",label:e("초록")},{value:"#ffc107",label:e("노랑")},{value:"#dc3545",label:e("빨강")},{value:"#6f42c1",label:e("보라")}])),o.setAttribute("value",this.eventForm.color),o.addEventListener("db-change",e=>{this.eventForm.color=e.detail.value});const c=document.createElement("db-time-picker");c.setAttribute("label","시작 시간"),c.setAttribute("full-width",""),c.setAttribute("value",this.eventForm.startTime),c.addEventListener("db-change",e=>{this.eventForm.startTime=e.detail.value});const h=document.createElement("db-time-picker");h.setAttribute("label","종료 시간"),h.setAttribute("full-width",""),h.setAttribute("value",this.eventForm.endTime),h.addEventListener("db-change",e=>{this.eventForm.endTime=e.detail.value}),t.append(a,n,l,r,o,c,h);const m=document.createElement("div");m.className="designbase-wc-modal__body",m.setAttribute("data-modal-part","body"),m.appendChild(t);const u=document.createElement("div");u.className="designbase-wc-modal__footer",u.setAttribute("data-modal-part","footer");const v=document.createElement("div");if(v.className=`${d}__modal-actions`,this.isEditing){const t=document.createElement("db-button");t.setAttribute("variant","destructive"),t.textContent=e("삭제"),t.addEventListener("click",()=>this.deleteEvent()),v.appendChild(t)}const p=document.createElement("div");p.className=`${d}__modal-buttons`;const g=document.createElement("db-button");g.setAttribute("variant","secondary"),g.textContent=e("취소"),g.addEventListener("click",()=>this.closeModal());const b=document.createElement("db-button");b.setAttribute("variant","primary"),b.textContent=this.isEditing?"수정":"저장",b.addEventListener("click",()=>this.saveEvent()),p.append(g,b),v.appendChild(p),u.appendChild(v),this.modalEl.append(m,u)}render(){this.className=d,this.replaceChildren(),this.headerEl&&this.bodyEl&&(this.renderHeader(),this.bodyEl.replaceChildren(),this.bodyEl.appendChild(this.renderMonthView()),this.append(this.headerEl,this.bodyEl),this.renderModal(),this.showEventModal&&this.modalEl&&this.appendChild(this.modalEl))}}customElements.get("db-calendar")||customElements.define("db-calendar",DbCalendar);export{DbCalendar};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CARD_VARIANTS as
|
|
1
|
+
import{dbText as e}from"../core/i18n.js";import{CARD_VARIANTS as t,CARD_SIZES as s}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbCard extends HTMLElement{constructor(){super(...arguments),this.selectCheckbox=null,this.imageNode=null,this.handleClick=e=>{if(this.disabled||this.loading)return e.preventDefault(),void e.stopPropagation();this.clickable&&this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0}))},this.handleKeyDown=e=>{!this.clickable||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.click())},this.handleSelect=e=>{if(e?.stopPropagation(),this.disabled||this.loading||!this.selectable)return;const t=!this.selected;this.toggleAttribute("selected",t),this.selectCheckbox&&(t?this.selectCheckbox.setAttribute("checked",""):this.selectCheckbox.removeAttribute("checked")),this.dispatchEvent(new CustomEvent("db-select",{bubbles:!0,composed:!0,detail:{selected:t}}))}}static get observedAttributes(){return["variant","size","prism","full-width","clickable","hoverable","selectable","selected","disabled","loading","image","image-alt"]}get variant(){return this.getAttribute("variant")||"default"}set variant(e){this.setAttribute("variant",e)}get size(){return this.getAttribute("size")||"m"}set size(e){this.setAttribute("size",e)}get clickable(){return this.hasAttribute("clickable")}set clickable(e){this.toggleAttribute("clickable",e)}get disabled(){return this.hasAttribute("disabled")}set disabled(e){this.toggleAttribute("disabled",e)}get loading(){return this.hasAttribute("loading")}set loading(e){this.toggleAttribute("loading",e)}get fullWidth(){return this.hasAttribute("full-width")}set fullWidth(e){this.toggleAttribute("full-width",e)}get hoverable(){return this.hasAttribute("hoverable")}set hoverable(e){this.toggleAttribute("hoverable",e)}get selectable(){return this.hasAttribute("selectable")}set selectable(e){this.toggleAttribute("selectable",e)}get selected(){return this.hasAttribute("selected")}set selected(e){this.toggleAttribute("selected",e)}connectedCallback(){this.addEventListener("click",this.handleClick),this.addEventListener("keydown",this.handleKeyDown),this.sync()}disconnectedCallback(){this.removeEventListener("click",this.handleClick),this.removeEventListener("keydown",this.handleKeyDown)}attributeChangedCallback(e){this.isConnected&&(this.sync(),"selected"===e&&this.selectCheckbox&&(this.selected?this.selectCheckbox.setAttribute("checked",""):this.selectCheckbox.removeAttribute("checked")))}hasMediaSection(){return!!this.getAttribute("image")||null!==this.querySelector(':scope > .designbase-wc-card__thumbnail, :scope > .designbase-wc-card__media, :scope > [slot="media"], :scope > [slot="thumbnail"]')}hasFooterSection(){return null!==this.querySelector(':scope > .designbase-wc-card__footer, :scope > [slot="footer"]')}syncImageMedia(){const e=this.getAttribute("image"),t=this.querySelector(':scope > .designbase-wc-card__thumbnail, :scope > .designbase-wc-card__media, :scope > [slot="media"], :scope > [slot="thumbnail"]');if(!e)return void(this.imageNode&&(this.imageNode.remove(),this.imageNode=null));if(t&&t!==this.imageNode)return void(this.imageNode&&(this.imageNode.remove(),this.imageNode=null));if(!this.imageNode){this.imageNode=document.createElement("div"),this.imageNode.className="designbase-wc-card__media designbase-wc-card__thumbnail",this.imageNode.setAttribute("slot","media");const e=document.createElement("img");e.className="designbase-wc-card__thumbnail-image",this.imageNode.append(e);const t=this.querySelector(':scope > .designbase-wc-card__body, :scope > [slot="body"], :scope > .designbase-wc-card__footer, :scope > [slot="footer"]');t?this.insertBefore(this.imageNode,t):this.insertBefore(this.imageNode,this.firstChild)}const s=this.imageNode.querySelector("img");s&&(s.src=e,s.alt=this.getAttribute("image-alt")||"")}sync(){this.syncImageMedia(),this.syncAttributes(),this.syncOverlays()}syncOverlays(){const t=this.querySelector(":scope > .designbase-wc-card__loading-overlay"),s=this.querySelector(":scope > .designbase-wc-card__select-overlay");if(this.loading){if(!t){const e=document.createElement("div");e.className="designbase-wc-card__loading-overlay",e.setAttribute("aria-live","polite"),e.setAttribute("aria-busy","true");const t=document.createElement("div");t.className="designbase-wc-card__loading-spinner",e.append(t),this.append(e)}}else t?.remove();if(this.selectable)if(s)this.selectCheckbox&&(this.selected?this.selectCheckbox.setAttribute("checked",""):this.selectCheckbox.removeAttribute("checked"));else{const t=document.createElement("div");t.className="designbase-wc-card__select-overlay",t.addEventListener("click",e=>this.handleSelect(e));const s=document.createElement("db-checkbox");s.className="designbase-wc-card__select-checkbox",s.setAttribute("size","s"),s.setAttribute("has-label","false"),s.setAttribute("aria-label",e("카드 선택")),this.selected&&s.setAttribute("checked",""),s.addEventListener("click",e=>e.stopPropagation()),s.addEventListener("db-change",e=>{e.stopPropagation(),this.handleSelect()}),t.append(s),this.append(t),this.selectCheckbox=s}else s?.remove(),this.selectCheckbox=null}syncAttributes(){this.classList.add("designbase-wc-card"),this.setAttribute("aria-disabled",String(this.disabled||this.loading)),!this.clickable||this.disabled||this.loading?(this.removeAttribute("role"),this.removeAttribute("tabindex"),this.removeAttribute("aria-pressed")):(this.setAttribute("role","button"),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0"),this.setAttribute("aria-pressed",String(this.hasAttribute("selected")))),t.forEach(e=>this.classList.remove(`designbase-wc-card--${e}`)),s.forEach(e=>this.classList.remove(`designbase-wc-card--${e}`)),this.classList.add(`designbase-wc-card--${t.includes(this.variant)?this.variant:"default"}`),this.classList.add(`designbase-wc-card--${s.includes(this.size)?this.size:"m"}`),this.classList.toggle("designbase-wc-card--prism",this.hasAttribute("prism")),this.classList.toggle("designbase-wc-card--full-width",this.hasAttribute("full-width")),this.classList.toggle("designbase-wc-card--clickable",this.clickable),this.classList.toggle("designbase-wc-card--hoverable",this.hasAttribute("hoverable")),this.classList.toggle("designbase-wc-card--selectable",this.hasAttribute("selectable")),this.classList.toggle("designbase-wc-card--selected",this.hasAttribute("selected")),this.classList.toggle("designbase-wc-card--disabled",this.disabled),this.classList.toggle("designbase-wc-card--loading",this.loading),this.classList.toggle("designbase-wc-card--with-media",this.hasMediaSection()),this.classList.toggle("designbase-wc-card--with-thumbnail",this.hasMediaSection()),this.classList.toggle("designbase-wc-card--with-footer",this.hasFooterSection())}}customElements.get("db-card")||customElements.define("db-card",DbCard);export{DbCard};
|
|
@@ -7,7 +7,8 @@ type DbCarouselItem = {
|
|
|
7
7
|
};
|
|
8
8
|
declare class DbCarousel extends HTMLElement {
|
|
9
9
|
private currentIndex;
|
|
10
|
-
private
|
|
10
|
+
private engine?;
|
|
11
|
+
private autoplay?;
|
|
11
12
|
private isAutoPlaying;
|
|
12
13
|
static get observedAttributes(): string[];
|
|
13
14
|
get items(): DbCarouselItem[];
|
|
@@ -17,8 +18,7 @@ declare class DbCarousel extends HTMLElement {
|
|
|
17
18
|
attributeChangedCallback(name: string): void;
|
|
18
19
|
private getBool;
|
|
19
20
|
private clampCurrentIndex;
|
|
20
|
-
private
|
|
21
|
-
private startAutoPlay;
|
|
21
|
+
private destroyEngine;
|
|
22
22
|
private getIndicatorType;
|
|
23
23
|
private getIndicatorSize;
|
|
24
24
|
private goTo;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDbIcon as
|
|
1
|
+
import{createDbIcon as e}from"./db-icons.js";import{t}from"../core/i18n.js";import{b as s}from"../node_modules/@designbasekorea/carousel/dist/chunks/chunk-AGE5BHQ4.js";import{a as i}from"../node_modules/@designbasekorea/carousel/dist/chunks/chunk-GM4TCAP5.js";import{coerceToContract as n}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{CAROUSEL_SIZES as o,CAROUSEL_VARIANTS as a}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbCarousel extends HTMLElement{constructor(){super(...arguments),this.currentIndex=0,this.isAutoPlaying=!1}static get observedAttributes(){return["items","size","variant","theme","transition","auto-play","auto-play-interval","infinite","show-navigation","show-indicators","indicator-style","show-auto-play-control","show-title","show-description","disabled","readonly"]}get items(){try{const e=JSON.parse(this.getAttribute("items")||"[]");return Array.isArray(e)?e:[]}catch{return[]}}set items(e){this.setAttribute("items","string"==typeof e?e:JSON.stringify(e))}connectedCallback(){this.style.display="block",this.clampCurrentIndex(),this.isAutoPlaying=this.getBool("auto-play"),this.render()}disconnectedCallback(){this.destroyEngine()}attributeChangedCallback(e){this.isConnected&&("items"===e&&this.clampCurrentIndex(),"auto-play"!==e&&"auto-play-interval"!==e||(this.isAutoPlaying=this.getBool("auto-play")),this.render())}getBool(e,t=!1){if(!this.hasAttribute(e))return t;const s=this.getAttribute(e);return""===s||"true"===s}clampCurrentIndex(){this.currentIndex>=this.items.length&&(this.currentIndex=0)}destroyEngine(){const e=this.isAutoPlaying;this.autoplay?.destroy(),this.autoplay=void 0,this.engine?.destroy(),this.engine=void 0,this.isAutoPlaying=e}getIndicatorType(){if(this.getBool("show-auto-play-control",!0)&&this.getBool("show-indicators",!0)&&this.items.length>1)return"combined";const e=this.getAttribute("indicator-style")||"dots";return"lines"===e?"line":"numbers"===e?"numbers":"dots"}getIndicatorSize(){const e=n(this.getAttribute("size"),o,"m");return"l"===e||"xl"===e?"m":"s"}goTo(e){this.getBool("disabled")||this.getBool("readonly")||e<0||e>=this.items.length||this.engine?.goTo(e)}goToPrev(){this.getBool("disabled")||this.getBool("readonly")||this.engine?.prev()}goToNext(){this.getBool("disabled")||this.getBool("readonly")||this.engine?.next()}render(){this.destroyEngine();const r=n(this.getAttribute("size"),o,"m"),l=n(this.getAttribute("variant"),a,"default"),c=this.getAttribute("theme")||"light",d=this.getAttribute("transition")||"slide",u=this.getBool("show-navigation",!0),h=this.getBool("show-indicators",!0),g=this.getBool("show-auto-play-control",!0),b=this.getBool("show-title",!0),m=this.getBool("show-description",!0),p=this.getBool("disabled"),y=this.getBool("readonly"),v=this.getAttribute("indicator-style")||"dots",A=g&&h&&this.items.length>1;this.className=["designbase-wc-carousel","db-slide",`designbase-wc-carousel--size-${r}`,`designbase-wc-carousel--variant-${l}`,`designbase-wc-carousel--theme-${c}`,`designbase-wc-carousel--transition-${d}`,`designbase-wc-carousel--indicator-${v}`,p&&"designbase-wc-carousel--disabled",y&&"designbase-wc-carousel--readonly"].filter(Boolean).join(" ");const w=document.createElement("div");w.className="designbase-wc-carousel__container";const _=document.createElement("div");if(_.className="designbase-wc-carousel__track db-slide__viewport",(p||y)&&(_.style.overflowX="hidden"),this.items.forEach((e,t)=>{const s=document.createElement("div");s.className="designbase-wc-carousel__slide"+(t===this.currentIndex?" designbase-wc-carousel__slide--active":""),s.style.flex="0 0 100%",s.style.width="100%",s.style.height="100%",s.style.minWidth="0";const i=e.image?"#ffffff":"";if(i&&(s.style.color=i),e.image){const i=document.createElement("div");i.className="designbase-wc-carousel__slide-image";const n=document.createElement("img");n.className="designbase-wc-carousel__slide-img",n.src=e.image,n.alt=e.alt||e.title||`Slide ${t+1}`,i.append(n),s.append(i)}if(b&&e.title||m&&e.description){const t=document.createElement("div");if(t.className="designbase-wc-carousel__slide-info",i&&(t.style.color=i),b&&e.title){const s=document.createElement("h3");s.className="designbase-wc-carousel__slide-title",s.textContent=e.title,i&&(s.style.color=i),t.append(s)}if(m&&e.description){const s=document.createElement("p");s.className="designbase-wc-carousel__slide-description",s.textContent=e.description,i&&(s.style.color=i),t.append(s)}s.append(t)}s.addEventListener("click",()=>{p||y||this.dispatchEvent(new CustomEvent("db-item-click",{detail:{item:e,index:t},bubbles:!0,composed:!0}))}),_.append(s)}),w.append(_),u&&this.items.length>1){const s=document.createElement("button");s.className="designbase-wc-carousel__nav-button designbase-wc-carousel__nav-button--prev",s.type="button",s.setAttribute("aria-label",t("carousel.previous")),s.append(e("chevron-left",20)),s.disabled=p||y,s.addEventListener("click",()=>this.goToPrev());const i=document.createElement("button");i.className="designbase-wc-carousel__nav-button designbase-wc-carousel__nav-button--next",i.type="button",i.setAttribute("aria-label",t("carousel.next")),i.append(e("chevron-right",20)),i.disabled=p||y,i.addEventListener("click",()=>this.goToNext()),w.append(s,i)}const f=[w];if(h&&this.items.length>1){const e=document.createElement("div");e.className="designbase-wc-carousel__controls";const t=document.createElement("div");t.className="designbase-wc-carousel__indicators";const s=document.createElement("db-indicator");s.setAttribute("current",String(this.currentIndex)),s.setAttribute("total",String(this.items.length)),s.setAttribute("type",this.getIndicatorType()),s.setAttribute("size",this.getIndicatorSize()),s.setAttribute("clickable",""),A&&(s.setAttribute("timer",""),s.setAttribute("progress","0"),s.setAttribute("timer-duration",String(Math.max(1e3,Number(this.getAttribute("auto-play-interval")||5e3)))),s.setAttribute("auto-roll","false"),this.isAutoPlaying?s.setAttribute("playing",""):s.removeAttribute("playing"),(p||y)&&s.setAttribute("playback-disabled","")),s.addEventListener("db-step-click",e=>{const t=e;this.goTo(t.detail.index)}),s.addEventListener("db-playing-change",e=>{const t=e;this.isAutoPlaying=t.detail.playing,p||y||(this.isAutoPlaying?this.autoplay?.play():this.autoplay?.pause())}),t.append(s),e.append(t),f.push(e)}this.replaceChildren(...f),this.engine=s(this,{startIndex:this.currentIndex,slidesPerView:1,gap:0,rewind:this.getBool("infinite",!0),drag:!p&&!y,keyboard:!p&&!y,label:this.getAttribute("aria-label")||"Carousel"});const sync=()=>{const e=this.engine.getState(),t=e.index!==this.currentIndex;this.currentIndex=e.index,_.querySelectorAll(".designbase-wc-carousel__slide").forEach((t,s)=>{t.classList.toggle("designbase-wc-carousel__slide--active",e.visible.includes(s))});const s=this.querySelector("db-indicator");s?.getAttribute("current")!==String(e.index)&&s?.setAttribute("current",String(e.index));const i=this.querySelector(".designbase-wc-carousel__nav-button--prev"),n=this.querySelector(".designbase-wc-carousel__nav-button--next");i&&(i.disabled=p||y||!e.canPrev),n&&(n.disabled=p||y||!e.canNext),t&&this.dispatchEvent(new CustomEvent("db-slide-change",{detail:{index:e.index},bubbles:!0,composed:!0}))};this.engine.on("change",sync),this.engine.on("refresh",sync),sync(),this.autoplay=i(this.engine,{delay:Math.max(1e3,Number(this.getAttribute("auto-play-interval")||5e3)),playOnInit:this.isAutoPlaying&&!p&&!y}),this.autoplay.onProgress(e=>{A&&this.querySelector("db-indicator")?.setAttribute("progress",String(e.progress))}),this.autoplay.onChange(e=>{p||y||(this.isAutoPlaying=e);const t=this.querySelector("db-indicator");A&&t?.toggleAttribute("playing",e)})}}customElements.get("db-carousel")||customElements.define("db-carousel",DbCarousel);export{DbCarousel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isDbIconName as t,createDbIcon as e}from"./db-icons.js";import"./db-button.js";import"./db-chip.js";import"./db-voice-control.js";const s=[{id:"image",label:"사진·이미지",icon:"gallery",accept:"image/*",multiple:!0},{id:"video",label:"동영상",icon:"video",accept:"video/*",multiple:!0},{id:"file",label:"문서·파일",icon:"file-new",accept:"",multiple:!0},{id:"camera",label:"카메라 촬영",icon:"camera",accept:"image/*",capture:"environment"}];function kindFromMime(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":"file"}const i={image:"gallery",video:"video",file:"file-new"};let a=0;class DbChatComposer extends HTMLElement{constructor(){super(...arguments),this.built=!1,this._tools=[],this._attachOptions=s,this._attachments=[],this.attachMenuOpen=!1,this.dragDepth=0,this.handleAttachClick=()=>{this.disabled||(this.attachMenuOpen?this.closeAttachMenu():this.openAttachMenu())},this.handleOutsideClick=t=>{this.attachMenuOpen&&(this.attachWrap.contains(t.target)||this.closeAttachMenu())},this.handleFilePicked=()=>{const t=Array.from(this.fileInput.files||[]);if(!t.length)return;const e=this.fileInput.dataset.type||"file";this.addFiles(t,e)},this.handleDragEnter=t=>{this.hasAttribute("attach")&&!this.disabled&&this.hasDragFiles(t)&&(t.preventDefault(),this.dragDepth+=1,this.showDropOverlay(!0))},this.handleDragOver=t=>{this.hasAttribute("attach")&&!this.disabled&&this.hasDragFiles(t)&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))},this.handleDragLeave=t=>{this.hasAttribute("attach")&&this.hasDragFiles(t)&&(this.dragDepth=Math.max(0,this.dragDepth-1),0===this.dragDepth&&this.showDropOverlay(!1))},this.handleDrop=t=>{if(!this.hasAttribute("attach")||this.disabled)return;if(!this.hasDragFiles(t))return;t.preventDefault(),t.stopPropagation(),this.dragDepth=0,this.showDropOverlay(!1);const e=Array.from(t.dataTransfer?.files||[]);e.length&&(this.addFiles(e,"drop"),this.focusInput())},this.handleInput=()=>{this.autoGrow(),this.syncSendState(),this.dispatchEvent(new CustomEvent("db-input",{detail:{value:this.field.value},bubbles:!0,composed:!0}))},this.handleKeyDown=t=>"Escape"===t.key&&this.voiceActive?(t.preventDefault(),void this.dispatchEvent(new CustomEvent("db-voice",{detail:{action:"cancel"},bubbles:!0,composed:!0}))):"Escape"===t.key&&this.attachMenuOpen?(t.preventDefault(),void this.closeAttachMenu()):void("Enter"!==t.key||t.shiftKey||t.isComposing||(t.preventDefault(),this.submit())),this.handleSendClick=()=>{this.disabled||this.voiceActive||(this.streaming?this.dispatchEvent(new CustomEvent("db-stop",{bubbles:!0,composed:!0})):this.submit())}}static get observedAttributes(){return["placeholder","value","disabled","streaming","voice","attach","max-length","send-label","voice-state","voice-message","voice-disabled"]}get value(){return this.field?.value??this.getAttribute("value")??""}set value(t){this.field&&(this.field.value=t,this.autoGrow(),this.syncSendState()),t?this.setAttribute("value",t):this.removeAttribute("value")}get streaming(){return this.hasAttribute("streaming")}set streaming(t){this.toggleAttribute("streaming",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",t)}get tools(){return this._tools}set tools(t){this._tools=Array.isArray(t)?t:[],this.built&&this.renderTools()}get attachOptions(){return this._attachOptions}set attachOptions(t){this._attachOptions=Array.isArray(t)&&t.length?t:s,this.built&&this.renderAttachMenu()}get attachments(){return this._attachments.map(t=>({...t}))}connectedCallback(){this.built||this.build(),this.sync(),requestAnimationFrame(()=>this.autoGrow()),document.addEventListener("click",this.handleOutsideClick,!0),this.addEventListener("dragenter",this.handleDragEnter),this.addEventListener("dragover",this.handleDragOver),this.addEventListener("dragleave",this.handleDragLeave),this.addEventListener("drop",this.handleDrop)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick,!0),this.removeEventListener("dragenter",this.handleDragEnter),this.removeEventListener("dragover",this.handleDragOver),this.removeEventListener("dragleave",this.handleDragLeave),this.removeEventListener("drop",this.handleDrop),this._attachments.forEach(t=>t.preview&&URL.revokeObjectURL(t.preview))}attributeChangedCallback(t){if(this.built){if("value"===t){const t=this.getAttribute("value")||"";return this.field.value!==t&&(this.field.value=t,this.autoGrow()),void this.syncSendState()}"streaming"!==t?this.sync():this.renderSendButton()}}build(){this.built=!0,this.className="designbase-wc-chat-composer",this.replaceChildren();const t=document.createElement("div");t.className="designbase-wc-chat-composer__surface",this.attachmentsEl=document.createElement("div"),this.attachmentsEl.className="designbase-wc-chat-composer__attachments",this.attachmentsEl.hidden=!0;const e=document.createElement("div");e.className="designbase-wc-chat-composer__field-row",this.field=document.createElement("textarea"),this.field.className="designbase-wc-chat-composer__field",this.field.rows=1,this.field.addEventListener("input",this.handleInput),this.field.addEventListener("keydown",this.handleKeyDown),e.append(this.field);const s=document.createElement("div");s.className="designbase-wc-chat-composer__toolbar";const i=document.createElement("div");i.className="designbase-wc-chat-composer__leading",this.attachWrap=document.createElement("div"),this.attachWrap.className="designbase-wc-chat-composer__attach-wrap",this.attachBtn=document.createElement("db-button"),this.attachBtn.className="designbase-wc-chat-composer__attach",this.attachBtn.setAttribute("variant","ghost"),this.attachBtn.setAttribute("icon-only",""),this.attachBtn.setAttribute("radius","pill"),this.attachBtn.setAttribute("size","m"),this.attachBtn.setAttribute("start-icon","paperclip"),this.attachBtn.setAttribute("aria-label","첨부"),this.attachBtn.setAttribute("aria-haspopup","menu"),this.attachBtn.addEventListener("db-click",this.handleAttachClick),this.attachMenu=document.createElement("div"),this.attachMenu.className="designbase-wc-chat-composer__attach-menu",this.attachMenu.setAttribute("role","menu"),this.attachMenu.hidden=!0,this.attachWrap.append(this.attachBtn,this.attachMenu),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.className="designbase-wc-chat-composer__file-input",this.fileInput.hidden=!0,this.fileInput.addEventListener("change",this.handleFilePicked),this.toolsEl=document.createElement("div"),this.toolsEl.className="designbase-wc-chat-composer__tools",i.append(this.attachWrap,this.toolsEl);const a=document.createElement("div");a.className="designbase-wc-chat-composer__trailing",this.micBtn=document.createElement("db-voice-control"),this.micBtn.setAttribute("compact","");for(const t of["start","stop","cancel"])this.micBtn.addEventListener(`db-${t}`,e=>{e.stopPropagation(),this.disabled||this.streaming||this.hasAttribute("voice-disabled")||this.dispatchEvent(new CustomEvent("db-voice",{detail:{action:t},bubbles:!0,composed:!0}))});this.micBtn.classList.add("designbase-wc-chat-composer__mic"),this.sendBtn=document.createElement("db-button"),this.sendBtn.className="designbase-wc-chat-composer__send",this.sendBtn.setAttribute("icon-only",""),this.sendBtn.setAttribute("radius","pill"),this.sendBtn.setAttribute("size","m"),this.sendBtn.addEventListener("db-click",this.handleSendClick),a.append(this.micBtn,this.sendBtn),s.append(i,a),t.append(this.attachmentsEl,e,s),this.dropOverlay=document.createElement("div"),this.dropOverlay.className="designbase-wc-chat-composer__drop-overlay",this.dropOverlay.hidden=!0,this.dropOverlay.setAttribute("aria-hidden","true"),this.dropOverlay.innerHTML='<span class="designbase-wc-chat-composer__drop-label">파일을 놓으면 첨부됩니다</span>',this.append(t,this.dropOverlay,this.fileInput),this.renderTools(),this.renderAttachMenu(),this.renderSendButton()}makeIconButton(t,e,s){const i=document.createElement("db-button");return i.setAttribute("variant","ghost"),i.setAttribute("icon-only",""),i.setAttribute("radius","pill"),i.setAttribute("size","m"),i.setAttribute("start-icon",t),i.setAttribute("aria-label",e),i.addEventListener("db-click",()=>{this.disabled||this.dispatchEvent(new CustomEvent(s,{bubbles:!0,composed:!0}))}),i}sync(){this.classList.toggle("designbase-wc-chat-composer--disabled",this.disabled),this.classList.toggle("designbase-wc-chat-composer--streaming",this.streaming),this.field.placeholder=this.getAttribute("placeholder")||"메시지를 입력하세요…",this.field.disabled=this.disabled,this.field.readOnly=this.voiceActive;const t=this.getAttribute("max-length");t?this.field.maxLength=Number(t):this.field.removeAttribute("maxlength"),this.attachWrap.hidden=!this.hasAttribute("attach"),this.micBtn.hidden=!this.hasAttribute("voice"),this.micBtn.setAttribute("state",this.getAttribute("voice-state")||"idle"),this.micBtn.setAttribute("message",this.getAttribute("voice-message")||""),this.micBtn.toggleAttribute("disabled",this.disabled||this.streaming||this.hasAttribute("voice-disabled")),this.hasAttribute("attach")||this.closeAttachMenu(),this.autoGrow(),this.syncSendState()}renderTools(){this.toolsEl.replaceChildren();for(const e of this._tools){const s=document.createElement("db-chip");s.setAttribute("label",e.label),s.setAttribute("size","s"),s.setAttribute("clickable",""),s.setAttribute("variant",e.active?"primary":"default"),e.icon&&t(e.icon)&&s.setAttribute("start-icon",e.icon),s.setAttribute("aria-pressed",String(!!e.active)),s.addEventListener("db-click",()=>{this.disabled||(e.active=!e.active,s.setAttribute("variant",e.active?"primary":"default"),s.setAttribute("aria-pressed",String(!!e.active)),this.dispatchEvent(new CustomEvent("db-tool-toggle",{detail:{id:e.id,active:!!e.active},bubbles:!0,composed:!0})))}),this.toolsEl.append(s)}}renderAttachMenu(){this.attachMenu.replaceChildren();for(const s of this._attachOptions){const i=document.createElement("button");i.type="button",i.className="designbase-wc-chat-composer__attach-item",i.setAttribute("role","menuitem");const a=document.createElement("span");a.className="designbase-wc-chat-composer__attach-item-icon",s.icon&&t(s.icon)&&a.append(e(s.icon,18));const n=document.createElement("span");n.className="designbase-wc-chat-composer__attach-item-text";const h=document.createElement("span");if(h.className="designbase-wc-chat-composer__attach-item-label",h.textContent=s.label,n.append(h),s.description){const t=document.createElement("span");t.className="designbase-wc-chat-composer__attach-item-desc",t.textContent=s.description,n.append(t)}i.append(a,n),i.addEventListener("click",()=>this.chooseAttachOption(s)),this.attachMenu.append(i)}}renderAttachments(){this.attachmentsEl.replaceChildren(),this.attachmentsEl.hidden=0===this._attachments.length;for(const t of this._attachments){if("image"===t.kind&&t.preview){const s=document.createElement("div");s.className="designbase-wc-chat-composer__thumb";const i=document.createElement("img");i.src=t.preview,i.alt=t.name;const a=document.createElement("button");a.type="button",a.className="designbase-wc-chat-composer__thumb-remove",a.setAttribute("aria-label",`${t.name} 제거`),a.append(e("close",12)),a.addEventListener("click",()=>this.removeAttachment(t.id)),s.append(i,a),this.attachmentsEl.append(s);continue}const s=document.createElement("db-chip");s.setAttribute("label",t.name),s.setAttribute("size","s"),s.setAttribute("variant","neutral"),s.setAttribute("deletable",""),s.setAttribute("start-icon",i[t.kind]),s.addEventListener("db-delete",()=>this.removeAttachment(t.id)),this.attachmentsEl.append(s)}this.syncSendState()}renderSendButton(){const t=this.streaming;this.sendBtn.setAttribute("variant",t?"secondary":"primary"),this.sendBtn.setAttribute("start-icon",t?"stop":"send"),this.sendBtn.setAttribute("aria-label",t?"생성 중지":"전송"),this.syncSendState()}get voiceActive(){return this.hasAttribute("voice")&&["starting","listening","stopping"].includes(this.getAttribute("voice-state")||"idle")}syncSendState(){if(!this.sendBtn)return;const t=0===this.value.trim().length&&0===this._attachments.length,e=this.disabled||this.voiceActive||!this.streaming&&t;this.sendBtn.toggleAttribute("disabled",e)}autoGrow(){this.field&&0!==this.field.clientWidth&&(this.field.style.height="auto",this.field.style.height=`${Math.min(this.field.scrollHeight,200)}px`)}openAttachMenu(){this.attachMenuOpen=!0,this.attachMenu.hidden=!1,this.attachBtn.setAttribute("aria-expanded","true"),this.classList.add("designbase-wc-chat-composer--attach-open"),requestAnimationFrame(()=>this.attachMenu.classList.add("designbase-wc-chat-composer__attach-menu--visible"))}closeAttachMenu(){this.attachMenuOpen&&(this.attachMenuOpen=!1,this.attachMenu.hidden=!0,this.attachMenu.classList.remove("designbase-wc-chat-composer__attach-menu--visible"),this.attachBtn.setAttribute("aria-expanded","false"),this.classList.remove("designbase-wc-chat-composer--attach-open"))}chooseAttachOption(t){this.closeAttachMenu(),this.dispatchEvent(new CustomEvent("db-attach",{detail:{type:t.id},bubbles:!0,composed:!0})),void 0!==t.accept&&(this.fileInput.value="",this.fileInput.accept=t.accept,this.fileInput.multiple=!!t.multiple,t.capture?this.fileInput.setAttribute("capture",t.capture):this.fileInput.removeAttribute("capture"),this.fileInput.dataset.type=t.id,this.fileInput.click())}hasDragFiles(t){return Array.from(t.dataTransfer?.types||[]).includes("Files")}showDropOverlay(t){this.dropOverlay&&(this.dropOverlay.hidden=!t,this.classList.toggle("designbase-wc-chat-composer--drop-active",t))}addFile(t){if(this.hasAttachment(t))return!1;const e=kindFromMime(t.type),s={id:`att-${a+=1}`,name:t.name,size:t.size,mime:t.type,kind:e,file:t,preview:"image"===e?URL.createObjectURL(t):void 0};return this._attachments.push(s),this.renderAttachments(),this.dispatchEvent(new CustomEvent("db-attachment-add",{detail:{attachment:this.attachmentMeta(s)},bubbles:!0,composed:!0})),!0}hasAttachment(t){return this._attachments.some(e=>e.file&&e.file.name===t.name&&e.file.size===t.size&&e.file.type===t.type&&e.file.lastModified===t.lastModified)}attachmentMeta(t){return{id:t.id,name:t.name,size:t.size,mime:t.mime,kind:t.kind,file:t.file,preview:t.preview}}submit(){const t=this.field.value.trim();if(!t&&0===this._attachments.length||this.disabled||this.streaming||this.voiceActive)return;const e=new CustomEvent("db-send",{detail:{value:t,attachments:this._attachments.map(t=>this.attachmentMeta(t))},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(e)&&(this.clear(),this.clearAttachments())}addFiles(t,e="file"){const s=Array.from(t||[]).filter(Boolean);if(!s.length)return;const i=s.filter(t=>this.addFile(t));i.length&&this.dispatchEvent(new CustomEvent("db-attach-files",{detail:{type:e,files:i},bubbles:!0,composed:!0}))}send(){this.submit()}clear(){this.value=""}removeAttachment(t){const e=this._attachments.find(e=>e.id===t);e&&(e.preview&&URL.revokeObjectURL(e.preview),this._attachments=this._attachments.filter(e=>e.id!==t),this.renderAttachments(),this.dispatchEvent(new CustomEvent("db-attachment-remove",{detail:{id:t},bubbles:!0,composed:!0})))}clearAttachments(){this._attachments.forEach(t=>t.preview&&URL.revokeObjectURL(t.preview)),this._attachments=[],this.renderAttachments()}addAttachment(t){if(t instanceof File)return void this.addFile(t);if(t.file&&this.hasAttachment(t.file))return;const e=kindFromMime(t.mime);this._attachments.push({id:`att-${a+=1}`,kind:e,...t}),this.renderAttachments()}focusInput(){this.field?.focus()}setStreaming(t){this.streaming=t}}customElements.get("db-chat-composer")||customElements.define("db-chat-composer",DbChatComposer);export{DbChatComposer};
|
|
1
|
+
import{labelFrom as t,dbText as e,dbFormat as s}from"../core/i18n.js";import{setHostClasses as i}from"../core/host-class.js";import{isDbIconName as a,createDbIcon as n}from"./db-icons.js";import"./db-button.js";import"./db-chip.js";import"./db-voice-control.js";const DEFAULT_ATTACH_OPTIONS=()=>[{id:"image",label:e("사진·이미지"),icon:"gallery",accept:"image/*",multiple:!0},{id:"video",label:e("동영상"),icon:"video",accept:"video/*",multiple:!0},{id:"file",label:e("문서·파일"),icon:"file-new",accept:"",multiple:!0},{id:"camera",label:e("카메라 촬영"),icon:"camera",accept:"image/*",capture:"environment"}];function kindFromMime(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":"file"}const h={image:"gallery",video:"video",file:"file-new"};let c=0;class DbChatComposer extends HTMLElement{constructor(){super(...arguments),this.built=!1,this._tools=[],this._attachOptions=DEFAULT_ATTACH_OPTIONS(),this._attachments=[],this.attachMenuOpen=!1,this.dragDepth=0,this.handleAttachClick=()=>{this.disabled||(this.attachMenuOpen?this.closeAttachMenu():this.openAttachMenu())},this.handleOutsideClick=t=>{this.attachMenuOpen&&(this.attachWrap.contains(t.target)||this.closeAttachMenu())},this.handleFilePicked=()=>{const t=Array.from(this.fileInput.files||[]);if(!t.length)return;const e=this.fileInput.dataset.type||"file";this.addFiles(t,e)},this.handleDragEnter=t=>{this.hasAttribute("attach")&&!this.disabled&&this.hasDragFiles(t)&&(t.preventDefault(),this.dragDepth+=1,this.showDropOverlay(!0))},this.handleDragOver=t=>{this.hasAttribute("attach")&&!this.disabled&&this.hasDragFiles(t)&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))},this.handleDragLeave=t=>{this.hasAttribute("attach")&&this.hasDragFiles(t)&&(this.dragDepth=Math.max(0,this.dragDepth-1),0===this.dragDepth&&this.showDropOverlay(!1))},this.handleDrop=t=>{if(!this.hasAttribute("attach")||this.disabled)return;if(!this.hasDragFiles(t))return;t.preventDefault(),t.stopPropagation(),this.dragDepth=0,this.showDropOverlay(!1);const e=Array.from(t.dataTransfer?.files||[]);e.length&&(this.addFiles(e,"drop"),this.focusInput())},this.handleInput=()=>{this.autoGrow(),this.syncSendState(),this.dispatchEvent(new CustomEvent("db-input",{detail:{value:this.field.value},bubbles:!0,composed:!0}))},this.handleKeyDown=t=>"Escape"===t.key&&this.voiceActive?(t.preventDefault(),void this.dispatchEvent(new CustomEvent("db-voice",{detail:{action:"cancel"},bubbles:!0,composed:!0}))):"Escape"===t.key&&this.attachMenuOpen?(t.preventDefault(),void this.closeAttachMenu()):void("Enter"!==t.key||t.shiftKey||t.isComposing||(t.preventDefault(),this.submit())),this.handleSendClick=()=>{this.disabled||this.voiceActive||(this.streaming?this.dispatchEvent(new CustomEvent("db-stop",{bubbles:!0,composed:!0})):this.submit())}}static get observedAttributes(){return["placeholder","value","disabled","streaming","voice","attach","max-length","send-label","stop-label","attach-label","voice-state","voice-message","voice-disabled"]}get value(){return this.field?.value??this.getAttribute("value")??""}set value(t){this.field&&(this.field.value=t,this.autoGrow(),this.syncSendState()),t?this.setAttribute("value",t):this.removeAttribute("value")}get streaming(){return this.hasAttribute("streaming")}set streaming(t){this.toggleAttribute("streaming",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",t)}get tools(){return this._tools}set tools(t){this._tools=Array.isArray(t)?t:[],this.built&&this.renderTools()}get attachOptions(){return this._attachOptions}set attachOptions(t){this._attachOptions=Array.isArray(t)&&t.length?t:DEFAULT_ATTACH_OPTIONS(),this.built&&this.renderAttachMenu()}get attachments(){return this._attachments.map(t=>({...t}))}connectedCallback(){this.built||this.build(),this.sync(),requestAnimationFrame(()=>this.autoGrow()),document.addEventListener("click",this.handleOutsideClick,!0),this.addEventListener("dragenter",this.handleDragEnter),this.addEventListener("dragover",this.handleDragOver),this.addEventListener("dragleave",this.handleDragLeave),this.addEventListener("drop",this.handleDrop)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick,!0),this.removeEventListener("dragenter",this.handleDragEnter),this.removeEventListener("dragover",this.handleDragOver),this.removeEventListener("dragleave",this.handleDragLeave),this.removeEventListener("drop",this.handleDrop),this._attachments.forEach(t=>t.preview&&URL.revokeObjectURL(t.preview))}attributeChangedCallback(e){if(this.built){if("value"===e){const t=this.getAttribute("value")||"";return this.field.value!==t&&(this.field.value=t,this.autoGrow()),void this.syncSendState()}"streaming"!==e&&"send-label"!==e&&"stop-label"!==e?"attach-label"!==e?this.sync():this.attachBtn.setAttribute("aria-label",t(this,"attach-label","chatComposer.attach")):this.renderSendButton()}}build(){this.built=!0,i(this,["designbase-wc-chat-composer"]),this.replaceChildren();const s=document.createElement("div");s.className="designbase-wc-chat-composer__surface",this.attachmentsEl=document.createElement("div"),this.attachmentsEl.className="designbase-wc-chat-composer__attachments",this.attachmentsEl.hidden=!0;const a=document.createElement("div");a.className="designbase-wc-chat-composer__field-row",this.field=document.createElement("textarea"),this.field.className="designbase-wc-chat-composer__field",this.field.rows=1,this.field.addEventListener("input",this.handleInput),this.field.addEventListener("keydown",this.handleKeyDown),a.append(this.field);const n=document.createElement("div");n.className="designbase-wc-chat-composer__toolbar";const h=document.createElement("div");h.className="designbase-wc-chat-composer__leading",this.attachWrap=document.createElement("div"),this.attachWrap.className="designbase-wc-chat-composer__attach-wrap",this.attachBtn=document.createElement("db-button"),this.attachBtn.className="designbase-wc-chat-composer__attach",this.attachBtn.setAttribute("variant","ghost"),this.attachBtn.setAttribute("icon-only",""),this.attachBtn.setAttribute("radius","pill"),this.attachBtn.setAttribute("size","m"),this.attachBtn.setAttribute("start-icon","paperclip"),this.attachBtn.setAttribute("aria-label",t(this,"attach-label","chatComposer.attach")),this.attachBtn.setAttribute("aria-haspopup","menu"),this.attachBtn.addEventListener("db-click",this.handleAttachClick),this.attachMenu=document.createElement("div"),this.attachMenu.className="designbase-wc-chat-composer__attach-menu",this.attachMenu.setAttribute("role","menu"),this.attachMenu.hidden=!0,this.attachWrap.append(this.attachBtn,this.attachMenu),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.className="designbase-wc-chat-composer__file-input",this.fileInput.hidden=!0,this.fileInput.addEventListener("change",this.handleFilePicked),this.toolsEl=document.createElement("div"),this.toolsEl.className="designbase-wc-chat-composer__tools",h.append(this.attachWrap,this.toolsEl);const c=document.createElement("div");c.className="designbase-wc-chat-composer__trailing",this.micBtn=document.createElement("db-voice-control"),this.micBtn.setAttribute("compact","");for(const t of["start","stop","cancel"])this.micBtn.addEventListener(`db-${t}`,e=>{e.stopPropagation(),this.disabled||this.streaming||this.hasAttribute("voice-disabled")||this.dispatchEvent(new CustomEvent("db-voice",{detail:{action:t},bubbles:!0,composed:!0}))});this.micBtn.classList.add("designbase-wc-chat-composer__mic"),this.sendBtn=document.createElement("db-button"),this.sendBtn.className="designbase-wc-chat-composer__send",this.sendBtn.setAttribute("icon-only",""),this.sendBtn.setAttribute("radius","pill"),this.sendBtn.setAttribute("size","m"),this.sendBtn.addEventListener("db-click",this.handleSendClick),c.append(this.micBtn,this.sendBtn),n.append(h,c),s.append(this.attachmentsEl,a,n),this.dropOverlay=document.createElement("div"),this.dropOverlay.className="designbase-wc-chat-composer__drop-overlay",this.dropOverlay.hidden=!0,this.dropOverlay.setAttribute("aria-hidden","true");const r=document.createElement("span");r.className="designbase-wc-chat-composer__drop-label",r.textContent=e("파일을 놓으면 첨부됩니다"),this.dropOverlay.append(r),this.append(s,this.dropOverlay,this.fileInput),this.renderTools(),this.renderAttachMenu(),this.renderSendButton()}makeIconButton(t,e,s){const i=document.createElement("db-button");return i.setAttribute("variant","ghost"),i.setAttribute("icon-only",""),i.setAttribute("radius","pill"),i.setAttribute("size","m"),i.setAttribute("start-icon",t),i.setAttribute("aria-label",e),i.addEventListener("db-click",()=>{this.disabled||this.dispatchEvent(new CustomEvent(s,{bubbles:!0,composed:!0}))}),i}sync(){this.classList.toggle("designbase-wc-chat-composer--disabled",this.disabled),this.classList.toggle("designbase-wc-chat-composer--streaming",this.streaming),this.field.placeholder=t(this,"placeholder","chatComposer.placeholder"),this.field.disabled=this.disabled,this.field.readOnly=this.voiceActive;const e=this.getAttribute("max-length");e?this.field.maxLength=Number(e):this.field.removeAttribute("maxlength"),this.attachWrap.hidden=!this.hasAttribute("attach"),this.micBtn.hidden=!this.hasAttribute("voice"),this.micBtn.setAttribute("state",this.getAttribute("voice-state")||"idle"),this.micBtn.setAttribute("message",this.getAttribute("voice-message")||""),this.micBtn.toggleAttribute("disabled",this.disabled||this.streaming||this.hasAttribute("voice-disabled")),this.hasAttribute("attach")||this.closeAttachMenu(),this.autoGrow(),this.syncSendState()}renderTools(){this.toolsEl.replaceChildren();for(const t of this._tools){const e=document.createElement("db-chip");e.setAttribute("label",t.label),e.setAttribute("size","s"),e.setAttribute("clickable",""),e.setAttribute("variant",t.active?"primary":"default"),t.icon&&a(t.icon)&&e.setAttribute("start-icon",t.icon),e.setAttribute("aria-pressed",String(!!t.active)),e.addEventListener("db-click",()=>{this.disabled||(t.active=!t.active,e.setAttribute("variant",t.active?"primary":"default"),e.setAttribute("aria-pressed",String(!!t.active)),this.dispatchEvent(new CustomEvent("db-tool-toggle",{detail:{id:t.id,active:!!t.active},bubbles:!0,composed:!0})))}),this.toolsEl.append(e)}}renderAttachMenu(){this.attachMenu.replaceChildren();for(const t of this._attachOptions){const e=document.createElement("button");e.type="button",e.className="designbase-wc-chat-composer__attach-item",e.setAttribute("role","menuitem");const s=document.createElement("span");s.className="designbase-wc-chat-composer__attach-item-icon",t.icon&&a(t.icon)&&s.append(n(t.icon,18));const i=document.createElement("span");i.className="designbase-wc-chat-composer__attach-item-text";const h=document.createElement("span");if(h.className="designbase-wc-chat-composer__attach-item-label",h.textContent=t.label,i.append(h),t.description){const e=document.createElement("span");e.className="designbase-wc-chat-composer__attach-item-desc",e.textContent=t.description,i.append(e)}e.append(s,i),e.addEventListener("click",()=>this.chooseAttachOption(t)),this.attachMenu.append(e)}}renderAttachments(){this.attachmentsEl.replaceChildren(),this.attachmentsEl.hidden=0===this._attachments.length;for(const t of this._attachments){if("image"===t.kind&&t.preview){const e=document.createElement("div");e.className="designbase-wc-chat-composer__thumb";const i=document.createElement("img");i.src=t.preview,i.alt=t.name;const a=document.createElement("button");a.type="button",a.className="designbase-wc-chat-composer__thumb-remove",a.setAttribute("aria-label",s("{0} 제거",[t.name])),a.append(n("close",12)),a.addEventListener("click",()=>this.removeAttachment(t.id)),e.append(i,a),this.attachmentsEl.append(e);continue}const e=document.createElement("db-chip");e.setAttribute("label",t.name),e.setAttribute("size","s"),e.setAttribute("variant","neutral"),e.setAttribute("deletable",""),e.setAttribute("start-icon",h[t.kind]),e.addEventListener("db-delete",()=>this.removeAttachment(t.id)),this.attachmentsEl.append(e)}this.syncSendState()}renderSendButton(){const e=this.streaming;this.sendBtn.setAttribute("variant",e?"secondary":"primary"),this.sendBtn.setAttribute("start-icon",e?"stop":"send"),this.sendBtn.setAttribute("aria-label",e?t(this,"stop-label","chatComposer.stop"):t(this,"send-label","chatComposer.send")),this.syncSendState()}get voiceActive(){return this.hasAttribute("voice")&&["starting","listening","stopping"].includes(this.getAttribute("voice-state")||"idle")}syncSendState(){if(!this.sendBtn)return;const t=0===this.value.trim().length&&0===this._attachments.length,e=this.disabled||this.voiceActive||!this.streaming&&t;this.sendBtn.toggleAttribute("disabled",e)}autoGrow(){this.field&&0!==this.field.clientWidth&&(this.field.style.height="auto",this.field.style.height=`${Math.min(this.field.scrollHeight,200)}px`)}openAttachMenu(){this.attachMenuOpen=!0,this.attachMenu.hidden=!1,this.attachBtn.setAttribute("aria-expanded","true"),this.classList.add("designbase-wc-chat-composer--attach-open"),requestAnimationFrame(()=>this.attachMenu.classList.add("designbase-wc-chat-composer__attach-menu--visible"))}closeAttachMenu(){this.attachMenuOpen&&(this.attachMenuOpen=!1,this.attachMenu.hidden=!0,this.attachMenu.classList.remove("designbase-wc-chat-composer__attach-menu--visible"),this.attachBtn.setAttribute("aria-expanded","false"),this.classList.remove("designbase-wc-chat-composer--attach-open"))}chooseAttachOption(t){this.closeAttachMenu(),this.dispatchEvent(new CustomEvent("db-attach",{detail:{type:t.id},bubbles:!0,composed:!0})),void 0!==t.accept&&(this.fileInput.value="",this.fileInput.accept=t.accept,this.fileInput.multiple=!!t.multiple,t.capture?this.fileInput.setAttribute("capture",t.capture):this.fileInput.removeAttribute("capture"),this.fileInput.dataset.type=t.id,this.fileInput.click())}hasDragFiles(t){return Array.from(t.dataTransfer?.types||[]).includes("Files")}showDropOverlay(t){this.dropOverlay&&(this.dropOverlay.hidden=!t,this.classList.toggle("designbase-wc-chat-composer--drop-active",t))}addFile(t){if(this.hasAttachment(t))return!1;const e=kindFromMime(t.type),s={id:`att-${c+=1}`,name:t.name,size:t.size,mime:t.type,kind:e,file:t,preview:"image"===e?URL.createObjectURL(t):void 0};return this._attachments.push(s),this.renderAttachments(),this.dispatchEvent(new CustomEvent("db-attachment-add",{detail:{attachment:this.attachmentMeta(s)},bubbles:!0,composed:!0})),!0}hasAttachment(t){return this._attachments.some(e=>e.file&&e.file.name===t.name&&e.file.size===t.size&&e.file.type===t.type&&e.file.lastModified===t.lastModified)}attachmentMeta(t){return{id:t.id,name:t.name,size:t.size,mime:t.mime,kind:t.kind,file:t.file,preview:t.preview}}submit(){const t=this.field.value.trim();if(!t&&0===this._attachments.length||this.disabled||this.streaming||this.voiceActive)return;const e=new CustomEvent("db-send",{detail:{value:t,attachments:this._attachments.map(t=>this.attachmentMeta(t))},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(e)&&(this.clear(),this.clearAttachments())}addFiles(t,e="file"){const s=Array.from(t||[]).filter(Boolean);if(!s.length)return;const i=s.filter(t=>this.addFile(t));i.length&&this.dispatchEvent(new CustomEvent("db-attach-files",{detail:{type:e,files:i},bubbles:!0,composed:!0}))}send(){this.submit()}clear(){this.value=""}removeAttachment(t){const e=this._attachments.find(e=>e.id===t);e&&(e.preview&&URL.revokeObjectURL(e.preview),this._attachments=this._attachments.filter(e=>e.id!==t),this.renderAttachments(),this.dispatchEvent(new CustomEvent("db-attachment-remove",{detail:{id:t},bubbles:!0,composed:!0})))}clearAttachments(){this._attachments.forEach(t=>t.preview&&URL.revokeObjectURL(t.preview)),this._attachments=[],this.renderAttachments()}addAttachment(t){if(t instanceof File)return void this.addFile(t);if(t.file&&this.hasAttachment(t.file))return;const e=kindFromMime(t.mime);this._attachments.push({id:`att-${c+=1}`,kind:e,...t}),this.renderAttachments()}focusInput(){this.field?.focus()}setStreaming(t){this.streaming=t}}customElements.get("db-chat-composer")||customElements.define("db-chat-composer",DbChatComposer);export{DbChatComposer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{dbText as t}from"../core/i18n.js";import{createDbIcon as e}from"./db-icons.js";import{sanitizeHtmlFragment as s}from"../core/safe-html.js";import"./db-avatar.js";import"./db-chat-message.js";import"./db-chat-typing.js";import"./db-chat-composer.js";const r="designbase-wc-chat-room";let a=0;function el(t,e,s){const r=document.createElement(t);return e&&(r.className=e),null!=s&&(r.textContent=s),r}class DbChatRoom extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.typing=!1,this.dragDepth=0,this._messages=[],this.handleDragEnter=t=>{this.hasDragFiles(t)&&(t.preventDefault(),this.dragDepth+=1,this.showDropOverlay(!0))},this.handleDragOver=t=>{this.hasDragFiles(t)&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))},this.handleDragLeave=()=>{this.dragDepth=Math.max(0,this.dragDepth-1),0===this.dragDepth&&this.showDropOverlay(!1)},this.handleDrop=t=>{if(!this.hasDragFiles(t))return;t.preventDefault(),t.stopPropagation(),this.dragDepth=0,this.showDropOverlay(!1);const e=Array.from(t.dataTransfer?.files||[]);e.length&&this.composer&&(this.composer.addFiles(e,"drop"),this.composer.focusInput())}}static get observedAttributes(){return["peer-name","peer-avatar","peer-initials","peer-status","placeholder","online","show-back"]}set messages(t){this._messages=Array.isArray(t)?t.map(t=>({id:`r${a+=1}`,...t})):[],this.built&&this.renderThread()}get messages(){return this._messages}connectedCallback(){this.built||this.build(),this.sync(),this.addEventListener("dragenter",this.handleDragEnter),this.addEventListener("dragover",this.handleDragOver),this.addEventListener("dragleave",this.handleDragLeave),this.addEventListener("drop",this.handleDrop)}disconnectedCallback(){this.removeEventListener("dragenter",this.handleDragEnter),this.removeEventListener("dragover",this.handleDragOver),this.removeEventListener("dragleave",this.handleDragLeave),this.removeEventListener("drop",this.handleDrop)}attributeChangedCallback(){this.built&&this.sync()}build(){this.built=!0,this.className=r,this.replaceChildren(),this.headerEl=el("div",`${r}__header`),this.scrollEl=el("div",`${r}__scroll`),this.threadEl=el("div",`${r}__thread`),this.scrollEl.append(this.threadEl),this.dockEl=el("div",`${r}__dock`),this.dropOverlay=el("div",`${r}__drop-overlay`),this.dropOverlay.hidden=!0,this.dropOverlay.setAttribute("aria-hidden","true"),this.dropOverlay.append(el("span",`${r}__drop-label`,"파일을 놓으면 첨부됩니다")),this.composer=document.createElement("db-chat-composer"),this.composer.setAttribute("attach",""),this.composer.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지 보내기…"),this.composer.addEventListener("db-send",t=>{t.stopPropagation();const e=t.detail,s=e?.value?.trim()||"",r=e?.attachments||[];if(!s&&!r.length)return;const a=r.map(t=>({name:t.name,kind:t.kind,mime:t.mime,url:t.file?URL.createObjectURL(t.file):t.preview}));this.dispatchEvent(new CustomEvent("db-send",{detail:{value:s,attachments:a},bubbles:!0,composed:!0})),this.addMessage({mine:!0,text:s,time:this.nowLabel(),attachments:a.length?a:void 0})}),this.dockEl.append(this.composer),this.append(this.headerEl,this.scrollEl,this.dockEl,this.dropOverlay),this.renderThread()}sync(){this.renderHeader(),this.composer.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지 보내기…")}renderHeader(){if(this.headerEl.replaceChildren(),this.hasAttribute("show-back")){const s=el("button",`${r}__back`);s.type="button",s.setAttribute("aria-label",t("뒤로")),s.append(e("chevron-left",20)),s.addEventListener("click",()=>this.dispatchEvent(new CustomEvent("db-back",{bubbles:!0,composed:!0}))),this.headerEl.append(s)}const s=document.createElement("db-avatar");s.className=`${r}__avatar`,s.setAttribute("size","m"),s.setAttribute("variant","primary");const a=this.getAttribute("peer-avatar"),i=this.getAttribute("peer-initials");a?s.setAttribute("src",a):i&&s.setAttribute("initials",i),this.hasAttribute("online")&&s.setAttribute("status","online");const n=el("div",`${r}__meta`);n.append(el("span",`${r}__name`,this.getAttribute("peer-name")||"대화"));const h=this.getAttribute("peer-status")||(this.hasAttribute("online")?"온라인":"");h&&n.append(el("span",`${r}__status`,h)),this.headerEl.append(s,n)}renderThread(){this.threadEl.replaceChildren(),this._messages.forEach(t=>this.threadEl.append(this.buildMessage(t))),this.typing&&this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollToEnd())}buildMessage(t){const e=el("db-chat-message");return e.dataset.id=t.id||"",e.setAttribute("role",t.mine?"user":"assistant"),!t.mine&&t.name&&e.setAttribute("name",t.name),t.time&&e.setAttribute("timestamp",t.time),!t.mine&&t.avatarSrc&&e.setAttribute("avatar-src",t.avatarSrc),!t.mine&&t.avatarInitials&&e.setAttribute("avatar-initials",t.avatarInitials),null!=t.html?e.replaceChildren(s(t.html)):e.textContent=t.text||"",t.attachments?.length&&(e.attachments=t.attachments),e}buildTyping(){const t=el("db-chat-typing");return t.setAttribute("name",this.getAttribute("peer-name")||""),t.setAttribute("avatar-initials",this.getAttribute("peer-initials")||""),t}scrollToEnd(){this.scrollEl.scrollTop=this.scrollEl.scrollHeight}nowLabel(){const t=new Date,e=t.getHours();return`${e<12?"오전":"오후"} ${e%12==0?12:e%12}:${t.getMinutes().toString().padStart(2,"0")}`}hasDragFiles(t){return Array.from(t.dataTransfer?.types||[]).includes("Files")}showDropOverlay(t){this.dropOverlay.hidden=!t,this.classList.toggle(`${r}--drop-active`,t)}addMessage(t){const e={id:`r${a+=1}`,...t};this._messages.push(e);const s=this.threadEl.querySelector("db-chat-typing"),r=this.buildMessage(e);return s?this.threadEl.insertBefore(r,s):this.threadEl.append(r),requestAnimationFrame(()=>this.scrollToEnd()),e.id}setMessages(t){this.messages=t}setTyping(t){if(this.typing=Boolean(t),!this.built)return;const e=this.threadEl.querySelector("db-chat-typing");this.typing&&!e?(this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollToEnd())):!this.typing&&e&&e.remove()}focusInput(){this.composer?.focusInput()}getComposer(){return this.composer}}customElements.get("db-chat-room")||customElements.define("db-chat-room",DbChatRoom);export{DbChatRoom};
|