@designbasekorea/ui-wc 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/LICENSE-WORLD-MAP.md +10 -0
- package/README.md +58 -0
- package/dist/esm/components/db-achievement-list.d.ts +2 -0
- package/dist/esm/components/db-achievement-list.js +1 -1
- package/dist/esm/components/db-activity-heatmap.d.ts +1 -0
- package/dist/esm/components/db-activity-heatmap.js +1 -1
- package/dist/esm/components/db-ad-banner.d.ts +2 -0
- package/dist/esm/components/db-ad-banner.js +1 -1
- package/dist/esm/components/db-ai-chat-list.d.ts +5 -1
- package/dist/esm/components/db-ai-chat-list.js +1 -1
- package/dist/esm/components/db-ai-chat.d.ts +2 -0
- package/dist/esm/components/db-ai-chat.js +1 -1
- package/dist/esm/components/db-ai-file-tree.js +1 -1
- package/dist/esm/components/db-alert.d.ts +1 -0
- package/dist/esm/components/db-alert.js +1 -1
- package/dist/esm/components/db-audio-player.d.ts +2 -0
- package/dist/esm/components/db-audio-player.js +1 -1
- package/dist/esm/components/db-avatar.d.ts +1 -0
- package/dist/esm/components/db-avatar.js +1 -1
- package/dist/esm/components/db-banner.d.ts +2 -0
- package/dist/esm/components/db-banner.js +1 -1
- package/dist/esm/components/db-button.d.ts +7 -1
- package/dist/esm/components/db-button.js +1 -1
- package/dist/esm/components/db-calendar.d.ts +5 -0
- package/dist/esm/components/db-calendar.js +1 -1
- package/dist/esm/components/db-card.d.ts +1 -0
- package/dist/esm/components/db-card.js +1 -1
- package/dist/esm/components/db-chat-composer.d.ts +3 -0
- package/dist/esm/components/db-chat-composer.js +1 -1
- package/dist/esm/components/db-chat-message.d.ts +2 -0
- package/dist/esm/components/db-chat-message.js +1 -1
- package/dist/esm/components/db-chat-room.d.ts +1 -0
- package/dist/esm/components/db-chat-room.js +1 -1
- package/dist/esm/components/db-chat-typing.d.ts +2 -0
- package/dist/esm/components/db-chat-typing.js +1 -1
- package/dist/esm/components/db-chat-widget.d.ts +9 -0
- package/dist/esm/components/db-chat-widget.js +1 -1
- package/dist/esm/components/db-chip.d.ts +2 -0
- package/dist/esm/components/db-chip.js +1 -1
- package/dist/esm/components/db-code-block.d.ts +1 -0
- package/dist/esm/components/db-code-block.js +1 -1
- package/dist/esm/components/db-color-picker.d.ts +4 -0
- package/dist/esm/components/db-color-picker.js +1 -1
- package/dist/esm/components/db-color-swatch.d.ts +3 -0
- package/dist/esm/components/db-color-swatch.js +1 -1
- package/dist/esm/components/db-cookie-banner.d.ts +3 -0
- package/dist/esm/components/db-cookie-banner.js +1 -1
- package/dist/esm/components/db-countdown.d.ts +2 -1
- package/dist/esm/components/db-countdown.js +1 -1
- package/dist/esm/components/db-date-picker.d.ts +3 -0
- package/dist/esm/components/db-date-picker.js +1 -1
- package/dist/esm/components/db-dropdown.d.ts +1 -0
- package/dist/esm/components/db-dropdown.js +1 -1
- package/dist/esm/components/db-dropzone.d.ts +2 -0
- package/dist/esm/components/db-dropzone.js +1 -1
- package/dist/esm/components/db-email-verify.d.ts +1 -0
- package/dist/esm/components/db-email-verify.js +1 -1
- package/dist/esm/components/db-file-uploader.d.ts +2 -0
- package/dist/esm/components/db-file-uploader.js +1 -1
- package/dist/esm/components/db-form.d.ts +2 -0
- package/dist/esm/components/db-form.js +1 -1
- package/dist/esm/components/db-gantt.d.ts +2 -0
- package/dist/esm/components/db-gantt.js +1 -1
- package/dist/esm/components/db-image-list.d.ts +3 -0
- package/dist/esm/components/db-image-list.js +1 -1
- package/dist/esm/components/db-image.d.ts +1 -0
- package/dist/esm/components/db-image.js +1 -1
- package/dist/esm/components/db-input-group.d.ts +30 -0
- package/dist/esm/components/db-input-group.js +1 -0
- package/dist/esm/components/db-input.d.ts +1 -0
- package/dist/esm/components/db-input.js +1 -1
- package/dist/esm/components/db-kanban.d.ts +3 -0
- package/dist/esm/components/db-kanban.js +1 -1
- package/dist/esm/components/db-lightbox.d.ts +2 -0
- package/dist/esm/components/db-lightbox.js +1 -1
- package/dist/esm/components/db-list.d.ts +2 -0
- package/dist/esm/components/db-list.js +1 -1
- package/dist/esm/components/db-markdown-editor.d.ts +2 -0
- package/dist/esm/components/db-markdown-editor.js +1 -1
- package/dist/esm/components/db-menu-item.js +1 -1
- package/dist/esm/components/db-navbar.d.ts +3 -0
- package/dist/esm/components/db-navbar.js +1 -1
- package/dist/esm/components/db-node.d.ts +1 -0
- package/dist/esm/components/db-node.js +1 -1
- package/dist/esm/components/db-onboarding-modal.d.ts +2 -0
- package/dist/esm/components/db-onboarding-modal.js +1 -1
- package/dist/esm/components/db-otp-input.d.ts +4 -1
- package/dist/esm/components/db-otp-input.js +1 -1
- package/dist/esm/components/db-page-header.js +1 -1
- package/dist/esm/components/db-popover.d.ts +1 -0
- package/dist/esm/components/db-popover.js +1 -1
- package/dist/esm/components/db-progress-step.d.ts +2 -0
- package/dist/esm/components/db-progress-step.js +1 -1
- package/dist/esm/components/db-range-slider.d.ts +1 -0
- package/dist/esm/components/db-range-slider.js +1 -1
- package/dist/esm/components/db-rating.d.ts +1 -0
- package/dist/esm/components/db-rating.js +1 -1
- package/dist/esm/components/db-search-bar.d.ts +2 -0
- package/dist/esm/components/db-search-bar.js +1 -1
- package/dist/esm/components/db-section-logo-cloud.js +1 -1
- package/dist/esm/components/db-share.d.ts +5 -0
- package/dist/esm/components/db-share.js +1 -1
- package/dist/esm/components/db-sidebar.d.ts +3 -0
- package/dist/esm/components/db-sidebar.js +1 -1
- package/dist/esm/components/db-signature.d.ts +2 -0
- package/dist/esm/components/db-signature.js +1 -1
- package/dist/esm/components/db-spinner.d.ts +2 -0
- package/dist/esm/components/db-spinner.js +1 -1
- package/dist/esm/components/db-stepper.d.ts +2 -0
- package/dist/esm/components/db-stepper.js +1 -1
- package/dist/esm/components/db-table.d.ts +2 -0
- package/dist/esm/components/db-table.js +1 -1
- package/dist/esm/components/db-tabs.d.ts +1 -0
- package/dist/esm/components/db-tabs.js +1 -1
- package/dist/esm/components/db-ticket.js +1 -1
- package/dist/esm/components/db-time-picker.d.ts +2 -0
- package/dist/esm/components/db-time-picker.js +1 -1
- package/dist/esm/components/db-timeline.d.ts +4 -0
- package/dist/esm/components/db-timeline.js +1 -1
- package/dist/esm/components/db-toast.d.ts +2 -0
- package/dist/esm/components/db-toast.js +1 -1
- package/dist/esm/components/db-tool-layout.d.ts +92 -0
- package/dist/esm/components/db-tool-layout.js +1 -0
- package/dist/esm/components/db-tool-panel.d.ts +50 -0
- package/dist/esm/components/db-tool-panel.js +1 -0
- package/dist/esm/components/db-top-banner.d.ts +2 -0
- package/dist/esm/components/db-top-banner.js +1 -1
- package/dist/esm/components/db-video-player.d.ts +3 -0
- package/dist/esm/components/db-video-player.js +1 -1
- package/dist/esm/components/db-world-map.d.ts +60 -0
- package/dist/esm/components/db-world-map.js +1 -0
- package/dist/esm/components/db-youtube-player.d.ts +2 -0
- package/dist/esm/components/db-youtube-player.js +1 -1
- package/dist/esm/components/db-zoom-control.d.ts +52 -0
- package/dist/esm/components/db-zoom-control.js +1 -0
- package/dist/esm/components/input-validation.js +1 -1
- package/dist/esm/components/paper-card.d.ts +2 -0
- package/dist/esm/components/paper-card.js +1 -1
- package/dist/esm/core/i18n-copy.js +1 -1
- package/dist/esm/core/i18n-en.js +1 -1
- package/dist/esm/core/i18n.d.ts +31 -1
- package/dist/esm/core/i18n.js +1 -1
- package/dist/esm/helpers/world-countries.js +1 -0
- package/dist/esm/helpers/world-land.js +1 -0
- package/dist/esm/index.d.ts +6 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/node_modules/@designbasekorea/ui-contracts/dist/components.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.css +1 -1
- package/dist/index.d.ts +442 -6
- package/dist/index.esm.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +837 -71
- package/dist/react/index.esm.js +1 -1
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sanitizeHref as e}from"../core/safe-url.js";import"./db-badge.js";import{PAGE_HEADER_VARIANTS as t,PAGE_HEADER_ALIGNS as i}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const s=new WeakMap;class DbPageHeader extends HTMLElement{constructor(){super(...arguments),this.internalTabId="",this.isRendering=!1,this.compact=!1,this.motionArmed=!1,this.expandedHeight=0,this.settling=!1,this.updateStickySpace=()=>{if(!this.stickySpacer)return;const e=this.getBoundingClientRect().height;this.compact||this.settling||(this.expandedHeight=e),this.stickySpacer.style.height=`${Math.max(0,this.expandedHeight-e)}px`},this.stickyOffset=0,this.refreshSticky=()=>this.observeSticky(),this.refreshOffset=()=>{this.stickyMarker&&(parseFloat(getComputedStyle(this).top)||0)!==this.stickyOffset&&this.observeSticky()},this.handleBack=()=>{const t=new CustomEvent("db-back",{bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(t),t.defaultPrevented||function navigatePageHeaderBack(t="/"){if("undefined"==typeof window)return;const i=window.history.state?.idx;if("number"==typeof i&&i>0)return void window.history.back();(()=>{try{return!!document.referrer&&new URL(document.referrer).origin===window.location.origin}catch{return!1}})()||window.history.length>1?window.history.back():window.location.assign(e(t,"/"))}(this.getAttribute("back-fallback-href")||"/")},this.handleTabChange=e=>{const t=e.detail,i=t?.selectedId??this.parseTabs()[t?.index??0]?.id??String(t?.index??0);this.hasAttribute("selected-tab-id")||(this.internalTabId=i),this.dispatchEvent(new CustomEvent("db-tab-change",{bubbles:!0,composed:!0,detail:{tabId:i}}))}}static get observedAttributes(){return["title","subtitle","description","breadcrumbs","variant","show-back-button","back-fallback-href","back-label","tabs","selected-tab-id","default-selected-tab-id","align","sticky","compact-on-scroll","background","count"]}observeSticky(){if(this.stickyObserver?.disconnect(),!this.hasAttribute("sticky")||!this.hasAttribute("compact-on-scroll"))return this.stickyMarker?.remove(),this.stickyMarker=void 0,this.stickySpacer?.remove(),this.stickySpacer=void 0,this.sizeObserver?.disconnect(),void this.setCompact(!1);this.stickyMarker||(this.stickyMarker=document.createElement("span"),this.stickyMarker.setAttribute("aria-hidden","true"),this.stickyMarker.style.cssText="display:block;height:1px;margin-bottom:-1px;pointer-events:none;overflow-anchor:none",this.before(this.stickyMarker)),this.stickySpacer||(this.stickySpacer=document.createElement("span"),this.stickySpacer.setAttribute("aria-hidden","true"),this.stickySpacer.style.cssText="display:block;height:0;pointer-events:none;overflow-anchor:none",this.after(this.stickySpacer),this.expandedHeight=this.getBoundingClientRect().height,this.sizeObserver=new ResizeObserver(this.updateStickySpace),this.sizeObserver.observe(this));let e=this.parentElement;for(;e&&e!==document.body&&e!==document.documentElement&&!/(auto|scroll)/.test(getComputedStyle(e).overflowY);)e=e.parentElement;e!==document.body&&e!==document.documentElement||(e=null),this.scrollRoot=e||document.documentElement;const t=parseFloat(getComputedStyle(this).top)||0;this.stickyOffset=t,this.stickyObserver=new IntersectionObserver(([e])=>{this.setCompact(!e.isIntersecting&&e.boundingClientRect.top<(e.rootBounds?.top??t)),this.motionArmed||(this.motionArmed=!0,requestAnimationFrame(()=>requestAnimationFrame(()=>{this.isConnected&&this.motionArmed&&this.setAttribute("data-motion","")})))},{root:e,rootMargin:`-${t}px 0px 0px 0px`,threshold:0}),this.stickyObserver.observe(this.stickyMarker)}setCompact(e){if(this.compact===e)return;if(void 0!==this.motionFrame&&cancelAnimationFrame(this.motionFrame),this.releaseAnchor?.(),this.releaseAnchor=void 0,e&&!this.settling&&(this.expandedHeight=this.getBoundingClientRect().height),this.compact=e,this.settling=!!this.stickySpacer,this.settling&&(this.releaseAnchor=function holdScrollAnchor(e){let t=s.get(e);return t||(t={count:0,value:e.style.getPropertyValue("overflow-anchor"),priority:e.style.getPropertyPriority("overflow-anchor")},s.set(e,t),e.style.setProperty("overflow-anchor","none")),t.count++,()=>{const t=s.get(e);!t||--t.count>0||("none"===e.style.getPropertyValue("overflow-anchor")&&(t.value?e.style.setProperty("overflow-anchor",t.value,t.priority):e.style.removeProperty("overflow-anchor")),s.delete(e))}}(this.scrollRoot||document.documentElement)),this.toggleAttribute("data-compact",e),this.updateStickySpace(),!this.settling)return;let t=-1,i=0;const settle=()=>{this.updateStickySpace();const e=this.getBoundingClientRect().height,s=this.getAnimations({subtree:!0}).some(e=>e instanceof CSSTransition&&"running"===e.playState);i=!s&&Math.abs(e-t)<.1?i+1:0,t=e,i<2?this.motionFrame=requestAnimationFrame(settle):(this.motionFrame=void 0,this.settling=!1,this.updateStickySpace(),this.releaseAnchor?.(),this.releaseAnchor=void 0)};this.motionFrame=requestAnimationFrame(settle)}connectedCallback(){this.syncDefaultTab(),this.render(),this.observeSticky(),window.addEventListener("resize",this.refreshSticky),window.addEventListener("scroll",this.refreshOffset,!0),this.childObserver=new MutationObserver(()=>{this.isRendering||this.hasPendingSlottedChildren()&&this.render()}),this.childObserver.observe(this,{childList:!0})}disconnectedCallback(){this.childObserver?.disconnect(),this.stickyObserver?.disconnect(),this.sizeObserver?.disconnect(),void 0!==this.motionFrame&&cancelAnimationFrame(this.motionFrame),this.motionFrame=void 0,this.settling=!1,this.compact=!1,this.motionArmed=!1,this.removeAttribute("data-compact"),this.removeAttribute("data-motion"),this.releaseAnchor?.(),this.releaseAnchor=void 0,this.stickySpacer?.remove(),this.stickySpacer=void 0,this.stickyMarker?.remove(),this.stickyMarker=void 0,window.removeEventListener("resize",this.refreshSticky),window.removeEventListener("scroll",this.refreshOffset,!0)}attributeChangedCallback(e){this.isConnected&&("default-selected-tab-id"!==e&&"tabs"!==e||this.syncDefaultTab(),this.render(),"sticky"!==e&&"compact-on-scroll"!==e||this.observeSticky())}hasPendingSlottedChildren(){return Array.from(this.children).some(e=>{const t=e.getAttribute("slot");return"actions"===t||"meta"===t||"description"===t||"leading"===t})}syncDefaultTab(){if(this.internalTabId)return;const e=this.parseTabs(),t=this.getAttribute("default-selected-tab-id");this.internalTabId=t||e[0]?.id||""}parseTabs(){try{const e=JSON.parse(this.getAttribute("tabs")||"[]");return Array.isArray(e)?e:[]}catch{return[]}}parseBreadcrumbs(){try{const e=JSON.parse(this.getAttribute("breadcrumbs")||"[]");return Array.isArray(e)?e:[]}catch{return[]}}getActiveTabId(){return this.getAttribute("selected-tab-id")||this.internalTabId}getVariant(){const e=this.getAttribute("variant")||"default";return t.includes(e)?e:"default"}getAlign(){const e=this.getAttribute("align")||"center";return i.includes(e)?e:"center"}collectLeading(){const e=Array.from(this.querySelectorAll(':scope > [slot="leading"]'));if(e.length)return e;const t=this.querySelector(".designbase-wc-page-header__leading");return t?.children.length?Array.from(t.children):[]}collectActions(){const e=Array.from(this.querySelectorAll(':scope > [slot="actions"]'));if(e.length)return e;const t=this.querySelector(".designbase-wc-page-header__cta");if(t?.children.length)return Array.from(t.children);const i=this.querySelector(".designbase-wc-page-header__actions");return i?.children.length?Array.from(i.children):[]}collectMeta(){const e=Array.from(this.querySelectorAll(':scope > [slot="meta"]'));if(e.length)return e;const t=this.querySelector(".designbase-wc-page-header__meta");return t?.children.length?Array.from(t.children):[]}renderMinimalAside(e,t){if(!e.length&&!t.length)return null;const i=document.createElement("div");if(i.className="designbase-wc-page-header__aside",e.length){const t=document.createElement("div");t.className="designbase-wc-page-header__meta",e.forEach(e=>t.append(e)),i.append(t)}if(t.length){const e=document.createElement("div");e.className="designbase-wc-page-header__cta",t.forEach(t=>e.append(t)),i.append(e)}return i}collectDescriptionSlot(){const e=this.querySelector(':scope > [slot="description"]');if(e)return e;const t=this.querySelector(":scope .designbase-wc-page-header__description"),i=t?.firstElementChild;return i||null}renderTitleBlock(e){const t=document.createDocumentFragment(),i=this.getAttribute("title")?.trim()||"",s=this.getAttribute("subtitle")?.trim()||"",r=this.getAttribute("description")?.trim()||"",n=Boolean(e&&(e.textContent?.trim()||e.children.length));if(i){const e=document.createElement("h1");if(e.className="designbase-wc-page-header__title",e.textContent=i,this.hasAttribute("count")){const t=document.createElement("db-badge");t.setAttribute("variant","secondary"),t.setAttribute("size","s"),t.setAttribute("aria-label",this.getAttribute("count")||"0"),t.textContent=this.getAttribute("count"),e.append(t)}t.append(e)}if(s){const e=document.createElement("h2");e.className="designbase-wc-page-header__subtitle",e.textContent=s,t.append(e)}if(n||r){const i=document.createElement("div");i.className="designbase-wc-page-header__description",n&&e?i.append(e):i.textContent=r,t.append(i)}return t}render(){this.isRendering=!0;const e=this.collectActions(),t=this.collectMeta(),i=this.collectLeading(),s=this.collectDescriptionSlot(),r="minimal"===this.getVariant(),n=this.getAlign(),a=this.parseBreadcrumbs(),c=this.parseTabs(),o=c.length>0,d=this.hasAttribute("show-back-button");if(this.className=["designbase-wc-page-header",r?"designbase-wc-page-header--minimal":`designbase-wc-page-header--${n}`,r&&o?"designbase-wc-page-header--has-tabs":""].filter(Boolean).join(" "),this.replaceChildren(),this.setCompact(this.compact),a.length){const e=document.createElement("div");e.className="designbase-wc-page-header__breadcrumbs";const t=document.createElement("db-breadcrumbs");t.setAttribute("size","s"),t.setAttribute("items",JSON.stringify(a)),e.append(t),this.append(e)}const h=document.createElement("div");h.className="designbase-wc-page-header__main";const l=document.createElement("div");if(l.className="designbase-wc-page-header__content",r&&(d||i.length)){const e=document.createElement("div");if(e.className="designbase-wc-page-header__title-row",i.length){const t=document.createElement("div");t.className="designbase-wc-page-header__leading",i.forEach(e=>t.append(e)),e.append(t)}if(d){const t=document.createElement("db-button");t.className="designbase-wc-page-header__back-button",t.setAttribute("variant","tertiary"),t.setAttribute("size","m"),t.setAttribute("icon-only",""),t.setAttribute("start-icon","chevron-left"),t.setAttribute("aria-label",this.getAttribute("back-label")||"뒤로가기"),t.setAttribute("tooltip",this.getAttribute("back-label")||"뒤로가기"),t.addEventListener("db-click",this.handleBack),e.append(t)}const t=document.createElement("div");t.className="designbase-wc-page-header__title-group",t.append(this.renderTitleBlock(s)),e.append(t),l.append(e)}else l.append(this.renderTitleBlock(s));if(h.append(l),r){const i=this.renderMinimalAside(t,e);i&&h.append(i)}if(this.append(h),!r&&e.length){const t=document.createElement("div");t.className="designbase-wc-page-header__actions",e.forEach(e=>t.append(e)),this.append(t)}if(!r&&t.length){const e=document.createElement("div");e.className="designbase-wc-page-header__meta",t.forEach(t=>e.append(t)),this.append(e)}this.renderMinimalTabs(r,o,c),queueMicrotask(()=>{this.isRendering=!1})}renderMinimalTabs(e,t,i){if(!e||!t)return;const s=document.createElement("div");s.className="designbase-wc-page-header__toolbar";const r=document.createElement("div");r.className="designbase-wc-page-header__tabs";const n=document.createElement("db-tabs");n.setAttribute("size","m"),n.setAttribute("items",JSON.stringify(i)),n.setAttribute("selected-id",this.getActiveTabId()),n.addEventListener("db-change",this.handleTabChange),r.append(n),s.append(r),this.append(s)}}customElements.get("db-page-header")||customElements.define("db-page-header",DbPageHeader);export{DbPageHeader};
|
|
1
|
+
import{sanitizeHref as e}from"../core/safe-url.js";import"./db-badge.js";import{PAGE_HEADER_VARIANTS as t,PAGE_HEADER_ALIGNS as i}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const s=new WeakMap;class DbPageHeader extends HTMLElement{constructor(){super(...arguments),this.internalTabId="",this.isRendering=!1,this.compact=!1,this.motionArmed=!1,this.expandedHeight=0,this.settling=!1,this.updateStickySpace=()=>{if(!this.stickySpacer)return;const e=this.getBoundingClientRect().height;this.compact||this.settling||(this.expandedHeight=e),this.stickySpacer.style.height=`${Math.max(0,this.expandedHeight-e)}px`},this.stickyOffset=0,this.refreshSticky=()=>this.observeSticky(),this.refreshOffset=()=>{this.stickyMarker&&(parseFloat(getComputedStyle(this).top)||0)!==this.stickyOffset&&this.observeSticky()},this.handleBack=()=>{const t=new CustomEvent("db-back",{bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(t),t.defaultPrevented||function navigatePageHeaderBack(t="/"){if("undefined"==typeof window)return;const i=window.history.state?.idx;if("number"==typeof i&&i>0)return void window.history.back();(()=>{try{return!!document.referrer&&new URL(document.referrer).origin===window.location.origin}catch{return!1}})()||window.history.length>1?window.history.back():window.location.assign(e(t,"/"))}(this.getAttribute("back-fallback-href")||"/")},this.handleTabChange=e=>{const t=e.detail,i=t?.selectedId??this.parseTabs()[t?.index??0]?.id??String(t?.index??0);this.hasAttribute("selected-tab-id")||(this.internalTabId=i),this.dispatchEvent(new CustomEvent("db-tab-change",{bubbles:!0,composed:!0,detail:{tabId:i}}))}}static get observedAttributes(){return["title","subtitle","subtitle-href","description","breadcrumbs","variant","show-back-button","back-fallback-href","back-label","tabs","selected-tab-id","default-selected-tab-id","align","sticky","compact-on-scroll","background","count"]}observeSticky(){if(this.stickyObserver?.disconnect(),!this.hasAttribute("sticky")||!this.hasAttribute("compact-on-scroll"))return this.stickyMarker?.remove(),this.stickyMarker=void 0,this.stickySpacer?.remove(),this.stickySpacer=void 0,this.sizeObserver?.disconnect(),void this.setCompact(!1);this.stickyMarker||(this.stickyMarker=document.createElement("span"),this.stickyMarker.setAttribute("aria-hidden","true"),this.stickyMarker.style.cssText="display:block;height:1px;margin-bottom:-1px;pointer-events:none;overflow-anchor:none",this.before(this.stickyMarker)),this.stickySpacer||(this.stickySpacer=document.createElement("span"),this.stickySpacer.setAttribute("aria-hidden","true"),this.stickySpacer.style.cssText="display:block;height:0;pointer-events:none;overflow-anchor:none",this.after(this.stickySpacer),this.expandedHeight=this.getBoundingClientRect().height,this.sizeObserver=new ResizeObserver(this.updateStickySpace),this.sizeObserver.observe(this));let e=this.parentElement;for(;e&&e!==document.body&&e!==document.documentElement&&!/(auto|scroll)/.test(getComputedStyle(e).overflowY);)e=e.parentElement;e!==document.body&&e!==document.documentElement||(e=null),this.scrollRoot=e||document.documentElement;const t=parseFloat(getComputedStyle(this).top)||0;this.stickyOffset=t,this.stickyObserver=new IntersectionObserver(([e])=>{this.setCompact(!e.isIntersecting&&e.boundingClientRect.top<(e.rootBounds?.top??t)),this.motionArmed||(this.motionArmed=!0,requestAnimationFrame(()=>requestAnimationFrame(()=>{this.isConnected&&this.motionArmed&&this.setAttribute("data-motion","")})))},{root:e,rootMargin:`-${t}px 0px 0px 0px`,threshold:0}),this.stickyObserver.observe(this.stickyMarker)}setCompact(e){if(this.compact===e)return;if(void 0!==this.motionFrame&&cancelAnimationFrame(this.motionFrame),this.releaseAnchor?.(),this.releaseAnchor=void 0,e&&!this.settling&&(this.expandedHeight=this.getBoundingClientRect().height),this.compact=e,this.settling=!!this.stickySpacer,this.settling&&(this.releaseAnchor=function holdScrollAnchor(e){let t=s.get(e);return t||(t={count:0,value:e.style.getPropertyValue("overflow-anchor"),priority:e.style.getPropertyPriority("overflow-anchor")},s.set(e,t),e.style.setProperty("overflow-anchor","none")),t.count++,()=>{const t=s.get(e);!t||--t.count>0||("none"===e.style.getPropertyValue("overflow-anchor")&&(t.value?e.style.setProperty("overflow-anchor",t.value,t.priority):e.style.removeProperty("overflow-anchor")),s.delete(e))}}(this.scrollRoot||document.documentElement)),this.toggleAttribute("data-compact",e),this.updateStickySpace(),!this.settling)return;let t=-1,i=0;const settle=()=>{this.updateStickySpace();const e=this.getBoundingClientRect().height,s=this.getAnimations({subtree:!0}).some(e=>e instanceof CSSTransition&&"running"===e.playState);i=!s&&Math.abs(e-t)<.1?i+1:0,t=e,i<2?this.motionFrame=requestAnimationFrame(settle):(this.motionFrame=void 0,this.settling=!1,this.updateStickySpace(),this.releaseAnchor?.(),this.releaseAnchor=void 0)};this.motionFrame=requestAnimationFrame(settle)}connectedCallback(){this.syncDefaultTab(),this.render(),this.observeSticky(),window.addEventListener("resize",this.refreshSticky),window.addEventListener("scroll",this.refreshOffset,!0),this.childObserver=new MutationObserver(()=>{this.isRendering||this.hasPendingSlottedChildren()&&this.render()}),this.childObserver.observe(this,{childList:!0})}disconnectedCallback(){this.childObserver?.disconnect(),this.stickyObserver?.disconnect(),this.sizeObserver?.disconnect(),void 0!==this.motionFrame&&cancelAnimationFrame(this.motionFrame),this.motionFrame=void 0,this.settling=!1,this.compact=!1,this.motionArmed=!1,this.removeAttribute("data-compact"),this.removeAttribute("data-motion"),this.releaseAnchor?.(),this.releaseAnchor=void 0,this.stickySpacer?.remove(),this.stickySpacer=void 0,this.stickyMarker?.remove(),this.stickyMarker=void 0,window.removeEventListener("resize",this.refreshSticky),window.removeEventListener("scroll",this.refreshOffset,!0)}attributeChangedCallback(e){this.isConnected&&("default-selected-tab-id"!==e&&"tabs"!==e||this.syncDefaultTab(),this.render(),"sticky"!==e&&"compact-on-scroll"!==e||this.observeSticky())}hasPendingSlottedChildren(){return Array.from(this.children).some(e=>{const t=e.getAttribute("slot");return"actions"===t||"meta"===t||"description"===t||"leading"===t})}syncDefaultTab(){if(this.internalTabId)return;const e=this.parseTabs(),t=this.getAttribute("default-selected-tab-id");this.internalTabId=t||e[0]?.id||""}parseTabs(){try{const e=JSON.parse(this.getAttribute("tabs")||"[]");return Array.isArray(e)?e:[]}catch{return[]}}parseBreadcrumbs(){try{const e=JSON.parse(this.getAttribute("breadcrumbs")||"[]");return Array.isArray(e)?e:[]}catch{return[]}}getActiveTabId(){return this.getAttribute("selected-tab-id")||this.internalTabId}getVariant(){const e=this.getAttribute("variant")||"default";return t.includes(e)?e:"default"}getAlign(){const e=this.getAttribute("align")||"center";return i.includes(e)?e:"center"}collectLeading(){const e=Array.from(this.querySelectorAll(':scope > [slot="leading"]'));if(e.length)return e;const t=this.querySelector(".designbase-wc-page-header__leading");return t?.children.length?Array.from(t.children):[]}collectActions(){const e=Array.from(this.querySelectorAll(':scope > [slot="actions"]'));if(e.length)return e;const t=this.querySelector(".designbase-wc-page-header__cta");if(t?.children.length)return Array.from(t.children);const i=this.querySelector(".designbase-wc-page-header__actions");return i?.children.length?Array.from(i.children):[]}collectMeta(){const e=Array.from(this.querySelectorAll(':scope > [slot="meta"]'));if(e.length)return e;const t=this.querySelector(".designbase-wc-page-header__meta");return t?.children.length?Array.from(t.children):[]}renderMinimalAside(e,t){if(!e.length&&!t.length)return null;const i=document.createElement("div");if(i.className="designbase-wc-page-header__aside",e.length){const t=document.createElement("div");t.className="designbase-wc-page-header__meta",e.forEach(e=>t.append(e)),i.append(t)}if(t.length){const e=document.createElement("div");e.className="designbase-wc-page-header__cta",t.forEach(t=>e.append(t)),i.append(e)}return i}collectDescriptionSlot(){const e=this.querySelector(':scope > [slot="description"]');if(e)return e;const t=this.querySelector(":scope .designbase-wc-page-header__description"),i=t?.firstElementChild;return i||null}renderTitleBlock(t){const i=document.createDocumentFragment(),s=this.getAttribute("title")?.trim()||"",r=this.getAttribute("subtitle")?.trim()||"",n=this.getAttribute("description")?.trim()||"",a=Boolean(t&&(t.textContent?.trim()||t.children.length));if(s){const e=document.createElement("h1");if(e.className="designbase-wc-page-header__title",e.textContent=s,this.hasAttribute("count")){const t=document.createElement("db-badge");t.setAttribute("variant","secondary"),t.setAttribute("size","s"),t.setAttribute("aria-label",this.getAttribute("count")||"0"),t.textContent=this.getAttribute("count"),e.append(t)}i.append(e)}if(r){const t=e(this.getAttribute("subtitle-href"),""),s=document.createElement(t?"a":"h2");s instanceof HTMLAnchorElement&&(s.href=t),s.className="designbase-wc-page-header__subtitle",s.textContent=r,i.append(s)}if(a||n){const e=document.createElement("div");e.className="designbase-wc-page-header__description",a&&t?e.append(t):e.textContent=n,i.append(e)}return i}render(){this.isRendering=!0;const e=this.collectActions(),t=this.collectMeta(),i=this.collectLeading(),s=this.collectDescriptionSlot(),r="minimal"===this.getVariant(),n=this.getAlign(),a=this.parseBreadcrumbs(),c=this.parseTabs(),o=c.length>0,d=this.hasAttribute("show-back-button");if(this.className=["designbase-wc-page-header",r?"designbase-wc-page-header--minimal":`designbase-wc-page-header--${n}`,r&&o?"designbase-wc-page-header--has-tabs":""].filter(Boolean).join(" "),this.replaceChildren(),this.setCompact(this.compact),a.length){const e=document.createElement("div");e.className="designbase-wc-page-header__breadcrumbs";const t=document.createElement("db-breadcrumbs");t.setAttribute("size","s"),t.setAttribute("items",JSON.stringify(a)),e.append(t),this.append(e)}const h=document.createElement("div");h.className="designbase-wc-page-header__main";const l=document.createElement("div");if(l.className="designbase-wc-page-header__content",i.length||r&&d){const e=document.createElement("div");if(e.className="designbase-wc-page-header__title-row",i.length){const t=document.createElement("div");t.className="designbase-wc-page-header__leading",i.forEach(e=>t.append(e)),e.append(t)}if(d){const t=document.createElement("db-button");t.className="designbase-wc-page-header__back-button",t.setAttribute("variant","tertiary"),t.setAttribute("size","m"),t.setAttribute("icon-only",""),t.setAttribute("start-icon","chevron-left"),t.setAttribute("aria-label",this.getAttribute("back-label")||"뒤로가기"),t.setAttribute("tooltip",this.getAttribute("back-label")||"뒤로가기"),t.addEventListener("db-click",this.handleBack),e.append(t)}const t=document.createElement("div");t.className="designbase-wc-page-header__title-group",t.append(this.renderTitleBlock(s)),e.append(t),l.append(e)}else l.append(this.renderTitleBlock(s));if(h.append(l),r){const i=this.renderMinimalAside(t,e);i&&h.append(i)}if(this.append(h),!r&&e.length){const t=document.createElement("div");t.className="designbase-wc-page-header__actions",e.forEach(e=>t.append(e)),this.append(t)}if(!r&&t.length){const e=document.createElement("div");e.className="designbase-wc-page-header__meta",t.forEach(t=>e.append(t)),this.append(e)}this.renderMinimalTabs(r,o,c),queueMicrotask(()=>{this.isRendering=!1})}renderMinimalTabs(e,t,i){if(!e||!t)return;const s=document.createElement("div");s.className="designbase-wc-page-header__toolbar";const r=document.createElement("div");r.className="designbase-wc-page-header__tabs";const n=document.createElement("db-tabs");n.setAttribute("size","m"),n.setAttribute("items",JSON.stringify(i)),n.setAttribute("selected-id",this.getActiveTabId()),n.addEventListener("db-change",this.handleTabChange),r.append(n),s.append(r),this.append(s)}}customElements.get("db-page-header")||customElements.define("db-page-header",DbPageHeader);export{DbPageHeader};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inheritThemeScope as e}from"../core/theme-scope.js";import{dbText as t}from"../core/i18n.js";import{POPOVER_PLACEMENTS as i,POPOVER_TRIGGERS as s}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbPopover extends HTMLElement{constructor(){super(...arguments),this.onDocMouseDown=null,this.onDocKeyDown=null,this.onExternalTriggerClick=null,this.handleTriggerClick=e=>{"click"===this.resolvedTrigger()&&(e.preventDefault(),e.stopPropagation(),this.setOpen(!this.isOpen()))},this.handleTriggerMouseEnter=()=>{"hover"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerMouseLeave=()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()},this.handleTriggerFocus=()=>{"focus"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerBlur=()=>{"focus"===this.resolvedTrigger()&&this.scheduleClose()},this.handleReposition=()=>{this.isOpen()&&(this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.repositionRaf=requestAnimationFrame(()=>{this.positionPanel(),this.repositionRaf=void 0}))}}static get observedAttributes(){return["open","placement","position","title","content","size","variant","trigger","delay","hide-delay","always-show","disabled","max-width","show-arrow","close-on-outside-click","close-on-escape","trigger-id"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(e){e?this.setAttribute("open",""):this.removeAttribute("open")}connectedCallback(){this.classList.add("designbase-wc-popover-host"),this.hasAttribute("placement")||this.hasAttribute("position")||this.setAttribute("placement","top"),this.render(),this.childObserver=new MutationObserver(()=>this.render()),this.childObserver.observe(this,{childList:!0}),this.bindExternalTrigger(),this.attachGlobalListeners(),this.syncOpenFromAttributes()}disconnectedCallback(){this.childObserver?.disconnect(),this.clearTimers(),this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.unbindExternalTrigger(),this.detachGlobalListeners(),this.removePanel()}attributeChangedCallback(e){this.isConnected&&("trigger-id"===e&&(this.unbindExternalTrigger(),this.bindExternalTrigger()),"open"!==e&&"always-show"!==e&&"disabled"!==e?("content"===e&&this.bodyEl&&(this.bodyEl.textContent=this.getAttribute("content")||""),this.isOpen()&&(this.updatePanelMetadata(),requestAnimationFrame(()=>this.positionPanel()))):this.syncOpenFromAttributes())}resolvedPlacement(){const e=this.getAttribute("position")||this.getAttribute("placement")||"top";return i.includes(e)?e:"top"}resolvedTrigger(){const e=this.getAttribute("trigger")||"click";return s.includes(e)?e:"click"}isControlled(){return this.hasAttribute("open")}isOpen(){return!this.hasAttribute("disabled")&&(!!this.hasAttribute("always-show")||(this.isControlled()?"false"!==this.getAttribute("open"):this.panel?.classList.contains("designbase-wc-popover--visible")??!1))}setOpen(e){this.hasAttribute("disabled")||this.hasAttribute("always-show")||(this.isControlled()?e?this.setAttribute("open",""):this.removeAttribute("open"):e?this.showPanel():this.hidePanel(),this.dispatchEvent(new CustomEvent("db-open-change",{bubbles:!0,composed:!0,detail:{open:e}})),e||this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0})))}syncOpenFromAttributes(){this.hasAttribute("always-show")?this.showPanel():this.isControlled()&&("false"!==this.getAttribute("open")?this.showPanel():this.hidePanel())}clearTimers(){this.showTimer&&clearTimeout(this.showTimer),this.hideTimer&&clearTimeout(this.hideTimer),this.showTimer=void 0,this.hideTimer=void 0}groupOf(e){return e.startsWith("top")?"top":e.startsWith("bottom")?"bottom":e.startsWith("left")?"left":"right"}collectTriggerChildren(){const isInternalNode=e=>e.hasAttribute("data-wc-internal")||"content"===e.getAttribute("slot")||e===this.triggerWrap,e=Array.from(this.children).filter(e=>!isInternalNode(e));return e.length>0?e:Array.from(this.triggerWrap?.children||[]).filter(e=>"content"!==e.getAttribute("slot"))}ensureTriggerWrap(){this.triggerWrap||(this.triggerWrap=document.createElement("span"),this.triggerWrap.className="designbase-wc-popover__trigger",this.triggerWrap.setAttribute("data-wc-internal",""),this.triggerWrap.tabIndex=this.hasAttribute("trigger-id")?-1:0,this.triggerWrap.addEventListener("click",this.handleTriggerClick),this.triggerWrap.addEventListener("mouseenter",this.handleTriggerMouseEnter),this.triggerWrap.addEventListener("mouseleave",this.handleTriggerMouseLeave),this.triggerWrap.addEventListener("focus",this.handleTriggerFocus),this.triggerWrap.addEventListener("blur",this.handleTriggerBlur))}mountTriggerChildren(e){this.triggerWrap&&e.forEach(e=>{e.parentElement!==this.triggerWrap&&this.triggerWrap.append(e)})}collectBodyChildren(){return[...Array.from(this.querySelectorAll(':scope > [slot="content"]')),...Array.from(this.bodyEl?.querySelectorAll(':scope > [slot="content"]')||[])]}bindExternalTrigger(){const e=this.getAttribute("trigger-id");e&&(this.triggerEl=document.getElementById(e),this.triggerEl&&(this.onExternalTriggerClick=()=>{"click"===this.resolvedTrigger()&&this.setOpen(!this.isOpen())},this.triggerEl.addEventListener("click",this.onExternalTriggerClick)))}unbindExternalTrigger(){this.triggerEl&&this.onExternalTriggerClick&&this.triggerEl.removeEventListener("click",this.onExternalTriggerClick),this.triggerEl=null,this.onExternalTriggerClick=null}attachGlobalListeners(){this.onDocMouseDown=e=>{if(!this.isOpen()||"false"===this.getAttribute("close-on-outside-click"))return;const t=e.target;this.panel?.contains(t)||this.triggerWrap?.contains(t)||this.triggerEl?.contains(t)||this.setOpen(!1)},this.onDocKeyDown=e=>{"Escape"===e.key&&this.isOpen()&&"false"!==this.getAttribute("close-on-escape")&&this.setOpen(!1)},document.addEventListener("mousedown",this.onDocMouseDown),document.addEventListener("keydown",this.onDocKeyDown)}detachGlobalListeners(){this.onDocMouseDown&&document.removeEventListener("mousedown",this.onDocMouseDown),this.onDocKeyDown&&document.removeEventListener("keydown",this.onDocKeyDown),this.onDocMouseDown=null,this.onDocKeyDown=null}scheduleOpen(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("delay")||0)):0;this.showTimer=setTimeout(()=>this.showPanel(),e)}scheduleClose(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("hide-delay")||80)):0;this.hideTimer=setTimeout(()=>this.setOpen(!1),e)}getTriggerRect(){const e=this.triggerEl||this.triggerWrap;return e?.getBoundingClientRect()}flipPlacementIfNeeded(e,t,i){const s=window.innerHeight,r=window.innerWidth,o=this.groupOf(e),n=t.top-i.height-8>=8,a=t.bottom+8+i.height<=s-8,h=t.left-i.width-8>=8,l=t.right+8+i.width<=r-8;return"top"===o&&!n&&a?e.replace(/^top/,"bottom"):"bottom"===o&&!a&&n?e.replace(/^bottom/,"top"):"left"===o&&!h&&l?e.replace(/^left/,"right"):"right"===o&&!l&&h?e.replace(/^right/,"left"):e}applyCoords(e,t,i){let s=0,r=0,o=0,n=0;const a=i.height,h=i.width,l=16;switch(e){case"top":s=t.top-i.height-8,r=t.left+t.width/2-i.width/2,o=a-5,n=h/2-5;break;case"top-start":s=t.top-i.height-8,r=t.left,o=a-5,n=11;break;case"top-end":s=t.top-i.height-8,r=t.right-i.width,o=a-5,n=h-l-5;break;case"bottom":s=t.bottom+8,r=t.left+t.width/2-i.width/2,o=-5,n=h/2-5;break;case"bottom-start":s=t.bottom+8,r=t.left,o=-5,n=11;break;case"bottom-end":s=t.bottom+8,r=t.right-i.width,o=-5,n=h-l-5;break;case"left":s=t.top+t.height/2-i.height/2,r=t.left-i.width-8,o=a/2-5,n=h-5;break;case"left-start":s=t.top,r=t.left-i.width-8,o=11,n=h-5;break;case"left-end":s=t.bottom-i.height,r=t.left-i.width-8,o=a-l-5,n=h-5;break;case"right":s=t.top+t.height/2-i.height/2,r=t.right+8,o=a/2-5,n=-5;break;case"right-start":s=t.top,r=t.right+8,o=11,n=-5;break;case"right-end":s=t.bottom-i.height,r=t.right+8,o=a-l-5,n=-5}const d=window.innerWidth,c=window.innerHeight;return r<8&&(r=8),r+i.width>d-8&&(r=d-i.width-8),s<8&&(s=8),s+i.height>c-8&&(s=c-i.height-8),{top:s,left:r,aTop:o,aLeft:n,placement:e}}positionPanel(){if(!this.panel)return;const e=this.getTriggerRect();if(!e)return;const t=Number(this.getAttribute("max-width")||300);this.panel.style.maxWidth=`${t}px`,this.panel.offsetHeight;const s=this.panel.getBoundingClientRect(),r=this.resolvedPlacement(),o=this.flipPlacementIfNeeded(r,e,s),{top:n,left:a,aTop:h,aLeft:l}=this.applyCoords(o,e,s);this.panel.style.top=`${n}px`,this.panel.style.left=`${a}px`,this.panel.dataset.placementGroup=this.groupOf(o),i.forEach(e=>{this.panel.classList.toggle(`designbase-wc-popover--${e}`,e===o)}),this.arrowEl&&(this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${o}`,this.arrowEl.style.top=`${h}px`,this.arrowEl.style.left=`${l}px`)}revealPanel(){this.panel&&(this.panel.classList.remove("designbase-wc-popover--visible"),this.positionPanel(),this.panel.offsetHeight,this.positionPanel(),this.panel.classList.add("designbase-wc-popover--visible"))}updatePanelMetadata(){if(!this.panel)return;const e=this.getAttribute("size")||"m",t=this.getAttribute("variant")||"default",i=this.resolvedPlacement();this.panel.className=["designbase-wc-popover",`designbase-wc-popover--${e}`,`designbase-wc-popover--${t}`,`designbase-wc-popover--${i}`,this.isOpen()?"designbase-wc-popover--visible":"",this.hasAttribute("disabled")?"designbase-wc-popover--disabled":""].filter(Boolean).join(" ")}ensurePanel(){if(this.panel)return;const i=document.createElement("div");i.className="designbase-wc-popover",i.setAttribute("data-wc-internal",""),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","false"),i.style.position="fixed",i.style.zIndex="9999";const s=document.createElement("div");s.className="designbase-wc-popover__content";const r=document.createElement("div");r.className="designbase-wc-popover__header";const o=document.createElement("h3");o.className="designbase-wc-popover__title";const n=document.createElement("db-button");n.className="designbase-wc-popover__close-button",n.setAttribute("variant","ghost"),n.setAttribute("size","s"),n.setAttribute("icon-only",""),n.setAttribute("start-icon","close"),n.setAttribute("aria-label",t("팝오버 닫기")),n.addEventListener("db-click",e=>{e.stopPropagation(),this.setOpen(!1)}),r.append(o,n),this.bodyEl=document.createElement("div"),this.bodyEl.className="designbase-wc-popover__body",s.append(r,this.bodyEl),i.append(s),"false"!==this.getAttribute("show-arrow")&&(this.arrowEl=document.createElement("div"),this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${this.resolvedPlacement()}`,i.append(this.arrowEl)),this.panel=i,this.panel.querySelector(".designbase-wc-popover__title").textContent=this.getAttribute("title")||"",this.panel.querySelector(".designbase-wc-popover__title").hidden=!this.getAttribute("title"),e(this,i),document.body.append(i),i.addEventListener("mouseenter",()=>{"hover"===this.resolvedTrigger()&&this.clearTimers()}),i.addEventListener("mouseleave",()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()})}showPanel(){if(this.hasAttribute("disabled"))return;this.ensurePanel(),this.updatePanelMetadata();const e=this.collectBodyChildren();e.length>0?this.bodyEl.replaceChildren(...e):this.bodyEl.textContent=this.getAttribute("content")||"";const t=this.panel.querySelector(".designbase-wc-popover__title");t.textContent=this.getAttribute("title")||"",t.hidden=!this.getAttribute("title"),requestAnimationFrame(()=>{this.revealPanel(),window.addEventListener("scroll",this.handleReposition,{capture:!0,passive:!0}),window.addEventListener("resize",this.handleReposition)})}hidePanel(){this.panel?.classList.remove("designbase-wc-popover--visible"),window.removeEventListener("scroll",this.handleReposition,!0),window.removeEventListener("resize",this.handleReposition),this.hasAttribute("always-show")||this.removePanel()}removePanel(){this.bodyEl?.querySelectorAll(':scope > [slot="content"]').forEach(e=>this.append(e)),this.panel?.remove(),this.panel=void 0,this.bodyEl=void 0,this.arrowEl=void 0}render(){this.ensureTriggerWrap();const e=this.collectTriggerChildren();this.mountTriggerChildren(e);const t=Boolean(this.getAttribute("trigger-id"));this.triggerWrap&&(e.length>0||!t?this.triggerWrap.parentElement!==this&&this.append(this.triggerWrap):this.triggerWrap.parentElement===this&&this.triggerWrap.remove()),this.hasAttribute("always-show")&&this.showPanel()}}customElements.get("db-popover")||customElements.define("db-popover",DbPopover);export{DbPopover};
|
|
1
|
+
import{inheritThemeScope as e}from"../core/theme-scope.js";import{subscribeDbLocale as t,dbText as i}from"../core/i18n.js";import{POPOVER_PLACEMENTS as s,POPOVER_TRIGGERS as r}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbPopover extends HTMLElement{constructor(){super(...arguments),this.onDocMouseDown=null,this.onDocKeyDown=null,this.onExternalTriggerClick=null,this.handleTriggerClick=e=>{"click"===this.resolvedTrigger()&&(e.preventDefault(),e.stopPropagation(),this.setOpen(!this.isOpen()))},this.handleTriggerMouseEnter=()=>{"hover"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerMouseLeave=()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()},this.handleTriggerFocus=()=>{"focus"===this.resolvedTrigger()&&this.scheduleOpen()},this.handleTriggerBlur=()=>{"focus"===this.resolvedTrigger()&&this.scheduleClose()},this.handleReposition=()=>{this.isOpen()&&(this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.repositionRaf=requestAnimationFrame(()=>{this.positionPanel(),this.repositionRaf=void 0}))}}static get observedAttributes(){return["open","placement","position","title","content","size","variant","trigger","delay","hide-delay","always-show","disabled","max-width","show-arrow","close-on-outside-click","close-on-escape","trigger-id"]}get open(){return this.hasAttribute("open")&&"false"!==this.getAttribute("open")}set open(e){e?this.setAttribute("open",""):this.removeAttribute("open")}connectedCallback(){this.classList.add("designbase-wc-popover-host"),this.hasAttribute("placement")||this.hasAttribute("position")||this.setAttribute("placement","top"),this.render(),this.childObserver=new MutationObserver(()=>this.render()),this.childObserver.observe(this,{childList:!0}),this.bindExternalTrigger(),this.attachGlobalListeners(),this.syncOpenFromAttributes(),this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>this.panel?.querySelector(".designbase-wc-popover__close-button")?.setAttribute("aria-label",i("팝오버 닫기")))}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.childObserver?.disconnect(),this.clearTimers(),this.repositionRaf&&cancelAnimationFrame(this.repositionRaf),this.unbindExternalTrigger(),this.detachGlobalListeners(),this.removePanel()}attributeChangedCallback(e){this.isConnected&&("trigger-id"===e&&(this.unbindExternalTrigger(),this.bindExternalTrigger()),"open"!==e&&"always-show"!==e&&"disabled"!==e?("content"===e&&this.bodyEl&&(this.bodyEl.textContent=this.getAttribute("content")||""),this.isOpen()&&(this.updatePanelMetadata(),requestAnimationFrame(()=>this.positionPanel()))):this.syncOpenFromAttributes())}resolvedPlacement(){const e=this.getAttribute("position")||this.getAttribute("placement")||"top";return s.includes(e)?e:"top"}resolvedTrigger(){const e=this.getAttribute("trigger")||"click";return r.includes(e)?e:"click"}isControlled(){return this.hasAttribute("open")}isOpen(){return!this.hasAttribute("disabled")&&(!!this.hasAttribute("always-show")||(this.isControlled()?"false"!==this.getAttribute("open"):this.panel?.classList.contains("designbase-wc-popover--visible")??!1))}setOpen(e){this.hasAttribute("disabled")||this.hasAttribute("always-show")||(this.isControlled()?e?this.setAttribute("open",""):this.removeAttribute("open"):e?this.showPanel():this.hidePanel(),this.dispatchEvent(new CustomEvent("db-open-change",{bubbles:!0,composed:!0,detail:{open:e}})),e||this.dispatchEvent(new CustomEvent("db-close",{bubbles:!0,composed:!0})))}syncOpenFromAttributes(){this.hasAttribute("always-show")?this.showPanel():this.isControlled()&&("false"!==this.getAttribute("open")?this.showPanel():this.hidePanel())}clearTimers(){this.showTimer&&clearTimeout(this.showTimer),this.hideTimer&&clearTimeout(this.hideTimer),this.showTimer=void 0,this.hideTimer=void 0}groupOf(e){return e.startsWith("top")?"top":e.startsWith("bottom")?"bottom":e.startsWith("left")?"left":"right"}collectTriggerChildren(){const isInternalNode=e=>e.hasAttribute("data-wc-internal")||"content"===e.getAttribute("slot")||e===this.triggerWrap,e=Array.from(this.children).filter(e=>!isInternalNode(e));return e.length>0?e:Array.from(this.triggerWrap?.children||[]).filter(e=>"content"!==e.getAttribute("slot"))}ensureTriggerWrap(){this.triggerWrap||(this.triggerWrap=document.createElement("span"),this.triggerWrap.className="designbase-wc-popover__trigger",this.triggerWrap.setAttribute("data-wc-internal",""),this.triggerWrap.tabIndex=this.hasAttribute("trigger-id")?-1:0,this.triggerWrap.addEventListener("click",this.handleTriggerClick),this.triggerWrap.addEventListener("mouseenter",this.handleTriggerMouseEnter),this.triggerWrap.addEventListener("mouseleave",this.handleTriggerMouseLeave),this.triggerWrap.addEventListener("focus",this.handleTriggerFocus),this.triggerWrap.addEventListener("blur",this.handleTriggerBlur))}mountTriggerChildren(e){this.triggerWrap&&e.forEach(e=>{e.parentElement!==this.triggerWrap&&this.triggerWrap.append(e)})}collectBodyChildren(){return[...Array.from(this.querySelectorAll(':scope > [slot="content"]')),...Array.from(this.bodyEl?.querySelectorAll(':scope > [slot="content"]')||[])]}bindExternalTrigger(){const e=this.getAttribute("trigger-id");e&&(this.triggerEl=document.getElementById(e),this.triggerEl&&(this.onExternalTriggerClick=()=>{"click"===this.resolvedTrigger()&&this.setOpen(!this.isOpen())},this.triggerEl.addEventListener("click",this.onExternalTriggerClick)))}unbindExternalTrigger(){this.triggerEl&&this.onExternalTriggerClick&&this.triggerEl.removeEventListener("click",this.onExternalTriggerClick),this.triggerEl=null,this.onExternalTriggerClick=null}attachGlobalListeners(){this.onDocMouseDown=e=>{if(!this.isOpen()||"false"===this.getAttribute("close-on-outside-click"))return;const t=e.target;this.panel?.contains(t)||this.triggerWrap?.contains(t)||this.triggerEl?.contains(t)||this.setOpen(!1)},this.onDocKeyDown=e=>{"Escape"===e.key&&this.isOpen()&&"false"!==this.getAttribute("close-on-escape")&&this.setOpen(!1)},document.addEventListener("mousedown",this.onDocMouseDown),document.addEventListener("keydown",this.onDocKeyDown)}detachGlobalListeners(){this.onDocMouseDown&&document.removeEventListener("mousedown",this.onDocMouseDown),this.onDocKeyDown&&document.removeEventListener("keydown",this.onDocKeyDown),this.onDocMouseDown=null,this.onDocKeyDown=null}scheduleOpen(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("delay")||0)):0;this.showTimer=setTimeout(()=>this.showPanel(),e)}scheduleClose(){this.clearTimers();const e="hover"===this.resolvedTrigger()?Math.max(0,Number(this.getAttribute("hide-delay")||80)):0;this.hideTimer=setTimeout(()=>this.setOpen(!1),e)}getTriggerRect(){const e=this.triggerEl||this.triggerWrap;return e?.getBoundingClientRect()}flipPlacementIfNeeded(e,t,i){const s=window.innerHeight,r=window.innerWidth,o=this.groupOf(e),n=t.top-i.height-8>=8,a=t.bottom+8+i.height<=s-8,h=t.left-i.width-8>=8,l=t.right+8+i.width<=r-8;return"top"===o&&!n&&a?e.replace(/^top/,"bottom"):"bottom"===o&&!a&&n?e.replace(/^bottom/,"top"):"left"===o&&!h&&l?e.replace(/^left/,"right"):"right"===o&&!l&&h?e.replace(/^right/,"left"):e}applyCoords(e,t,i){let s=0,r=0,o=0,n=0;const a=i.height,h=i.width,l=16;switch(e){case"top":s=t.top-i.height-8,r=t.left+t.width/2-i.width/2,o=a-5,n=h/2-5;break;case"top-start":s=t.top-i.height-8,r=t.left,o=a-5,n=11;break;case"top-end":s=t.top-i.height-8,r=t.right-i.width,o=a-5,n=h-l-5;break;case"bottom":s=t.bottom+8,r=t.left+t.width/2-i.width/2,o=-5,n=h/2-5;break;case"bottom-start":s=t.bottom+8,r=t.left,o=-5,n=11;break;case"bottom-end":s=t.bottom+8,r=t.right-i.width,o=-5,n=h-l-5;break;case"left":s=t.top+t.height/2-i.height/2,r=t.left-i.width-8,o=a/2-5,n=h-5;break;case"left-start":s=t.top,r=t.left-i.width-8,o=11,n=h-5;break;case"left-end":s=t.bottom-i.height,r=t.left-i.width-8,o=a-l-5,n=h-5;break;case"right":s=t.top+t.height/2-i.height/2,r=t.right+8,o=a/2-5,n=-5;break;case"right-start":s=t.top,r=t.right+8,o=11,n=-5;break;case"right-end":s=t.bottom-i.height,r=t.right+8,o=a-l-5,n=-5}const d=window.innerWidth,c=window.innerHeight;return r<8&&(r=8),r+i.width>d-8&&(r=d-i.width-8),s<8&&(s=8),s+i.height>c-8&&(s=c-i.height-8),{top:s,left:r,aTop:o,aLeft:n,placement:e}}positionPanel(){if(!this.panel)return;const e=this.getTriggerRect();if(!e)return;const t=Number(this.getAttribute("max-width")||300);this.panel.style.maxWidth=`${t}px`,this.panel.offsetHeight;const i=this.panel.getBoundingClientRect(),r=this.resolvedPlacement(),o=this.flipPlacementIfNeeded(r,e,i),{top:n,left:a,aTop:h,aLeft:l}=this.applyCoords(o,e,i);this.panel.style.top=`${n}px`,this.panel.style.left=`${a}px`,this.panel.dataset.placementGroup=this.groupOf(o),s.forEach(e=>{this.panel.classList.toggle(`designbase-wc-popover--${e}`,e===o)}),this.arrowEl&&(this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${o}`,this.arrowEl.style.top=`${h}px`,this.arrowEl.style.left=`${l}px`)}revealPanel(){this.panel&&(this.panel.classList.remove("designbase-wc-popover--visible"),this.positionPanel(),this.panel.offsetHeight,this.positionPanel(),this.panel.classList.add("designbase-wc-popover--visible"))}updatePanelMetadata(){if(!this.panel)return;const e=this.getAttribute("size")||"m",t=this.getAttribute("variant")||"default",i=this.resolvedPlacement();this.panel.className=["designbase-wc-popover",`designbase-wc-popover--${e}`,`designbase-wc-popover--${t}`,`designbase-wc-popover--${i}`,this.isOpen()?"designbase-wc-popover--visible":"",this.hasAttribute("disabled")?"designbase-wc-popover--disabled":""].filter(Boolean).join(" ")}ensurePanel(){if(this.panel)return;const t=document.createElement("div");t.className="designbase-wc-popover",t.setAttribute("data-wc-internal",""),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","false"),t.style.position="fixed",t.style.zIndex="9999";const s=document.createElement("div");s.className="designbase-wc-popover__content";const r=document.createElement("div");r.className="designbase-wc-popover__header";const o=document.createElement("h3");o.className="designbase-wc-popover__title";const n=document.createElement("db-button");n.className="designbase-wc-popover__close-button",n.setAttribute("variant","ghost"),n.setAttribute("size","s"),n.setAttribute("icon-only",""),n.setAttribute("start-icon","close"),n.setAttribute("aria-label",i("팝오버 닫기")),n.addEventListener("db-click",e=>{e.stopPropagation(),this.setOpen(!1)}),r.append(o,n),this.bodyEl=document.createElement("div"),this.bodyEl.className="designbase-wc-popover__body",s.append(r,this.bodyEl),t.append(s),"false"!==this.getAttribute("show-arrow")&&(this.arrowEl=document.createElement("div"),this.arrowEl.className=`designbase-wc-popover__arrow designbase-wc-popover__arrow--${this.resolvedPlacement()}`,t.append(this.arrowEl)),this.panel=t,this.panel.querySelector(".designbase-wc-popover__title").textContent=this.getAttribute("title")||"",this.panel.querySelector(".designbase-wc-popover__title").hidden=!this.getAttribute("title"),e(this,t),document.body.append(t),t.addEventListener("mouseenter",()=>{"hover"===this.resolvedTrigger()&&this.clearTimers()}),t.addEventListener("mouseleave",()=>{"hover"===this.resolvedTrigger()&&this.scheduleClose()})}showPanel(){if(this.hasAttribute("disabled"))return;this.ensurePanel(),this.updatePanelMetadata();const e=this.collectBodyChildren();e.length>0?this.bodyEl.replaceChildren(...e):this.bodyEl.textContent=this.getAttribute("content")||"";const t=this.panel.querySelector(".designbase-wc-popover__title");t.textContent=this.getAttribute("title")||"",t.hidden=!this.getAttribute("title"),requestAnimationFrame(()=>{this.revealPanel(),window.addEventListener("scroll",this.handleReposition,{capture:!0,passive:!0}),window.addEventListener("resize",this.handleReposition)})}hidePanel(){this.panel?.classList.remove("designbase-wc-popover--visible"),window.removeEventListener("scroll",this.handleReposition,!0),window.removeEventListener("resize",this.handleReposition),this.hasAttribute("always-show")||this.removePanel()}removePanel(){this.bodyEl?.querySelectorAll(':scope > [slot="content"]').forEach(e=>this.append(e)),this.panel?.remove(),this.panel=void 0,this.bodyEl=void 0,this.arrowEl=void 0}render(){this.ensureTriggerWrap();const e=this.collectTriggerChildren();this.mountTriggerChildren(e);const t=Boolean(this.getAttribute("trigger-id"));this.triggerWrap&&(e.length>0||!t?this.triggerWrap.parentElement!==this&&this.append(this.triggerWrap):this.triggerWrap.parentElement===this&&this.triggerWrap.remove()),this.hasAttribute("always-show")&&this.showPanel()}}customElements.get("db-popover")||customElements.define("db-popover",DbPopover);export{DbPopover};
|
|
@@ -7,10 +7,12 @@ interface DbProgressStepItemData {
|
|
|
7
7
|
disabled?: boolean;
|
|
8
8
|
}
|
|
9
9
|
declare class DbProgressStep extends HTMLElement {
|
|
10
|
+
private unsubscribeLocale?;
|
|
10
11
|
static get observedAttributes(): string[];
|
|
11
12
|
get items(): DbProgressStepItemData[];
|
|
12
13
|
set items(value: DbProgressStepItemData[] | string);
|
|
13
14
|
connectedCallback(): void;
|
|
15
|
+
disconnectedCallback(): void;
|
|
14
16
|
attributeChangedCallback(): void;
|
|
15
17
|
private resolveStatus;
|
|
16
18
|
private iconSize;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dbFormat as
|
|
1
|
+
import{subscribeDbLocale as e,dbFormat as t}from"../core/i18n.js";import{createDbIcon as s}from"./db-icons.js";import{coerceToContract as i}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{PROGRESS_STEP_SIZES as n}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbProgressStep extends HTMLElement{static get observedAttributes(){return["items","size","layout","current-step","clickable","full-width","disabled"]}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(),this.unsubscribeLocale?.(),this.unsubscribeLocale=e(()=>{const e=this.items;this.querySelectorAll(".designbase-wc-progress-step__item").forEach((s,i)=>{const n=s.querySelector(".designbase-wc-progress-step__indicator[aria-label]"),r=e[i];n&&r&&n.setAttribute("aria-label",t("{0} 단계로 이동",[r.title]))})})}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0}attributeChangedCallback(){this.render()}resolveStatus(e,t){const s=t.status??"pending";if("pending"!==s)return s;const i=Number(this.getAttribute("current-step")||0);return e<i?"completed":e===i?"active":"pending"}iconSize(e){return"s"===e?12:"l"===e?20:16}renderIndicatorContent(e,t,i){const n=document.createElement("div");if(n.className="designbase-wc-progress-step__icon","completed"===e)n.append(s("done",this.iconSize(i)));else if("error"===e)n.append(s("warning-filled",this.iconSize(i)));else{const e=document.createElement("span");e.className="designbase-wc-progress-step__number",e.textContent=String(t+1),n.append(e)}return n}handleStepClick(e,t){const s=this.hasAttribute("disabled"),i=this.hasAttribute("clickable");s||e.disabled||!i||this.dispatchEvent(new CustomEvent("db-step-click",{detail:{item:e,index:t},bubbles:!0,composed:!0}))}render(){const e=i(this.getAttribute("size"),n,"m"),s=this.getAttribute("layout")||"horizontal",r=this.hasAttribute("clickable"),a=this.hasAttribute("disabled"),c=this.items;this.className=["designbase-wc-progress-step",`designbase-wc-progress-step--${e}`,`designbase-wc-progress-step--${s}`,r&&"designbase-wc-progress-step--clickable",this.hasAttribute("full-width")&&"designbase-wc-progress-step--full-width",a&&"designbase-wc-progress-step--disabled"].filter(Boolean).join(" "),this.replaceChildren(),c.forEach((s,i)=>{const n=this.resolveStatus(i,s),o=i===c.length-1,d=r&&!a&&!s.disabled,p=r&&(a||Boolean(s.disabled)),l="completed"===(i>0?this.resolveStatus(i-1,c[i-1]):"pending")?"completed":n,b=document.createElement("div");b.className=["designbase-wc-progress-step__item",`designbase-wc-progress-step__item--${n}`,d&&"designbase-wc-progress-step__item--clickable",s.disabled&&"designbase-wc-progress-step__item--disabled"].filter(Boolean).join(" ");const m=document.createElement("div");m.className="designbase-wc-progress-step__indicator-container";const g=document.createElement("div");if(g.className="designbase-wc-progress-step__indicator",p&&(g.setAttribute("role","button"),g.setAttribute("aria-disabled","true")),d?(g.tabIndex=0,g.setAttribute("role","button"),g.setAttribute("aria-label",t("{0} 단계로 이동",[s.title])),g.addEventListener("click",()=>this.handleStepClick(s,i)),g.addEventListener("keydown",e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.handleStepClick(s,i))})):g.tabIndex=-1,"active"===n){const e=document.createElement("div");e.className="designbase-wc-progress-step__pulse",g.append(e)}if(g.append(this.renderIndicatorContent(n,i,e)),m.append(g),!o){const e=document.createElement("div");e.className=["designbase-wc-progress-step__connector",`designbase-wc-progress-step__connector--${l}`].join(" "),m.append(e)}b.append(m);const u=document.createElement("div");u.className="designbase-wc-progress-step__content";const h=document.createElement("div");h.className="designbase-wc-progress-step__header";const _=document.createElement("h3");if(_.className="designbase-wc-progress-step__title",_.textContent=s.title,h.append(_),u.append(h),s.description){const e=document.createElement("p");e.className="designbase-wc-progress-step__description",e.textContent=s.description,u.append(e)}if(s.timestamp){const e=document.createElement("span");e.className="designbase-wc-progress-step__timestamp",e.textContent=s.timestamp,u.append(e)}b.append(u),this.append(b)})}}customElements.get("db-progress-step")||customElements.define("db-progress-step",DbProgressStep);export{DbProgressStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{rafThrottle as t}from"../core/dom.js";import{setHostClasses as e}from"../core/host-class.js";import{dbUid as i}from"../core/uid.js";import{sliderBounds as s,sliderPercent as r,sliderValueAt as a,sliderValue as n}from"../core/range-values.js";import{coerceToContract as l}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{RANGE_SLIDER_SIZES as h,RANGE_SLIDER_VARIANTS as u,RANGE_SLIDER_VALUE_POSITIONS as o}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const c="designbase-wc-range-slider";class DbRangeSlider extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.headerEl=null,this.labelEl=null,this.valuesEl=null,this.containerEl=null,this.trackEl=null,this.fillEl=null,this.thumbEls=[],this.initialized=!1,this.reflecting=!1,this.pointerId=null,this.pointerThumb=null,this.currentValue=50,this.currentRange=[25,75],this.isDragging=!1,this.activeThumb=null,this.boundTrackClick=t=>this.handleTrackClick(t),this.boundPointerMove=t=>{t.pointerId===this.pointerId&&this.handlePointerMove(t)},this.boundPointerUp=t=>this.handlePointerUp(t),this.boundPointerCancel=t=>{t.pointerId===this.pointerId&&this.cancelDrag()},this.eventsBound=!1,this.handlePointerMove=t(t=>{this.isDragging&&this.isInteractive()&&t.pointerId===this.pointerId&&this.applyDragValue(this.percentToValue(this.getTrackPercent(t.clientX,t.clientY)))})}static get observedAttributes(){return["value","range","min","max","step","size","variant","show-value","show-label","label","value-position","value-fixed","show-thumb-tooltip","show-marks","marks","mark-labels","snap-marks","disabled","readonly","full-width","vertical","aria-label","aria-labelledby","aria-describedby","label-minimum","label-maximum"]}connectedCallback(){for(const t of["value","range","min","max","step","size","variant","disabled","readOnly","vertical"]){if(!Object.prototype.hasOwnProperty.call(this,t))continue;const e=this,i=e[t];delete e[t],e[t]=i}this.built||(this.build(),this.built=!0),this.readAttributeValues(),this.syncClasses(),this.syncDomOrder(),this.syncStructure(),this.syncVisuals(),this.syncA11y(),this.bindEvents(),this.tooltipResize??(this.tooltipResize=new ResizeObserver(()=>{this.isConnected&&(this.syncThumbTooltips(),this.syncMarkLabelBounds())})),this.tooltipResize.observe(this)}disconnectedCallback(){this.cancelDrag(),this.unbindEvents(),this.tooltipResize?.disconnect()}attributeChangedCallback(t,e,i){if(!this.built||this.reflecting)return;const s="range"===t&&null===e!=(null===i);this.isInteractive()&&!s&&"vertical"!==t||this.cancelDrag();const r=this.thumbEls.findIndex(t=>t===this.ownerDocument.activeElement),a=this.thumbEls[r];this.readAttributeValues(t),this.syncClasses(),(s||this.isStructuralAttribute(t))&&(this.syncDomOrder(),this.syncStructure()),this.syncVisuals(),this.syncA11y();const n=a?.isConnected?a:r>=0?this.thumbEls[Math.min(r,this.thumbEls.length-1)]:void 0;n&&!this.disabled&&this.ownerDocument.activeElement!==n&&n.focus({preventScroll:!0})}isStructuralAttribute(t){return["min","max","step","show-value","show-label","label","value-position","show-marks","marks","mark-labels","vertical","aria-label","aria-labelledby","aria-describedby","label-minimum","label-maximum"].includes(t)}get value(){return this.built?this.currentValue:this.clamp(this.getNumberAttr("value",50))}set value(t){this.currentValue=this.clamp(Number.isFinite(t)?t:50),this.setAttribute("value",String(this.currentValue)),this.syncVisuals(),this.syncA11y()}get range(){if(!this.hasAttribute("range"))return;const t=this.built?this.currentRange:this.parseRangeAttr(this.getAttribute("range"))??this.currentRange;return this.normalizeValues(t)}set range(t){if(null==t)return this.removeAttribute("range"),void(this.built&&(this.syncStructure(),this.syncVisuals()));const e=this.normalizeRangeInput(t);if(!e)return;this.currentRange=this.normalizeValues(e);const i=`${this.currentRange[0]},${this.currentRange[1]}`;this.getAttribute("range")!==i&&this.setAttribute("range",i),this.built&&(this.syncVisuals(),this.syncA11y())}get min(){return this.getNumberAttr("min",0)}set min(t){this.setAttribute("min",String(t))}get max(){return Math.max(this.min,this.getNumberAttr("max",100))}set max(t){this.setAttribute("max",String(t))}get step(){const t=this.getNumberAttr("step",1);return t>0?t:1}set step(t){this.setAttribute("step",String(t))}get size(){return l(this.getAttribute("size"),h,"m")}set size(t){this.setAttribute("size",t)}get variant(){return l(this.getAttribute("variant"),u,"default")}set variant(t){this.setAttribute("variant",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Boolean(t))}get readOnly(){return this.hasAttribute("readonly")}set readOnly(t){this.toggleAttribute("readonly",Boolean(t))}get vertical(){return this.hasAttribute("vertical")}set vertical(t){this.toggleAttribute("vertical",Boolean(t))}focus(t){this.thumbEls[0]?.focus(t)}get bounds(){return s(this.min,this.max,this.step)}normalizeValues(t){const e=this.clamp(t[0]),i=this.clamp(t[1]);return[Math.min(e,i),Math.max(e,i)]}build(){this.classList.add(c),this.headerEl=document.createElement("div"),this.headerEl.className=`${c}__header`,this.labelEl=document.createElement("span"),this.labelEl.className=`${c}__label`,this.valuesEl=document.createElement("div"),this.valuesEl.className=`${c}__values`,this.containerEl=document.createElement("div"),this.containerEl.className=`${c}__container`,this.trackEl=document.createElement("div"),this.trackEl.className=`${c}__track`,this.fillEl=document.createElement("div"),this.fillEl.className=`${c}__fill`,this.trackEl.appendChild(this.fillEl),this.containerEl.appendChild(this.trackEl)}getValuePosition(){const t=this.getAttribute("value-position");return t?l(t,o,this.shouldShowLabel()?"top":"right"):this.shouldShowLabel()?"top":"right"}shouldShowLabel(){return this.hasAttribute("show-label")&&Boolean(this.getAttribute("label")?.trim())}formatValue(t){const e=this.getAttribute("value-fixed");if(null!==e&&""!==e){const i=Number(e);if(Number.isFinite(i))return t.toFixed(Math.min(100,Math.max(0,Math.trunc(i))))}return String(t)}syncDomOrder(){if(!(this.headerEl&&this.valuesEl&&this.containerEl&&this.labelEl))return;const t=this.getValuePosition(),e=this.shouldShowLabel(),i=this.hasAttribute("show-value"),s=this.hasAttribute("range")||"top"===t;this.labelEl.textContent=this.getAttribute("label")?.trim()||"";const r=[...e?[this.labelEl]:[],...i&&s?[this.valuesEl]:[]];this.headerEl.replaceChildren(...r),this.containerEl.parentNode!==this&&this.append(this.containerEl),i&&!s?"bottom"===t?this.lastElementChild!==this.valuesEl&&this.append(this.valuesEl):this.valuesEl.nextElementSibling!==this.containerEl&&this.insertBefore(this.valuesEl,this.containerEl):s&&i||this.valuesEl.remove();const a=i&&!s&&"bottom"!==t?this.valuesEl:this.containerEl;r.length?this.headerEl.nextElementSibling!==a&&this.insertBefore(this.headerEl,a):this.headerEl.remove();const n=new Set([this.containerEl,...r.length?[this.headerEl]:[],...i&&!s?[this.valuesEl]:[]]);for(const t of Array.from(this.children))n.has(t)||t.remove()}bindEvents(){this.eventsBound||(this.containerEl?.addEventListener("click",this.boundTrackClick),this.eventsBound=!0)}unbindEvents(){this.eventsBound&&(this.containerEl?.removeEventListener("click",this.boundTrackClick),document.removeEventListener("pointermove",this.boundPointerMove),document.removeEventListener("pointerup",this.boundPointerUp),document.removeEventListener("pointercancel",this.boundPointerCancel),this.handlePointerMove.cancel(),this.eventsBound=!1)}readAttributeValues(t){const e=!this.initialized;if((e||"value"===t)&&(this.currentValue=this.clamp(this.getNumberAttr("value",50))),e||"range"===t){const t=this.parseRangeAttr(this.getAttribute("range"))??(this.hasAttribute("range")&&!this.getAttribute("range")?this.parseRangeAttr(this.getAttribute("value")):null);this.currentRange=t?this.normalizeValues(t):this.normalizeValues(this.currentRange)}this.currentValue=this.clamp(this.currentValue),this.currentRange=this.normalizeValues(this.currentRange),this.initialized=!0}syncClasses(){const t=this.size,i=this.variant,s=this.hasAttribute("range"),r=this.getValuePosition(),a=s?"top":r,n=this.hasAttribute("show-marks")&&this.parseMarks().length>0&&Object.keys(this.parseMarkLabels()).length>0,l=[c,`${c}--${t}`,`${c}--${i}`,`${c}--value-${a}`,this.shouldShowLabel()?`${c}--has-label`:"",this.hasAttribute("disabled")?`${c}--disabled`:"",this.hasAttribute("readonly")?`${c}--readonly`:"",this.hasAttribute("full-width")?`${c}--full-width`:"",this.hasAttribute("vertical")?`${c}--vertical`:"",this.hasAttribute("show-thumb-tooltip")?`${c}--show-tooltip`:"",s?`${c}--range`:"",n?`${c}--has-mark-labels`:""].filter(Boolean);if(e(this,l),this.trackEl){const t=[`${c}__track`];this.hasAttribute("disabled")&&t.push(`${c}__track--disabled`),this.hasAttribute("readonly")&&t.push(`${c}__track--readonly`),this.trackEl.className=t.join(" ")}}syncStructure(){if(!this.valuesEl||!this.trackEl||!this.fillEl)return;const t=this.hasAttribute("show-value"),e=this.hasAttribute("range"),i=this.hasAttribute("show-marks");if(this.valuesEl.innerHTML="",this.valuesEl.hidden=!t,t)if(e){const t=document.createElement("span");t.className=`${c}__value ${c}__value--min`;const e=document.createElement("span");e.className=`${c}__value-separator`,e.textContent="~",e.setAttribute("aria-hidden","true");const i=document.createElement("span");i.className=`${c}__value ${c}__value--max`,this.valuesEl.append(t,e,i)}else{const t=document.createElement("span");t.className=`${c}__value ${c}__value--single`,this.valuesEl.appendChild(t)}if(this.trackEl.querySelectorAll(`.${c}__mark`).forEach(t=>t.remove()),i){const t=this.parseMarks();if(t.length>0){const e=this.parseMarkLabels();t.forEach(t=>{const i=document.createElement("div");if(i.className=`${c}__mark`,i.setAttribute("aria-hidden","true"),i.dataset.value=String(t),this.isMarkActive(t)&&i.classList.add(`${c}__mark--active`),this.hasAttribute("vertical")?i.style.bottom=`${this.valueToPercent(t)}%`:i.style.left=`${this.valueToPercent(t)}%`,void 0!==e[t]){const s=document.createElement("span");s.className=`${c}__mark-label`,s.textContent=e[t],i.appendChild(s)}this.trackEl.insertBefore(i,this.fillEl)})}}const s=e?2:1;for(;this.thumbEls.length>s;)this.thumbEls.pop()?.remove();for(;this.thumbEls.length<s;){const t=document.createElement("div");t.className=`${c}__thumb`,t.setAttribute("role","slider"),t.setAttribute("draggable","false");const kind=()=>t.dataset.thumb||"single";t.addEventListener("pointerdown",t=>this.handleThumbPointerDown(t,kind())),t.addEventListener("keydown",t=>this.handleKeyDown(t,kind())),t.addEventListener("lostpointercapture",t=>{t.pointerId===this.pointerId&&this.cancelDrag()});const e=document.createElement("span");e.className=`${c}__thumb-tooltip`,e.setAttribute("aria-hidden","true"),e.hidden=!0,t.append(e),this.trackEl.append(t),this.thumbEls.push(t)}this.thumbEls.forEach((t,i)=>t.dataset.thumb=e?0===i?"min":"max":"single")}isMarkActive(t){if(this.hasAttribute("range")){const[e,i]=this.currentRange;return t>=e&&t<=i}return t<=this.currentValue}syncVisuals(){if(!this.fillEl)return;const t=this.hasAttribute("range"),e=this.min,i=this.max;if(t){const[t,s]=this.currentRange,r=this.valueToPercent(t),a=this.valueToPercent(s);this.hasAttribute("vertical")?(this.fillEl.style.left="",this.fillEl.style.width="",this.fillEl.style.bottom=`${r}%`,this.fillEl.style.height=a-r+"%"):(this.fillEl.style.bottom="",this.fillEl.style.height="",this.fillEl.style.left=`${r}%`,this.fillEl.style.width=a-r+"%"),this.thumbEls[0]&&(this.setThumbPosition(this.thumbEls[0],r),this.thumbEls[0].setAttribute("aria-valuemin",String(e)),this.thumbEls[0].setAttribute("aria-valuemax",String(s)),this.thumbEls[0].setAttribute("aria-valuenow",String(t))),this.thumbEls[1]&&(this.setThumbPosition(this.thumbEls[1],a),this.thumbEls[1].setAttribute("aria-valuemin",String(t)),this.thumbEls[1].setAttribute("aria-valuemax",String(i)),this.thumbEls[1].setAttribute("aria-valuenow",String(s)));const n=this.valuesEl?.querySelector(`.${c}__value--min`),l=this.valuesEl?.querySelector(`.${c}__value--max`);n&&(n.textContent=this.formatValue(t)),l&&(l.textContent=this.formatValue(s))}else{const t=this.valueToPercent(this.currentValue);this.hasAttribute("vertical")?(this.fillEl.style.left="",this.fillEl.style.width="",this.fillEl.style.bottom="0",this.fillEl.style.height=`${t}%`):(this.fillEl.style.bottom="",this.fillEl.style.height="",this.fillEl.style.left="0",this.fillEl.style.width=`${t}%`),this.thumbEls[0]&&(this.setThumbPosition(this.thumbEls[0],t),this.thumbEls[0].setAttribute("aria-valuemin",String(e)),this.thumbEls[0].setAttribute("aria-valuemax",String(i)),this.thumbEls[0].setAttribute("aria-valuenow",String(this.currentValue)));const s=this.valuesEl?.querySelector(`.${c}__value--single`);s&&(s.textContent=this.formatValue(this.currentValue))}this.syncThumbTooltips(),this.syncMarkLabelBounds(),this.trackEl?.querySelectorAll(`.${c}__mark`).forEach(t=>{const e=Number(t.dataset.value);t.classList.toggle(`${c}__mark--active`,this.isMarkActive(e))})}syncThumbTooltips(){const t=this.hasAttribute("range"),e=this.hasAttribute("show-thumb-tooltip");this.thumbEls.forEach((i,s)=>{const r=i.querySelector(`.${c}__thumb-tooltip`);if(!r)return;if(!e)return void(r.hidden=!0);r.hidden=!1;const a=t?0===s?this.currentRange[0]:this.currentRange[1]:this.currentValue;r.textContent=this.formatValue(a),this.fitFloatingText(r)})}fitFloatingText(t){const e=this.getBoundingClientRect();if(!e.width)return;t.style.maxWidth=`${e.width}px`,t.style.marginLeft="0px";const i=t.getBoundingClientRect(),s=i.left<e.left?e.left-i.left:i.right>e.right?e.right-i.right:0;s&&(t.style.marginLeft=`${s}px`)}syncMarkLabelBounds(){this.trackEl?.querySelectorAll(`.${c}__mark-label`).forEach(t=>this.fitFloatingText(t))}syncA11y(){if(!this.containerEl)return;const t=this.min,e=this.max,s=this.hasAttribute("range"),r=this.hasAttribute("disabled"),a=this.hasAttribute("readonly");this.containerEl.removeAttribute("role"),this.containerEl.removeAttribute("tabindex"),["aria-valuemin","aria-valuemax","aria-valuenow","aria-valuetext","aria-disabled","aria-readonly"].forEach(t=>this.containerEl?.removeAttribute(t));const n=this.getAttribute("aria-label")?.trim()||this.getAttribute("label")?.trim()||"Value";this.thumbEls.forEach((l,h)=>{const u=s?0===h?this.currentRange[0]:this.currentRange[1]:this.currentValue,o=s?`${n} ${0===h?this.getAttribute("label-minimum")||"minimum":this.getAttribute("label-maximum")||"maximum"}`:n;l.setAttribute("aria-label",o);const c=this.getAttribute("aria-labelledby");if(c)if(s){const t=l.querySelector("[data-range-endpoint]")??document.createElement("span");t.dataset.rangeEndpoint="",t.hidden=!0,t.id||(t.id=i("slider-endpoint")),t.textContent=0===h?this.getAttribute("label-minimum")||"minimum":this.getAttribute("label-maximum")||"maximum",t.parentNode||l.append(t),l.setAttribute("aria-labelledby",c+" "+t.id)}else l.setAttribute("aria-labelledby",c);else l.removeAttribute("aria-labelledby");const b=this.getAttribute("aria-describedby");b?l.setAttribute("aria-describedby",b):l.removeAttribute("aria-describedby"),l.setAttribute("aria-orientation",this.vertical?"vertical":"horizontal"),l.setAttribute("aria-valuemin",String(s&&1===h?this.currentRange[0]:t)),l.setAttribute("aria-valuemax",String(s&&0===h?this.currentRange[1]:e)),l.setAttribute("aria-valuenow",String(u)),l.setAttribute("aria-valuetext",this.formatValue(u)),l.setAttribute("aria-disabled",String(r)),l.setAttribute("aria-readonly",String(a)),l.setAttribute("tabindex",r?"-1":"0")})}setThumbPosition(t,e){this.hasAttribute("vertical")?(t.style.left="",t.style.bottom=`${e}%`):(t.style.bottom="",t.style.left=`${e}%`)}valueToPercent(t){return r(t,this.bounds)}percentToValue(t){return a(t,this.bounds)}clamp(t,e=this.min,i=this.max,r=this.step){const a=this.snapStops();return a.length>0&&Number.isFinite(t)?a.reduce((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e,a[0]):n(t,s(e,i,r))}snapStops(){return this.hasAttribute("snap-marks")?this.parseMarks():[]}adjacentStop(t,e){const i=this.snapStops();return(e>0?i.find(e=>e>t):[...i].reverse().find(e=>e<t))??t}getNumberAttr(t,e){const i=this.getAttribute(t);if(null===i||""===i)return e;const s=Number(i);return Number.isFinite(s)?s:e}normalizeRangeInput(t){if("string"==typeof t)return this.parseRangeAttr(t);if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);return Number.isFinite(e)&&Number.isFinite(i)?[e,i]:null}parseRangeAttr(t){if(!t)return null;if(t.startsWith("[")){try{const e=JSON.parse(t);if(Array.isArray(e)&&2===e.length){const t=Number(e[0]),i=Number(e[1]);if(Number.isFinite(t)&&Number.isFinite(i))return[t,i]}}catch{return null}return null}const e=t.split(",").map(t=>Number(t.trim()));return 2!==e.length||e.some(t=>!Number.isFinite(t))?null:[e[0],e[1]]}parseMarks(){return[...new Set(this.readMarks())].filter(t=>t>=this.min&&t<=this.max).sort((t,e)=>t-e)}readMarks(){const t=this.getAttribute("marks");if(!t)return[];if(t.startsWith("[")){try{const e=JSON.parse(t);if(Array.isArray(e))return e.map(t=>Number(t)).filter(t=>Number.isFinite(t))}catch{return[]}return[]}return t.split(",").map(t=>Number(t.trim())).filter(t=>Number.isFinite(t))}parseMarkLabels(){const t=this.getAttribute("mark-labels");if(!t)return{};try{const e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};const i={};return Object.entries(e).forEach(([t,e])=>{!Number.isFinite(Number(t))||"string"!=typeof e&&"number"!=typeof e||(i[Number(t)]=String(e))}),i}catch{return{}}}isInteractive(){return!this.hasAttribute("disabled")&&!this.hasAttribute("readonly")}getTrackPercent(t,e){if(!this.trackEl)return 0;const i=this.trackEl.getBoundingClientRect();if(!i.width||!i.height)return 0;if(this.hasAttribute("vertical")){const t=Math.max(i.top,Math.min(i.bottom,e));return(i.bottom-t)/i.height*100}return(Math.max(i.left,Math.min(i.right,t))-i.left)/i.width*100}handleThumbPointerDown(t,e){if(this.isInteractive()&&0===t.button&&!1!==t.isPrimary&&!this.isDragging){t.preventDefault(),this.isDragging=!0,this.pointerId=t.pointerId,this.activeThumb=e,this.pointerThumb=t.currentTarget,this.pointerThumb.focus({preventScroll:!0}),this.setThumbActive(e,!0);try{this.pointerThumb.setPointerCapture(t.pointerId)}catch{}document.addEventListener("pointermove",this.boundPointerMove),document.addEventListener("pointerup",this.boundPointerUp),document.addEventListener("pointercancel",this.boundPointerCancel)}}handleTrackClick(t){this.isInteractive()&&this.trackEl&&!t.target.closest(`.${c}__thumb`)&&this.commitValueAtPosition(this.percentToValue(this.getTrackPercent(t.clientX,t.clientY)))}handlePointerUp(t){this.isDragging&&t.pointerId===this.pointerId&&(this.handlePointerMove.cancel(),this.isInteractive()&&this.applyDragValue(this.percentToValue(this.getTrackPercent(t.clientX,t.clientY))),this.cancelDrag())}cancelDrag(){this.handlePointerMove.cancel(),this.activeThumb&&this.setThumbActive(this.activeThumb,!1);const t=this.pointerThumb,e=this.pointerId;this.isDragging=!1,this.activeThumb=null,this.pointerId=null,this.pointerThumb=null,document.removeEventListener("pointermove",this.boundPointerMove),document.removeEventListener("pointerup",this.boundPointerUp),document.removeEventListener("pointercancel",this.boundPointerCancel);try{t&&null!==e&&t.hasPointerCapture(e)&&t.releasePointerCapture(e)}catch{}}setThumbActive(t,e){if(this.hasAttribute("range")){const i=this.thumbEls["min"===t?0:1];return void i?.classList.toggle(`${c}__thumb--active`,e)}this.thumbEls[0]?.classList.toggle(`${c}__thumb--active`,e)}reflectCurrent(){this.reflecting=!0;try{const t=this.hasAttribute("range")?"range":"value",e="range"===t?this.currentRange.join(","):String(this.currentValue);this.getAttribute(t)!==e&&this.setAttribute(t,e)}finally{this.reflecting=!1}}applyDragValue(t){this.applyValue(t,this.activeThumb??"single")}applyValue(t,e){const i=this.clamp(t);if(this.hasAttribute("range")){const[t,s]=this.currentRange,r="min"===e?[Math.min(i,s),s]:[t,Math.max(i,t)];if(r[0]===t&&r[1]===s)return;this.currentRange=r}else{if(i===this.currentValue)return;this.currentValue=i}this.reflectCurrent(),this.syncVisuals(),this.syncA11y(),this.hasAttribute("range")?this.dispatchRangeChange():this.dispatchValueChange()}commitValueAtPosition(t){const e=this.hasAttribute("range")?Math.abs(t-this.currentRange[0])<=Math.abs(t-this.currentRange[1])?"min":"max":"single";this.thumbEls["max"===e?1:0]?.focus({preventScroll:!0}),this.applyValue(t,e)}handleKeyDown(t,e="single"){if(!this.isInteractive())return;const i=this.hasAttribute("range")?this.currentRange["max"===e?1:0]:this.currentValue;let s;if(this.snapStops().length>0){switch(t.key){case"ArrowLeft":case"ArrowDown":case"PageDown":s=this.adjacentStop(i,-1);break;case"ArrowRight":case"ArrowUp":case"PageUp":s=this.adjacentStop(i,1);break;case"Home":s=this.min;break;case"End":s=this.max;break;default:return}return t.preventDefault(),void this.applyValue(s,e)}switch(t.key){case"ArrowLeft":case"ArrowDown":s=i-this.step;break;case"ArrowRight":case"ArrowUp":s=i+this.step;break;case"PageDown":s=i-10*this.step;break;case"PageUp":s=i+10*this.step;break;case"Home":s=this.min;break;case"End":s=this.max;break;default:return}t.preventDefault(),this.applyValue(s,e)}dispatchValueChange(){this.dispatchEvent(new CustomEvent("db-change",{bubbles:!0,composed:!0,detail:{value:this.currentValue}}))}dispatchRangeChange(){const t=[...this.currentRange];for(const e of["db-change","db-range-change"])this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:{range:[...t]}}))}}customElements.get("db-range-slider")||customElements.define("db-range-slider",DbRangeSlider);export{DbRangeSlider};
|
|
1
|
+
import{rafThrottle as t}from"../core/dom.js";import{setHostClasses as e}from"../core/host-class.js";import{dbUid as i}from"../core/uid.js";import{subscribeDbLocale as s,dbText as r}from"../core/i18n.js";import{sliderBounds as a,sliderPercent as n,sliderValueAt as l,sliderValue as h}from"../core/range-values.js";import{coerceToContract as u}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{RANGE_SLIDER_SIZES as o,RANGE_SLIDER_VARIANTS as c,RANGE_SLIDER_VALUE_POSITIONS as b}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const m="designbase-wc-range-slider";class DbRangeSlider extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.headerEl=null,this.labelEl=null,this.valuesEl=null,this.containerEl=null,this.trackEl=null,this.fillEl=null,this.thumbEls=[],this.initialized=!1,this.reflecting=!1,this.pointerId=null,this.pointerThumb=null,this.currentValue=50,this.currentRange=[25,75],this.isDragging=!1,this.activeThumb=null,this.boundTrackClick=t=>this.handleTrackClick(t),this.boundPointerMove=t=>{t.pointerId===this.pointerId&&this.handlePointerMove(t)},this.boundPointerUp=t=>this.handlePointerUp(t),this.boundPointerCancel=t=>{t.pointerId===this.pointerId&&this.cancelDrag()},this.eventsBound=!1,this.handlePointerMove=t(t=>{this.isDragging&&this.isInteractive()&&t.pointerId===this.pointerId&&this.applyDragValue(this.percentToValue(this.getTrackPercent(t.clientX,t.clientY)))})}static get observedAttributes(){return["value","range","min","max","step","size","variant","show-value","show-label","label","value-position","value-fixed","show-thumb-tooltip","show-marks","marks","mark-labels","snap-marks","disabled","readonly","full-width","vertical","aria-label","aria-labelledby","aria-describedby","label-minimum","label-maximum"]}connectedCallback(){for(const t of["value","range","min","max","step","size","variant","disabled","readOnly","vertical"]){if(!Object.prototype.hasOwnProperty.call(this,t))continue;const e=this,i=e[t];delete e[t],e[t]=i}this.built||(this.build(),this.built=!0),this.readAttributeValues(),this.syncClasses(),this.syncDomOrder(),this.syncStructure(),this.syncVisuals(),this.syncA11y(),this.unsubscribeLocale?.(),this.unsubscribeLocale=s(()=>this.syncA11y()),this.bindEvents(),this.tooltipResize??(this.tooltipResize=new ResizeObserver(()=>{this.isConnected&&(this.syncThumbTooltips(),this.syncMarkLabelBounds())})),this.tooltipResize.observe(this)}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.cancelDrag(),this.unbindEvents(),this.tooltipResize?.disconnect()}attributeChangedCallback(t,e,i){if(!this.built||this.reflecting)return;const s="range"===t&&null===e!=(null===i);this.isInteractive()&&!s&&"vertical"!==t||this.cancelDrag();const r=this.thumbEls.findIndex(t=>t===this.ownerDocument.activeElement),a=this.thumbEls[r];this.readAttributeValues(t),this.syncClasses(),(s||this.isStructuralAttribute(t))&&(this.syncDomOrder(),this.syncStructure()),this.syncVisuals(),this.syncA11y();const n=a?.isConnected?a:r>=0?this.thumbEls[Math.min(r,this.thumbEls.length-1)]:void 0;n&&!this.disabled&&this.ownerDocument.activeElement!==n&&n.focus({preventScroll:!0})}isStructuralAttribute(t){return["min","max","step","show-value","show-label","label","value-position","show-marks","marks","mark-labels","vertical","aria-label","aria-labelledby","aria-describedby","label-minimum","label-maximum"].includes(t)}get value(){return this.built?this.currentValue:this.clamp(this.getNumberAttr("value",50))}set value(t){this.currentValue=this.clamp(Number.isFinite(t)?t:50),this.setAttribute("value",String(this.currentValue)),this.syncVisuals(),this.syncA11y()}get range(){if(!this.hasAttribute("range"))return;const t=this.built?this.currentRange:this.parseRangeAttr(this.getAttribute("range"))??this.currentRange;return this.normalizeValues(t)}set range(t){if(null==t)return this.removeAttribute("range"),void(this.built&&(this.syncStructure(),this.syncVisuals()));const e=this.normalizeRangeInput(t);if(!e)return;this.currentRange=this.normalizeValues(e);const i=`${this.currentRange[0]},${this.currentRange[1]}`;this.getAttribute("range")!==i&&this.setAttribute("range",i),this.built&&(this.syncVisuals(),this.syncA11y())}get min(){return this.getNumberAttr("min",0)}set min(t){this.setAttribute("min",String(t))}get max(){return Math.max(this.min,this.getNumberAttr("max",100))}set max(t){this.setAttribute("max",String(t))}get step(){const t=this.getNumberAttr("step",1);return t>0?t:1}set step(t){this.setAttribute("step",String(t))}get size(){return u(this.getAttribute("size"),o,"m")}set size(t){this.setAttribute("size",t)}get variant(){return u(this.getAttribute("variant"),c,"default")}set variant(t){this.setAttribute("variant",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Boolean(t))}get readOnly(){return this.hasAttribute("readonly")}set readOnly(t){this.toggleAttribute("readonly",Boolean(t))}get vertical(){return this.hasAttribute("vertical")}set vertical(t){this.toggleAttribute("vertical",Boolean(t))}focus(t){this.thumbEls[0]?.focus(t)}get bounds(){return a(this.min,this.max,this.step)}normalizeValues(t){const e=this.clamp(t[0]),i=this.clamp(t[1]);return[Math.min(e,i),Math.max(e,i)]}build(){this.classList.add(m),this.headerEl=document.createElement("div"),this.headerEl.className=`${m}__header`,this.labelEl=document.createElement("span"),this.labelEl.className=`${m}__label`,this.valuesEl=document.createElement("div"),this.valuesEl.className=`${m}__values`,this.containerEl=document.createElement("div"),this.containerEl.className=`${m}__container`,this.trackEl=document.createElement("div"),this.trackEl.className=`${m}__track`,this.fillEl=document.createElement("div"),this.fillEl.className=`${m}__fill`,this.trackEl.appendChild(this.fillEl),this.containerEl.appendChild(this.trackEl)}getValuePosition(){const t=this.getAttribute("value-position");return t?u(t,b,this.shouldShowLabel()?"top":"right"):this.shouldShowLabel()?"top":"right"}shouldShowLabel(){return this.hasAttribute("show-label")&&Boolean(this.getAttribute("label")?.trim())}formatValue(t){const e=this.getAttribute("value-fixed");if(null!==e&&""!==e){const i=Number(e);if(Number.isFinite(i))return t.toFixed(Math.min(100,Math.max(0,Math.trunc(i))))}return String(t)}syncDomOrder(){if(!(this.headerEl&&this.valuesEl&&this.containerEl&&this.labelEl))return;const t=this.getValuePosition(),e=this.shouldShowLabel(),i=this.hasAttribute("show-value"),s=this.hasAttribute("range")||"top"===t;this.labelEl.textContent=this.getAttribute("label")?.trim()||"";const r=[...e?[this.labelEl]:[],...i&&s?[this.valuesEl]:[]];this.headerEl.replaceChildren(...r),this.containerEl.parentNode!==this&&this.append(this.containerEl),i&&!s?"bottom"===t?this.lastElementChild!==this.valuesEl&&this.append(this.valuesEl):this.valuesEl.nextElementSibling!==this.containerEl&&this.insertBefore(this.valuesEl,this.containerEl):s&&i||this.valuesEl.remove();const a=i&&!s&&"bottom"!==t?this.valuesEl:this.containerEl;r.length?this.headerEl.nextElementSibling!==a&&this.insertBefore(this.headerEl,a):this.headerEl.remove();const n=new Set([this.containerEl,...r.length?[this.headerEl]:[],...i&&!s?[this.valuesEl]:[]]);for(const t of Array.from(this.children))n.has(t)||t.remove()}bindEvents(){this.eventsBound||(this.containerEl?.addEventListener("click",this.boundTrackClick),this.eventsBound=!0)}unbindEvents(){this.eventsBound&&(this.containerEl?.removeEventListener("click",this.boundTrackClick),document.removeEventListener("pointermove",this.boundPointerMove),document.removeEventListener("pointerup",this.boundPointerUp),document.removeEventListener("pointercancel",this.boundPointerCancel),this.handlePointerMove.cancel(),this.eventsBound=!1)}readAttributeValues(t){const e=!this.initialized;if((e||"value"===t)&&(this.currentValue=this.clamp(this.getNumberAttr("value",50))),e||"range"===t){const t=this.parseRangeAttr(this.getAttribute("range"))??(this.hasAttribute("range")&&!this.getAttribute("range")?this.parseRangeAttr(this.getAttribute("value")):null);this.currentRange=t?this.normalizeValues(t):this.normalizeValues(this.currentRange)}this.currentValue=this.clamp(this.currentValue),this.currentRange=this.normalizeValues(this.currentRange),this.initialized=!0}syncClasses(){const t=this.size,i=this.variant,s=this.hasAttribute("range"),r=this.getValuePosition(),a=s?"top":r,n=this.hasAttribute("show-marks")&&this.parseMarks().length>0&&Object.keys(this.parseMarkLabels()).length>0,l=[m,`${m}--${t}`,`${m}--${i}`,`${m}--value-${a}`,this.shouldShowLabel()?`${m}--has-label`:"",this.hasAttribute("disabled")?`${m}--disabled`:"",this.hasAttribute("readonly")?`${m}--readonly`:"",this.hasAttribute("full-width")?`${m}--full-width`:"",this.hasAttribute("vertical")?`${m}--vertical`:"",this.hasAttribute("show-thumb-tooltip")?`${m}--show-tooltip`:"",s?`${m}--range`:"",n?`${m}--has-mark-labels`:""].filter(Boolean);if(e(this,l),this.trackEl){const t=[`${m}__track`];this.hasAttribute("disabled")&&t.push(`${m}__track--disabled`),this.hasAttribute("readonly")&&t.push(`${m}__track--readonly`),this.trackEl.className=t.join(" ")}}syncStructure(){if(!this.valuesEl||!this.trackEl||!this.fillEl)return;const t=this.hasAttribute("show-value"),e=this.hasAttribute("range"),i=this.hasAttribute("show-marks");if(this.valuesEl.innerHTML="",this.valuesEl.hidden=!t,t)if(e){const t=document.createElement("span");t.className=`${m}__value ${m}__value--min`;const e=document.createElement("span");e.className=`${m}__value-separator`,e.textContent="~",e.setAttribute("aria-hidden","true");const i=document.createElement("span");i.className=`${m}__value ${m}__value--max`,this.valuesEl.append(t,e,i)}else{const t=document.createElement("span");t.className=`${m}__value ${m}__value--single`,this.valuesEl.appendChild(t)}if(this.trackEl.querySelectorAll(`.${m}__mark`).forEach(t=>t.remove()),i){const t=this.parseMarks();if(t.length>0){const e=this.parseMarkLabels();t.forEach(t=>{const i=document.createElement("div");if(i.className=`${m}__mark`,i.setAttribute("aria-hidden","true"),i.dataset.value=String(t),this.isMarkActive(t)&&i.classList.add(`${m}__mark--active`),this.hasAttribute("vertical")?i.style.bottom=`${this.valueToPercent(t)}%`:i.style.left=`${this.valueToPercent(t)}%`,void 0!==e[t]){const s=document.createElement("span");s.className=`${m}__mark-label`,s.textContent=e[t],i.appendChild(s)}this.trackEl.insertBefore(i,this.fillEl)})}}const s=e?2:1;for(;this.thumbEls.length>s;)this.thumbEls.pop()?.remove();for(;this.thumbEls.length<s;){const t=document.createElement("div");t.className=`${m}__thumb`,t.setAttribute("role","slider"),t.setAttribute("draggable","false");const kind=()=>t.dataset.thumb||"single";t.addEventListener("pointerdown",t=>this.handleThumbPointerDown(t,kind())),t.addEventListener("keydown",t=>this.handleKeyDown(t,kind())),t.addEventListener("lostpointercapture",t=>{t.pointerId===this.pointerId&&this.cancelDrag()});const e=document.createElement("span");e.className=`${m}__thumb-tooltip`,e.setAttribute("aria-hidden","true"),e.hidden=!0,t.append(e),this.trackEl.append(t),this.thumbEls.push(t)}this.thumbEls.forEach((t,i)=>t.dataset.thumb=e?0===i?"min":"max":"single")}isMarkActive(t){if(this.hasAttribute("range")){const[e,i]=this.currentRange;return t>=e&&t<=i}return t<=this.currentValue}syncVisuals(){if(!this.fillEl)return;const t=this.hasAttribute("range"),e=this.min,i=this.max;if(t){const[t,s]=this.currentRange,r=this.valueToPercent(t),a=this.valueToPercent(s);this.hasAttribute("vertical")?(this.fillEl.style.left="",this.fillEl.style.width="",this.fillEl.style.bottom=`${r}%`,this.fillEl.style.height=a-r+"%"):(this.fillEl.style.bottom="",this.fillEl.style.height="",this.fillEl.style.left=`${r}%`,this.fillEl.style.width=a-r+"%"),this.thumbEls[0]&&(this.setThumbPosition(this.thumbEls[0],r),this.thumbEls[0].setAttribute("aria-valuemin",String(e)),this.thumbEls[0].setAttribute("aria-valuemax",String(s)),this.thumbEls[0].setAttribute("aria-valuenow",String(t))),this.thumbEls[1]&&(this.setThumbPosition(this.thumbEls[1],a),this.thumbEls[1].setAttribute("aria-valuemin",String(t)),this.thumbEls[1].setAttribute("aria-valuemax",String(i)),this.thumbEls[1].setAttribute("aria-valuenow",String(s)));const n=this.valuesEl?.querySelector(`.${m}__value--min`),l=this.valuesEl?.querySelector(`.${m}__value--max`);n&&(n.textContent=this.formatValue(t)),l&&(l.textContent=this.formatValue(s))}else{const t=this.valueToPercent(this.currentValue);this.hasAttribute("vertical")?(this.fillEl.style.left="",this.fillEl.style.width="",this.fillEl.style.bottom="0",this.fillEl.style.height=`${t}%`):(this.fillEl.style.bottom="",this.fillEl.style.height="",this.fillEl.style.left="0",this.fillEl.style.width=`${t}%`),this.thumbEls[0]&&(this.setThumbPosition(this.thumbEls[0],t),this.thumbEls[0].setAttribute("aria-valuemin",String(e)),this.thumbEls[0].setAttribute("aria-valuemax",String(i)),this.thumbEls[0].setAttribute("aria-valuenow",String(this.currentValue)));const s=this.valuesEl?.querySelector(`.${m}__value--single`);s&&(s.textContent=this.formatValue(this.currentValue))}this.syncThumbTooltips(),this.syncMarkLabelBounds(),this.trackEl?.querySelectorAll(`.${m}__mark`).forEach(t=>{const e=Number(t.dataset.value);t.classList.toggle(`${m}__mark--active`,this.isMarkActive(e))})}syncThumbTooltips(){const t=this.hasAttribute("range"),e=this.hasAttribute("show-thumb-tooltip");this.thumbEls.forEach((i,s)=>{const r=i.querySelector(`.${m}__thumb-tooltip`);if(!r)return;if(!e)return void(r.hidden=!0);r.hidden=!1;const a=t?0===s?this.currentRange[0]:this.currentRange[1]:this.currentValue;r.textContent=this.formatValue(a),this.fitFloatingText(r)})}fitFloatingText(t){const e=this.getBoundingClientRect();if(!e.width)return;t.style.maxWidth=`${e.width}px`,t.style.marginLeft="0px";const i=t.getBoundingClientRect(),s=i.left<e.left?e.left-i.left:i.right>e.right?e.right-i.right:0;s&&(t.style.marginLeft=`${s}px`)}syncMarkLabelBounds(){this.trackEl?.querySelectorAll(`.${m}__mark-label`).forEach(t=>this.fitFloatingText(t))}syncA11y(){if(!this.containerEl)return;const t=this.min,e=this.max,s=this.hasAttribute("range"),a=this.hasAttribute("disabled"),n=this.hasAttribute("readonly");this.containerEl.removeAttribute("role"),this.containerEl.removeAttribute("tabindex"),["aria-valuemin","aria-valuemax","aria-valuenow","aria-valuetext","aria-disabled","aria-readonly"].forEach(t=>this.containerEl?.removeAttribute(t));const l=this.getAttribute("aria-label")?.trim()||this.getAttribute("label")?.trim()||r("슬라이더 값");this.thumbEls.forEach((h,u)=>{const o=s?0===u?this.currentRange[0]:this.currentRange[1]:this.currentValue,c=0===u?this.getAttribute("label-minimum")||r("범위 최솟값"):this.getAttribute("label-maximum")||r("범위 최댓값"),b=s?`${l} ${c}`:l;h.setAttribute("aria-label",b);const m=this.getAttribute("aria-labelledby");if(m)if(s){const t=h.querySelector("[data-range-endpoint]")??document.createElement("span");t.dataset.rangeEndpoint="",t.hidden=!0,t.id||(t.id=i("slider-endpoint")),t.textContent=c,t.parentNode||h.append(t),h.setAttribute("aria-labelledby",m+" "+t.id)}else h.setAttribute("aria-labelledby",m);else h.removeAttribute("aria-labelledby");const d=this.getAttribute("aria-describedby");d?h.setAttribute("aria-describedby",d):h.removeAttribute("aria-describedby"),h.setAttribute("aria-orientation",this.vertical?"vertical":"horizontal"),h.setAttribute("aria-valuemin",String(s&&1===u?this.currentRange[0]:t)),h.setAttribute("aria-valuemax",String(s&&0===u?this.currentRange[1]:e)),h.setAttribute("aria-valuenow",String(o)),h.setAttribute("aria-valuetext",this.formatValue(o)),h.setAttribute("aria-disabled",String(a)),h.setAttribute("aria-readonly",String(n)),h.setAttribute("tabindex",a?"-1":"0")})}setThumbPosition(t,e){this.hasAttribute("vertical")?(t.style.left="",t.style.bottom=`${e}%`):(t.style.bottom="",t.style.left=`${e}%`)}valueToPercent(t){return n(t,this.bounds)}percentToValue(t){return l(t,this.bounds)}clamp(t,e=this.min,i=this.max,s=this.step){const r=this.snapStops();return r.length>0&&Number.isFinite(t)?r.reduce((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e,r[0]):h(t,a(e,i,s))}snapStops(){return this.hasAttribute("snap-marks")?this.parseMarks():[]}adjacentStop(t,e){const i=this.snapStops();return(e>0?i.find(e=>e>t):[...i].reverse().find(e=>e<t))??t}getNumberAttr(t,e){const i=this.getAttribute(t);if(null===i||""===i)return e;const s=Number(i);return Number.isFinite(s)?s:e}normalizeRangeInput(t){if("string"==typeof t)return this.parseRangeAttr(t);if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);return Number.isFinite(e)&&Number.isFinite(i)?[e,i]:null}parseRangeAttr(t){if(!t)return null;if(t.startsWith("[")){try{const e=JSON.parse(t);if(Array.isArray(e)&&2===e.length){const t=Number(e[0]),i=Number(e[1]);if(Number.isFinite(t)&&Number.isFinite(i))return[t,i]}}catch{return null}return null}const e=t.split(",").map(t=>Number(t.trim()));return 2!==e.length||e.some(t=>!Number.isFinite(t))?null:[e[0],e[1]]}parseMarks(){return[...new Set(this.readMarks())].filter(t=>t>=this.min&&t<=this.max).sort((t,e)=>t-e)}readMarks(){const t=this.getAttribute("marks");if(!t)return[];if(t.startsWith("[")){try{const e=JSON.parse(t);if(Array.isArray(e))return e.map(t=>Number(t)).filter(t=>Number.isFinite(t))}catch{return[]}return[]}return t.split(",").map(t=>Number(t.trim())).filter(t=>Number.isFinite(t))}parseMarkLabels(){const t=this.getAttribute("mark-labels");if(!t)return{};try{const e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};const i={};return Object.entries(e).forEach(([t,e])=>{!Number.isFinite(Number(t))||"string"!=typeof e&&"number"!=typeof e||(i[Number(t)]=String(e))}),i}catch{return{}}}isInteractive(){return!this.hasAttribute("disabled")&&!this.hasAttribute("readonly")}getTrackPercent(t,e){if(!this.trackEl)return 0;const i=this.trackEl.getBoundingClientRect();if(!i.width||!i.height)return 0;if(this.hasAttribute("vertical")){const t=Math.max(i.top,Math.min(i.bottom,e));return(i.bottom-t)/i.height*100}return(Math.max(i.left,Math.min(i.right,t))-i.left)/i.width*100}handleThumbPointerDown(t,e){if(this.isInteractive()&&0===t.button&&!1!==t.isPrimary&&!this.isDragging){t.preventDefault(),this.isDragging=!0,this.pointerId=t.pointerId,this.activeThumb=e,this.pointerThumb=t.currentTarget,this.pointerThumb.focus({preventScroll:!0}),this.setThumbActive(e,!0);try{this.pointerThumb.setPointerCapture(t.pointerId)}catch{}document.addEventListener("pointermove",this.boundPointerMove),document.addEventListener("pointerup",this.boundPointerUp),document.addEventListener("pointercancel",this.boundPointerCancel)}}handleTrackClick(t){this.isInteractive()&&this.trackEl&&!t.target.closest(`.${m}__thumb`)&&this.commitValueAtPosition(this.percentToValue(this.getTrackPercent(t.clientX,t.clientY)))}handlePointerUp(t){this.isDragging&&t.pointerId===this.pointerId&&(this.handlePointerMove.cancel(),this.isInteractive()&&this.applyDragValue(this.percentToValue(this.getTrackPercent(t.clientX,t.clientY))),this.cancelDrag())}cancelDrag(){this.handlePointerMove.cancel(),this.activeThumb&&this.setThumbActive(this.activeThumb,!1);const t=this.pointerThumb,e=this.pointerId;this.isDragging=!1,this.activeThumb=null,this.pointerId=null,this.pointerThumb=null,document.removeEventListener("pointermove",this.boundPointerMove),document.removeEventListener("pointerup",this.boundPointerUp),document.removeEventListener("pointercancel",this.boundPointerCancel);try{t&&null!==e&&t.hasPointerCapture(e)&&t.releasePointerCapture(e)}catch{}}setThumbActive(t,e){if(this.hasAttribute("range")){const i=this.thumbEls["min"===t?0:1];return void i?.classList.toggle(`${m}__thumb--active`,e)}this.thumbEls[0]?.classList.toggle(`${m}__thumb--active`,e)}reflectCurrent(){this.reflecting=!0;try{const t=this.hasAttribute("range")?"range":"value",e="range"===t?this.currentRange.join(","):String(this.currentValue);this.getAttribute(t)!==e&&this.setAttribute(t,e)}finally{this.reflecting=!1}}applyDragValue(t){this.applyValue(t,this.activeThumb??"single")}applyValue(t,e){const i=this.clamp(t);if(this.hasAttribute("range")){const[t,s]=this.currentRange,r="min"===e?[Math.min(i,s),s]:[t,Math.max(i,t)];if(r[0]===t&&r[1]===s)return;this.currentRange=r}else{if(i===this.currentValue)return;this.currentValue=i}this.reflectCurrent(),this.syncVisuals(),this.syncA11y(),this.hasAttribute("range")?this.dispatchRangeChange():this.dispatchValueChange()}commitValueAtPosition(t){const e=this.hasAttribute("range")?Math.abs(t-this.currentRange[0])<=Math.abs(t-this.currentRange[1])?"min":"max":"single";this.thumbEls["max"===e?1:0]?.focus({preventScroll:!0}),this.applyValue(t,e)}handleKeyDown(t,e="single"){if(!this.isInteractive())return;const i=this.hasAttribute("range")?this.currentRange["max"===e?1:0]:this.currentValue;let s;if(this.snapStops().length>0){switch(t.key){case"ArrowLeft":case"ArrowDown":case"PageDown":s=this.adjacentStop(i,-1);break;case"ArrowRight":case"ArrowUp":case"PageUp":s=this.adjacentStop(i,1);break;case"Home":s=this.min;break;case"End":s=this.max;break;default:return}return t.preventDefault(),void this.applyValue(s,e)}switch(t.key){case"ArrowLeft":case"ArrowDown":s=i-this.step;break;case"ArrowRight":case"ArrowUp":s=i+this.step;break;case"PageDown":s=i-10*this.step;break;case"PageUp":s=i+10*this.step;break;case"Home":s=this.min;break;case"End":s=this.max;break;default:return}t.preventDefault(),this.applyValue(s,e)}dispatchValueChange(){this.dispatchEvent(new CustomEvent("db-change",{bubbles:!0,composed:!0,detail:{value:this.currentValue}}))}dispatchRangeChange(){const t=[...this.currentRange];for(const e of["db-change","db-range-change"])this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:{range:[...t]}}))}}customElements.get("db-range-slider")||customElements.define("db-range-slider",DbRangeSlider);export{DbRangeSlider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{subscribeDbLocale as e,t,getDbLocale as s}from"../core/i18n.js";import{createDbIcon as i}from"./db-icons.js";import{rafThrottle as r}from"../core/dom.js";import{coerceToContract as a}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{RATING_SIZES as n,RATING_VARIANTS as o}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const l=n,c=o,h=["stars","number","both","reviews","detailed"],g=["star","number","percentage","text"],u=["primary","secondary","success","warning","error","custom"];class DbRating extends HTMLElement{constructor(){super(...arguments),this.hoverValue=null,this.starsEl=null,this.handlePointerMove=r(e=>{if(!this.isInteractive()||!this.getBooleanAttr("hover-effect",!0))return;const t=e.target?.closest(".designbase-wc-rating__star");if(!t||!this.contains(t))return;const s=Number(t.dataset.index);if(!Number.isFinite(s))return;const i=this.getNumberAttr("max-value",5),r=this.getPointerValue(s,e.clientX,t,i);this.hoverValue!==r&&(this.hoverValue=r,this.classList.toggle("designbase-wc-rating--hovering",!0),this.refreshStars(),this.dispatchEvent(new CustomEvent("db-hover",{detail:{value:r},bubbles:!0,composed:!0})))}),this.handlePointerLeave=()=>{null!==this.hoverValue&&(this.hoverValue=null,this.classList.remove("designbase-wc-rating--hovering"),this.refreshStars())},this.handleClick=e=>{if(!this.isInteractive())return;const t=e.target?.closest(".designbase-wc-rating__star");if(!t||!this.contains(t))return;e.preventDefault();const s=Number(t.dataset.index);if(!Number.isFinite(s))return;const i=this.getNumberAttr("max-value",5),r=this.getPointerValue(s,e.clientX,t,i);this.hoverValue=null,this.classList.remove("designbase-wc-rating--hovering"),this.setAttribute("value",String(r)),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:r},bubbles:!0,composed:!0})),this.render()}}static get observedAttributes(){return["value","max-value","size","variant","type","display","review-count","rating-text","review-text","allow-half","readonly","disabled","clickable","color","custom-color","animated","hover-effect"]}connectedCallback(){this.addEventListener("mousemove",this.handlePointerMove),this.addEventListener("mouseleave",this.handlePointerLeave),this.addEventListener("click",this.handleClick),this.render(),this.unsubscribeLocale?.(),this.unsubscribeLocale=e(()=>this.render())}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.removeEventListener("mousemove",this.handlePointerMove),this.removeEventListener("mouseleave",this.handlePointerLeave),this.removeEventListener("click",this.handleClick)}attributeChangedCallback(){this.isConnected&&this.render()}getNumberAttr(e,t){const s=this.getAttribute(e);if(null===s||""===s)return t;const i=Number(s);return Number.isFinite(i)?i:t}getBooleanAttr(e,t=!1){if(!this.hasAttribute(e))return t;const s=this.getAttribute(e);return""===s||"true"===s}getOption(e,t,s){const i=this.getAttribute(e);return i&&t.includes(i)?i:s}normalizeSize(e){return"xs"===e||"s"===e?"s":"xl"===e||"l"===e?"l":"m"===e?"m":a(e,l,"m")}getStarIconSize(){const e=this.normalizeSize(this.getAttribute("size"));return"s"===e?16:"l"===e?24:20}supportsHalfSteps(){return this.getBooleanAttr("allow-half")||this.getBooleanAttr("clickable")}isInteractive(){return this.getBooleanAttr("clickable")&&!this.getBooleanAttr("readonly")&&!this.getBooleanAttr("disabled")}getStarFill(e,t,s){const i=e+1;return t>=i?1:s&&t>=i-.5?.5:0}getPointerValue(e,t,s,i){const r=s.getBoundingClientRect();let a;return a=this.supportsHalfSteps()&&t-r.left<r.width/2?e+.5:e+1,a/5*i}formatRating(e,s,i,r){const a=e/s*5;return"percentage"===i?`${Math.round(e/s*100)}%`:"number"===i?r?a.toFixed(1):String(Math.round(a)):"text"===i?t(a>=4.5?"rating.high":a>=3?"rating.medium":"rating.low"):`${a.toFixed(1)}/5`}updateStarElement(e,t,s,r,a){e.className=["designbase-wc-rating__star",0===t&&"designbase-wc-rating__star--empty",t>0&&a&&"designbase-wc-rating__star--hover-preview",r&&"designbase-wc-rating__star--clickable",this.getBooleanAttr("animated")&&"designbase-wc-rating__star--animated"].filter(Boolean).join(" "),e.dataset.index=String(s);const n=1===t?"star-filled":.5===t?"star-half":"star",o=this.getStarIconSize(),l=e.querySelector("svg");l?.getAttribute("data-designbase-icon")===n&&l.getAttribute("width")===String(o)||e.replaceChildren(i(n,o))}refreshStars(){if(!this.starsEl)return;const e=this.getNumberAttr("value",0),t=this.getNumberAttr("max-value",5),s=this.getBooleanAttr("allow-half",!1),i=this.getBooleanAttr("hover-effect",!0),r=null!==this.hoverValue&&i,a=(r?this.hoverValue:e)/t*5,n=this.isInteractive(),o=s||r,l=Array.from(this.starsEl.querySelectorAll(":scope > .designbase-wc-rating__star"));for(let e=0;e<5;e+=1){const t=this.getStarFill(e,a,o),s=r&&t>0,i=l[e]??document.createElement("span");i.setAttribute("aria-hidden","true"),this.updateStarElement(i,t,e,n,s),l[e]||this.starsEl.append(i)}for(let e=l.length-1;e>=5;e-=1)l[e]?.remove()}render(){const e=this.getNumberAttr("value",0),i=this.getNumberAttr("max-value",5),r=this.normalizeSize(this.getAttribute("size")),a=this.getOption("variant",c,"default"),n=this.getOption("type",g,"star"),o=this.getOption("display",h,"stars"),l=this.getOption("color",u,"primary"),d=this.getNumberAttr("review-count",0),m=this.getBooleanAttr("allow-half",!1),b=this.getBooleanAttr("readonly",!1),v=this.getBooleanAttr("disabled",!1),p=this.getBooleanAttr("clickable",!1),f=this.getBooleanAttr("hover-effect",!0),w=null!==this.hoverValue&&f;this.className=["designbase-wc-rating",`designbase-wc-rating--size-${r}`,`designbase-wc-rating--variant-${a}`,`designbase-wc-rating--type-${n}`,`designbase-wc-rating--display-${o}`,`designbase-wc-rating--color-${l}`,b&&"designbase-wc-rating--readonly",v&&"designbase-wc-rating--disabled",p&&"designbase-wc-rating--clickable",this.getBooleanAttr("animated")&&"designbase-wc-rating--animated",w&&"designbase-wc-rating--hovering"].filter(Boolean).join(" ");const A=this.getAttribute("custom-color");"custom"===l&&A?this.style.setProperty("--rating-color",A):this.style.removeProperty("--rating-color");let _=this.querySelector(':scope > [role="img"]');_||(_=document.createElement("div"),this.replaceChildren(_)),_.setAttribute("role","img"),_.setAttribute("aria-label",t("rating.label").replace("{value}",this.formatRating(e,i,n,m)));if("stars"===o||"both"===o||"detailed"===o){const e=_.querySelectorAll(":scope > .designbase-wc-rating__stars");e.forEach((e,t)=>{t>0&&e.remove()});const t=e[0];t?this.starsEl=t:(this.starsEl=document.createElement("div"),this.starsEl.className="designbase-wc-rating__stars",_.prepend(this.starsEl)),this.refreshStars()}else this.starsEl&&(this.starsEl.remove(),this.starsEl=null);const E=this.getAttribute("rating-text")||this.formatRating(e,i,n,m);let S=_.querySelector(".designbase-wc-rating__number-container");if("number"===o||"both"===o){if(!S){S=document.createElement("div"),S.className="designbase-wc-rating__number-container";const e=document.createElement("span");e.className="designbase-wc-rating__number",S.append(e),_.append(S)}const e=S.querySelector(".designbase-wc-rating__number");e&&(e.textContent=E)}else S?.remove();let y=_.querySelector(".designbase-wc-rating__review-count");if("reviews"===o||"detailed"===o){const e=this.getAttribute("review-text")||(d>0?t(1===d?"rating.review":"rating.reviews").replace("{count}",d.toLocaleString("ko"===s()?"ko-KR":"en-US")):"");e?(y||(y=document.createElement("span"),y.className="designbase-wc-rating__review-count",_.append(y)),y.textContent=e):y?.remove()}else y?.remove()}}customElements.get("db-rating")||customElements.define("db-rating",DbRating);export{DbRating};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
declare class DbSearchBar extends HTMLElement {
|
|
2
|
+
private unsubscribeLocale?;
|
|
2
3
|
static get observedAttributes(): string[];
|
|
3
4
|
private input?;
|
|
4
5
|
private clearButton?;
|
|
@@ -29,6 +30,7 @@ declare class DbSearchBar extends HTMLElement {
|
|
|
29
30
|
private clearSuggestionInterval;
|
|
30
31
|
private syncSuggestionRolling;
|
|
31
32
|
private syncPlaceholder;
|
|
33
|
+
private syncLocale;
|
|
32
34
|
private syncValueState;
|
|
33
35
|
private syncAttributes;
|
|
34
36
|
private bindGlobalShortcut;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inheritThemeScope as e}from"../core/theme-scope.js";import{dbText as t,dbFormat as s}from"../core/i18n.js";import{getDbComponentIconSize as a,createDbIcon as n}from"./db-icons.js";import{SEARCH_BAR_SIZES as r,SEARCH_BAR_RECENT_LAYOUTS as i}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbSearchBar extends HTMLElement{constructor(){super(...arguments),this.recentSearches=[],this.isFocused=!1,this.currentSuggestion=0,this.scrollParents=[]}static get observedAttributes(){return["value","default-value","placeholder","size","appearance","disabled","readonly","full-width","show-shortcut","shortcut-label","enable-recent-searches","recent-searches-key","recent-searches-layout","suggested-searches","suggestion-rolling-interval","categories","selected-category","search-results","empty-state-message"]}getResolvedSize(){const e=this.getAttribute("size")||"m";return r.includes(e)?e:"m"}getIconPx(){return a(this.getResolvedSize())}syncIcons(){const e=this.getIconPx();this.querySelector(".designbase-wc-search-bar__search-icon")?.replaceChildren(n("search",e)),this.clearButton?.replaceChildren(n("close",e))}hasInputValue(){return Boolean((this.input?.value??this.getAttribute("value")??"").trim())}get value(){return this.input?.value??this.getAttribute("value")??""}set value(e){this.setAttribute("value",e),this.input&&(this.input.value=e)}connectedCallback(){this.loadRecentSearches(),this.render(),this.bindGlobalShortcut()}disconnectedCallback(){this.clearSuggestionInterval(),this.unbindGlobalShortcut(),this.detachDropdownPortal(),this.blurTimer&&clearTimeout(this.blurTimer)}attributeChangedCallback(e){if(this.isConnected)return"value"===e&&this.input?(this.input.value=this.getAttribute("value")||"",this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"disabled"===e||"readonly"===e||"placeholder"===e||"show-shortcut"===e||"shortcut-label"===e||"selected-category"===e||"search-results"===e||"empty-state-message"===e||"suggested-searches"===e?(this.syncAttributes(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"enable-recent-searches"===e||"recent-searches-key"===e?(this.loadRecentSearches(),void this.updateDropdown()):void("categories"!==e&&"recent-searches-layout"!==e?this.render():this.updateDropdown())}focus(){this.input?.focus()}parseJsonArray(e){try{const t=JSON.parse(this.getAttribute(e)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}getRecentSearchesKey(){return this.getAttribute("recent-searches-key")||"searchbar-recent-searches"}loadRecentSearches(){if(this.hasAttribute("enable-recent-searches"))try{const e=localStorage.getItem(this.getRecentSearchesKey());this.recentSearches=e?JSON.parse(e):[],Array.isArray(this.recentSearches)||(this.recentSearches=[])}catch{this.recentSearches=[]}else this.recentSearches=[]}saveRecentSearches(){try{localStorage.setItem(this.getRecentSearchesKey(),JSON.stringify(this.recentSearches))}catch{}}clearSuggestionInterval(){this.suggestionInterval&&(clearInterval(this.suggestionInterval),this.suggestionInterval=void 0)}syncSuggestionRolling(){this.clearSuggestionInterval();const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=Number(this.getAttribute("suggestion-rolling-interval")||5e3);e.length>0&&!t&&(this.suggestionInterval=setInterval(()=>{this.currentSuggestion=(this.currentSuggestion+1)%e.length,this.syncPlaceholder(),this.updateDropdown()},s))}syncPlaceholder(){if(!this.input)return;const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=this.getAttribute("placeholder")||"검색...";e.length>0&&!t?this.input.placeholder=e[this.currentSuggestion]||s:this.input.placeholder=s}syncValueState(){const e=this.hasInputValue();this.classList.toggle("designbase-wc-search-bar--has-value",e),this.clearButton&&(this.clearButton.hidden=!e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.shortcutBadge&&(this.shortcutBadge.hidden=!this.hasAttribute("show-shortcut")||e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.syncIcons()}syncAttributes(){const e=this.getAttribute("size")||"m",t=this.hasAttribute("disabled"),s=this.hasAttribute("readonly"),a=this.hasAttribute("show-shortcut");this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${r.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",t&&"designbase-wc-search-bar--disabled",s&&"designbase-wc-search-bar--readonly",this.hasAttribute("full-width")&&"designbase-wc-search-bar--full-width",Boolean(this.hasInputValue())&&"designbase-wc-search-bar--has-value"].filter(Boolean).join(" "),this.input&&(this.input.disabled=t,this.input.readOnly=s),this.shortcutBadge&&(this.shortcutBadge.hidden=!a||this.hasInputValue()||t||s,this.shortcutBadge.textContent=this.getAttribute("shortcut-label")||"⌘K"),this.syncValueState()}bindGlobalShortcut(){this.unbindGlobalShortcut(),!this.hasAttribute("show-shortcut")||this.hasAttribute("disabled")||this.hasAttribute("readonly")||(this.globalKeyHandler=e=>{if(e.defaultPrevented||e.isComposing||!this.getClientRects().length)return;const t=e.metaKey||e.ctrlKey;let s="k";const a=(this.getAttribute("shortcut-label")||"⌘K").slice(-1).toLowerCase();a&&(s=a),t&&e.key.toLowerCase()===s&&(e.preventDefault(),this.focus())},window.addEventListener("keydown",this.globalKeyHandler))}unbindGlobalShortcut(){this.globalKeyHandler&&(window.removeEventListener("keydown",this.globalKeyHandler),this.globalKeyHandler=void 0)}positionDropdown(){if(!this.dropdown||this.dropdown.hidden)return;const e=this.getBoundingClientRect(),t=this.input?.getBoundingClientRect(),s=t??e;this.dropdown.style.top=`${s.bottom+4}px`,this.dropdown.style.left=`${e.left}px`,this.dropdown.style.width=`${e.width}px`,this.dropdown.style.right="auto"}bindRepositionListeners(){if(this.repositionHandler)return;this.repositionHandler=()=>{requestAnimationFrame(()=>this.positionDropdown())},window.addEventListener("scroll",this.repositionHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.repositionHandler),this.scrollParents=[];let e=this.parentElement;for(;e&&e!==document.body;){const t=getComputedStyle(e),s=/(auto|scroll|overlay)/.test(t.overflowY),a=/(auto|scroll|overlay)/.test(t.overflow);(s||a)&&e.scrollHeight>e.clientHeight&&(e.addEventListener("scroll",this.repositionHandler,{passive:!0}),this.scrollParents.push(e)),e=e.parentElement}}unbindRepositionListeners(){this.repositionHandler&&(window.removeEventListener("scroll",this.repositionHandler,!0),window.removeEventListener("resize",this.repositionHandler),this.scrollParents.forEach(e=>e.removeEventListener("scroll",this.repositionHandler)),this.scrollParents=[],this.repositionHandler=void 0)}attachDropdownPortal(){this.dropdown&&!this.dropdown.hidden&&(this.dropdown.classList.add("designbase-wc-search-bar__dropdown--portal"),this.dropdown.parentElement!==document.body&&(e(this,this.dropdown),document.body.append(this.dropdown)),requestAnimationFrame(()=>this.positionDropdown()),this.repositionHandler||this.bindRepositionListeners())}detachDropdownPortal(){this.unbindRepositionListeners(),this.dropdown&&(this.dropdown.classList.remove("designbase-wc-search-bar__dropdown--portal"),this.dropdown.style.top="",this.dropdown.style.left="",this.dropdown.style.width="",this.dropdown.style.right="",this.dropdown.parentElement===document.body&&this.isConnected&&this.append(this.dropdown))}shouldShowDropdown(){const e=this.hasInputValue(),t=this.parseJsonArray("categories"),s=this.parseJsonArray("suggested-searches"),a=this.getAttribute("search-results"),n=this.getAttribute("empty-state-message");return this.isFocused&&(t.length>0||this.hasAttribute("enable-recent-searches")&&this.recentSearches.length>0&&!e||s.length>0&&!e||null!==a&&e||Boolean(n)&&!e&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===s.length)}formatSearchResult(e){if("string"==typeof e||"number"==typeof e)return String(e);if(e&&"object"==typeof e){const t=e;if("string"==typeof t.title)return t.title;if("string"==typeof t.label)return t.label}return String(e)}handleSearch(e){const t=(e??this.value).trim();t&&(this.dispatchEvent(new CustomEvent("db-search",{detail:{value:t},bubbles:!0,composed:!0})),this.hasAttribute("enable-recent-searches")&&(this.recentSearches=[t,...this.recentSearches.filter(e=>e!==t)].slice(0,10),this.saveRecentSearches(),this.updateDropdown()))}updateDropdown(){if(!this.dropdown)return;const e=this.shouldShowDropdown();if(this.dropdown.hidden=!e,this.classList.toggle("designbase-wc-search-bar--dropdown-open",e),!e)return this.dropdown.replaceChildren(),void this.detachDropdownPortal();this.dropdown.replaceChildren();const r=this.hasInputValue(),o=this.parseJsonArray("categories"),c=this.parseJsonArray("suggested-searches"),h=this.getAttribute("selected-category")||"",d=this.parseJsonArray("search-results"),l=this.getAttribute("empty-state-message"),u=i.includes(this.getAttribute("recent-searches-layout")||"vertical")&&this.getAttribute("recent-searches-layout")||"vertical";if(o.length>0){const e=document.createElement("div");e.className="designbase-wc-search-bar__categories",o.forEach(t=>{const s=document.createElement("db-chip");s.setAttribute("label",t),s.setAttribute("size","s"),s.setAttribute("variant",t===h?"primary":"default"),s.setAttribute("clickable",""),s.addEventListener("mousedown",e=>{e.preventDefault(),this.setAttribute("selected-category",t),this.dispatchEvent(new CustomEvent("db-category-change",{detail:{category:t},bubbles:!0,composed:!0})),this.updateDropdown()}),e.append(s)}),this.dropdown.append(e)}if(r&&this.hasAttribute("search-results")){const e=document.createElement("div");if(e.className="designbase-wc-search-bar__results",d.length>0){const t=document.createElement("ul");t.className="designbase-wc-search-bar__results-list",d.forEach((e,s)=>{const a=document.createElement("li");a.className="designbase-wc-search-bar__result-item",a.textContent=this.formatSearchResult(e),a.addEventListener("mousedown",t=>{t.preventDefault(),this.isFocused=!1,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-search-result-click",{detail:{result:e,index:s},bubbles:!0,composed:!0}))}),t.append(a)}),e.append(t)}else{const s=document.createElement("div");s.className="designbase-wc-search-bar__results-empty",s.textContent=t("검색 결과가 없습니다."),e.append(s)}return this.dropdown.append(e),void this.attachDropdownPortal()}if(this.hasAttribute("enable-recent-searches")&&!r&&this.recentSearches.length>0){const e=document.createElement("div");e.className=`designbase-wc-search-bar__recent-searches designbase-wc-search-bar__recent-searches--${u}`;const r=document.createElement("div");r.className="designbase-wc-search-bar__recent-header";const i=document.createElement("span");i.className="designbase-wc-search-bar__recent-title",i.textContent=t("최근 검색어");const o=document.createElement("button");o.type="button",o.className="designbase-wc-search-bar__clear-all-button",o.setAttribute("aria-label",t("모든 최근 검색어 삭제")),o.textContent=t("전체 삭제"),o.addEventListener("mousedown",e=>{e.preventDefault(),this.recentSearches=[];try{localStorage.removeItem(this.getRecentSearchesKey())}catch{}this.updateDropdown()}),r.append(i,o);const c=document.createElement("div");c.className="designbase-wc-search-bar__recent-list",this.recentSearches.forEach(e=>{const t=document.createElement("div");t.className="designbase-wc-search-bar__recent-item";const r=document.createElement("button");r.type="button",r.className="designbase-wc-search-bar__recent-search-button",r.textContent=e,r.addEventListener("mousedown",t=>{if(t.preventDefault(),!this.input)return;this.input.value=e,this.setAttribute("value",e),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(e);const s={value:e};this.dispatchEvent(new CustomEvent("db-input",{detail:s,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:s,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()});const i=document.createElement("button");i.type="button",i.className="designbase-wc-search-bar__recent-remove-button",i.setAttribute("aria-label",s("{0} 삭제",[e])),i.append(n("close",a("s"))),i.addEventListener("mousedown",t=>{t.preventDefault(),this.recentSearches=this.recentSearches.filter(t=>t!==e),this.saveRecentSearches(),this.updateDropdown()}),t.append(r,i),c.append(t)}),e.append(r,c),this.dropdown.append(e)}if(c.length>0&&!r){const e=document.createElement("div");e.className="designbase-wc-search-bar__suggestions";const s=document.createElement("div");s.className="designbase-wc-search-bar__suggestions-header";const a=document.createElement("span");a.className="designbase-wc-search-bar__suggestions-title",a.textContent=t("추천 검색어"),s.append(a);const n=document.createElement("div");n.className="designbase-wc-search-bar__suggestions-list",c.forEach((e,t)=>{const s=document.createElement("button");s.type="button",s.className=["designbase-wc-search-bar__suggestion-item",t===this.currentSuggestion&&"designbase-wc-search-bar__suggestion-item--active"].filter(Boolean).join(" "),s.textContent=e,s.addEventListener("mousedown",t=>{if(t.preventDefault(),!this.input)return;this.clearSuggestionInterval(),this.input.value=e,this.setAttribute("value",e),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(e);const s={value:e};this.dispatchEvent(new CustomEvent("db-input",{detail:s,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:s,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()}),n.append(s)}),e.append(s,n),this.dropdown.append(e)}if(l&&!r&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===c.length){const e=document.createElement("div");e.className="designbase-wc-search-bar__empty-state",e.textContent=l,this.dropdown.append(e)}this.attachDropdownPortal()}render(){const e=this.getAttribute("size")||"m",s=this.hasAttribute("disabled"),a=this.hasAttribute("readonly"),i=this.hasAttribute("full-width"),o=this.hasAttribute("show-shortcut"),c=this.getAttribute("value")??this.getAttribute("default-value")??"",h=Boolean(c.trim()),d=this.getIconPx();this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${r.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",s&&"designbase-wc-search-bar--disabled",a&&"designbase-wc-search-bar--readonly",i&&"designbase-wc-search-bar--full-width",h&&"designbase-wc-search-bar--has-value",this.shouldShowDropdown()&&"designbase-wc-search-bar--dropdown-open"].filter(Boolean).join(" "),this.setAttribute("role","search"),this.clearSuggestionInterval(),this.detachDropdownPortal(),this.replaceChildren();const l=document.createElement("div");l.className="designbase-wc-search-bar__container";const u=document.createElement("div");u.className="designbase-wc-search-bar__search-icon",u.setAttribute("aria-hidden","true"),u.append(n("search",d));const b=document.createElement("input");if(b.type="text",b.className="designbase-wc-search-bar__input",b.value=c,b.disabled=s,b.readOnly=a,b.setAttribute("aria-label",t("검색어 입력")),this.input=b,o){const t=document.createElement("db-badge");t.className="designbase-wc-search-bar__shortcut-badge",t.setAttribute("size","l"===e?"m":"s"),t.setAttribute("variant","secondary"),t.setAttribute("type","text"),t.setAttribute("aria-hidden","true"),t.textContent=this.getAttribute("shortcut-label")||"⌘K",t.hidden=h||s||a,this.shortcutBadge=t,l.append(u,b,t)}else l.append(u,b);const p=document.createElement("button");p.type="button",p.className="designbase-wc-search-bar__clear-button",p.setAttribute("aria-label",t("검색어 지우기")),p.hidden=!h||s||a,p.append(n("close",d)),this.clearButton=p,l.append(p);const g=document.createElement("div");g.className="designbase-wc-search-bar__dropdown",g.hidden=!0,g.addEventListener("mousedown",e=>{e.preventDefault()}),this.dropdown=g,b.addEventListener("input",()=>{this.setAttribute("value",b.value),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling();const e={value:b.value};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),b.addEventListener("keydown",e=>{"Enter"===e.key&&this.handleSearch()}),b.addEventListener("focus",()=>{this.isFocused=!0,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-focus",{bubbles:!0,composed:!0}))}),b.addEventListener("blur",()=>{this.isFocused=!1,this.blurTimer&&clearTimeout(this.blurTimer),this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-blur",{bubbles:!0,composed:!0}))}),p.addEventListener("click",()=>{b.value="",this.setAttribute("value",""),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling(),b.focus(),this.dispatchEvent(new CustomEvent("db-clear",{bubbles:!0,composed:!0}));const e={value:""};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),this.append(l,g),this.syncIcons(),this.syncPlaceholder(),this.syncSuggestionRolling(),this.bindGlobalShortcut(),this.updateDropdown()}}customElements.get("db-search-bar")||customElements.define("db-search-bar",DbSearchBar);export{DbSearchBar};
|
|
1
|
+
import{inheritThemeScope as e}from"../core/theme-scope.js";import{subscribeDbLocale as t,dbText as s,dbFormat as a}from"../core/i18n.js";import{getDbComponentIconSize as r,createDbIcon as n}from"./db-icons.js";import{SEARCH_BAR_SIZES as i,SEARCH_BAR_RECENT_LAYOUTS as o}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbSearchBar extends HTMLElement{constructor(){super(...arguments),this.recentSearches=[],this.isFocused=!1,this.currentSuggestion=0,this.scrollParents=[]}static get observedAttributes(){return["value","default-value","placeholder","size","appearance","disabled","readonly","full-width","show-shortcut","shortcut-label","enable-recent-searches","recent-searches-key","recent-searches-layout","suggested-searches","suggestion-rolling-interval","categories","selected-category","search-results","empty-state-message"]}getResolvedSize(){const e=this.getAttribute("size")||"m";return i.includes(e)?e:"m"}getIconPx(){return r(this.getResolvedSize())}syncIcons(){const e=this.getIconPx();this.querySelector(".designbase-wc-search-bar__search-icon")?.replaceChildren(n("search",e)),this.clearButton?.replaceChildren(n("close",e))}hasInputValue(){return Boolean((this.input?.value??this.getAttribute("value")??"").trim())}get value(){return this.input?.value??this.getAttribute("value")??""}set value(e){this.setAttribute("value",e),this.input&&(this.input.value=e)}connectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=t(()=>this.syncLocale()),this.loadRecentSearches(),this.render(),this.bindGlobalShortcut()}disconnectedCallback(){this.unsubscribeLocale?.(),this.unsubscribeLocale=void 0,this.clearSuggestionInterval(),this.unbindGlobalShortcut(),this.detachDropdownPortal(),this.blurTimer&&clearTimeout(this.blurTimer)}attributeChangedCallback(e){if(this.isConnected)return"value"===e&&this.input?(this.input.value=this.getAttribute("value")||"",this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"disabled"===e||"readonly"===e||"placeholder"===e||"show-shortcut"===e||"shortcut-label"===e||"selected-category"===e||"search-results"===e||"empty-state-message"===e||"suggested-searches"===e?(this.syncAttributes(),this.syncPlaceholder(),this.updateDropdown(),void this.syncSuggestionRolling()):"enable-recent-searches"===e||"recent-searches-key"===e?(this.loadRecentSearches(),void this.updateDropdown()):void("categories"!==e&&"recent-searches-layout"!==e?this.render():this.updateDropdown())}focus(){this.input?.focus()}parseJsonArray(e){try{const t=JSON.parse(this.getAttribute(e)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}getRecentSearchesKey(){return this.getAttribute("recent-searches-key")||"searchbar-recent-searches"}loadRecentSearches(){if(this.hasAttribute("enable-recent-searches"))try{const e=localStorage.getItem(this.getRecentSearchesKey());this.recentSearches=e?JSON.parse(e):[],Array.isArray(this.recentSearches)||(this.recentSearches=[])}catch{this.recentSearches=[]}else this.recentSearches=[]}saveRecentSearches(){try{localStorage.setItem(this.getRecentSearchesKey(),JSON.stringify(this.recentSearches))}catch{}}clearSuggestionInterval(){this.suggestionInterval&&(clearInterval(this.suggestionInterval),this.suggestionInterval=void 0)}syncSuggestionRolling(){this.clearSuggestionInterval();const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),s=Number(this.getAttribute("suggestion-rolling-interval")||5e3);e.length>0&&!t&&(this.suggestionInterval=setInterval(()=>{this.currentSuggestion=(this.currentSuggestion+1)%e.length,this.syncPlaceholder(),this.updateDropdown()},s))}syncPlaceholder(){if(!this.input)return;const e=this.parseJsonArray("suggested-searches"),t=this.hasInputValue(),a=this.getAttribute("placeholder")||s("검색...");e.length>0&&!t?this.input.placeholder=e[this.currentSuggestion]||a:this.input.placeholder=a}syncLocale(){this.syncPlaceholder(),this.input?.setAttribute("aria-label",s("검색어 입력")),this.clearButton?.setAttribute("aria-label",s("검색어 지우기"));const setText=(e,t)=>{const a=this.dropdown?.querySelector(e);a&&(a.textContent=s(t))};setText(".designbase-wc-search-bar__results-empty","검색 결과가 없습니다."),setText(".designbase-wc-search-bar__recent-title","최근 검색어"),setText(".designbase-wc-search-bar__suggestions-title","추천 검색어");const e=this.dropdown?.querySelector(".designbase-wc-search-bar__clear-all-button");e&&(e.textContent=s("전체 삭제"),e.setAttribute("aria-label",s("모든 최근 검색어 삭제"))),this.dropdown?.querySelectorAll(".designbase-wc-search-bar__recent-item").forEach(e=>{const t=e.querySelector(".designbase-wc-search-bar__recent-search-button")?.textContent;t&&e.querySelector(".designbase-wc-search-bar__recent-remove-button")?.setAttribute("aria-label",a("{0} 삭제",[t]))})}syncValueState(){const e=this.hasInputValue();this.classList.toggle("designbase-wc-search-bar--has-value",e),this.clearButton&&(this.clearButton.hidden=!e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.shortcutBadge&&(this.shortcutBadge.hidden=!this.hasAttribute("show-shortcut")||e||this.hasAttribute("disabled")||this.hasAttribute("readonly")),this.syncIcons()}syncAttributes(){const e=this.getAttribute("size")||"m",t=this.hasAttribute("disabled"),s=this.hasAttribute("readonly"),a=this.hasAttribute("show-shortcut");this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${i.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",t&&"designbase-wc-search-bar--disabled",s&&"designbase-wc-search-bar--readonly",this.hasAttribute("full-width")&&"designbase-wc-search-bar--full-width",Boolean(this.hasInputValue())&&"designbase-wc-search-bar--has-value"].filter(Boolean).join(" "),this.input&&(this.input.disabled=t,this.input.readOnly=s),this.shortcutBadge&&(this.shortcutBadge.hidden=!a||this.hasInputValue()||t||s,this.shortcutBadge.textContent=this.getAttribute("shortcut-label")||"⌘K"),this.syncValueState()}bindGlobalShortcut(){this.unbindGlobalShortcut(),!this.hasAttribute("show-shortcut")||this.hasAttribute("disabled")||this.hasAttribute("readonly")||(this.globalKeyHandler=e=>{if(e.defaultPrevented||e.isComposing||!this.getClientRects().length)return;const t=e.metaKey||e.ctrlKey;let s="k";const a=(this.getAttribute("shortcut-label")||"⌘K").slice(-1).toLowerCase();a&&(s=a),t&&e.key.toLowerCase()===s&&(e.preventDefault(),this.focus())},window.addEventListener("keydown",this.globalKeyHandler))}unbindGlobalShortcut(){this.globalKeyHandler&&(window.removeEventListener("keydown",this.globalKeyHandler),this.globalKeyHandler=void 0)}positionDropdown(){if(!this.dropdown||this.dropdown.hidden)return;const e=this.getBoundingClientRect(),t=this.input?.getBoundingClientRect(),s=t??e;this.dropdown.style.top=`${s.bottom+4}px`,this.dropdown.style.left=`${e.left}px`,this.dropdown.style.width=`${e.width}px`,this.dropdown.style.right="auto"}bindRepositionListeners(){if(this.repositionHandler)return;this.repositionHandler=()=>{requestAnimationFrame(()=>this.positionDropdown())},window.addEventListener("scroll",this.repositionHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.repositionHandler),this.scrollParents=[];let e=this.parentElement;for(;e&&e!==document.body;){const t=getComputedStyle(e),s=/(auto|scroll|overlay)/.test(t.overflowY),a=/(auto|scroll|overlay)/.test(t.overflow);(s||a)&&e.scrollHeight>e.clientHeight&&(e.addEventListener("scroll",this.repositionHandler,{passive:!0}),this.scrollParents.push(e)),e=e.parentElement}}unbindRepositionListeners(){this.repositionHandler&&(window.removeEventListener("scroll",this.repositionHandler,!0),window.removeEventListener("resize",this.repositionHandler),this.scrollParents.forEach(e=>e.removeEventListener("scroll",this.repositionHandler)),this.scrollParents=[],this.repositionHandler=void 0)}attachDropdownPortal(){this.dropdown&&!this.dropdown.hidden&&(this.dropdown.classList.add("designbase-wc-search-bar__dropdown--portal"),this.dropdown.parentElement!==document.body&&(e(this,this.dropdown),document.body.append(this.dropdown)),requestAnimationFrame(()=>this.positionDropdown()),this.repositionHandler||this.bindRepositionListeners())}detachDropdownPortal(){this.unbindRepositionListeners(),this.dropdown&&(this.dropdown.classList.remove("designbase-wc-search-bar__dropdown--portal"),this.dropdown.style.top="",this.dropdown.style.left="",this.dropdown.style.width="",this.dropdown.style.right="",this.dropdown.parentElement===document.body&&this.isConnected&&this.append(this.dropdown))}shouldShowDropdown(){const e=this.hasInputValue(),t=this.parseJsonArray("categories"),s=this.parseJsonArray("suggested-searches"),a=this.getAttribute("search-results"),r=this.getAttribute("empty-state-message");return this.isFocused&&(t.length>0||this.hasAttribute("enable-recent-searches")&&this.recentSearches.length>0&&!e||s.length>0&&!e||null!==a&&e||Boolean(r)&&!e&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===s.length)}formatSearchResult(e){if("string"==typeof e||"number"==typeof e)return String(e);if(e&&"object"==typeof e){const t=e;if("string"==typeof t.title)return t.title;if("string"==typeof t.label)return t.label}return String(e)}handleSearch(e){const t=(e??this.value).trim();t&&(this.dispatchEvent(new CustomEvent("db-search",{detail:{value:t},bubbles:!0,composed:!0})),this.hasAttribute("enable-recent-searches")&&(this.recentSearches=[t,...this.recentSearches.filter(e=>e!==t)].slice(0,10),this.saveRecentSearches(),this.updateDropdown()))}updateDropdown(){if(!this.dropdown)return;const e=this.shouldShowDropdown();if(this.dropdown.hidden=!e,this.classList.toggle("designbase-wc-search-bar--dropdown-open",e),!e)return this.dropdown.replaceChildren(),void this.detachDropdownPortal();this.dropdown.replaceChildren();const t=this.hasInputValue(),i=this.parseJsonArray("categories"),c=this.parseJsonArray("suggested-searches"),h=this.getAttribute("selected-category")||"",d=this.parseJsonArray("search-results"),l=this.getAttribute("empty-state-message"),u=o.includes(this.getAttribute("recent-searches-layout")||"vertical")&&this.getAttribute("recent-searches-layout")||"vertical";if(i.length>0){const e=document.createElement("div");e.className="designbase-wc-search-bar__categories",i.forEach(t=>{const s=document.createElement("db-chip");s.setAttribute("label",t),s.setAttribute("size","s"),s.setAttribute("variant",t===h?"primary":"default"),s.setAttribute("clickable",""),s.addEventListener("mousedown",e=>{e.preventDefault(),this.setAttribute("selected-category",t),this.dispatchEvent(new CustomEvent("db-category-change",{detail:{category:t},bubbles:!0,composed:!0})),this.updateDropdown()}),e.append(s)}),this.dropdown.append(e)}if(t&&this.hasAttribute("search-results")){const e=document.createElement("div");if(e.className="designbase-wc-search-bar__results",d.length>0){const t=document.createElement("ul");t.className="designbase-wc-search-bar__results-list",d.forEach((e,s)=>{const a=document.createElement("li");a.className="designbase-wc-search-bar__result-item",a.textContent=this.formatSearchResult(e),a.addEventListener("mousedown",t=>{t.preventDefault(),this.isFocused=!1,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-search-result-click",{detail:{result:e,index:s},bubbles:!0,composed:!0}))}),t.append(a)}),e.append(t)}else{const t=document.createElement("div");t.className="designbase-wc-search-bar__results-empty",t.textContent=s("검색 결과가 없습니다."),e.append(t)}return this.dropdown.append(e),void this.attachDropdownPortal()}if(this.hasAttribute("enable-recent-searches")&&!t&&this.recentSearches.length>0){const e=document.createElement("div");e.className=`designbase-wc-search-bar__recent-searches designbase-wc-search-bar__recent-searches--${u}`;const t=document.createElement("div");t.className="designbase-wc-search-bar__recent-header";const i=document.createElement("span");i.className="designbase-wc-search-bar__recent-title",i.textContent=s("최근 검색어");const o=document.createElement("button");o.type="button",o.className="designbase-wc-search-bar__clear-all-button",o.setAttribute("aria-label",s("모든 최근 검색어 삭제")),o.textContent=s("전체 삭제"),o.addEventListener("mousedown",e=>{e.preventDefault(),this.recentSearches=[];try{localStorage.removeItem(this.getRecentSearchesKey())}catch{}this.updateDropdown()}),t.append(i,o);const c=document.createElement("div");c.className="designbase-wc-search-bar__recent-list",this.recentSearches.forEach(e=>{const t=document.createElement("div");t.className="designbase-wc-search-bar__recent-item";const s=document.createElement("button");s.type="button",s.className="designbase-wc-search-bar__recent-search-button",s.textContent=e,s.addEventListener("mousedown",t=>{if(t.preventDefault(),!this.input)return;this.input.value=e,this.setAttribute("value",e),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(e);const s={value:e};this.dispatchEvent(new CustomEvent("db-input",{detail:s,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:s,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()});const i=document.createElement("button");i.type="button",i.className="designbase-wc-search-bar__recent-remove-button",i.setAttribute("aria-label",a("{0} 삭제",[e])),i.append(n("close",r("s"))),i.addEventListener("mousedown",t=>{t.preventDefault(),this.recentSearches=this.recentSearches.filter(t=>t!==e),this.saveRecentSearches(),this.updateDropdown()}),t.append(s,i),c.append(t)}),e.append(t,c),this.dropdown.append(e)}if(c.length>0&&!t){const e=document.createElement("div");e.className="designbase-wc-search-bar__suggestions";const t=document.createElement("div");t.className="designbase-wc-search-bar__suggestions-header";const a=document.createElement("span");a.className="designbase-wc-search-bar__suggestions-title",a.textContent=s("추천 검색어"),t.append(a);const r=document.createElement("div");r.className="designbase-wc-search-bar__suggestions-list",c.forEach((e,t)=>{const s=document.createElement("button");s.type="button",s.className=["designbase-wc-search-bar__suggestion-item",t===this.currentSuggestion&&"designbase-wc-search-bar__suggestion-item--active"].filter(Boolean).join(" "),s.textContent=e,s.addEventListener("mousedown",t=>{if(t.preventDefault(),!this.input)return;this.clearSuggestionInterval(),this.input.value=e,this.setAttribute("value",e),this.syncValueState(),this.syncPlaceholder(),this.handleSearch(e);const s={value:e};this.dispatchEvent(new CustomEvent("db-input",{detail:s,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:s,bubbles:!0,composed:!0})),this.isFocused=!1,this.updateDropdown()}),r.append(s)}),e.append(t,r),this.dropdown.append(e)}if(l&&!t&&(!this.hasAttribute("enable-recent-searches")||0===this.recentSearches.length)&&0===c.length){const e=document.createElement("div");e.className="designbase-wc-search-bar__empty-state",e.textContent=l,this.dropdown.append(e)}this.attachDropdownPortal()}render(){const e=this.getAttribute("size")||"m",t=this.hasAttribute("disabled"),a=this.hasAttribute("readonly"),r=this.hasAttribute("full-width"),o=this.hasAttribute("show-shortcut"),c=this.getAttribute("value")??this.getAttribute("default-value")??"",h=Boolean(c.trim()),d=this.getIconPx();this.className=["designbase-wc-search-bar",`designbase-wc-search-bar--${i.includes(e)?e:"m"}`,"pill"===this.getAttribute("appearance")&&"designbase-wc-search-bar--appearance-pill",t&&"designbase-wc-search-bar--disabled",a&&"designbase-wc-search-bar--readonly",r&&"designbase-wc-search-bar--full-width",h&&"designbase-wc-search-bar--has-value",this.shouldShowDropdown()&&"designbase-wc-search-bar--dropdown-open"].filter(Boolean).join(" "),this.setAttribute("role","search"),this.clearSuggestionInterval(),this.detachDropdownPortal(),this.replaceChildren();const l=document.createElement("div");l.className="designbase-wc-search-bar__container";const u=document.createElement("div");u.className="designbase-wc-search-bar__search-icon",u.setAttribute("aria-hidden","true"),u.append(n("search",d));const b=document.createElement("input");if(b.type="text",b.className="designbase-wc-search-bar__input",b.value=c,b.disabled=t,b.readOnly=a,b.setAttribute("aria-label",s("검색어 입력")),this.input=b,o){const s=document.createElement("db-badge");s.className="designbase-wc-search-bar__shortcut-badge",s.setAttribute("size","l"===e?"m":"s"),s.setAttribute("variant","secondary"),s.setAttribute("type","text"),s.setAttribute("aria-hidden","true"),s.textContent=this.getAttribute("shortcut-label")||"⌘K",s.hidden=h||t||a,this.shortcutBadge=s,l.append(u,b,s)}else l.append(u,b);const p=document.createElement("button");p.type="button",p.className="designbase-wc-search-bar__clear-button",p.setAttribute("aria-label",s("검색어 지우기")),p.hidden=!h||t||a,p.append(n("close",d)),this.clearButton=p,l.append(p);const g=document.createElement("div");g.className="designbase-wc-search-bar__dropdown",g.hidden=!0,g.addEventListener("mousedown",e=>{e.preventDefault()}),this.dropdown=g,b.addEventListener("input",()=>{this.setAttribute("value",b.value),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling();const e={value:b.value};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),b.addEventListener("keydown",e=>{"Enter"===e.key&&this.handleSearch()}),b.addEventListener("focus",()=>{this.isFocused=!0,this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-focus",{bubbles:!0,composed:!0}))}),b.addEventListener("blur",()=>{this.isFocused=!1,this.blurTimer&&clearTimeout(this.blurTimer),this.updateDropdown(),this.dispatchEvent(new CustomEvent("db-blur",{bubbles:!0,composed:!0}))}),p.addEventListener("click",()=>{b.value="",this.setAttribute("value",""),this.syncValueState(),this.syncPlaceholder(),this.updateDropdown(),this.syncSuggestionRolling(),b.focus(),this.dispatchEvent(new CustomEvent("db-clear",{bubbles:!0,composed:!0}));const e={value:""};this.dispatchEvent(new CustomEvent("db-input",{detail:e,bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("db-change",{detail:e,bubbles:!0,composed:!0}))}),this.append(l,g),this.syncIcons(),this.syncPlaceholder(),this.syncSuggestionRolling(),this.bindGlobalShortcut(),this.updateDropdown()}}customElements.get("db-search-bar")||customElements.define("db-search-bar",DbSearchBar);export{DbSearchBar};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applySectionBlockHeader as e}from"./section-block-header-utils.js";import{syncMarketingBlockHost as t}from"./marketing-block-host-utils.js";import{sanitizeHref as s}from"../core/safe-url.js";import{coerceToContract as i}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{SECTION_LOGO_CLOUD_VARIANTS as n,SECTION_ALIGNS as a,SECTION_LOGO_CLOUD_SIZES as
|
|
1
|
+
import{applySectionBlockHeader as e}from"./section-block-header-utils.js";import{syncMarketingBlockHost as t}from"./marketing-block-host-utils.js";import{sanitizeHref as s}from"../core/safe-url.js";import{coerceToContract as i}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";import{SECTION_LOGO_CLOUD_VARIANTS as n,SECTION_ALIGNS as a,SECTION_LOGO_CLOUD_SIZES as r}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const l="designbase-wc-section-logo-cloud";class DbSectionLogoCloud extends HTMLElement{constructor(){super(...arguments),this.built=!1}static get observedAttributes(){return["headline","subtitle","description","badge","logos","variant","align","content-padding","size","full-width","full-height","overflow-visible"]}connectedCallback(){this.style.display="block",this.built||(this.built=!0,this.build()),this.updateUI()}attributeChangedCallback(){this.built&&this.updateUI()}parseLogos(){try{const e=JSON.parse(this.getAttribute("logos")||"[]");return Array.isArray(e)?e:[]}catch{return[]}}parseBadge(){try{const e=this.getAttribute("badge");return e?JSON.parse(e):null}catch{return null}}build(){this.innerEl=document.createElement("div"),this.innerEl.className=`${l}__inner`,this.headerEl=document.createElement("div"),this.headerEl.className="designbase-wc-section-block-header",this.headerEl.innerHTML='\n <db-badge class="designbase-wc-section-block-header__badge" hidden></db-badge>\n <h2 class="designbase-wc-section-block-header__headline"></h2>\n <p class="designbase-wc-section-block-header__subtitle"></p>\n <p class="designbase-wc-section-block-header__description"></p>\n ',this.contentEl=document.createElement("div"),this.innerEl.append(this.headerEl,this.contentEl),this.append(this.innerEl)}updateUI(){const o=this.getAttribute("headline")||"함께하는 파트너",c=this.getAttribute("subtitle")||"",d=this.getAttribute("description")||"",h=i(this.getAttribute("variant"),n,"grid"),u=this.getAttribute("content-padding")||"m",b=i(this.getAttribute("align"),a,"center"),g=i(this.getAttribute("size"),r,"m"),m=this.parseBadge(),p=this.parseLogos();if(this.className=[l,`${l}--${h}`,`${l}--size-${g}`,`${l}--padding-${u}`].join(" "),t(this,l),this.headerEl&&e(this.headerEl,{headline:o,subtitle:c,description:d,badge:m,align:b}),this.contentEl){if(this.contentEl.replaceChildren(),"marquee"===h){this.contentEl.className=`${l}__marquee`;const e=document.createElement("db-marquee");return e.setAttribute("items",JSON.stringify(p.map(e=>e.src?{src:e.src,alt:e.alt,href:e.href,height:48}:e.label??e.alt))),void this.contentEl.append(e)}this.contentEl.className=`${l}__grid`,p.forEach(e=>{const t=s(e.href,""),i=document.createElement(t?"a":"div");if(i.className=`${l}__item`,t&&i instanceof HTMLAnchorElement&&(i.href=t,i.target="_blank",i.rel="noopener noreferrer"),e.src){const t=document.createElement("img");t.src=e.src,t.alt=e.alt,t.className=`${l}__image`,i.append(t)}else{const t=document.createElement("span");t.className=`${l}__label`,t.textContent=e.label??e.alt,i.append(t)}this.contentEl.append(i)})}}}customElements.get("db-section-logo-cloud")||customElements.define("db-section-logo-cloud",DbSectionLogoCloud);export{DbSectionLogoCloud};
|
|
@@ -8,8 +8,13 @@ declare class DbShare extends HTMLElement {
|
|
|
8
8
|
private modalEl;
|
|
9
9
|
private contentSlot;
|
|
10
10
|
private dropdownEl;
|
|
11
|
+
private unsubscribeLocale?;
|
|
11
12
|
connectedCallback(): void;
|
|
12
13
|
disconnectedCallback(): void;
|
|
14
|
+
private platformName;
|
|
15
|
+
private platformAriaLabel;
|
|
16
|
+
private copySuccessLabel;
|
|
17
|
+
private syncLocale;
|
|
13
18
|
private getVariant;
|
|
14
19
|
private getSize;
|
|
15
20
|
private getPosition;
|