@designbasekorea/ui-wc 0.8.0 → 0.8.2

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.
Files changed (158) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -0
  3. package/dist/esm/components/animation-background/controls.js +1 -1
  4. package/dist/esm/components/animation-background/layers.js +1 -1
  5. package/dist/esm/components/db-activity-heatmap.d.ts +38 -0
  6. package/dist/esm/components/db-activity-heatmap.js +1 -0
  7. package/dist/esm/components/db-animation-background.d.ts +2 -0
  8. package/dist/esm/components/db-animation-background.js +1 -1
  9. package/dist/esm/components/db-app-badge.d.ts +2 -0
  10. package/dist/esm/components/db-app-badge.js +1 -1
  11. package/dist/esm/components/db-audio-player.d.ts +4 -0
  12. package/dist/esm/components/db-audio-player.js +1 -1
  13. package/dist/esm/components/db-avatar.js +1 -1
  14. package/dist/esm/components/db-backdrop.d.ts +4 -0
  15. package/dist/esm/components/db-backdrop.js +1 -1
  16. package/dist/esm/components/db-badge.d.ts +2 -2
  17. package/dist/esm/components/db-badge.js +1 -1
  18. package/dist/esm/components/db-banner.d.ts +5 -0
  19. package/dist/esm/components/db-banner.js +1 -1
  20. package/dist/esm/components/db-bottom-navigation.js +1 -1
  21. package/dist/esm/components/db-bottom-sheet.d.ts +5 -0
  22. package/dist/esm/components/db-bottom-sheet.js +1 -1
  23. package/dist/esm/components/db-button.d.ts +13 -0
  24. package/dist/esm/components/db-button.js +1 -1
  25. package/dist/esm/components/db-calendar.js +1 -1
  26. package/dist/esm/components/db-card.js +1 -1
  27. package/dist/esm/components/db-carousel.js +1 -1
  28. package/dist/esm/components/db-chat-composer.d.ts +14 -0
  29. package/dist/esm/components/db-chat-composer.js +1 -1
  30. package/dist/esm/components/db-chat-message.d.ts +15 -2
  31. package/dist/esm/components/db-chat-message.js +1 -1
  32. package/dist/esm/components/db-chat-orb.d.ts +6 -8
  33. package/dist/esm/components/db-chat-orb.js +1 -1
  34. package/dist/esm/components/db-chat-room.d.ts +12 -1
  35. package/dist/esm/components/db-chat-room.js +1 -1
  36. package/dist/esm/components/db-chat-welcome.js +1 -1
  37. package/dist/esm/components/db-chat-widget.d.ts +43 -10
  38. package/dist/esm/components/db-chat-widget.js +1 -1
  39. package/dist/esm/components/db-checkbox.d.ts +11 -0
  40. package/dist/esm/components/db-checkbox.js +1 -1
  41. package/dist/esm/components/db-chip.js +1 -1
  42. package/dist/esm/components/db-color-picker.js +1 -1
  43. package/dist/esm/components/db-confirm.d.ts +5 -0
  44. package/dist/esm/components/db-confirm.js +1 -1
  45. package/dist/esm/components/db-container.js +1 -1
  46. package/dist/esm/components/db-cookie-banner.js +1 -1
  47. package/dist/esm/components/db-date-picker.d.ts +3 -0
  48. package/dist/esm/components/db-date-picker.js +1 -1
  49. package/dist/esm/components/db-divider.js +1 -1
  50. package/dist/esm/components/db-download-progress.d.ts +3 -4
  51. package/dist/esm/components/db-download-progress.js +1 -1
  52. package/dist/esm/components/db-drawer.d.ts +5 -1
  53. package/dist/esm/components/db-drawer.js +1 -1
  54. package/dist/esm/components/db-dropdown.js +1 -1
  55. package/dist/esm/components/db-dropzone.js +1 -1
  56. package/dist/esm/components/db-email-verify.d.ts +2 -2
  57. package/dist/esm/components/db-email-verify.js +1 -1
  58. package/dist/esm/components/db-file-uploader.js +1 -1
  59. package/dist/esm/components/db-floating-action-button.d.ts +1 -0
  60. package/dist/esm/components/db-floating-action-button.js +1 -1
  61. package/dist/esm/components/db-footer.js +1 -1
  62. package/dist/esm/components/db-gantt.js +1 -1
  63. package/dist/esm/components/db-indicator.js +1 -1
  64. package/dist/esm/components/db-input.d.ts +7 -0
  65. package/dist/esm/components/db-input.js +1 -1
  66. package/dist/esm/components/db-kanban.js +1 -1
  67. package/dist/esm/components/db-lightbox.d.ts +4 -0
  68. package/dist/esm/components/db-lightbox.js +1 -1
  69. package/dist/esm/components/db-list.js +1 -1
  70. package/dist/esm/components/db-masonry.js +1 -1
  71. package/dist/esm/components/db-menu-item.js +1 -1
  72. package/dist/esm/components/db-modal.d.ts +10 -0
  73. package/dist/esm/components/db-modal.js +1 -1
  74. package/dist/esm/components/db-navbar.d.ts +4 -2
  75. package/dist/esm/components/db-navbar.js +1 -1
  76. package/dist/esm/components/db-onboarding-modal.d.ts +3 -0
  77. package/dist/esm/components/db-onboarding-modal.js +1 -1
  78. package/dist/esm/components/db-otp-input.d.ts +3 -2
  79. package/dist/esm/components/db-otp-input.js +1 -1
  80. package/dist/esm/components/db-page-header.js +1 -1
  81. package/dist/esm/components/db-phone-verify.d.ts +2 -2
  82. package/dist/esm/components/db-phone-verify.js +1 -1
  83. package/dist/esm/components/db-popover.js +1 -1
  84. package/dist/esm/components/db-progress-step.js +1 -1
  85. package/dist/esm/components/db-progress.js +1 -1
  86. package/dist/esm/components/db-progressbar.js +1 -1
  87. package/dist/esm/components/db-radio.d.ts +1 -0
  88. package/dist/esm/components/db-radio.js +1 -1
  89. package/dist/esm/components/db-range-slider.d.ts +9 -4
  90. package/dist/esm/components/db-range-slider.js +1 -1
  91. package/dist/esm/components/db-rating.js +1 -1
  92. package/dist/esm/components/db-resizable-panels.d.ts +14 -0
  93. package/dist/esm/components/db-resizable-panels.js +1 -1
  94. package/dist/esm/components/db-search-bar.js +1 -1
  95. package/dist/esm/components/db-section-cta.js +1 -1
  96. package/dist/esm/components/db-section-feature.js +1 -1
  97. package/dist/esm/components/db-section-pricing.js +1 -1
  98. package/dist/esm/components/db-section.js +1 -1
  99. package/dist/esm/components/db-segment-control.js +1 -1
  100. package/dist/esm/components/db-select.d.ts +8 -0
  101. package/dist/esm/components/db-select.js +1 -1
  102. package/dist/esm/components/db-sidebar.d.ts +55 -6
  103. package/dist/esm/components/db-sidebar.js +1 -1
  104. package/dist/esm/components/db-skeleton.js +1 -1
  105. package/dist/esm/components/db-spinner.d.ts +4 -0
  106. package/dist/esm/components/db-spinner.js +1 -1
  107. package/dist/esm/components/db-split-view.js +1 -1
  108. package/dist/esm/components/db-stat.js +1 -1
  109. package/dist/esm/components/db-stepper.js +1 -1
  110. package/dist/esm/components/db-table.js +1 -1
  111. package/dist/esm/components/db-tabs.js +1 -1
  112. package/dist/esm/components/db-testimonial.js +1 -1
  113. package/dist/esm/components/db-textarea.js +1 -1
  114. package/dist/esm/components/db-time-picker.d.ts +5 -2
  115. package/dist/esm/components/db-time-picker.js +1 -1
  116. package/dist/esm/components/db-timeline.js +1 -1
  117. package/dist/esm/components/db-toast.d.ts +8 -1
  118. package/dist/esm/components/db-toast.js +1 -1
  119. package/dist/esm/components/db-toggle.d.ts +2 -0
  120. package/dist/esm/components/db-toggle.js +1 -1
  121. package/dist/esm/components/db-tooltip.js +1 -1
  122. package/dist/esm/components/db-top-banner.js +1 -1
  123. package/dist/esm/components/db-tutorial.d.ts +1 -0
  124. package/dist/esm/components/db-tutorial.js +1 -1
  125. package/dist/esm/components/db-two-factor.d.ts +2 -2
  126. package/dist/esm/components/db-two-factor.js +1 -1
  127. package/dist/esm/components/db-video-player.d.ts +3 -0
  128. package/dist/esm/components/db-video-player.js +1 -1
  129. package/dist/esm/components/section-block-header-utils.js +1 -1
  130. package/dist/esm/core/a11y.d.ts +40 -0
  131. package/dist/esm/core/a11y.js +1 -0
  132. package/dist/esm/core/base-element.d.ts +41 -0
  133. package/dist/esm/core/base-element.js +1 -0
  134. package/dist/esm/core/dom.d.ts +35 -0
  135. package/dist/esm/core/dom.js +1 -0
  136. package/dist/esm/core/focus-trap.d.ts +41 -0
  137. package/dist/esm/core/focus-trap.js +1 -0
  138. package/dist/esm/core/i18n.d.ts +82 -0
  139. package/dist/esm/core/i18n.js +1 -0
  140. package/dist/esm/core/scroll-lock.d.ts +19 -0
  141. package/dist/esm/core/scroll-lock.js +1 -0
  142. package/dist/esm/core/uid.d.ts +23 -0
  143. package/dist/esm/core/uid.js +1 -0
  144. package/dist/esm/helpers/toast.d.ts +10 -10
  145. package/dist/esm/helpers/toast.js +1 -1
  146. package/dist/esm/index.d.ts +12 -3
  147. package/dist/esm/index.js +1 -1
  148. package/dist/esm/node_modules/@designbasekorea/ui-contracts/dist/components.js +1 -0
  149. package/dist/esm/node_modules/@designbasekorea/ui-contracts/dist/primitives.js +1 -0
  150. package/dist/index.cjs +1 -1
  151. package/dist/index.css +1 -1
  152. package/dist/index.d.ts +602 -59
  153. package/dist/index.esm.js +1 -1
  154. package/dist/react/index.cjs +1 -1
  155. package/dist/react/index.d.ts +495 -56
  156. package/dist/react/index.esm.js +1 -1
  157. package/package.json +12 -3
  158. /package/dist/chunks/{lottie-78a72482.js → lottie-3f885725.js} +0 -0
@@ -1 +1 @@
1
- const t=["xs","s","m","l","xl"],e=["aurora","ocean","emerald","violet","mono"],i=["idle","thinking","listening"],s=["auto","light","dark"];function pick(t,e,i){return t.includes(e)?e:i}const a={aurora:{core:[22,20,52],lights:[[236,92,220],[70,140,250],[42,208,158]],rim:[199,210,254],glow:[120,110,240]},ocean:{core:[10,32,62],lights:[[56,189,248],[34,211,238],[96,165,250]],rim:[165,243,252],glow:[59,130,246]},emerald:{core:[6,42,38],lights:[[52,211,153],[74,222,128],[163,230,53]],rim:[187,247,208],glow:[34,197,94]},violet:{core:[40,12,82],lights:[[192,132,252],[168,85,247],[240,171,252]],rim:[245,208,254],glow:[139,92,246]},mono:{core:[30,34,44],lights:[[229,231,235],[156,163,175],[249,250,251]],rim:[255,255,255],glow:[156,163,175]}},r={aurora:{core:[240,240,250],lights:[[235,96,224],[74,144,246],[26,196,150]],rim:[150,130,210],glow:[138,128,244]},ocean:{core:[226,248,255],lights:[[14,165,233],[34,211,238],[96,165,250]],rim:[64,150,181],glow:[56,189,248]},emerald:{core:[228,250,240],lights:[[16,185,129],[74,222,128],[163,230,53]],rim:[57,145,111],glow:[52,211,153]},violet:{core:[246,233,255],lights:[[168,85,247],[217,70,239],[240,171,252]],rim:[143,91,183],glow:[192,132,252]},mono:{core:[243,246,250],lights:[[148,163,184],[203,213,225],[255,255,255]],rim:[100,116,139],glow:[148,163,184]}},n={idle:{speed:1.55,amp:.38,turb:.95,glow:1.15,breatheSpeed:1.9,breatheAmt:.055,lightAlpha:.95,autoRipple:0},thinking:{speed:3.2,amp:.5,turb:1.45,glow:1.85,breatheSpeed:4.2,breatheAmt:.075,lightAlpha:1.35,autoRipple:0},listening:{speed:1.45,amp:.32,turb:.9,glow:1.2,breatheSpeed:2.1,breatheAmt:.035,lightAlpha:.95,autoRipple:1.7}};function rgba(t,e){return`rgba(${t[0]},${t[1]},${t[2]},${e})`}function mix(t,e,i){return[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i,t[2]+(e[2]-t[2])*i]}function clamp(t,e,i){return Math.min(i,Math.max(e,t))}function numberAttribute(t,e,i,s,a){const r=t.getAttribute(e);if(null===r||""===r.trim())return i;const n=Number(r);return Number.isFinite(n)?clamp(n,s,a):i}const h=2*Math.PI,o="undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,l=new Set;let c=0;function tick(t){l.forEach(e=>e.frame(t)),c=l.size?requestAnimationFrame(tick):0}class DbChatOrb extends HTMLElement{constructor(){super(...arguments),this.dpr=1,this.cssW=0,this.cssH=0,this.t0=0,this.lastFrame=0,this.resizeObs=null,this.io=null,this.themeObserver=null,this.themeMedia=null,this.visible=!1,this.hover={x:0,y:0,tx:0,ty:0},this.ripples=[],this.lastAutoRipple=0,this.lastVoiceRipple=0,this.previousVoiceLevel=0,this.displayedVoiceLevel=0,this.inputStream=null,this.audioContext=null,this.audioSource=null,this.analyser=null,this.analyserData=null,this.onPointerMove=t=>{const e=this.getBoundingClientRect();e.width&&(this.hover.tx=Math.max(-1,Math.min(1,2*((t.clientX-e.left)/e.width-.5))),this.hover.ty=Math.max(-1,Math.min(1,2*((t.clientY-e.top)/e.height-.5))))},this.onPointerLeave=()=>{this.hover.tx=0,this.hover.ty=0},this.onPointerDown=()=>{this.addRipple(performance.now(),1)},this.onThemeChange=()=>{o&&this.frame(performance.now())}}static get observedAttributes(){return["size","variant","state","theme","voice-level","min-scale","max-scale"]}get size(){return pick(t,this.getAttribute("size"),"l")}set size(t){this.setAttribute("size",t)}get variant(){return pick(e,this.getAttribute("variant"),"aurora")}set variant(t){this.setAttribute("variant",t)}get state(){return pick(i,this.getAttribute("state"),"idle")}set state(t){this.setAttribute("state",t)}get theme(){return pick(s,this.getAttribute("theme"),"auto")}set theme(t){this.setAttribute("theme",t)}get voiceLevel(){return numberAttribute(this,"voice-level",0,0,1)}set voiceLevel(t){const e=Number(t);this.setAttribute("voice-level",String(clamp(Number.isFinite(e)?e:0,0,1)))}get minScale(){return numberAttribute(this,"min-scale",.88,.5,1.5)}set minScale(t){const e=Number(t);this.setAttribute("min-scale",String(clamp(Number.isFinite(e)?e:.88,.5,1.5)))}get maxScale(){return Math.max(this.minScale,numberAttribute(this,"max-scale",1.18,.5,1.7))}set maxScale(t){const e=Number(t);this.setAttribute("max-scale",String(clamp(Number.isFinite(e)?e:1.18,.5,1.7)))}get audioStream(){return this.inputStream}set audioStream(t){(t!==this.inputStream||null!==t&&!this.analyser)&&(this.stopAudioAnalysis(),this.inputStream=t&&"function"==typeof t.getAudioTracks?t:null,this.isConnected&&this.inputStream&&this.startAudioAnalysis(this.inputStream))}connectedCallback(){this.syncClasses(),this.setAttribute("aria-hidden","true"),this.canvas||this.build(),this.t0=performance.now(),this.lastFrame=0,this.observeTheme(),this.inputStream&&this.startAudioAnalysis(this.inputStream),"undefined"!=typeof ResizeObserver&&(this.resizeObs=new ResizeObserver(()=>this.resize()),this.resizeObs.observe(this)),this.resize(),o?this.frame(this.t0+1600):"undefined"!=typeof IntersectionObserver?(this.io=new IntersectionObserver(t=>{for(const e of t)this.setVisible(e.isIntersecting)},{threshold:.01}),this.io.observe(this)):this.setVisible(!0)}disconnectedCallback(){this.setVisible(!1),this.resizeObs?.disconnect(),this.resizeObs=null,this.io?.disconnect(),this.io=null,this.themeObserver?.disconnect(),this.themeObserver=null,this.themeMedia?.removeEventListener("change",this.onThemeChange),this.themeMedia=null,this.stopAudioAnalysis()}attributeChangedCallback(t){this.canvas&&("size"!==t&&"variant"!==t&&"state"!==t||this.syncClasses(),o&&this.frame(performance.now()))}setVisible(t){t!==this.visible&&(this.visible=t,t?(l.add(this),function ensureTicking(){c||!l.size||o||(c=requestAnimationFrame(tick))}()):l.delete(this))}syncClasses(){this.className=["designbase-wc-chat-orb",`designbase-wc-chat-orb--${this.size}`,`designbase-wc-chat-orb--${this.variant}`,`designbase-wc-chat-orb--${this.state}`].join(" ")}build(){this.replaceChildren(),this.canvas=document.createElement("canvas"),this.canvas.className="designbase-wc-chat-orb__canvas",this.ctx=this.canvas.getContext("2d"),this.append(this.canvas),this.addEventListener("pointermove",this.onPointerMove),this.addEventListener("pointerleave",this.onPointerLeave),this.addEventListener("pointerdown",this.onPointerDown)}addRipple(t,e){this.ripples.push({start:t,strength:clamp(e,.2,1)})}observeTheme(){"undefined"==typeof MutationObserver||this.themeObserver||(this.themeObserver=new MutationObserver(this.onThemeChange),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","data-color-mode","class"]})),"function"!=typeof window.matchMedia||this.themeMedia||(this.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),this.themeMedia.addEventListener("change",this.onThemeChange))}isDarkContext(){if("dark"===this.theme)return!0;if("light"===this.theme)return!1;const t=this.parentElement?.closest("[data-theme], [data-color-mode]"),e=t?.getAttribute("data-color-mode");if("dark"===e)return!0;if("light"===e)return!1;const i=t?.getAttribute("data-theme");if("dark"===i)return!0;if("light"===i)return!1;const s=document.documentElement,a=s.getAttribute("data-color-mode");if("dark"===a)return!0;if("light"===a)return!1;const r=s.getAttribute("data-theme");return"dark"===r||"light"!==r&&(this.themeMedia?.matches??!1)}startAudioAnalysis(t){if(this.analyser)return;const e=window.AudioContext??window.webkitAudioContext;if(e)try{const i=new e,s=i.createAnalyser();s.fftSize=512,s.smoothingTimeConstant=.58;const a=i.createMediaStreamSource(t);a.connect(s),this.audioContext=i,this.audioSource=a,this.analyser=s,this.analyserData=new Float32Array(s.fftSize),"suspended"===i.state&&i.resume().catch(()=>{})}catch{this.stopAudioAnalysis()}}stopAudioAnalysis(){try{this.audioSource?.disconnect(),this.analyser?.disconnect()}catch{}this.audioContext&&this.audioContext.close().catch(()=>{}),this.audioContext=null,this.audioSource=null,this.analyser=null,this.analyserData=null}sampleVoiceLevel(t){if(this.analyser&&this.analyserData){this.analyser.getFloatTimeDomainData(this.analyserData);let t=0;for(const e of this.analyserData)t+=e*e;return{level:clamp((Math.sqrt(t/this.analyserData.length)-.01)/.11,0,1),hasInput:!0}}if(this.hasAttribute("voice-level"))return{level:this.voiceLevel,hasInput:!0};return{level:clamp(.16+.12*(Math.sin(2.05*t)+1)+.42*Math.pow(Math.max(0,Math.sin(.86*t+.7)),5),0,1),hasInput:!1}}resize(){this.canvas&&(this.dpr=Math.min(2,window.devicePixelRatio||1),this.cssW=this.clientWidth||72,this.cssH=this.clientHeight||this.cssW,this.canvas.width=Math.round(this.cssW*this.dpr),this.canvas.height=Math.round(this.cssH*this.dpr),o&&this.frame(this.t0+1600))}frame(t){const e=this.ctx;if(!e||!this.cssW)return;const i=this.lastFrame?Math.min((t-this.lastFrame)/1e3,.1):1/60;this.lastFrame=t;const s=(t-this.t0)/1e3,o=this.cssW,l=this.cssH,c=o/2,d=l/2,m=Math.min(o,l)/2,u=this.isDarkContext(),p=u?a[this.variant]:r[this.variant],g=n[this.state];this.hover.x+=.08*(this.hover.tx-this.hover.x),this.hover.y+=.08*(this.hover.ty-this.hover.y);const b="listening"===this.state?this.sampleVoiceLevel(s):{level:0,hasInput:!1},v=b.level>this.displayedVoiceLevel?19:7;this.displayedVoiceLevel+=(b.level-this.displayedVoiceLevel)*(1-Math.exp(-v*i)),"listening"!==this.state&&this.displayedVoiceLevel<.001&&(this.displayedVoiceLevel=0);const f=Math.pow(clamp(this.displayedVoiceLevel,0,1),.72),y="listening"===this.state?this.minScale+(this.maxScale-this.minScale)*f:1,w=g.breatheAmt*("listening"===this.state?.55:1),A=1+Math.sin(s*g.breatheSpeed)*w,S="listening"===this.state?f:"thinking"===this.state?1:.55,M="thinking"===this.state?1.38:1,C=.68*m*A*y*("thinking"===this.state?1.1:1),x=.99*m;e.setTransform(this.dpr,0,0,this.dpr,0,0),e.clearRect(0,0,o,l),e.globalCompositeOperation="source-over",e.filter="none";const k="thinking"===this.state?u?.42:.22:u?.28:.5,O=u?mix(p.core,p.lights[0],k):"thinking"===this.state?mix(p.core,p.lights[0],.35):mix(p.core,[255,255,255],.5),z=mix(p.core,p.lights[1],u?"thinking"===this.state?.35:0:"thinking"===this.state?.28:.12),L=e.createRadialGradient(c,d-.12*C,.1*C,c,d,C);L.addColorStop(0,rgba(O,u?1:.96)),L.addColorStop(.72,rgba(z,u?1:.9)),L.addColorStop(.93,rgba(z,u?.72:.5)),L.addColorStop(1,rgba(z,0)),e.fillStyle=L,e.beginPath(),e.arc(c,d,C,0,h),e.fill(),e.globalCompositeOperation=u?"lighter":"source-over";const R=p.lights.length;for(let t=0;t<R;t+=1){const i=2.1*t,a=g.turb*(.85+.55*S),r=Math.sin(s*g.speed+i)*g.amp+Math.sin(s*g.speed*1.7+1.4*i)*g.amp*a*.75+Math.sin(s*g.speed*.45+.7*i)*g.amp*.35,n=Math.cos(s*g.speed*.9+1.3*i)*g.amp+Math.cos(s*g.speed*2+i)*g.amp*a*.75+Math.cos(s*g.speed*.55+.9*i)*g.amp*.35,o="thinking"===this.state?.42:.28,l=t/R*h-.5*Math.PI+s*g.speed*o,m=C*("thinking"===this.state?.52:.44),b=c+Math.cos(l)*m+r*C+this.hover.x*C*.12,v=d+Math.sin(l)*m+n*C+this.hover.y*C*.12,f=C*M*(.92+.28*S+.12*Math.sin(s*g.speed*1.3+i)),y="thinking"===this.state?mix(p.lights[t],u?[255,255,255]:p.core,u?.1:.18):p.lights[t],w=(u?.62:.78)*g.lightAlpha*(.85+.28*S)*("thinking"===this.state?1.22:1);e.save(),e.filter=`blur(${C*(u?.15:.18)*("thinking"===this.state?.92:1)}px)`;const A=e.createRadialGradient(b,v,0,b,v,f);A.addColorStop(0,rgba(y,Math.min(1,w))),A.addColorStop(.48,rgba(y,Math.min(1,.5*w))),A.addColorStop(1,rgba(y,0)),e.fillStyle=A,e.beginPath(),e.arc(b,v,f,0,h),e.fill(),e.restore()}e.filter="none",e.globalCompositeOperation="destination-in";const D=e.createRadialGradient(c,d,.6*C,c,d,C);D.addColorStop(0,"rgba(0,0,0,1)"),D.addColorStop(.86,"rgba(0,0,0,1)"),D.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=D,e.beginPath(),e.arc(c,d,C,0,h),e.fill(),e.globalCompositeOperation="source-atop";const V=c-.22*C+this.hover.x*C*.1,F=d-.28*C+this.hover.y*C*.1,E=e.createRadialGradient(V,F,0,V,F,.95*C);E.addColorStop(0,`rgba(255,255,255,${u?.12:.2})`),E.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=E,e.fillRect(c-C,d-C,2*C,2*C),e.globalCompositeOperation="destination-over";const P=e.createRadialGradient(c,d,.7*C,c,d,x),T=(u?.32:.14)*g.glow*(.85+.28*S);P.addColorStop(0,rgba(p.glow,T)),P.addColorStop(1,rgba(p.glow,0)),e.fillStyle=P,e.beginPath(),e.arc(c,d,x,0,h),e.fill(),e.globalCompositeOperation="source-over",e.filter="none"}}customElements.get("db-chat-orb")||customElements.define("db-chat-orb",DbChatOrb);export{DbChatOrb};
1
+ import{CHAT_ORB_SIZES as t,CHAT_ORB_VARIANTS as e,CHAT_ORB_STATES as i,CHAT_ORB_THEMES as s}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";function pick(t,e,i){return t.includes(e)?e:i}const a={aurora:{core:[22,20,52],lights:[[236,92,220],[70,140,250],[42,208,158]],rim:[199,210,254],glow:[120,110,240]},ocean:{core:[10,32,62],lights:[[56,189,248],[34,211,238],[96,165,250]],rim:[165,243,252],glow:[59,130,246]},emerald:{core:[6,42,38],lights:[[52,211,153],[74,222,128],[163,230,53]],rim:[187,247,208],glow:[34,197,94]},violet:{core:[40,12,82],lights:[[192,132,252],[168,85,247],[240,171,252]],rim:[245,208,254],glow:[139,92,246]},mono:{core:[30,34,44],lights:[[229,231,235],[156,163,175],[249,250,251]],rim:[255,255,255],glow:[156,163,175]}},r={aurora:{core:[240,240,250],lights:[[235,96,224],[74,144,246],[26,196,150]],rim:[150,130,210],glow:[138,128,244]},ocean:{core:[226,248,255],lights:[[14,165,233],[34,211,238],[96,165,250]],rim:[64,150,181],glow:[56,189,248]},emerald:{core:[228,250,240],lights:[[16,185,129],[74,222,128],[163,230,53]],rim:[57,145,111],glow:[52,211,153]},violet:{core:[246,233,255],lights:[[168,85,247],[217,70,239],[240,171,252]],rim:[143,91,183],glow:[192,132,252]},mono:{core:[243,246,250],lights:[[148,163,184],[203,213,225],[255,255,255]],rim:[100,116,139],glow:[148,163,184]}},n={idle:{speed:1.55,amp:.38,turb:.95,glow:1.15,breatheSpeed:1.9,breatheAmt:.055,lightAlpha:.95,autoRipple:0},thinking:{speed:3.2,amp:.5,turb:1.45,glow:1.85,breatheSpeed:4.2,breatheAmt:.075,lightAlpha:1.35,autoRipple:0},listening:{speed:1.45,amp:.32,turb:.9,glow:1.2,breatheSpeed:2.1,breatheAmt:.035,lightAlpha:.95,autoRipple:1.7}};function rgba(t,e){return`rgba(${t[0]},${t[1]},${t[2]},${e})`}function mix(t,e,i){return[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i,t[2]+(e[2]-t[2])*i]}function clamp(t,e,i){return Math.min(i,Math.max(e,t))}function numberAttribute(t,e,i,s,a){const r=t.getAttribute(e);if(null===r||""===r.trim())return i;const n=Number(r);return Number.isFinite(n)?clamp(n,s,a):i}const h=2*Math.PI;function prefersReducedMotion(){return"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}const o=new Set;let l=0;function tick(t){o.forEach(e=>e.frame(t)),l=o.size?requestAnimationFrame(tick):0}class DbChatOrb extends HTMLElement{constructor(){super(...arguments),this.dpr=1,this.cssW=0,this.cssH=0,this.t0=0,this.lastFrame=0,this.resizeObs=null,this.io=null,this.themeObserver=null,this.themeMedia=null,this.visible=!1,this.hover={x:0,y:0,tx:0,ty:0},this.ripples=[],this.lastAutoRipple=0,this.lastVoiceRipple=0,this.previousVoiceLevel=0,this.displayedVoiceLevel=0,this.inputStream=null,this.audioContext=null,this.audioSource=null,this.analyser=null,this.analyserData=null,this.onPointerMove=t=>{const e=this.getBoundingClientRect();e.width&&(this.hover.tx=Math.max(-1,Math.min(1,2*((t.clientX-e.left)/e.width-.5))),this.hover.ty=Math.max(-1,Math.min(1,2*((t.clientY-e.top)/e.height-.5))))},this.onPointerLeave=()=>{this.hover.tx=0,this.hover.ty=0},this.onPointerDown=()=>{this.addRipple(performance.now(),1)},this.onThemeChange=()=>{prefersReducedMotion()&&this.frame(performance.now())}}static get observedAttributes(){return["size","variant","state","theme","voice-level","min-scale","max-scale"]}get size(){return pick(t,this.getAttribute("size"),"l")}set size(t){this.setAttribute("size",t)}get variant(){return pick(e,this.getAttribute("variant"),"aurora")}set variant(t){this.setAttribute("variant",t)}get state(){return pick(i,this.getAttribute("state"),"idle")}set state(t){this.setAttribute("state",t)}get theme(){return pick(s,this.getAttribute("theme"),"auto")}set theme(t){this.setAttribute("theme",t)}get voiceLevel(){return numberAttribute(this,"voice-level",0,0,1)}set voiceLevel(t){const e=Number(t);this.setAttribute("voice-level",String(clamp(Number.isFinite(e)?e:0,0,1)))}get minScale(){return numberAttribute(this,"min-scale",.88,.5,1.5)}set minScale(t){const e=Number(t);this.setAttribute("min-scale",String(clamp(Number.isFinite(e)?e:.88,.5,1.5)))}get maxScale(){return Math.max(this.minScale,numberAttribute(this,"max-scale",1.18,.5,1.7))}set maxScale(t){const e=Number(t);this.setAttribute("max-scale",String(clamp(Number.isFinite(e)?e:1.18,.5,1.7)))}get audioStream(){return this.inputStream}set audioStream(t){(t!==this.inputStream||null!==t&&!this.analyser)&&(this.stopAudioAnalysis(),this.inputStream=t&&"function"==typeof t.getAudioTracks?t:null,this.isConnected&&this.inputStream&&this.startAudioAnalysis(this.inputStream))}connectedCallback(){this.syncClasses(),this.setAttribute("aria-hidden","true"),this.canvas||this.build(),this.t0=performance.now(),this.lastFrame=0,this.observeTheme(),this.inputStream&&this.startAudioAnalysis(this.inputStream),"undefined"!=typeof ResizeObserver&&(this.resizeObs=new ResizeObserver(()=>this.resize()),this.resizeObs.observe(this)),this.resize(),prefersReducedMotion()?this.frame(this.t0+1600):"undefined"!=typeof IntersectionObserver?(this.io=new IntersectionObserver(t=>{for(const e of t)this.setVisible(e.isIntersecting)},{threshold:.01}),this.io.observe(this)):this.setVisible(!0)}disconnectedCallback(){this.setVisible(!1),this.resizeObs?.disconnect(),this.resizeObs=null,this.io?.disconnect(),this.io=null,this.themeObserver?.disconnect(),this.themeObserver=null,this.themeMedia?.removeEventListener("change",this.onThemeChange),this.themeMedia=null,this.stopAudioAnalysis()}attributeChangedCallback(t){this.canvas&&("size"!==t&&"variant"!==t&&"state"!==t||this.syncClasses(),prefersReducedMotion()&&this.frame(performance.now()))}setVisible(t){t!==this.visible&&(this.visible=t,t?(o.add(this),function ensureTicking(){l||!o.size||prefersReducedMotion()||(l=requestAnimationFrame(tick))}()):o.delete(this))}syncClasses(){this.className=["designbase-wc-chat-orb",`designbase-wc-chat-orb--${this.size}`,`designbase-wc-chat-orb--${this.variant}`,`designbase-wc-chat-orb--${this.state}`].join(" ")}build(){this.replaceChildren(),this.canvas=document.createElement("canvas"),this.canvas.className="designbase-wc-chat-orb__canvas",this.ctx=this.canvas.getContext("2d"),this.append(this.canvas),this.addEventListener("pointermove",this.onPointerMove),this.addEventListener("pointerleave",this.onPointerLeave),this.addEventListener("pointerdown",this.onPointerDown)}addRipple(t,e){this.ripples.push({start:t,strength:clamp(e,.2,1)})}observeTheme(){"undefined"==typeof MutationObserver||this.themeObserver||(this.themeObserver=new MutationObserver(this.onThemeChange),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","data-color-mode","class"]})),"function"!=typeof window.matchMedia||this.themeMedia||(this.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),this.themeMedia.addEventListener("change",this.onThemeChange))}isDarkContext(){if("dark"===this.theme)return!0;if("light"===this.theme)return!1;const t=this.parentElement?.closest("[data-theme], [data-color-mode]"),e=t?.getAttribute("data-color-mode");if("dark"===e)return!0;if("light"===e)return!1;const i=t?.getAttribute("data-theme");if("dark"===i)return!0;if("light"===i)return!1;const s=document.documentElement,a=s.getAttribute("data-color-mode");if("dark"===a)return!0;if("light"===a)return!1;const r=s.getAttribute("data-theme");return"dark"===r||"light"!==r&&(this.themeMedia?.matches??!1)}startAudioAnalysis(t){if(this.analyser)return;const e=window.AudioContext??window.webkitAudioContext;if(e)try{const i=new e,s=i.createAnalyser();s.fftSize=512,s.smoothingTimeConstant=.58;const a=i.createMediaStreamSource(t);a.connect(s),this.audioContext=i,this.audioSource=a,this.analyser=s,this.analyserData=new Float32Array(s.fftSize),"suspended"===i.state&&i.resume().catch(()=>{})}catch{this.stopAudioAnalysis()}}stopAudioAnalysis(){try{this.audioSource?.disconnect(),this.analyser?.disconnect()}catch{}this.audioContext&&this.audioContext.close().catch(()=>{}),this.audioContext=null,this.audioSource=null,this.analyser=null,this.analyserData=null}sampleVoiceLevel(t){if(this.analyser&&this.analyserData){this.analyser.getFloatTimeDomainData(this.analyserData);let t=0;for(const e of this.analyserData)t+=e*e;return{level:clamp((Math.sqrt(t/this.analyserData.length)-.01)/.11,0,1),hasInput:!0}}if(this.hasAttribute("voice-level"))return{level:this.voiceLevel,hasInput:!0};return{level:clamp(.16+.12*(Math.sin(2.05*t)+1)+.42*Math.pow(Math.max(0,Math.sin(.86*t+.7)),5),0,1),hasInput:!1}}resize(){this.canvas&&(this.dpr=Math.min(2,window.devicePixelRatio||1),this.cssW=this.clientWidth||72,this.cssH=this.clientHeight||this.cssW,this.canvas.width=Math.round(this.cssW*this.dpr),this.canvas.height=Math.round(this.cssH*this.dpr),prefersReducedMotion()&&this.frame(this.t0+1600))}frame(t){const e=this.ctx;if(!e||!this.cssW)return;const i=this.lastFrame?Math.min((t-this.lastFrame)/1e3,.1):1/60;this.lastFrame=t;const s=(t-this.t0)/1e3,o=this.cssW,l=this.cssH,c=o/2,d=l/2,u=Math.min(o,l)/2,m=this.isDarkContext(),p=m?a[this.variant]:r[this.variant],g=n[this.state];this.hover.x+=.08*(this.hover.tx-this.hover.x),this.hover.y+=.08*(this.hover.ty-this.hover.y);const b="listening"===this.state?this.sampleVoiceLevel(s):{level:0,hasInput:!1},v=b.level>this.displayedVoiceLevel?19:7;this.displayedVoiceLevel+=(b.level-this.displayedVoiceLevel)*(1-Math.exp(-v*i)),"listening"!==this.state&&this.displayedVoiceLevel<.001&&(this.displayedVoiceLevel=0);const f=Math.pow(clamp(this.displayedVoiceLevel,0,1),.72),y="listening"===this.state?this.minScale+(this.maxScale-this.minScale)*f:1,w=g.breatheAmt*("listening"===this.state?.55:1),M=1+Math.sin(s*g.breatheSpeed)*w,A="listening"===this.state?f:"thinking"===this.state?1:.55,S="thinking"===this.state?1.38:1,C=.68*u*M*y*("thinking"===this.state?1.1:1),x=.99*u;e.setTransform(this.dpr,0,0,this.dpr,0,0),e.clearRect(0,0,o,l),e.globalCompositeOperation="source-over",e.filter="none";const k="thinking"===this.state?m?.42:.22:m?.28:.5,O=m?mix(p.core,p.lights[0],k):"thinking"===this.state?mix(p.core,p.lights[0],.35):mix(p.core,[255,255,255],.5),R=mix(p.core,p.lights[1],m?"thinking"===this.state?.35:0:"thinking"===this.state?.28:.12),z=e.createRadialGradient(c,d-.12*C,.1*C,c,d,C);z.addColorStop(0,rgba(O,m?1:.96)),z.addColorStop(.72,rgba(R,m?1:.9)),z.addColorStop(.93,rgba(R,m?.72:.5)),z.addColorStop(1,rgba(R,0)),e.fillStyle=z,e.beginPath(),e.arc(c,d,C,0,h),e.fill(),e.globalCompositeOperation=m?"lighter":"source-over";const L=p.lights.length;for(let t=0;t<L;t+=1){const i=2.1*t,a=g.turb*(.85+.55*A),r=Math.sin(s*g.speed+i)*g.amp+Math.sin(s*g.speed*1.7+1.4*i)*g.amp*a*.75+Math.sin(s*g.speed*.45+.7*i)*g.amp*.35,n=Math.cos(s*g.speed*.9+1.3*i)*g.amp+Math.cos(s*g.speed*2+i)*g.amp*a*.75+Math.cos(s*g.speed*.55+.9*i)*g.amp*.35,o="thinking"===this.state?.42:.28,l=t/L*h-.5*Math.PI+s*g.speed*o,u=C*("thinking"===this.state?.52:.44),b=c+Math.cos(l)*u+r*C+this.hover.x*C*.12,v=d+Math.sin(l)*u+n*C+this.hover.y*C*.12,f=C*S*(.92+.28*A+.12*Math.sin(s*g.speed*1.3+i)),y="thinking"===this.state?mix(p.lights[t],m?[255,255,255]:p.core,m?.1:.18):p.lights[t],w=(m?.62:.78)*g.lightAlpha*(.85+.28*A)*("thinking"===this.state?1.22:1);e.save(),e.filter=`blur(${C*(m?.15:.18)*("thinking"===this.state?.92:1)}px)`;const M=e.createRadialGradient(b,v,0,b,v,f);M.addColorStop(0,rgba(y,Math.min(1,w))),M.addColorStop(.48,rgba(y,Math.min(1,.5*w))),M.addColorStop(1,rgba(y,0)),e.fillStyle=M,e.beginPath(),e.arc(b,v,f,0,h),e.fill(),e.restore()}e.filter="none",e.globalCompositeOperation="destination-in";const D=e.createRadialGradient(c,d,.6*C,c,d,C);D.addColorStop(0,"rgba(0,0,0,1)"),D.addColorStop(.86,"rgba(0,0,0,1)"),D.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=D,e.beginPath(),e.arc(c,d,C,0,h),e.fill(),e.globalCompositeOperation="source-atop";const V=c-.22*C+this.hover.x*C*.1,F=d-.28*C+this.hover.y*C*.1,E=e.createRadialGradient(V,F,0,V,F,.95*C);E.addColorStop(0,`rgba(255,255,255,${m?.12:.2})`),E.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=E,e.fillRect(c-C,d-C,2*C,2*C),e.globalCompositeOperation="destination-over";const P=e.createRadialGradient(c,d,.7*C,c,d,x),T=(m?.32:.14)*g.glow*(.85+.28*A);P.addColorStop(0,rgba(p.glow,T)),P.addColorStop(1,rgba(p.glow,0)),e.fillStyle=P,e.beginPath(),e.arc(c,d,x,0,h),e.fill(),e.globalCompositeOperation="source-over",e.filter="none"}}customElements.get("db-chat-orb")||customElements.define("db-chat-orb",DbChatOrb);export{DbChatOrb};
@@ -1,5 +1,5 @@
1
1
  import './db-avatar.js';
2
- import './db-chat-message.js';
2
+ import { DbChatMessageAttachment } from './db-chat-message.js';
3
3
  import './db-chat-typing.js';
4
4
  import { DbChatComposer } from './db-chat-composer.js';
5
5
 
@@ -14,6 +14,7 @@ interface DbChatRoomMessage {
14
14
  name?: string;
15
15
  avatarSrc?: string;
16
16
  avatarInitials?: string;
17
+ attachments?: DbChatMessageAttachment[];
17
18
  }
18
19
  /**
19
20
  * 사람 간 1:1/그룹 대화 화면. 상단 헤더(상대 정보) + 메시지 스레드 + 하단 컴포저.
@@ -33,15 +34,18 @@ declare class DbChatRoom extends HTMLElement {
33
34
  static get observedAttributes(): string[];
34
35
  private built;
35
36
  private typing;
37
+ private dragDepth;
36
38
  private _messages;
37
39
  private headerEl;
38
40
  private scrollEl;
39
41
  private threadEl;
40
42
  private dockEl;
43
+ private dropOverlay;
41
44
  private composer;
42
45
  set messages(v: DbChatRoomMessage[]);
43
46
  get messages(): DbChatRoomMessage[];
44
47
  connectedCallback(): void;
48
+ disconnectedCallback(): void;
45
49
  attributeChangedCallback(): void;
46
50
  private build;
47
51
  private sync;
@@ -50,6 +54,13 @@ declare class DbChatRoom extends HTMLElement {
50
54
  private buildMessage;
51
55
  private buildTyping;
52
56
  private scrollToEnd;
57
+ private nowLabel;
58
+ private hasDragFiles;
59
+ private handleDragEnter;
60
+ private handleDragOver;
61
+ private handleDragLeave;
62
+ private handleDrop;
63
+ private showDropOverlay;
53
64
  /** 메시지 추가. 추가된 id 반환 */
54
65
  addMessage(msg: DbChatRoomMessage): string;
55
66
  /** 전체 메시지 교체 */
@@ -1 +1 @@
1
- import{createDbIcon as t}from"./db-icons.js";import"./db-avatar.js";import"./db-chat-message.js";import"./db-chat-typing.js";import"./db-chat-composer.js";const e="designbase-wc-chat-room";let s=0;function el(t,e,s){const i=document.createElement(t);return e&&(i.className=e),null!=s&&(i.textContent=s),i}class DbChatRoom extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.typing=!1,this._messages=[]}static get observedAttributes(){return["peer-name","peer-avatar","peer-initials","peer-status","placeholder","online","show-back"]}set messages(t){this._messages=Array.isArray(t)?t.map(t=>({id:`r${s+=1}`,...t})):[],this.built&&this.renderThread()}get messages(){return this._messages}connectedCallback(){this.built||this.build(),this.sync()}attributeChangedCallback(){this.built&&this.sync()}build(){this.built=!0,this.className=e,this.replaceChildren(),this.headerEl=el("div",`${e}__header`),this.scrollEl=el("div",`${e}__scroll`),this.threadEl=el("div",`${e}__thread`),this.scrollEl.append(this.threadEl),this.dockEl=el("div",`${e}__dock`),this.composer=document.createElement("db-chat-composer"),this.composer.setAttribute("attach",""),this.composer.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지 보내기…"),this.composer.addEventListener("db-send",t=>{t.stopPropagation();const e=t.detail;this.dispatchEvent(new CustomEvent("db-send",{detail:e,bubbles:!0,composed:!0}))}),this.dockEl.append(this.composer),this.append(this.headerEl,this.scrollEl,this.dockEl),this.renderThread()}sync(){this.renderHeader(),this.composer.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지 보내기…")}renderHeader(){if(this.headerEl.replaceChildren(),this.hasAttribute("show-back")){const s=el("button",`${e}__back`);s.type="button",s.setAttribute("aria-label","뒤로"),s.append(t("chevron-left",20)),s.addEventListener("click",()=>this.dispatchEvent(new CustomEvent("db-back",{bubbles:!0,composed:!0}))),this.headerEl.append(s)}const s=document.createElement("db-avatar");s.className=`${e}__avatar`,s.setAttribute("size","m"),s.setAttribute("variant","primary");const i=this.getAttribute("peer-avatar"),a=this.getAttribute("peer-initials");i?s.setAttribute("src",i):a&&s.setAttribute("initials",a),this.hasAttribute("online")&&s.setAttribute("status","online");const r=el("div",`${e}__meta`);r.append(el("span",`${e}__name`,this.getAttribute("peer-name")||"대화"));const n=this.getAttribute("peer-status")||(this.hasAttribute("online")?"온라인":"");n&&r.append(el("span",`${e}__status`,n)),this.headerEl.append(s,r)}renderThread(){this.threadEl.replaceChildren(),this._messages.forEach(t=>this.threadEl.append(this.buildMessage(t))),this.typing&&this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollToEnd())}buildMessage(t){const e=el("db-chat-message");return e.dataset.id=t.id||"",e.setAttribute("role",t.mine?"user":"assistant"),!t.mine&&t.name&&e.setAttribute("name",t.name),t.time&&e.setAttribute("timestamp",t.time),!t.mine&&t.avatarSrc&&e.setAttribute("avatar-src",t.avatarSrc),!t.mine&&t.avatarInitials&&e.setAttribute("avatar-initials",t.avatarInitials),null!=t.html?e.innerHTML=t.html:e.textContent=t.text||"",e}buildTyping(){const t=el("db-chat-typing");return t.setAttribute("name",this.getAttribute("peer-name")||""),t.setAttribute("avatar-initials",this.getAttribute("peer-initials")||""),t}scrollToEnd(){this.scrollEl.scrollTop=this.scrollEl.scrollHeight}addMessage(t){const e={id:`r${s+=1}`,...t};this._messages.push(e);const i=this.threadEl.querySelector("db-chat-typing"),a=this.buildMessage(e);return i?this.threadEl.insertBefore(a,i):this.threadEl.append(a),requestAnimationFrame(()=>this.scrollToEnd()),e.id}setMessages(t){this.messages=t}setTyping(t){if(this.typing=Boolean(t),!this.built)return;const e=this.threadEl.querySelector("db-chat-typing");this.typing&&!e?(this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollToEnd())):!this.typing&&e&&e.remove()}focusInput(){this.composer?.focusInput()}getComposer(){return this.composer}}customElements.get("db-chat-room")||customElements.define("db-chat-room",DbChatRoom);export{DbChatRoom};
1
+ import{createDbIcon as t}from"./db-icons.js";import"./db-avatar.js";import"./db-chat-message.js";import"./db-chat-typing.js";import"./db-chat-composer.js";const e="designbase-wc-chat-room";let s=0;function el(t,e,s){const a=document.createElement(t);return e&&(a.className=e),null!=s&&(a.textContent=s),a}class DbChatRoom extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.typing=!1,this.dragDepth=0,this._messages=[],this.handleDragEnter=t=>{this.hasDragFiles(t)&&(t.preventDefault(),this.dragDepth+=1,this.showDropOverlay(!0))},this.handleDragOver=t=>{this.hasDragFiles(t)&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))},this.handleDragLeave=()=>{this.dragDepth=Math.max(0,this.dragDepth-1),0===this.dragDepth&&this.showDropOverlay(!1)},this.handleDrop=t=>{if(!this.hasDragFiles(t))return;t.preventDefault(),t.stopPropagation(),this.dragDepth=0,this.showDropOverlay(!1);const e=Array.from(t.dataTransfer?.files||[]);e.length&&this.composer&&(this.composer.addFiles(e,"drop"),this.composer.focusInput())}}static get observedAttributes(){return["peer-name","peer-avatar","peer-initials","peer-status","placeholder","online","show-back"]}set messages(t){this._messages=Array.isArray(t)?t.map(t=>({id:`r${s+=1}`,...t})):[],this.built&&this.renderThread()}get messages(){return this._messages}connectedCallback(){this.built||this.build(),this.sync(),this.addEventListener("dragenter",this.handleDragEnter),this.addEventListener("dragover",this.handleDragOver),this.addEventListener("dragleave",this.handleDragLeave),this.addEventListener("drop",this.handleDrop)}disconnectedCallback(){this.removeEventListener("dragenter",this.handleDragEnter),this.removeEventListener("dragover",this.handleDragOver),this.removeEventListener("dragleave",this.handleDragLeave),this.removeEventListener("drop",this.handleDrop)}attributeChangedCallback(){this.built&&this.sync()}build(){this.built=!0,this.className=e,this.replaceChildren(),this.headerEl=el("div",`${e}__header`),this.scrollEl=el("div",`${e}__scroll`),this.threadEl=el("div",`${e}__thread`),this.scrollEl.append(this.threadEl),this.dockEl=el("div",`${e}__dock`),this.dropOverlay=el("div",`${e}__drop-overlay`),this.dropOverlay.hidden=!0,this.dropOverlay.setAttribute("aria-hidden","true"),this.dropOverlay.append(el("span",`${e}__drop-label`,"파일을 놓으면 첨부됩니다")),this.composer=document.createElement("db-chat-composer"),this.composer.setAttribute("attach",""),this.composer.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지 보내기…"),this.composer.addEventListener("db-send",t=>{t.stopPropagation();const e=t.detail,s=e?.value?.trim()||"",a=e?.attachments||[];if(!s&&!a.length)return;const r=a.map(t=>({name:t.name,kind:t.kind,mime:t.mime,url:t.file?URL.createObjectURL(t.file):t.preview}));this.dispatchEvent(new CustomEvent("db-send",{detail:{value:s,attachments:r},bubbles:!0,composed:!0})),this.addMessage({mine:!0,text:s,time:this.nowLabel(),attachments:r.length?r:void 0})}),this.dockEl.append(this.composer),this.append(this.headerEl,this.scrollEl,this.dockEl,this.dropOverlay),this.renderThread()}sync(){this.renderHeader(),this.composer.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지 보내기…")}renderHeader(){if(this.headerEl.replaceChildren(),this.hasAttribute("show-back")){const s=el("button",`${e}__back`);s.type="button",s.setAttribute("aria-label","뒤로"),s.append(t("chevron-left",20)),s.addEventListener("click",()=>this.dispatchEvent(new CustomEvent("db-back",{bubbles:!0,composed:!0}))),this.headerEl.append(s)}const s=document.createElement("db-avatar");s.className=`${e}__avatar`,s.setAttribute("size","m"),s.setAttribute("variant","primary");const a=this.getAttribute("peer-avatar"),r=this.getAttribute("peer-initials");a?s.setAttribute("src",a):r&&s.setAttribute("initials",r),this.hasAttribute("online")&&s.setAttribute("status","online");const i=el("div",`${e}__meta`);i.append(el("span",`${e}__name`,this.getAttribute("peer-name")||"대화"));const n=this.getAttribute("peer-status")||(this.hasAttribute("online")?"온라인":"");n&&i.append(el("span",`${e}__status`,n)),this.headerEl.append(s,i)}renderThread(){this.threadEl.replaceChildren(),this._messages.forEach(t=>this.threadEl.append(this.buildMessage(t))),this.typing&&this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollToEnd())}buildMessage(t){const e=el("db-chat-message");return e.dataset.id=t.id||"",e.setAttribute("role",t.mine?"user":"assistant"),!t.mine&&t.name&&e.setAttribute("name",t.name),t.time&&e.setAttribute("timestamp",t.time),!t.mine&&t.avatarSrc&&e.setAttribute("avatar-src",t.avatarSrc),!t.mine&&t.avatarInitials&&e.setAttribute("avatar-initials",t.avatarInitials),null!=t.html?e.innerHTML=t.html:e.textContent=t.text||"",t.attachments?.length&&(e.attachments=t.attachments),e}buildTyping(){const t=el("db-chat-typing");return t.setAttribute("name",this.getAttribute("peer-name")||""),t.setAttribute("avatar-initials",this.getAttribute("peer-initials")||""),t}scrollToEnd(){this.scrollEl.scrollTop=this.scrollEl.scrollHeight}nowLabel(){const t=new Date,e=t.getHours();return`${e<12?"오전":"오후"} ${e%12==0?12:e%12}:${t.getMinutes().toString().padStart(2,"0")}`}hasDragFiles(t){return Array.from(t.dataTransfer?.types||[]).includes("Files")}showDropOverlay(t){this.dropOverlay.hidden=!t,this.classList.toggle(`${e}--drop-active`,t)}addMessage(t){const e={id:`r${s+=1}`,...t};this._messages.push(e);const a=this.threadEl.querySelector("db-chat-typing"),r=this.buildMessage(e);return a?this.threadEl.insertBefore(r,a):this.threadEl.append(r),requestAnimationFrame(()=>this.scrollToEnd()),e.id}setMessages(t){this.messages=t}setTyping(t){if(this.typing=Boolean(t),!this.built)return;const e=this.threadEl.querySelector("db-chat-typing");this.typing&&!e?(this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollToEnd())):!this.typing&&e&&e.remove()}focusInput(){this.composer?.focusInput()}getComposer(){return this.composer}}customElements.get("db-chat-room")||customElements.define("db-chat-room",DbChatRoom);export{DbChatRoom};
@@ -1 +1 @@
1
- import"./db-chat-orb.js";const e=["center","left"];class DbChatWelcome extends HTMLElement{static get observedAttributes(){return["greeting","title","highlight","subtitle","align","orb-variant","orb-state","orb-size","hide-orb","avatar-src"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const t=this.getAttribute("greeting")||"",a=this.getAttribute("title")||"",s=this.getAttribute("highlight")||"",c=this.getAttribute("subtitle")||"",i=e.includes(this.getAttribute("align"))?this.getAttribute("align"):"center",n=this.getAttribute("avatar-src"),r=this.hasAttribute("hide-orb");if(this.className=`designbase-wc-chat-welcome designbase-wc-chat-welcome--${i}`,this.replaceChildren(),n){const e=document.createElement("div");e.className="designbase-wc-chat-welcome__media";const t=document.createElement("img");t.className="designbase-wc-chat-welcome__logo",t.src=n,t.alt="",t.setAttribute("aria-hidden","true"),e.append(t),this.append(e)}else if(!r){const e=document.createElement("db-chat-orb");e.className="designbase-wc-chat-welcome__orb",e.setAttribute("size",this.getAttribute("orb-size")||"l"),e.setAttribute("variant",this.getAttribute("orb-variant")||"aurora"),e.setAttribute("state",this.getAttribute("orb-state")||"idle"),this.append(e)}const l=document.createElement("h1");if(l.className="designbase-wc-chat-welcome__heading",t){const e=document.createElement("span");e.className="designbase-wc-chat-welcome__greeting",e.textContent=t,l.append(e)}if(a){const e=document.createElement("span");e.className="designbase-wc-chat-welcome__title",this.appendTitle(e,a,s),l.append(e)}if(this.append(l),c){const e=document.createElement("p");e.className="designbase-wc-chat-welcome__subtitle",e.textContent=c,this.append(e)}}appendTitle(e,t,a){const s=a?t.indexOf(a):-1;if(-1===s)return void(e.textContent=t);const c=t.slice(0,s),i=t.slice(s+a.length);c&&e.append(document.createTextNode(c));const n=document.createElement("span");n.className="designbase-wc-chat-welcome__highlight",n.textContent=a,e.append(n),i&&e.append(document.createTextNode(i))}}customElements.get("db-chat-welcome")||customElements.define("db-chat-welcome",DbChatWelcome);export{DbChatWelcome};
1
+ import"./db-chat-orb.js";import{CHAT_WELCOME_ALIGNS as e}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbChatWelcome extends HTMLElement{static get observedAttributes(){return["greeting","title","highlight","subtitle","align","orb-variant","orb-state","orb-size","hide-orb","avatar-src"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const t=this.getAttribute("greeting")||"",s=this.getAttribute("title")||"",a=this.getAttribute("highlight")||"",i=this.getAttribute("subtitle")||"",c=e.includes(this.getAttribute("align"))?this.getAttribute("align"):"center",n=this.getAttribute("avatar-src"),r=this.hasAttribute("hide-orb");if(this.className=`designbase-wc-chat-welcome designbase-wc-chat-welcome--${c}`,this.replaceChildren(),n){const e=document.createElement("div");e.className="designbase-wc-chat-welcome__media";const t=document.createElement("img");t.className="designbase-wc-chat-welcome__logo",t.src=n,t.alt="",t.setAttribute("aria-hidden","true"),e.append(t),this.append(e)}else if(!r){const e=document.createElement("db-chat-orb");e.className="designbase-wc-chat-welcome__orb",e.setAttribute("size",this.getAttribute("orb-size")||"l"),e.setAttribute("variant",this.getAttribute("orb-variant")||"aurora"),e.setAttribute("state",this.getAttribute("orb-state")||"idle"),this.append(e)}const o=document.createElement("h1");if(o.className="designbase-wc-chat-welcome__heading",t){const e=document.createElement("span");e.className="designbase-wc-chat-welcome__greeting",e.textContent=t,o.append(e)}if(s){const e=document.createElement("span");e.className="designbase-wc-chat-welcome__title",this.appendTitle(e,s,a),o.append(e)}if(this.append(o),i){const e=document.createElement("p");e.className="designbase-wc-chat-welcome__subtitle",e.textContent=i,this.append(e)}}appendTitle(e,t,s){const a=s?t.indexOf(s):-1;if(-1===a)return void(e.textContent=t);const i=t.slice(0,a),c=t.slice(a+s.length);i&&e.append(document.createTextNode(i));const n=document.createElement("span");n.className="designbase-wc-chat-welcome__highlight",n.textContent=s,e.append(n),c&&e.append(document.createTextNode(c))}}customElements.get("db-chat-welcome")||customElements.define("db-chat-welcome",DbChatWelcome);export{DbChatWelcome};
@@ -6,11 +6,12 @@ import { DbChatSuggestion } from './db-chat-suggestions.js';
6
6
  import './db-chat-message.js';
7
7
  import './db-chat-typing.js';
8
8
  import './db-avatar.js';
9
+ import { CHAT_WIDGET_VIEWS, CHAT_WIDGET_POSITIONS } from '@designbasekorea/ui-contracts';
9
10
 
10
- declare const VIEWS: readonly ["home", "messages", "conversation", "help"];
11
- type ChatView = (typeof VIEWS)[number];
12
- declare const POSITIONS: readonly ["bottom-right", "bottom-left"];
13
- type ChatPosition = (typeof POSITIONS)[number];
11
+ type ChatView = (typeof CHAT_WIDGET_VIEWS)[number];
12
+ type ChatPosition = (typeof CHAT_WIDGET_POSITIONS)[number];
13
+ /** 홈 메뉴 선택 시 위젯 내부 이동. `none`이면 이벤트만 발행(호스트가 처리) */
14
+ type DbChatWidgetMenuAction = 'conversation' | 'help' | 'none';
14
15
  interface DbChatWidgetMessage {
15
16
  id?: string;
16
17
  /** `assistant`(상담원/봇) 또는 `user` */
@@ -22,6 +23,13 @@ interface DbChatWidgetMessage {
22
23
  avatarInitials?: string;
23
24
  /** 말풍선 액션 (예: 'copy,like,dislike') — db-chat-message 로 전달 */
24
25
  actions?: string;
26
+ /** 첨부 파일/이미지 */
27
+ attachments?: Array<{
28
+ name: string;
29
+ kind?: 'image' | 'video' | 'file';
30
+ url?: string;
31
+ mime?: string;
32
+ }>;
25
33
  }
26
34
  interface DbChatWidgetConversation {
27
35
  id?: string;
@@ -33,6 +41,15 @@ interface DbChatWidgetConversation {
33
41
  unread?: number;
34
42
  online?: boolean;
35
43
  }
44
+ /** 홈 바로가기 메뉴 — 필요한 항목만 `menuItems`로 전달 (없으면 숨김) */
45
+ interface DbChatWidgetMenuItem extends DbChatSuggestion {
46
+ action?: DbChatWidgetMenuAction;
47
+ }
48
+ /** 도움말 문서 — 클릭 시 상세(`article`) 화면으로 이동 */
49
+ interface DbChatWidgetArticle extends DbChatSuggestion {
50
+ /** 상세 본문. 없으면 description을 본문으로 사용 */
51
+ body?: string;
52
+ }
36
53
  /**
37
54
  * FAB 로 열고 닫는 우측 하단 채팅 상담 위젯(껍데기).
38
55
  *
@@ -46,11 +63,12 @@ interface DbChatWidgetConversation {
46
63
  * @fires db-toggle - FAB 토글 (detail: { open })
47
64
  * @fires db-view-change - 화면 전환 (detail: { view })
48
65
  * @fires db-send - 메시지 전송 (detail: { text })
49
- * @fires db-menu-select - 홈 메뉴 선택 (detail: { id, value })
66
+ * @fires db-menu-select - 홈 메뉴 선택 (detail: { id, value, action })
50
67
  * @fires db-quick-reply - 빠른 답변 선택 (detail: { id, value })
51
68
  * @fires db-article-select - 도움말 문서 선택 (detail: { id, title })
52
69
  * @fires db-conversation-select - 대화 목록 선택 (detail: { id })
53
70
  * @fires db-message-action - 말풍선 액션 (detail: { action, text })
71
+ * @fires db-start-chat - 대화 시작 CTA (홈·메시지 empty)
54
72
  *
55
73
  * @example
56
74
  * const chat = document.createElement('db-chat-widget');
@@ -69,6 +87,8 @@ declare class DbChatWidget extends HTMLElement {
69
87
  static get observedAttributes(): string[];
70
88
  private built;
71
89
  private typing;
90
+ private helpQuery;
91
+ private _activeArticle;
72
92
  private _messages;
73
93
  private _conversations;
74
94
  private _menuItems;
@@ -95,16 +115,24 @@ declare class DbChatWidget extends HTMLElement {
95
115
  get messages(): DbChatWidgetMessage[];
96
116
  set conversations(v: DbChatWidgetConversation[]);
97
117
  get conversations(): DbChatWidgetConversation[];
98
- set menuItems(v: DbChatSuggestion[]);
99
- get menuItems(): DbChatSuggestion[];
118
+ set menuItems(v: DbChatWidgetMenuItem[]);
119
+ get menuItems(): DbChatWidgetMenuItem[];
100
120
  set quickReplies(v: DbChatSuggestion[]);
101
121
  get quickReplies(): DbChatSuggestion[];
102
- set articles(v: DbChatSuggestion[]);
103
- get articles(): DbChatSuggestion[];
122
+ set articles(v: DbChatWidgetArticle[]);
123
+ get articles(): DbChatWidgetArticle[];
104
124
  connectedCallback(): void;
125
+ disconnectedCallback(): void;
126
+ /** 열린 위젯 패널은 Escape 로 닫히고 포커스는 런처로 돌아간다 (A11Y-ESCAPE) */
127
+ private handleDocumentKeyDown;
105
128
  attributeChangedCallback(name: string, oldVal: string | null, newVal: string | null): void;
106
129
  private hydrateFromAttributes;
107
130
  private build;
131
+ private panelDragDepth;
132
+ private handlePanelDragEnter;
133
+ private handlePanelDragOver;
134
+ private handlePanelDragLeave;
135
+ private handlePanelDrop;
108
136
  private sync;
109
137
  private syncOpenState;
110
138
  private renderBadge;
@@ -115,9 +143,14 @@ declare class DbChatWidget extends HTMLElement {
115
143
  private renderMessages;
116
144
  private renderConversation;
117
145
  private renderHelp;
146
+ private renderHelpResults;
147
+ private renderArticle;
148
+ private openArticle;
149
+ private startConversation;
118
150
  private buildMessage;
119
151
  private buildTyping;
120
152
  private buildEmpty;
153
+ private buildStartChatButton;
121
154
  private renderFooter;
122
155
  private renderNav;
123
156
  private scrollThreadToEnd;
@@ -143,4 +176,4 @@ declare global {
143
176
  }
144
177
 
145
178
  export { DbChatWidget };
146
- export type { DbChatWidgetConversation, DbChatWidgetMessage };
179
+ export type { DbChatWidgetArticle, DbChatWidgetConversation, DbChatWidgetMenuAction, DbChatWidgetMenuItem, DbChatWidgetMessage };
@@ -1 +1 @@
1
- import{createDbIcon as t}from"./db-icons.js";import"./db-chat-orb.js";import"./db-badge.js";import"./db-chat-welcome.js";import"./db-chat-composer.js";import"./db-chat-suggestions.js";import"./db-chat-message.js";import"./db-chat-typing.js";import"./db-avatar.js";const e=["home","messages","conversation","help"],i=["bottom-right","bottom-left"],s=[{id:"products",title:"제품·정책 알아보기",description:"AI가 정확하게 안내해 드려요",icon:"sparkle"},{id:"services",title:"상담원과 대화하기",description:"지금 바로 대화를 시작하세요",icon:"mail"},{id:"status",title:"주문·배송 조회",description:"진행 상황을 확인해 보세요",icon:"package"}],a=[{id:"products",title:"제품·정책 알아보기"},{id:"services",title:"서비스 상담하기"}],r=[{id:"m1",role:"assistant",name:"상담원",text:"안녕하세요. 무엇을 도와드릴까요? 제품과 정책을 24시간 정확하게 안내해 드릴게요.",time:"오후 12:31"},{id:"m2",role:"assistant",name:"상담원",text:"아래에서 원하시는 도움을 선택하시거나, 자유롭게 메시지를 입력해 주세요.",time:"오후 12:31",actions:"like,dislike"}],n=[{id:"c1",name:"디지털 상담원",avatarInitials:"상",preview:"무엇을 도와드릴까요? 24시간 대기중이에요.",time:"방금",unread:1,online:!0},{id:"c2",name:"결제·환불 지원",avatarInitials:"결",preview:"환불 요청이 정상 접수되었습니다.",time:"어제"},{id:"c3",name:"온보딩 도우미",avatarInitials:"온",preview:"설치가 완료되면 알려드릴게요.",time:"3일 전"}],o=[{id:"a1",title:"시작하기 — 5분 만에 설정 완료",description:"계정 생성부터 첫 배포까지",icon:"sparkle"},{id:"a2",title:"요금제와 결제 안내",description:"플랜 비교 · 청구 주기",icon:"star"},{id:"a3",title:"팀원 초대와 권한 관리",description:"역할별 접근 권한 설정",icon:"user"},{id:"a4",title:"데이터 내보내기·백업",description:"안전하게 보관하는 방법",icon:"download"}],h={chat:'<path d="M4 5.5A1.5 1.5 0 0 1 5.5 4h13A1.5 1.5 0 0 1 20 5.5v9a1.5 1.5 0 0 1-1.5 1.5H9l-4 3.5V16H5.5A1.5 1.5 0 0 1 4 14.5z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>',home:'<path d="M4 10.5 12 4l8 6.5M6 9.5V19a1 1 0 0 0 1 1h3.5v-4.5a1.5 1.5 0 0 1 3 0V20H17a1 1 0 0 0 1-1V9.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>',help:'<circle cx="12" cy="12" r="8.25" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.9.6c0 1.7-2.5 2-2.5 3.6" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><circle cx="12" cy="16.6" r="0.95" fill="currentColor"/>',"close-x":'<path d="m6.5 6.5 11 11m0-11-11 11" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>'};function widgetIcon(t,e=20){const i=document.createElement("template");return i.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="${e}" height="${e}" fill="none" aria-hidden="true" focusable="false">${h[t]}</svg>`,i.content.firstElementChild}function el(t,e,i){const s=document.createElement(t);return e&&(s.className=e),null!=i&&(s.textContent=i),s}function parseJson(t,e){if(!t)return e;try{const i=JSON.parse(t);return Array.isArray(i)?i:e}catch{return e}}const l="designbase-wc-chat";class DbChatWidget extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.typing=!1,this._messages=r,this._conversations=n,this._menuItems=s,this._quickReplies=a,this._articles=o,this.composer=null,this.threadEl=null}static get observedAttributes(){return["open","view","position","agent-name","agent-avatar","agent-status","greeting","title","subtitle","placeholder","unread","accent","orb-variant","launcher-label","search-enabled"]}get open(){return this.hasAttribute("open")}set open(t){this.toggleAttribute("open",Boolean(t))}get view(){const t=this.getAttribute("view");return e.includes(t)?t:"home"}set view(t){this.setAttribute("view",t)}get position(){const t=this.getAttribute("position");return i.includes(t)?t:"bottom-right"}set position(t){this.setAttribute("position",t)}get unread(){return Number(this.getAttribute("unread")||0)}set unread(t){this.setAttribute("unread",String(t))}set messages(t){this._messages=Array.isArray(t)?t:[],this.built&&"conversation"===this.view&&this.renderBody()}get messages(){return this._messages}set conversations(t){this._conversations=Array.isArray(t)?t:[],this.built&&this.renderBody()}get conversations(){return this._conversations}set menuItems(t){this._menuItems=Array.isArray(t)?t:[],this.built&&"home"===this.view&&this.renderBody()}get menuItems(){return this._menuItems}set quickReplies(t){this._quickReplies=Array.isArray(t)?t:[],this.built&&"conversation"===this.view&&this.renderBody()}get quickReplies(){return this._quickReplies}set articles(t){this._articles=Array.isArray(t)?t:[],this.built&&"help"===this.view&&this.renderBody()}get articles(){return this._articles}connectedCallback(){this.hydrateFromAttributes(),this.build(),this.sync()}attributeChangedCallback(t,e,i){if(this.built&&e!==i){if("open"!==t)return"view"===t?(this.sync(),void this.dispatch("db-view-change",{view:this.view})):void this.sync();this.syncOpenState()}}hydrateFromAttributes(){this._messages=parseJson(this.getAttribute("messages"),this._messages),this._conversations=parseJson(this.getAttribute("conversations"),this._conversations),this._menuItems=parseJson(this.getAttribute("menu-items"),this._menuItems),this._quickReplies=parseJson(this.getAttribute("quick-replies"),this._quickReplies),this._articles=parseJson(this.getAttribute("articles"),this._articles)}build(){if(this.built)return;this.built=!0,this.classList.add(l),this.replaceChildren(),this.launcher=el("button",`${l}__launcher`),this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog");const t=el("span",`${l}__launcher-icon ${l}__launcher-icon--open`),e=el("db-chat-orb");e.setAttribute("size","s"),e.setAttribute("variant",this.getAttribute("orb-variant")||"violet"),e.setAttribute("state","idle"),t.append(e);const i=el("span",`${l}__launcher-icon ${l}__launcher-icon--close`);i.append(widgetIcon("close-x",24)),this.launcherBadge=document.createElement("db-badge"),this.launcherBadge.className=`${l}__launcher-badge`,this.launcherBadge.setAttribute("badge-style","number"),this.launcherBadge.setAttribute("variant","danger"),this.launcherBadge.setAttribute("size","s"),this.launcherBadge.setAttribute("max-count","99"),this.launcher.append(t,i,this.launcherBadge),this.launcher.addEventListener("click",()=>this.toggle()),this.panel=el("div",`${l}__panel`),this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-modal","false"),this.headerEl=el("div",`${l}__header`),this.bodyEl=el("div",`${l}__body`),this.footerEl=el("div",`${l}__footer`),this.navEl=el("div",`${l}__nav`),this.panel.append(this.headerEl,this.bodyEl,this.footerEl,this.navEl),this.append(this.panel,this.launcher)}sync(){i.forEach(t=>this.classList.toggle(`${l}--${t}`,t===this.position)),e.forEach(t=>this.classList.toggle(`${l}--view-${t}`,t===this.view));const t=this.getAttribute("accent");t?this.style.setProperty("--dbchat-accent",t):this.style.removeProperty("--dbchat-accent"),this.renderBadge(),this.renderHeader(),this.renderBody(),this.renderFooter(),this.renderNav(),this.syncOpenState()}syncOpenState(){const t=this.open;this.classList.toggle(`${l}--open`,t),this.launcher.setAttribute("aria-expanded",String(t)),this.panel.setAttribute("aria-hidden",String(!t)),t?this.panel.removeAttribute("inert"):this.panel.setAttribute("inert",""),this.launcher.setAttribute("aria-label",this.getAttribute("launcher-label")||(t?"상담창 닫기":"상담 시작하기")),t&&"conversation"===this.view&&requestAnimationFrame(()=>this.composer?.focusInput())}renderBadge(){const t=this.unread;t>0?this.launcherBadge.setAttribute("count",String(t)):this.launcherBadge.removeAttribute("count"),this.launcherBadge.hidden=t<=0}renderHeader(){this.headerEl.replaceChildren();const e=this.view,i=this.getAttribute("agent-name")||"디지털 상담원",s=el("div",`${l}__header-bar`);if("conversation"===e){const e=this.iconButton(t("chevron-left",20),"뒤로",()=>this.setView("messages")),a=el("div",`${l}__header-identity`),r=el("db-chat-orb");r.className=`${l}__header-orb`,r.setAttribute("size","xs"),r.setAttribute("variant",this.getAttribute("orb-variant")||"violet");const n=el("div",`${l}__header-meta`);n.append(el("span",`${l}__header-name`,i),el("span",`${l}__header-status`,this.getAttribute("agent-status")||"보통 몇 분 내 응답")),a.append(r,n),s.append(e,a,this.iconButton(widgetIcon("close-x",20),"닫기",()=>this.close()))}else{const t="home"===e?"홈":"messages"===e?"메시지":"도움말";s.append(el("span",`${l}__header-title`,t),this.iconButton(widgetIcon("close-x",20),"닫기",()=>this.close()))}this.headerEl.append(s)}iconButton(t,e,i){const s=el("button",`${l}__icon-btn`);return s.type="button",s.setAttribute("aria-label",e),s.append(t),s.addEventListener("click",i),s}renderBody(){if(this.built)switch(this.threadEl=null,this.bodyEl.replaceChildren(),this.bodyEl.classList.toggle(`${l}__body--thread`,"conversation"===this.view),this.view){case"home":this.renderHome();break;case"messages":this.renderMessages();break;case"conversation":this.renderConversation();break;case"help":this.renderHelp()}}renderHome(){const e=el("db-chat-welcome",`${l}__welcome`);e.setAttribute("greeting",this.getAttribute("greeting")||"안녕하세요"),e.setAttribute("title",this.getAttribute("title")||"무엇을 도와드릴까요?"),e.setAttribute("highlight",this.getAttribute("highlight")||this.getAttribute("title")||"도와드릴까요"),e.setAttribute("subtitle",this.getAttribute("subtitle")||"제품·정책을 24시간 정확하게 안내해 드릴게요."),e.setAttribute("orb-variant",this.getAttribute("orb-variant")||"violet"),e.setAttribute("align","left"),e.setAttribute("orb-size","m"),this.bodyEl.append(e);const i=this._conversations[0];if(i){const e=el("button",`${l}__recent`);e.type="button";const s=el("db-avatar",`${l}__recent-avatar`);s.setAttribute("size","s"),s.setAttribute("variant","primary"),i.avatarSrc?s.setAttribute("src",i.avatarSrc):s.setAttribute("initials",i.avatarInitials||i.name.charAt(0)||"상"),i.online&&s.setAttribute("status","online"),i.unread&&(s.setAttribute("badge",String(i.unread)),s.setAttribute("badge-style","number"),s.setAttribute("badge-variant","primary"),s.setAttribute("badge-max-count","99"));const a=el("div",`${l}__recent-body`);a.append(el("span",`${l}__recent-title`,"최근 대화 이어가기"),el("span",`${l}__recent-preview`,i.preview||"")),e.append(s,a,t("chevron-right",18)),e.addEventListener("click",()=>{this.dispatch("db-conversation-select",{id:i.id}),this.setView("conversation")}),this.bodyEl.append(e)}if(this._menuItems.length){const t=el("db-chat-suggestions",`${l}__menu`);t.setAttribute("layout","card"),t.setAttribute("columns","1"),t.items=this._menuItems,t.addEventListener("db-select",t=>{t.stopPropagation();const e=t.detail;this.dispatch("db-menu-select",e),this.setView("conversation")}),this.bodyEl.append(t)}if("false"!==this.getAttribute("search-enabled")){const e=el("button",`${l}__search-entry`);e.type="button",e.append(t("search",18),el("span",void 0,"도움말 검색")),e.addEventListener("click",()=>this.setView("help")),this.bodyEl.append(e)}}renderMessages(){if(!this._conversations.length)return void this.bodyEl.append(this.buildEmpty("진행 중인 대화가 없어요","새 대화를 시작해 보세요."));const t=el("div",`${l}__conv-list`);this._conversations.forEach(e=>{const i=el("button",`${l}__conv`);i.type="button";const s=el("db-avatar",`${l}__conv-avatar`);s.setAttribute("size","m"),s.setAttribute("variant","primary"),e.avatarSrc?s.setAttribute("src",e.avatarSrc):s.setAttribute("initials",e.avatarInitials||e.name.charAt(0)||"?"),e.online&&s.setAttribute("status","online");const a=el("div",`${l}__conv-body`),r=el("div",`${l}__conv-top`);if(r.append(el("span",`${l}__conv-name`,e.name)),e.time&&r.append(el("span",`${l}__conv-time`,e.time)),a.append(r,el("span",`${l}__conv-preview`,e.preview||"")),i.append(s,a),e.unread){const t=el("db-badge",`${l}__conv-unread`);t.setAttribute("badge-style","number"),t.setAttribute("variant","primary"),t.setAttribute("size","s"),t.setAttribute("max-count","99"),t.setAttribute("count",String(e.unread)),i.append(t)}i.addEventListener("click",()=>{this.dispatch("db-conversation-select",{id:e.id}),this.setView("conversation")}),t.append(i)}),this.bodyEl.append(t)}renderConversation(){const t=el("div",`${l}__thread`);if(this._messages.forEach(e=>t.append(this.buildMessage(e))),this.threadEl=t,this.bodyEl.append(t),this.typing&&t.append(this.buildTyping()),this._quickReplies.length){const t=el("db-chat-suggestions");t.setAttribute("data-dbchat","quick"),t.setAttribute("layout","chip"),t.items=this._quickReplies,t.addEventListener("db-select",t=>{t.stopPropagation();const e=t.detail;this.dispatch("db-quick-reply",e),this.addMessage({role:"user",text:e.title,time:this.nowLabel()})}),this.bodyEl.append(t)}requestAnimationFrame(()=>this.scrollThreadToEnd())}renderHelp(){const e=el("div",`${l}__help-search`),i=el("span",`${l}__help-search-icon`);i.append(t("search",18));const s=el("input",`${l}__help-input`);if(s.type="search",s.placeholder="도움말 검색…",e.append(i,s),this.bodyEl.append(e),!this._articles.length)return void this.bodyEl.append(this.buildEmpty("문서가 없어요","검색어를 바꿔보세요."));const a=el("db-chat-suggestions",`${l}__articles`);a.setAttribute("layout","card"),a.setAttribute("columns","1"),a.items=this._articles,a.addEventListener("db-select",t=>{t.stopPropagation();const e=t.detail;this.dispatch("db-article-select",{id:e.id,title:e.title})}),this.bodyEl.append(a)}buildMessage(t){const e="user"===t.role?"user":"assistant",i=el("db-chat-message");return i.setAttribute("role",e),t.name&&i.setAttribute("name",t.name),t.time&&i.setAttribute("timestamp",t.time),t.avatarSrc&&i.setAttribute("avatar-src",t.avatarSrc),t.avatarInitials&&i.setAttribute("avatar-initials",t.avatarInitials),t.actions&&i.setAttribute("actions",t.actions),i.textContent=t.text,i.addEventListener("db-action",t=>{t.stopPropagation(),this.dispatch("db-message-action",t.detail)}),i}buildTyping(){const t=el("db-chat-typing",`${l}__typing`);return t.setAttribute("name",this.getAttribute("agent-name")||"상담원"),t.setAttribute("label","입력 중"),t}buildEmpty(t,e){const i=el("div",`${l}__empty`),s=el("db-chat-orb",`${l}__empty-orb`);return s.setAttribute("size","m"),s.setAttribute("variant",this.getAttribute("orb-variant")||"violet"),i.append(s,el("p",`${l}__empty-title`,t),el("p",`${l}__empty-desc`,e)),i}renderFooter(){const t="conversation"===this.view;if(this.footerEl.hidden=!t,!t)return this.composer=null,void this.footerEl.replaceChildren();if(!this.composer){this.footerEl.replaceChildren();const t=el("db-chat-composer",`${l}__composer`);t.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지를 입력하세요…"),t.setAttribute("attach",""),t.setAttribute("voice",""),t.addEventListener("db-send",e=>{e.stopPropagation();const i=e.detail?.value?.trim();i&&(t.clear(),this.dispatch("db-send",{text:i}),this.addMessage({role:"user",text:i,time:this.nowLabel()}))}),t.addEventListener("db-stop",t=>{t.stopPropagation(),this.dispatch("db-stop")}),t.addEventListener("db-attach",t=>{t.stopPropagation(),this.dispatch("db-attach")}),t.addEventListener("db-voice",t=>{t.stopPropagation(),this.dispatch("db-voice")}),this.composer=t,this.footerEl.append(t)}}renderNav(){this.navEl.replaceChildren();const t="conversation"!==this.view;if(this.navEl.hidden=!t,!t)return;[{view:"home",icon:"home",label:"홈"},{view:"messages",icon:"chat",label:"메시지"},{view:"help",icon:"help",label:"도움말"}].forEach(t=>{const e=el("button",`${l}__tab`);e.type="button";const i=this.view===t.view;if(e.classList.toggle(`${l}__tab--active`,i),e.setAttribute("aria-current",String(i)),e.append(widgetIcon(t.icon,22),el("span",`${l}__tab-label`,t.label)),"messages"===t.view&&this.unread>0){const t=el("db-badge",`${l}__tab-badge`);t.setAttribute("badge-style","dot"),t.setAttribute("variant","danger"),t.setAttribute("size","s"),e.append(t)}e.addEventListener("click",()=>this.setView(t.view)),this.navEl.append(e)})}scrollThreadToEnd(){this.bodyEl.scrollTop=this.bodyEl.scrollHeight}nowLabel(){const t=new Date,e=t.getHours();return`${e<12?"오전":"오후"} ${e%12==0?12:e%12}:${t.getMinutes().toString().padStart(2,"0")}`}dispatch(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}openWidget(){this.open||(this.open=!0,this.dispatch("db-open"),this.dispatch("db-toggle",{open:!0}))}close(){this.open&&(this.open=!1,this.dispatch("db-close"),this.dispatch("db-toggle",{open:!1}))}toggle(){this.open?this.close():this.openWidget()}setView(t){this.view!==t&&(this.view=t)}addMessage(t){if(this._messages=[...this._messages,{id:`m${Date.now()}`,...t}],"conversation"===this.view)if(this.built&&this.threadEl){const e=this.threadEl.querySelector("db-chat-typing");this.threadEl.insertBefore(this.buildMessage(t),e),requestAnimationFrame(()=>this.scrollThreadToEnd())}else this.built&&this.renderBody();else this.view="conversation"}setTyping(t){if(this.typing=Boolean(t),!this.built||"conversation"!==this.view||!this.threadEl)return;const e=this.threadEl.querySelector("db-chat-typing");this.typing&&!e?(this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollThreadToEnd())):!this.typing&&e&&e.remove()}setStreaming(t){this.composer?.setStreaming(Boolean(t))}setMessages(t){this.messages=t}}customElements.get("db-chat-widget")||customElements.define("db-chat-widget",DbChatWidget);export{DbChatWidget};
1
+ import{createDbIcon as t,isDbIconName as e}from"./db-icons.js";import"./db-chat-orb.js";import"./db-badge.js";import"./db-chat-welcome.js";import"./db-chat-composer.js";import"./db-chat-suggestions.js";import"./db-chat-message.js";import"./db-chat-typing.js";import"./db-avatar.js";import{CHAT_WIDGET_VIEWS as i,CHAT_WIDGET_POSITIONS as s}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";const n=[{id:"products",title:"제품·정책 알아보기",description:"AI가 정확하게 안내해 드려요",icon:"sparkle",action:"help"},{id:"services",title:"상담원과 대화하기",description:"지금 바로 대화를 시작하세요",icon:"mail",action:"conversation"}],a=[{id:"products",title:"제품·정책 알아보기"},{id:"services",title:"서비스 상담하기"},{id:"refund",title:"환불·결제 문의"},{id:"account",title:"계정·로그인 도움"}],r=[{id:"m1",role:"assistant",name:"상담원",text:"안녕하세요. 무엇을 도와드릴까요? 제품과 정책을 24시간 정확하게 안내해 드릴게요.",time:"오후 12:31"},{id:"m2",role:"assistant",name:"상담원",text:"아래에서 원하시는 도움을 선택하시거나, 자유롭게 메시지를 입력해 주세요.",time:"오후 12:31",actions:"like,dislike"}],o=[{id:"c1",name:"디지털 상담원",avatarInitials:"상",preview:"무엇을 도와드릴까요? 24시간 대기중이에요.",time:"방금",unread:1,online:!0},{id:"c2",name:"결제·환불 지원",avatarInitials:"결",preview:"환불 요청이 정상 접수되었습니다.",time:"어제"},{id:"c3",name:"온보딩 도우미",avatarInitials:"온",preview:"설치가 완료되면 알려드릴게요.",time:"3일 전"}],l=[{id:"a1",title:"시작하기 — 5분 만에 설정 완료",description:"계정 생성부터 첫 배포까지",icon:"sparkle",body:"계정을 만들고 첫 프로젝트를 배포하기까지 약 5분이면 충분합니다.\n\n1. 회원가입 후 이메일 인증\n2. 워크스페이스 생성\n3. 템플릿 선택 또는 빈 프로젝트 시작\n4. 배포 버튼을 눌러 미리보기 URL 확인"},{id:"a2",title:"요금제와 결제 안내",description:"플랜 비교 · 청구 주기",icon:"star",body:"Free · Pro · Team 플랜을 제공합니다. 청구는 월간 또는 연간으로 선택할 수 있으며, 연간 결제는 할인율이 적용됩니다.\n\n결제 수단 변경과 영수증 다운로드는 설정 > 결제에서 가능합니다."},{id:"a3",title:"팀원 초대와 권한 관리",description:"역할별 접근 권한 설정",icon:"user",body:"Owner · Admin · Member · Viewer 역할을 지원합니다.\n\n설정 > 팀원에서 이메일로 초대하고, 역할은 언제든 변경할 수 있습니다."},{id:"a4",title:"데이터 내보내기·백업",description:"안전하게 보관하는 방법",icon:"download",body:"프로젝트 데이터는 JSON · CSV로 내보낼 수 있습니다. 자동 백업은 Pro 이상에서 매일 실행되며, 설정 > 데이터에서 수동 백업도 가능합니다."}],h={chat:'<path d="M4 5.5A1.5 1.5 0 0 1 5.5 4h13A1.5 1.5 0 0 1 20 5.5v9a1.5 1.5 0 0 1-1.5 1.5H9l-4 3.5V16H5.5A1.5 1.5 0 0 1 4 14.5z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>',home:'<path d="M4 10.5 12 4l8 6.5M6 9.5V19a1 1 0 0 0 1 1h3.5v-4.5a1.5 1.5 0 0 1 3 0V20H17a1 1 0 0 0 1-1V9.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>',help:'<circle cx="12" cy="12" r="8.25" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.9.6c0 1.7-2.5 2-2.5 3.6" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><circle cx="12" cy="16.6" r="0.95" fill="currentColor"/>',"close-x":'<path d="m6.5 6.5 11 11m0-11-11 11" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>'};function widgetIcon(t,e=20){const i=document.createElementNS("http://www.w3.org/2000/svg","svg");return i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(e)),i.setAttribute("height",String(e)),i.setAttribute("fill","none"),i.setAttribute("aria-hidden","true"),i.setAttribute("focusable","false"),i.innerHTML=h[t],i}function el(t,e,i){const s=document.createElement(t);return e&&(s.className=e),null!=i&&(s.textContent=i),s}function parseJson(t,e){if(!t)return e;try{const i=JSON.parse(t);return Array.isArray(i)?i:e}catch{return e}}const d="designbase-wc-chat";class DbChatWidget extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.typing=!1,this.helpQuery="",this._activeArticle=null,this._messages=r,this._conversations=o,this._menuItems=n,this._quickReplies=a,this._articles=l,this.composer=null,this.threadEl=null,this.handleDocumentKeyDown=t=>{"Escape"===t.key&&this.open&&(t.preventDefault(),this.close(),this.launcher?.focus())},this.panelDragDepth=0,this.handlePanelDragEnter=t=>{"conversation"===this.view&&this.composer&&Array.from(t.dataTransfer?.types||[]).includes("Files")&&(t.preventDefault(),this.panelDragDepth+=1,this.bodyEl.classList.add(`${d}__body--drop-active`))},this.handlePanelDragOver=t=>{"conversation"===this.view&&this.composer&&Array.from(t.dataTransfer?.types||[]).includes("Files")&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))},this.handlePanelDragLeave=()=>{this.panelDragDepth=Math.max(0,this.panelDragDepth-1),0===this.panelDragDepth&&this.bodyEl.classList.remove(`${d}__body--drop-active`)},this.handlePanelDrop=t=>{if("conversation"!==this.view||!this.composer)return;if(!Array.from(t.dataTransfer?.types||[]).includes("Files"))return;t.preventDefault(),t.stopPropagation(),this.panelDragDepth=0,this.bodyEl.classList.remove(`${d}__body--drop-active`);const e=Array.from(t.dataTransfer?.files||[]);e.length&&(this.composer.addFiles(e,"drop"),this.composer.focusInput())}}static get observedAttributes(){return["open","view","position","agent-name","agent-avatar","agent-status","greeting","title","subtitle","placeholder","unread","accent","orb-variant","launcher-label"]}get open(){return this.hasAttribute("open")}set open(t){this.toggleAttribute("open",Boolean(t))}get view(){const t=this.getAttribute("view");return i.includes(t)?t:"home"}set view(t){this.setAttribute("view",t)}get position(){const t=this.getAttribute("position");return s.includes(t)?t:"bottom-right"}set position(t){this.setAttribute("position",t)}get unread(){return Number(this.getAttribute("unread")||0)}set unread(t){this.setAttribute("unread",String(t))}set messages(t){this._messages=Array.isArray(t)?t:[],this.built&&"conversation"===this.view&&this.renderBody()}get messages(){return this._messages}set conversations(t){this._conversations=Array.isArray(t)?t:[],this.built&&this.renderBody()}get conversations(){return this._conversations}set menuItems(t){this._menuItems=Array.isArray(t)?t:[],this.built&&"home"===this.view&&this.renderBody()}get menuItems(){return this._menuItems}set quickReplies(t){this._quickReplies=Array.isArray(t)?t:[],this.built&&"conversation"===this.view&&this.renderBody()}get quickReplies(){return this._quickReplies}set articles(t){this._articles=Array.isArray(t)?t:[],!this.built||"help"!==this.view&&"article"!==this.view||this.renderBody()}get articles(){return this._articles}connectedCallback(){this.hydrateFromAttributes(),this.build(),this.sync(),document.addEventListener("keydown",this.handleDocumentKeyDown)}disconnectedCallback(){document.removeEventListener("keydown",this.handleDocumentKeyDown)}attributeChangedCallback(t,e,i){if(this.built&&e!==i){if("open"!==t)return"view"===t?(this.sync(),void this.dispatch("db-view-change",{view:this.view})):void this.sync();this.syncOpenState()}}hydrateFromAttributes(){this._messages=parseJson(this.getAttribute("messages"),this._messages),this._conversations=parseJson(this.getAttribute("conversations"),this._conversations),this._menuItems=parseJson(this.getAttribute("menu-items"),this._menuItems),this._quickReplies=parseJson(this.getAttribute("quick-replies"),this._quickReplies),this._articles=parseJson(this.getAttribute("articles"),this._articles)}build(){if(this.built)return;this.built=!0,this.classList.add(d),this.replaceChildren(),this.launcher=el("button",`${d}__launcher`),this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog");const t=el("span",`${d}__launcher-icon ${d}__launcher-icon--open`),e=el("db-chat-orb");e.setAttribute("size","s"),e.setAttribute("variant",this.getAttribute("orb-variant")||"violet"),e.setAttribute("state","idle"),t.append(e);const i=el("span",`${d}__launcher-icon ${d}__launcher-icon--close`);i.append(widgetIcon("close-x",24)),this.launcherBadge=document.createElement("db-badge"),this.launcherBadge.className=`${d}__launcher-badge`,this.launcherBadge.setAttribute("type","number"),this.launcherBadge.setAttribute("variant","danger"),this.launcherBadge.setAttribute("size","s"),this.launcherBadge.setAttribute("max-count","99"),this.launcher.append(t,i),this.launcher.addEventListener("click",()=>this.toggle()),this.panel=el("div",`${d}__panel`),this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-modal","false"),this.headerEl=el("div",`${d}__header`),this.bodyEl=el("div",`${d}__body`),this.footerEl=el("div",`${d}__footer`),this.navEl=el("div",`${d}__nav`),this.panel.append(this.headerEl,this.bodyEl,this.footerEl,this.navEl),this.append(this.panel,this.launcher,this.launcherBadge),this.bodyEl.addEventListener("dragenter",this.handlePanelDragEnter),this.bodyEl.addEventListener("dragover",this.handlePanelDragOver),this.bodyEl.addEventListener("dragleave",this.handlePanelDragLeave),this.bodyEl.addEventListener("drop",this.handlePanelDrop)}sync(){s.forEach(t=>this.classList.toggle(`${d}--${t}`,t===this.position)),i.forEach(t=>this.classList.toggle(`${d}--view-${t}`,t===this.view));const t=this.getAttribute("accent");t?this.style.setProperty("--dbchat-accent",t):this.style.removeProperty("--dbchat-accent"),this.renderBadge(),this.renderHeader(),this.renderBody(),this.renderFooter(),this.renderNav(),this.syncOpenState()}syncOpenState(){const t=this.open;this.classList.toggle(`${d}--open`,t),this.launcher.setAttribute("aria-expanded",String(t)),this.panel.setAttribute("aria-hidden",String(!t)),t?this.panel.removeAttribute("inert"):this.panel.setAttribute("inert",""),this.launcher.setAttribute("aria-label",this.getAttribute("launcher-label")||(t?"상담창 닫기":"상담 시작하기")),t&&"conversation"===this.view&&requestAnimationFrame(()=>this.composer?.focusInput())}renderBadge(){const t=this.unread;t>0?this.launcherBadge.setAttribute("count",String(t)):this.launcherBadge.removeAttribute("count"),this.launcherBadge.hidden=t<=0}renderHeader(){this.headerEl.replaceChildren();const e=this.view,i=this.getAttribute("agent-name")||"디지털 상담원",s=el("div",`${d}__header-bar`);if("conversation"===e){const e=this.iconButton(t("chevron-left",20),"뒤로",()=>this.setView("messages")),n=el("div",`${d}__header-identity`),a=el("db-chat-orb");a.className=`${d}__header-orb`,a.setAttribute("size","xs"),a.setAttribute("variant",this.getAttribute("orb-variant")||"violet");const r=el("div",`${d}__header-meta`);r.append(el("span",`${d}__header-name`,i),el("span",`${d}__header-status`,this.getAttribute("agent-status")||"보통 몇 분 내 응답")),n.append(a,r),s.append(e,n,this.iconButton(widgetIcon("close-x",20),"닫기",()=>this.close()))}else if("article"===e){const e=this.iconButton(t("chevron-left",20),"뒤로",()=>{this._activeArticle=null,this.setView("help")});s.append(e,el("span",`${d}__header-title`,this._activeArticle?.title||"도움말"),this.iconButton(widgetIcon("close-x",20),"닫기",()=>this.close()))}else{const t="home"===e?"홈":"messages"===e?"메시지":"도움말";s.append(el("span",`${d}__header-title`,t),this.iconButton(widgetIcon("close-x",20),"닫기",()=>this.close()))}this.headerEl.append(s)}iconButton(t,e,i){const s=el("button",`${d}__icon-btn`);return s.type="button",s.setAttribute("aria-label",e),s.append(t),s.addEventListener("click",i),s}renderBody(){if(this.built)switch(this.threadEl=null,this.bodyEl.replaceChildren(),this.bodyEl.classList.toggle(`${d}__body--thread`,"conversation"===this.view),this.bodyEl.classList.toggle(`${d}__body--article`,"article"===this.view),this.view){case"home":this.renderHome();break;case"messages":this.renderMessages();break;case"conversation":this.renderConversation();break;case"help":this.renderHelp();break;case"article":this.renderArticle()}}renderHome(){const e=el("db-chat-welcome",`${d}__welcome`);e.setAttribute("greeting",this.getAttribute("greeting")||"안녕하세요"),e.setAttribute("title",this.getAttribute("title")||"무엇을 도와드릴까요?"),e.setAttribute("highlight",this.getAttribute("highlight")||this.getAttribute("title")||"도와드릴까요"),e.setAttribute("subtitle",this.getAttribute("subtitle")||"제품·정책을 24시간 정확하게 안내해 드릴게요."),e.setAttribute("orb-variant",this.getAttribute("orb-variant")||"violet"),e.setAttribute("align","left"),e.setAttribute("orb-size","m"),this.bodyEl.append(e);const i=this._conversations[0];if(i){const e=el("button",`${d}__recent`);e.type="button";const s=el("db-avatar",`${d}__recent-avatar`);s.setAttribute("size","s"),s.setAttribute("variant","primary"),i.avatarSrc?s.setAttribute("src",i.avatarSrc):s.setAttribute("initials",i.avatarInitials||i.name.charAt(0)||"상"),i.online&&s.setAttribute("status","online"),i.unread&&(s.setAttribute("badge",String(i.unread)),s.setAttribute("type","number"),s.setAttribute("badge-variant","primary"),s.setAttribute("badge-max-count","99"));const n=el("div",`${d}__recent-body`);n.append(el("span",`${d}__recent-title`,"최근 대화 이어가기"),el("span",`${d}__recent-preview`,i.preview||"")),e.append(s,n,t("chevron-right",18)),e.addEventListener("click",()=>{this.dispatch("db-conversation-select",{id:i.id}),this.setView("conversation")}),this.bodyEl.append(e)}else this.bodyEl.append(this.buildStartChatButton("대화 시작하기","primary"));if(this._menuItems.length){const t=el("db-chat-suggestions",`${d}__menu`);t.setAttribute("layout","card"),t.setAttribute("columns","1"),t.items=this._menuItems,t.addEventListener("db-select",t=>{t.stopPropagation();const e=t.detail,i=this._menuItems.find(t=>(t.id??t.title)===e.id),s=i?.action??"none";this.dispatch("db-menu-select",{...e,action:s}),"conversation"===s?this.startConversation():"help"===s&&this.setView("help")}),this.bodyEl.append(t)}}renderMessages(){if(!this._conversations.length)return void this.bodyEl.append(this.buildEmpty("아직 대화가 없어요","궁금한 점이 있으면 새 대화를 시작해 보세요.",{ctaLabel:"대화 시작하기",onCta:()=>this.startConversation()}));const t=el("div",`${d}__conv-list`);this._conversations.forEach(e=>{const i=el("button",`${d}__conv`);i.type="button";const s=el("db-avatar",`${d}__conv-avatar`);s.setAttribute("size","m"),s.setAttribute("variant","primary"),e.avatarSrc?s.setAttribute("src",e.avatarSrc):s.setAttribute("initials",e.avatarInitials||e.name.charAt(0)||"?"),e.online&&s.setAttribute("status","online");const n=el("div",`${d}__conv-body`),a=el("div",`${d}__conv-top`);if(a.append(el("span",`${d}__conv-name`,e.name)),e.time&&a.append(el("span",`${d}__conv-time`,e.time)),n.append(a,el("span",`${d}__conv-preview`,e.preview||"")),i.append(s,n),e.unread){const t=el("db-badge",`${d}__conv-unread`);t.setAttribute("type","number"),t.setAttribute("variant","primary"),t.setAttribute("size","s"),t.setAttribute("max-count","99"),t.setAttribute("count",String(e.unread)),i.append(t)}i.addEventListener("click",()=>{this.dispatch("db-conversation-select",{id:e.id}),this.setView("conversation")}),t.append(i)}),this.bodyEl.append(t)}renderConversation(){const t=el("div",`${d}__thread`);if(this._messages.forEach(e=>t.append(this.buildMessage(e))),this.threadEl=t,this.bodyEl.append(t),this.typing&&t.append(this.buildTyping()),this._quickReplies.length){const t=el("db-chat-suggestions");t.setAttribute("data-dbchat","quick"),t.setAttribute("layout","chip"),t.items=this._quickReplies,t.addEventListener("db-select",t=>{t.stopPropagation();const e=t.detail;this.dispatch("db-quick-reply",e),this.addMessage({role:"user",text:e.title,time:this.nowLabel()})}),this.bodyEl.append(t)}requestAnimationFrame(()=>this.scrollThreadToEnd())}renderHelp(){const e=el("div",`${d}__help-search`),i=el("span",`${d}__help-search-icon`);i.append(t("search",18));const s=el("input",`${d}__help-input`);s.type="search",s.placeholder="도움말 검색…",s.value=this.helpQuery,s.addEventListener("input",()=>{this.helpQuery=s.value,this.renderHelpResults()}),e.append(i,s),this.bodyEl.append(e);const n=el("div",`${d}__help-results`);this.bodyEl.append(n),this.renderHelpResults()}renderHelpResults(){const t=this.bodyEl.querySelector(`.${d}__help-results`);if(!t)return;t.replaceChildren();const e=this.helpQuery.trim().toLowerCase(),i=e?this._articles.filter(t=>t.title.toLowerCase().includes(e)||(t.description||"").toLowerCase().includes(e)||(t.body||"").toLowerCase().includes(e)):this._articles;if(!i.length)return void t.append(this.buildEmpty(e?"검색 결과가 없어요":"문서가 없어요",e?"다른 검색어로 다시 시도해 보세요.":"도움말 문서가 준비되면 여기에 표시됩니다."));const s=el("db-chat-suggestions",`${d}__articles`);s.setAttribute("layout","card"),s.setAttribute("columns","1"),s.items=i,s.addEventListener("db-select",t=>{t.stopPropagation();const e=t.detail,s=this._articles.find(t=>(t.id??t.title)===e.id)||i.find(t=>(t.id??t.title)===e.id);this.dispatch("db-article-select",{id:e.id,title:e.title}),s&&this.openArticle(s)}),t.append(s)}renderArticle(){const i=this._activeArticle;if(!i)return void this.setView("help");const s=el("article",`${d}__article`);if(i.icon&&e(i.icon)){const e=el("div",`${d}__article-icon`);e.append(t(i.icon,22)),s.append(e)}s.append(el("h2",`${d}__article-title`,i.title)),i.description&&s.append(el("p",`${d}__article-desc`,i.description));const n=el("div",`${d}__article-body`);(i.body||i.description||"").split(/\n{2,}/).forEach(t=>{const e=el("p",void 0,t.trim());e.textContent&&n.append(e)}),s.append(n);const a=this.buildStartChatButton("이 내용으로 문의하기","secondary");s.append(a),this.bodyEl.append(s)}openArticle(t){this._activeArticle=t,this.setView("article")}startConversation(){this.dispatch("db-start-chat"),this.setView("conversation")}buildMessage(t){const e="user"===t.role?"user":"assistant",i=el("db-chat-message");return i.setAttribute("role",e),t.name&&i.setAttribute("name",t.name),t.time&&i.setAttribute("timestamp",t.time),t.avatarSrc&&i.setAttribute("avatar-src",t.avatarSrc),t.avatarInitials&&i.setAttribute("avatar-initials",t.avatarInitials),t.actions&&i.setAttribute("actions",t.actions),i.textContent=t.text||"",t.attachments?.length&&(i.attachments=t.attachments),i.addEventListener("db-action",t=>{t.stopPropagation(),this.dispatch("db-message-action",t.detail)}),i}buildTyping(){const t=el("db-chat-typing",`${d}__typing`);return t.setAttribute("name",this.getAttribute("agent-name")||"상담원"),t.setAttribute("label","입력 중"),t}buildEmpty(t,e,i){const s=el("div",`${d}__empty`),n=el("db-chat-orb",`${d}__empty-orb`);return n.setAttribute("size","m"),n.setAttribute("variant",this.getAttribute("orb-variant")||"violet"),s.append(n,el("p",`${d}__empty-title`,t),el("p",`${d}__empty-desc`,e)),i?.ctaLabel&&i.onCta&&s.append(this.buildStartChatButton(i.ctaLabel,"primary",i.onCta)),s}buildStartChatButton(t,e="primary",i){const s=el("button",`${d}__cta ${d}__cta--${e}`);return s.type="button",s.append(widgetIcon("chat",18),el("span",void 0,t)),s.addEventListener("click",()=>i?i():this.startConversation()),s}renderFooter(){const t="conversation"===this.view;if(this.footerEl.hidden=!t,!t)return this.composer=null,void this.footerEl.replaceChildren();if(!this.composer){this.footerEl.replaceChildren();const t=el("db-chat-composer",`${d}__composer`);t.setAttribute("placeholder",this.getAttribute("placeholder")||"메시지를 입력하세요…"),t.setAttribute("attach",""),t.setAttribute("voice",""),t.addEventListener("db-send",t=>{t.stopPropagation();const e=t.detail,i=e?.value?.trim()||"",s=e?.attachments||[];if(!i&&!s.length)return;const n=s.map(t=>({name:t.name,kind:t.kind,mime:t.mime,url:t.file?URL.createObjectURL(t.file):t.preview}));this.dispatch("db-send",{text:i,attachments:n}),this.addMessage({role:"user",text:i,time:this.nowLabel(),attachments:n.length?n:void 0})}),t.addEventListener("db-stop",t=>{t.stopPropagation(),this.dispatch("db-stop")}),t.addEventListener("db-attach",t=>{t.stopPropagation(),this.dispatch("db-attach")}),t.addEventListener("db-voice",t=>{t.stopPropagation(),this.dispatch("db-voice")}),this.composer=t,this.footerEl.append(t)}}renderNav(){this.navEl.replaceChildren();const t="conversation"!==this.view&&"article"!==this.view;if(this.navEl.hidden=!t,!t)return;[{view:"home",icon:"home",label:"홈"},{view:"messages",icon:"chat",label:"메시지"},{view:"help",icon:"help",label:"도움말"}].forEach(t=>{const e=el("button",`${d}__tab`);e.type="button";const i=this.view===t.view;if(e.classList.toggle(`${d}__tab--active`,i),e.setAttribute("aria-current",String(i)),e.append(widgetIcon(t.icon,22),el("span",`${d}__tab-label`,t.label)),"messages"===t.view&&this.unread>0){const t=el("db-badge",`${d}__tab-badge`);t.setAttribute("type","dot"),t.setAttribute("variant","danger"),t.setAttribute("size","s"),e.append(t)}e.addEventListener("click",()=>{"help"===t.view&&(this.helpQuery=""),this.setView(t.view)}),this.navEl.append(e)})}scrollThreadToEnd(){this.bodyEl.scrollTop=this.bodyEl.scrollHeight}nowLabel(){const t=new Date,e=t.getHours();return`${e<12?"오전":"오후"} ${e%12==0?12:e%12}:${t.getMinutes().toString().padStart(2,"0")}`}dispatch(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}openWidget(){this.open||(this.open=!0,this.dispatch("db-open"),this.dispatch("db-toggle",{open:!0}))}close(){this.open&&(this.open=!1,this.dispatch("db-close"),this.dispatch("db-toggle",{open:!1}))}toggle(){this.open?this.close():this.openWidget()}setView(t){this.view!==t&&(this.view=t)}addMessage(t){if(this._messages=[...this._messages,{id:`m${Date.now()}`,...t}],"conversation"===this.view)if(this.built&&this.threadEl){const e=this.threadEl.querySelector("db-chat-typing");this.threadEl.insertBefore(this.buildMessage(t),e),requestAnimationFrame(()=>this.scrollThreadToEnd())}else this.built&&this.renderBody();else this.view="conversation"}setTyping(t){if(this.typing=Boolean(t),!this.built||"conversation"!==this.view||!this.threadEl)return;const e=this.threadEl.querySelector("db-chat-typing");this.typing&&!e?(this.threadEl.append(this.buildTyping()),requestAnimationFrame(()=>this.scrollThreadToEnd())):!this.typing&&e&&e.remove()}setStreaming(t){this.composer?.setStreaming(Boolean(t))}setMessages(t){this.messages=t}}customElements.get("db-chat-widget")||customElements.define("db-chat-widget",DbChatWidget);export{DbChatWidget};
@@ -5,6 +5,8 @@ declare class DbCheckbox extends HTMLElement {
5
5
  private visual?;
6
6
  private labelEl?;
7
7
  private built;
8
+ private userInteracted;
9
+ private readonly cleanups;
8
10
  get checked(): boolean;
9
11
  set checked(value: boolean);
10
12
  get indeterminate(): boolean;
@@ -15,13 +17,22 @@ declare class DbCheckbox extends HTMLElement {
15
17
  set readOnly(value: boolean);
16
18
  get required(): boolean;
17
19
  set required(value: boolean);
20
+ /** 계약에 없는 값은 기본값으로 되돌린다 — throw 하지 않는다 (STD-COERCE) */
18
21
  get size(): string;
19
22
  set size(value: string);
20
23
  connectedCallback(): void;
24
+ disconnectedCallback(): void;
25
+ /** form.reset() 이후 네이티브 input 의 실제 상태를 호스트 attribute 로 되돌린다 */
26
+ private syncAfterReset;
21
27
  attributeChangedCallback(name: string): void;
22
28
  private get hasLabel();
23
29
  private build;
24
30
  private handleChange;
31
+ /**
32
+ * 네이티브 검증 상태를 보조기술에 노출한다.
33
+ * 값 자체는 네이티브 input 이 폼에 싣고, 여기서는 표현만 맞춘다.
34
+ */
35
+ private syncValidity;
25
36
  private syncState;
26
37
  private syncVisual;
27
38
  private syncClasses;
@@ -1 +1 @@
1
- import{createDbIcon as t}from"./db-icons.js";const e=["s","m","l"];class DbCheckbox extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.handleChange=()=>{if(!this.input)return;const t=this.input.checked;this.toggleAttribute("checked",t),this.indeterminate&&(this.removeAttribute("indeterminate"),this.input.indeterminate=!1),this.syncVisual(),this.syncClasses(),this.dispatchEvent(new CustomEvent("db-change",{detail:{checked:t,selected:t},bubbles:!0,composed:!0}))}}static get observedAttributes(){return["checked","selected","default-checked","default-selected","indeterminate","size","disabled","readonly","required","name","value","has-label"]}get checked(){return this.input?.checked??(this.hasAttribute("checked")||this.hasAttribute("selected"))}set checked(t){this.toggleAttribute("checked",t),this.input&&(this.input.checked=t,this.syncVisual(),this.syncClasses())}get indeterminate(){return this.hasAttribute("indeterminate")}set indeterminate(t){this.toggleAttribute("indeterminate",t),this.input&&(this.input.indeterminate=t,this.syncVisual(),this.syncClasses())}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",t),this.input&&(this.input.disabled=t),this.syncClasses()}get readOnly(){return this.hasAttribute("readonly")}set readOnly(t){this.toggleAttribute("readonly",t),this.input&&(this.input.readOnly=t),this.syncClasses()}get required(){return this.hasAttribute("required")}set required(t){this.toggleAttribute("required",t),this.input&&(this.input.required=t)}get size(){return this.getAttribute("size")||"m"}set size(t){this.setAttribute("size",t)}connectedCallback(){this.style.display="contents",this.built||this.build(),this.syncState()}attributeChangedCallback(t){if(this.built)return"checked"===t||"selected"===t?(this.input&&(this.input.checked=this.hasAttribute("checked")||this.hasAttribute("selected")),this.syncVisual(),void this.syncClasses()):void this.syncState()}get hasLabel(){return!this.hasAttribute("has-label")||"false"!==this.getAttribute("has-label")}build(){for(this.root=document.createElement("label"),this.root.className="designbase-wc-checkbox",this.input=document.createElement("input"),this.input.type="checkbox",this.input.className="designbase-wc-checkbox__input",this.visual=document.createElement("span"),this.visual.className="designbase-wc-checkbox__visual",this.visual.setAttribute("aria-hidden","true"),this.labelEl=document.createElement("span"),this.labelEl.className="designbase-wc-checkbox__label";this.firstChild;)this.labelEl.appendChild(this.firstChild);this.root.append(this.input,this.visual,this.labelEl),this.appendChild(this.root),this.input.addEventListener("change",this.handleChange),this.built=!0}syncState(){if(!this.root||!this.input||!this.visual)return;const t=this.hasAttribute("checked")||this.hasAttribute("selected")||!this.hasAttribute("checked")&&!this.hasAttribute("selected")&&(this.hasAttribute("default-checked")||this.hasAttribute("default-selected")),e=this.hasAttribute("indeterminate");this.input.checked=t,this.input.indeterminate=e,this.input.disabled=this.disabled,this.input.readOnly=this.readOnly,this.input.required=this.required,this.input.name=this.getAttribute("name")||"",this.input.value=this.getAttribute("value")||"",this.hasLabel?this.labelEl?.removeAttribute("hidden"):this.labelEl?.setAttribute("hidden",""),this.syncVisual(),this.syncClasses()}syncVisual(){if(this.visual&&this.input){if(this.visual.replaceChildren(),this.input.indeterminate){const e=document.createElement("span");return e.className="designbase-wc-checkbox__indeterminate-icon",e.appendChild(t("minus",16)),void this.visual.appendChild(e)}if(this.input.checked){const e=document.createElement("span");e.className="designbase-wc-checkbox__check-icon",e.appendChild(t("done",16)),this.visual.appendChild(e)}}}syncClasses(){if(!this.root||!this.input)return;const t=e.includes(this.size)?this.size:"m",i=this.hasLabel&&Boolean(this.labelEl?.textContent?.trim());this.root.className=["designbase-wc-checkbox",`designbase-wc-checkbox--${t}`,this.input.checked&&"designbase-wc-checkbox--selected",this.input.indeterminate&&"designbase-wc-checkbox--indeterminate",this.disabled&&"designbase-wc-checkbox--disabled",this.readOnly&&"designbase-wc-checkbox--readonly",!i&&"designbase-wc-checkbox--no-label"].filter(Boolean).join(" ")}}customElements.get("db-checkbox")||customElements.define("db-checkbox",DbCheckbox);export{DbCheckbox};
1
+ import{createDbIcon as t}from"./db-icons.js";import{CleanupBag as e}from"../core/dom.js";import{CHECKBOX_SIZES as i}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";import{coerceToContract as s}from"../node_modules/@designbasekorea/ui-contracts/dist/primitives.js";class DbCheckbox extends HTMLElement{constructor(){super(...arguments),this.built=!1,this.userInteracted=!1,this.cleanups=new e,this.handleChange=()=>{if(!this.input)return;this.userInteracted=!0;const t=this.input.checked;this.toggleAttribute("checked",t),this.indeterminate&&(this.removeAttribute("indeterminate"),this.input.indeterminate=!1),this.syncVisual(),this.syncClasses(),this.syncValidity(),this.dispatchEvent(new CustomEvent("db-change",{detail:{checked:t,selected:t},bubbles:!0,composed:!0}))}}static get observedAttributes(){return["checked","selected","default-checked","default-selected","indeterminate","size","disabled","readonly","required","name","value","has-label"]}get checked(){return this.input?.checked??(this.hasAttribute("checked")||this.hasAttribute("selected"))}set checked(t){this.toggleAttribute("checked",t),this.input&&(this.input.checked=t,this.syncVisual(),this.syncClasses())}get indeterminate(){return this.hasAttribute("indeterminate")}set indeterminate(t){this.toggleAttribute("indeterminate",t),this.input&&(this.input.indeterminate=t,this.syncVisual(),this.syncClasses())}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",t),this.input&&(this.input.disabled=t),this.syncClasses()}get readOnly(){return this.hasAttribute("readonly")}set readOnly(t){this.toggleAttribute("readonly",t),this.input&&(this.input.readOnly=t),this.syncClasses()}get required(){return this.hasAttribute("required")}set required(t){this.toggleAttribute("required",t),this.input&&(this.input.required=t)}get size(){return s(this.getAttribute("size"),i,"m")}set size(t){this.setAttribute("size",t)}connectedCallback(){this.style.display="contents",this.built||this.build(),this.syncState();const t=this.input?.form;t&&this.cleanups.listen(t,"reset",()=>{window.setTimeout(()=>this.syncAfterReset(),0)})}disconnectedCallback(){this.cleanups.run()}syncAfterReset(){this.input&&(this.toggleAttribute("checked",this.input.checked),this.removeAttribute("selected"),this.syncVisual(),this.syncClasses())}attributeChangedCallback(t){if(this.built)return"checked"===t||"selected"===t?(this.input&&(this.input.checked=this.hasAttribute("checked")||this.hasAttribute("selected")),this.syncVisual(),void this.syncClasses()):void this.syncState()}get hasLabel(){return!this.hasAttribute("has-label")||"false"!==this.getAttribute("has-label")}build(){for(this.root=document.createElement("label"),this.root.className="designbase-wc-checkbox",this.input=document.createElement("input"),this.input.type="checkbox",this.input.className="designbase-wc-checkbox__input",this.visual=document.createElement("span"),this.visual.className="designbase-wc-checkbox__visual",this.visual.setAttribute("aria-hidden","true"),this.labelEl=document.createElement("span"),this.labelEl.className="designbase-wc-checkbox__label";this.firstChild;)this.labelEl.appendChild(this.firstChild);this.root.append(this.input,this.visual,this.labelEl),this.appendChild(this.root),this.input.addEventListener("change",this.handleChange),this.built=!0}syncValidity(){if(!this.input)return;const t=!this.input.checkValidity();this.input.setAttribute("aria-invalid",String(t)),this.classList.toggle("designbase-wc-checkbox--invalid",t)}syncState(){if(!this.root||!this.input||!this.visual)return;const t=this.hasAttribute("checked")||this.hasAttribute("selected")||!this.userInteracted&&(this.hasAttribute("default-checked")||this.hasAttribute("default-selected")),e=this.hasAttribute("indeterminate");this.input.checked=t,this.input.defaultChecked=this.hasAttribute("default-checked")||this.hasAttribute("default-selected")||this.hasAttribute("checked")||this.hasAttribute("selected"),this.input.indeterminate=e,this.input.disabled=this.disabled,this.input.readOnly=this.readOnly,this.input.required=this.required,this.input.name=this.getAttribute("name")||"",this.input.value=this.getAttribute("value")||"",this.hasLabel?this.labelEl?.removeAttribute("hidden"):this.labelEl?.setAttribute("hidden",""),this.syncVisual(),this.syncClasses()}syncVisual(){if(this.visual&&this.input){if(this.visual.replaceChildren(),this.input.indeterminate){const e=document.createElement("span");return e.className="designbase-wc-checkbox__indeterminate-icon",e.appendChild(t("minus",16)),void this.visual.appendChild(e)}if(this.input.checked){const e=document.createElement("span");e.className="designbase-wc-checkbox__check-icon",e.appendChild(t("done",16)),this.visual.appendChild(e)}}}syncClasses(){if(!this.root||!this.input)return;const t=i.includes(this.size)?this.size:"m",e=this.hasLabel&&Boolean(this.labelEl?.textContent?.trim());this.root.className=["designbase-wc-checkbox",`designbase-wc-checkbox--${t}`,this.input.checked&&"designbase-wc-checkbox--selected",this.input.indeterminate&&"designbase-wc-checkbox--indeterminate",this.disabled&&"designbase-wc-checkbox--disabled",this.readOnly&&"designbase-wc-checkbox--readonly",!e&&"designbase-wc-checkbox--no-label"].filter(Boolean).join(" ")}}customElements.get("db-checkbox")||customElements.define("db-checkbox",DbCheckbox);export{DbCheckbox};
@@ -1 +1 @@
1
- import{isDbIconName as e,createDbIcon as t}from"./db-icons.js";const i=["s","m","l"],s=["default","primary","success","warning","danger","info","neutral"];class DbChip extends HTMLElement{static get observedAttributes(){return["label","size","variant","deletable","disabled","selected","full-width","clickable","start-icon","end-icon"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}iconSize(e){return"s"===e?12:"l"===e?20:16}render(){const n=this.getAttribute("label")||this.textContent?.trim()||"",c=this.getAttribute("size")||"m",a=this.getAttribute("variant")||"default",d=this.hasAttribute("disabled"),l=this.hasAttribute("deletable"),b=this.hasAttribute("selected"),h=this.hasAttribute("full-width"),r=this.hasAttribute("clickable"),o=this.getAttribute("start-icon"),p=this.getAttribute("end-icon"),u=i.includes(c)?c:"m",m=s.includes(a)?a:"default",g=this.iconSize(u);if(this.className=["designbase-wc-chip",`designbase-wc-chip--${u}`,`designbase-wc-chip--${m}`,l&&"designbase-wc-chip--deletable",d&&"designbase-wc-chip--disabled",b&&"designbase-wc-chip--selected",r&&"designbase-wc-chip--clickable",h&&"designbase-wc-chip--full-width"].filter(Boolean).join(" "),this.replaceChildren(),r&&!d?(this.setAttribute("role","button"),this.tabIndex=0):(this.removeAttribute("role"),this.removeAttribute("tabindex")),o&&e(o)){const e=document.createElement("span");e.className="designbase-wc-chip__start-icon",e.append(t(o,g)),this.append(e)}const w=document.createElement("span");if(w.className="designbase-wc-chip__label",w.textContent=n,this.append(w),p&&e(p)&&!l){const e=document.createElement("span");e.className="designbase-wc-chip__end-icon",e.append(t(p,g)),this.append(e)}if(l){const e=document.createElement("button");e.type="button",e.className="designbase-wc-chip__delete-button",e.disabled=d,e.setAttribute("aria-label",`${n} 삭제`),e.append(t("close",g)),e.addEventListener("click",e=>{e.stopPropagation(),d||this.dispatchEvent(new CustomEvent("db-delete",{bubbles:!0,composed:!0}))}),this.append(e)}this.onclick=()=>{!d&&r&&this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0}))},this.onkeydown=e=>{"Enter"!==e.key&&" "!==e.key||d||!r||(e.preventDefault(),this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0})))}}}customElements.get("db-chip")||customElements.define("db-chip",DbChip);export{DbChip};
1
+ import{isDbIconName as e,createDbIcon as t}from"./db-icons.js";import{CHIP_SIZES as s,CHIP_VARIANTS as i}from"../node_modules/@designbasekorea/ui-contracts/dist/components.js";class DbChip extends HTMLElement{static get observedAttributes(){return["label","size","variant","deletable","disabled","selected","full-width","clickable","start-icon","end-icon"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}iconSize(e){return"s"===e?12:"l"===e?20:16}render(){const n=this.getAttribute("label")||this.textContent?.trim()||"",a=this.getAttribute("size")||"m",c=this.getAttribute("variant")||"default",d=this.hasAttribute("disabled"),l=this.hasAttribute("deletable"),b=this.hasAttribute("selected"),r=this.hasAttribute("full-width"),o=this.hasAttribute("clickable"),h=this.getAttribute("start-icon"),p=this.getAttribute("end-icon"),u=s.includes(a)?a:"m",m=i.includes(c)?c:"default",g=this.iconSize(u);if(this.className=["designbase-wc-chip",`designbase-wc-chip--${u}`,`designbase-wc-chip--${m}`,l&&"designbase-wc-chip--deletable",d&&"designbase-wc-chip--disabled",b&&"designbase-wc-chip--selected",o&&"designbase-wc-chip--clickable",r&&"designbase-wc-chip--full-width"].filter(Boolean).join(" "),this.replaceChildren(),o&&!d?(this.setAttribute("role","button"),this.tabIndex=0,this.setAttribute("aria-pressed",String(b))):(this.removeAttribute("role"),this.removeAttribute("tabindex"),this.removeAttribute("aria-pressed")),h&&e(h)){const e=document.createElement("span");e.className="designbase-wc-chip__start-icon",e.append(t(h,g)),this.append(e)}const w=document.createElement("span");if(w.className="designbase-wc-chip__label",w.textContent=n,this.append(w),p&&e(p)&&!l){const e=document.createElement("span");e.className="designbase-wc-chip__end-icon",e.append(t(p,g)),this.append(e)}if(l){const e=document.createElement("button");e.type="button",e.className="designbase-wc-chip__delete-button",e.disabled=d,e.setAttribute("aria-label",`${n} 삭제`),e.append(t("close",g)),e.addEventListener("click",e=>{e.stopPropagation(),d||this.dispatchEvent(new CustomEvent("db-delete",{bubbles:!0,composed:!0}))}),this.append(e)}this.onclick=()=>{!d&&o&&this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0}))},this.onkeydown=e=>{"Enter"!==e.key&&" "!==e.key||d||!o||(e.preventDefault(),this.dispatchEvent(new CustomEvent("db-click",{bubbles:!0,composed:!0})))}}}customElements.get("db-chip")||customElements.define("db-chip",DbChip);export{DbChip};
@@ -1 +1 @@
1
- import{hexToRgb as t,rgbToHsv as e,hsvToRgb as i,toHex as s,rgbToHsl as l,formatColor as n,normalizeHex as o,isHex as a,clamp as r}from"./color-picker-utils.js";import{getDbComponentIconSize as h,createDbIcon as d}from"./db-icons.js";const p=["s","m","l"],u=["dropdown","modal"],c=["input","swatch"],g=["bottom-start","bottom-end","top-start","top-end"],E="#006FFF",m=t(E)??{r:0,g:111,b:255},b=e(m.r,m.g,m.b),v=JSON.stringify([{label:"HEX",value:"hex"},{label:"RGB",value:"rgb"},{label:"RGBA",value:"rgba"},{label:"HSL",value:"hsl"},{label:"HSLA",value:"hsla"}]);class DbColorPicker extends HTMLElement{constructor(){super(...arguments),this.h=b.h,this.s=b.s,this.v=b.v,this.a=100,this.open=!1,this.format="hex",this.colorInput=E,this.alphaInput="100",this.isCopied=!1,this.tempColor="",this.dragging=null,this.mounted=!1,this.copiedTimer=null,this.debounceTimer=null,this.lastEmittedHex="",this.suppressNextValueSync=!1,this.didMount=!1,this.triggerInputFocused=!1,this.panelInputFocused=!1,this.panelAlphaInputFocused=!1,this.handleOutsideClick=t=>{if(!this.open||"dropdown"!==this.getOption("type",u,"dropdown"))return;const e=t.target;this.contains(e)||this.formatSelectEl?.contains(e)||(this.open=!1,this.update())},this.handleDocumentMouseMove=t=>{"area"===this.dragging&&(this.getBool("disabled")||this.getBool("readonly")||this.updateFromArea(t.clientX,t.clientY))},this.handleDocumentMouseUp=()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))},this.handleModalCancel=()=>{const i=t(this.tempColor);if(i){const t=e(i.r,i.g,i.b);this.h=t.h,this.s=t.s,this.v=t.v}this.open=!1,this.update(),this.dispatchEvent(new CustomEvent("db-cancel",{bubbles:!0,composed:!0}))},this.handleModalApply=()=>{this.open=!1,this.actuallyEmit(),this.dispatchEvent(new CustomEvent("db-apply",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})),this.update()}}static get observedAttributes(){return["size","type","trigger","position","value","default-value","show-input","show-alpha","show-format-selector","show-copy-button","show-eyedropper","disabled","readonly","full-width","error","on-change-format","change-debounce-ms","emit-during-drag"]}connectedCallback(){this.mounted||this.mount(),this.syncFromValueAttr(!0),this.update(),document.addEventListener("mousedown",this.handleOutsideClick),document.addEventListener("mousemove",this.handleDocumentMouseMove),document.addEventListener("mouseup",this.handleDocumentMouseUp)}disconnectedCallback(){document.removeEventListener("mousedown",this.handleOutsideClick),document.removeEventListener("mousemove",this.handleDocumentMouseMove),document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.copiedTimer&&clearTimeout(this.copiedTimer),this.debounceTimer&&clearTimeout(this.debounceTimer)}attributeChangedCallback(t){this.mounted&&("value"!==t&&"default-value"!==t||this.syncFromValueAttr(!1),this.update())}getBool(t,e=!1){if(!this.hasAttribute(t))return e;const i=this.getAttribute(t);return""===i||"true"===i}getOption(t,e,i){const s=this.getAttribute(t);return s&&e.includes(s)?s:i}getIconSize(){return h(this.getOption("size",p,"m"))}getRgb(){return i(this.h,this.s,this.v)}getHex(){const t=this.getRgb();return s(t.r,t.g,t.b)}getHsl(){const t=this.getRgb();return l(t.r,t.g,t.b)}getUiFormatted(){const t=this.getRgb(),e=this.getHex(),i=this.getHsl();return n(this.format,t,e,i,this.a)}getOutward(){return"hex"===("ui"===this.getAttribute("on-change-format")?"ui":"hex")?this.getHex():this.getUiFormatted()}syncFromValueAttr(i){const s=this.getAttribute("value")??(i?this.getAttribute("default-value"):null)??(i?E:null);if(null==s)return;const l=o(s);if(!a(l))return;if(!i&&this.suppressNextValueSync&&l===this.lastEmittedHex)return void(this.suppressNextValueSync=!1);const n=t(l);if(!n)return;const r=e(n.r,n.g,n.b);this.h=r.h,this.s=r.s,this.v=r.v,this.colorInput=l,this.lastEmittedHex=l}actuallyEmit(){const t=o(this.getHex()),e=this.hasAttribute("value")&&a(this.getAttribute("value")||"")?o(this.getAttribute("value")||""):null;e&&e===t||this.lastEmittedHex!==t&&(this.lastEmittedHex=t,this.suppressNextValueSync=!0,this.setAttribute("value",t),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})))}scheduleEmit(){const t=this.getBool("emit-during-drag",!0);if(this.dragging&&!t)return;const e=Number(this.getAttribute("change-debounce-ms")||"0");if(e>0)return this.debounceTimer&&clearTimeout(this.debounceTimer),void(this.debounceTimer=setTimeout(()=>this.actuallyEmit(),e));this.actuallyEmit()}onColorStateChanged(t=!1){this.didMount?(!t||this.getBool("emit-during-drag",!0),this.scheduleEmit()):this.didMount=!0}updateFromArea(t,e){const i=this.colorFieldEl;if(!i)return;const s=i.getBoundingClientRect(),l=r(t-s.left,0,s.width),n=r(e-s.top,0,s.height);this.s=l/s.width*100,this.v=100-n/s.height*100,this.updateVisuals(),this.onColorStateChanged()}getInputValue(t){return t?t.getAttribute("value")??"":""}setInputValue(t,e){t&&void 0!==e&&t.setAttribute("value",e)}getPanelControlSize(){return"s"===this.getOption("size",p,"m")?"s":"m"}commitColorInput(i){const s=("trigger"===i?this.triggerInputEl?.value:this.getInputValue(this.panelValueInputEl)??"").trim();if(/^#([0-9A-Fa-f]{6})$/.test(s)){const i=t(s),l=e(i.r,i.g,i.b);return this.h=l.h,this.s=l.s,this.v=l.v,this.colorInput=o(s),this.updateVisuals(),void this.onColorStateChanged()}let l=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(s);if(l){const t=r(parseInt(l[1],10),0,255),i=r(parseInt(l[2],10),0,255),s=r(parseInt(l[3],10),0,255),n=e(t,i,s);return this.h=n.h,this.s=n.s,this.v=n.v,this.colorInput=`rgb(${t}, ${i}, ${s})`,this.updateVisuals(),void this.onColorStateChanged()}if(l=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i.exec(s),l){const t=r(parseInt(l[1],10),0,255),i=r(parseInt(l[2],10),0,255),s=r(parseInt(l[3],10),0,255),n=parseFloat(l[4]),o=e(t,i,s);this.h=o.h,this.s=o.s,this.v=o.v,this.a=Math.round(100*n),this.alphaInput=String(this.a),this.colorInput=`rgba(${t}, ${i}, ${s}, ${n})`,this.updateVisuals(),this.onColorStateChanged()}}commitAlphaInput(){const t=Number(this.getInputValue(this.panelAlphaInputEl).trim()||this.alphaInput);if(!Number.isNaN(t)&&t>=0&&t<=100){const e=Math.round(t);this.a=e,this.alphaInput=String(e),this.updateVisuals(),this.onColorStateChanged()}else this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput)}async onCopy(){try{await navigator.clipboard.writeText(this.getUiFormatted()),this.isCopied=!0,this.updateCopyButtons(),this.copiedTimer&&clearTimeout(this.copiedTimer),this.copiedTimer=setTimeout(()=>{this.isCopied=!1,this.updateCopyButtons()},1600)}catch{}}async onEyedrop(){try{if("EyeDropper"in window){const i=new window.EyeDropper,{sRGBHex:s}=await i.open(),l=t(s);if(!l)return;const n=e(l.r,l.g,l.b);this.h=n.h,this.s=n.s,this.v=n.v,this.updateVisuals(),this.onColorStateChanged()}}catch{}}toggleOpen(){if(this.getBool("disabled")||this.getBool("readonly"))return;if("modal"===this.getOption("type",u,"dropdown"))return this.tempColor=this.getHex(),this.open=!0,void this.update();this.open=!this.open,this.update()}close(){this.open&&"dropdown"===this.getOption("type",u,"dropdown")&&(this.open=!1,this.update())}mount(){this.mounted=!0;const t=this.getIconSize();this.triggerEl=document.createElement("div"),this.triggerEl.className="designbase-wc-color-picker__trigger",this.triggerEl.addEventListener("click",()=>this.toggleOpen());const e=document.createElement("div");e.className="designbase-wc-color-picker__color-display",this.colorBoxEl=document.createElement("div"),this.colorBoxEl.className="designbase-wc-color-picker__color-box",e.append(this.colorBoxEl),this.triggerInputEl=document.createElement("input"),this.triggerInputEl.type="text",this.triggerInputEl.className="designbase-wc-color-picker__input",this.triggerInputEl.placeholder="#000000",this.triggerInputEl.addEventListener("click",t=>t.stopPropagation()),this.triggerInputEl.addEventListener("focus",()=>{this.triggerInputFocused=!0}),this.triggerInputEl.addEventListener("blur",()=>{this.triggerInputFocused=!1;const t="hex"===this.format?o(this.getUiFormatted()):this.getUiFormatted();this.triggerInputEl&&this.triggerInputEl.value!==t&&(this.triggerInputEl.value=t,this.colorInput=t)}),this.triggerInputEl.addEventListener("input",()=>{this.triggerInputEl&&(this.colorInput=this.triggerInputEl.value)}),this.triggerInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("trigger")});const i=document.createElement("div");i.className="designbase-wc-color-picker__trigger-actions",this.triggerCopyBtn=document.createElement("button"),this.triggerCopyBtn.type="button",this.triggerCopyBtn.className="designbase-wc-color-picker__copy-button-inline",this.triggerCopyBtn.setAttribute("aria-label","Copy color value"),this.triggerCopyBtn.addEventListener("click",t=>{t.stopPropagation(),this.onCopy()}),this.toggleBtn=document.createElement("button"),this.toggleBtn.type="button",this.toggleBtn.className="designbase-wc-color-picker__toggle",this.toggleBtn.setAttribute("aria-label","Toggle color picker"),this.toggleBtn.append(d("chevron-down",t)),i.append(this.triggerCopyBtn,this.toggleBtn),this.triggerEl.append(e,this.triggerInputEl,i),this.dropdownEl=document.createElement("div"),this.dropdownEl.className="designbase-wc-color-picker__dropdown",this.dropdownEl.addEventListener("click",t=>t.stopPropagation()),this.dropdownEl.hidden=!0;const s=document.createElement("div");s.className="designbase-wc-color-picker__selector";const l=document.createElement("div");l.className="designbase-wc-color-picker__color-area",this.colorFieldEl=document.createElement("div"),this.colorFieldEl.className="designbase-wc-color-picker__color-field",this.colorPointerEl=document.createElement("div"),this.colorPointerEl.className="designbase-wc-color-picker__color-pointer",this.colorFieldEl.append(this.colorPointerEl),this.colorFieldEl.addEventListener("mousedown",t=>{this.getBool("disabled")||this.getBool("readonly")||(t.preventDefault(),this.dragging="area",this.updateFromArea(t.clientX,t.clientY))}),this.colorFieldEl.addEventListener("touchstart",t=>{if(this.getBool("disabled")||this.getBool("readonly"))return;this.dragging="area";const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchmove",t=>{if("area"!==this.dragging)return;const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchend",()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))}),l.append(this.colorFieldEl);const n=document.createElement("div");n.className="designbase-wc-color-picker__controls",this.eyedropperBtnEl=document.createElement("db-button"),this.eyedropperBtnEl.setAttribute("variant","tertiary"),this.eyedropperBtnEl.setAttribute("size",this.getPanelControlSize()),this.eyedropperBtnEl.setAttribute("icon-only",""),this.eyedropperBtnEl.setAttribute("start-icon","eyedropper"),this.eyedropperBtnEl.setAttribute("aria-label","Eyedropper tool"),this.eyedropperBtnEl.addEventListener("click",()=>{this.onEyedrop()});const a=document.createElement("div");a.className="designbase-wc-color-picker__slider-container";const h=document.createElement("div");h.className="designbase-wc-color-picker__hue-slider",this.hueSliderEl=document.createElement("input"),this.hueSliderEl.type="range",this.hueSliderEl.min="0",this.hueSliderEl.max="360",this.hueSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--hue",this.hueSliderEl.addEventListener("input",()=>{this.h=parseFloat(this.hueSliderEl.value),this.updateVisuals(),this.onColorStateChanged()}),h.append(this.hueSliderEl),this.alphaSliderWrapEl=document.createElement("div"),this.alphaSliderWrapEl.className="designbase-wc-color-picker__alpha-slider",this.alphaSliderEl=document.createElement("input"),this.alphaSliderEl.type="range",this.alphaSliderEl.min="0",this.alphaSliderEl.max="100",this.alphaSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--alpha",this.alphaSliderEl.addEventListener("input",()=>{this.a=r(parseInt(this.alphaSliderEl.value,10),0,100),this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.updateVisuals(),this.onColorStateChanged()}),this.alphaSliderWrapEl.append(this.alphaSliderEl),a.append(h,this.alphaSliderWrapEl),n.append(this.eyedropperBtnEl,a);const p=document.createElement("div");p.className="designbase-wc-color-picker__value-display",this.formatSelectEl=document.createElement("db-select"),this.formatSelectEl.setAttribute("size","s"),this.formatSelectEl.setAttribute("position","top"),this.formatSelectEl.setAttribute("show-clear-button","false"),this.formatSelectEl.setAttribute("options",v),this.formatSelectEl.addEventListener("db-change",t=>{const e=t.detail,i=e?.value;i&&(this.format=i,this.updateVisuals())}),this.panelValueInputEl=document.createElement("db-input"),this.panelValueInputEl.classList.add("designbase-wc-color-picker__value-input"),this.panelValueInputEl.setAttribute("size","s"),this.panelValueInputEl.setAttribute("placeholder","#000000"),this.panelValueInputEl.addEventListener("db-focus",()=>{this.panelInputFocused=!0}),this.panelValueInputEl.addEventListener("db-blur",()=>{this.panelInputFocused=!1;const t="hex"===this.format?o(this.getUiFormatted()):this.getUiFormatted();this.getInputValue(this.panelValueInputEl)!==t&&(this.setInputValue(this.panelValueInputEl,t),this.colorInput=t)}),this.panelValueInputEl.addEventListener("db-input",t=>{const e=t.detail;void 0!==e?.value&&(this.colorInput=e.value)}),this.panelValueInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("panel")}),this.panelAlphaWrapEl=document.createElement("div"),this.panelAlphaWrapEl.className="designbase-wc-color-picker__alpha-input-wrap",this.panelAlphaInputEl=document.createElement("db-input"),this.panelAlphaInputEl.classList.add("designbase-wc-color-picker__alpha-input"),this.panelAlphaInputEl.setAttribute("size","s"),this.panelAlphaInputEl.setAttribute("placeholder","100"),this.panelAlphaInputEl.setAttribute("aria-label","Alpha percent"),this.panelAlphaInputEl.addEventListener("db-focus",()=>{this.panelAlphaInputFocused=!0}),this.panelAlphaInputEl.addEventListener("db-blur",()=>{this.panelAlphaInputFocused=!1,this.commitAlphaInput()}),this.panelAlphaInputEl.addEventListener("db-input",t=>{const e=t.detail,i=(e?.value??"").replace(/[^\d]/g,"").slice(0,3);i!==e?.value&&this.setInputValue(this.panelAlphaInputEl,i),this.alphaInput=i}),this.panelAlphaInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitAlphaInput()});const u=document.createElement("span");u.className="designbase-wc-color-picker__alpha-suffix",u.textContent="%",this.panelAlphaWrapEl.append(this.panelAlphaInputEl,u),this.panelCopyBtnEl=document.createElement("db-button"),this.panelCopyBtnEl.setAttribute("variant","tertiary"),this.panelCopyBtnEl.setAttribute("size","s"),this.panelCopyBtnEl.setAttribute("icon-only",""),this.panelCopyBtnEl.setAttribute("start-icon","copy"),this.panelCopyBtnEl.setAttribute("aria-label","Copy color value"),this.panelCopyBtnEl.addEventListener("click",()=>{this.onCopy()}),p.append(this.formatSelectEl,this.panelValueInputEl,this.panelAlphaWrapEl,this.panelCopyBtnEl),s.append(l,n,p),this.selectorEl=s,this.dropdownEl.append(s),this.modalEl=document.createElement("db-modal"),this.modalEl.setAttribute("size","s"),this.modalEl.setAttribute("title","색상 선택"),this.modalEl.setAttribute("close-on-escape","true"),this.modalEl.addEventListener("db-close",this.handleModalCancel),this.modalBodyEl=document.createElement("div"),this.modalBodyEl.className="designbase-wc-modal__body designbase-wc-color-picker__modal-body",this.modalBodyEl.setAttribute("data-modal-part","body");const c=document.createElement("div");c.className="designbase-wc-modal__footer",c.setAttribute("data-modal-part","footer");const g=document.createElement("db-button");g.setAttribute("variant","tertiary"),g.setAttribute("size","m"),g.textContent="취소",g.addEventListener("click",this.handleModalCancel);const E=document.createElement("db-button");E.setAttribute("variant","primary"),E.setAttribute("size","m"),E.textContent="적용",E.addEventListener("click",this.handleModalApply),c.append(g,E),this.modalEl.append(this.modalBodyEl,c),this.replaceChildren(this.triggerEl,this.dropdownEl,this.modalEl)}updateCopyButtons(){const t=this.getIconSize(),e=this.isCopied?"done":"copy";this.triggerCopyBtn&&this.triggerCopyBtn.replaceChildren(d(e,t)),this.panelCopyBtnEl&&this.panelCopyBtnEl.setAttribute("start-icon",e)}updateVisuals(){const t=this.getRgb(),e=this.getHex(),i=this.getBool("show-alpha",!0),s=this.getUiFormatted(),l="hex"===this.format?o(s):s;!this.triggerInputFocused&&this.triggerInputEl&&(this.triggerInputEl.value=l),!this.panelInputFocused&&this.panelValueInputEl&&this.setInputValue(this.panelValueInputEl,l),this.colorBoxEl&&(this.colorBoxEl.style.backgroundColor=i?`rgba(${t.r}, ${t.g}, ${t.b}, ${this.a/100})`:e),this.colorFieldEl&&(this.colorFieldEl.style.backgroundImage=`\n linear-gradient(to top, rgba(0,0,0,1), rgba(0,0,0,0)),\n linear-gradient(to right, #ffffff, hsl(${this.h}, 100%, 50%))\n `),this.colorPointerEl&&(this.colorPointerEl.style.left=`${this.s}%`,this.colorPointerEl.style.top=100-this.v+"%",this.colorPointerEl.style.backgroundColor=`rgb(${t.r}, ${t.g}, ${t.b})`),this.hueSliderEl&&(this.hueSliderEl.value=String(this.h),this.hueSliderEl.style.background="linear-gradient(to right,\n hsl(0,100%,50%),\n hsl(60,100%,50%),\n hsl(120,100%,50%),\n hsl(180,100%,50%),\n hsl(240,100%,50%),\n hsl(300,100%,50%),\n hsl(360,100%,50%))"),this.alphaSliderEl&&(this.alphaSliderEl.value=String(this.a),this.alphaSliderEl.style.backgroundImage=`\n linear-gradient(45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(-45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(-45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(to right, rgba(${t.r}, ${t.g}, ${t.b}, 0), rgba(${t.r}, ${t.g}, ${t.b}, 1))\n `,this.alphaSliderEl.style.backgroundSize="8px 8px,8px 8px,8px 8px,8px 8px,100% 100%",this.alphaSliderEl.style.backgroundPosition="0 0,0 4px,4px -4px,-4px 0,0 0",this.alphaSliderEl.style.backgroundColor="var(--db-surface-base)"),this.panelAlphaInputEl&&!this.panelAlphaInputFocused&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.formatSelectEl&&this.formatSelectEl.getAttribute("value")!==this.format&&this.formatSelectEl.setAttribute("value",this.format),this.colorInput=l}update(){if(!this.mounted)return;const t=this.getOption("size",p,"m"),e=this.getOption("type",u,"dropdown"),i=this.getOption("position",g,"bottom-start"),s=this.getBool("disabled"),l=this.getBool("readonly"),n=this.getBool("show-input",!0),o=this.getBool("show-alpha",!0),a=this.getBool("show-format-selector",!0),r=this.getBool("show-copy-button",!0),h=this.getBool("show-eyedropper",!0),d="undefined"!=typeof window&&"EyeDropper"in window,E=this.getOption("trigger",c,"input"),m="swatch"===E;if(this.className=["designbase-wc-color-picker",`designbase-wc-color-picker--${t}`,`designbase-wc-color-picker--${i}`,`designbase-wc-color-picker--trigger-${E}`,this.open&&"dropdown"===e&&"designbase-wc-color-picker--open",this.getBool("full-width")&&"designbase-wc-color-picker--full-width",this.getBool("error")&&"designbase-wc-color-picker--error",s&&"designbase-wc-color-picker--disabled",l&&"designbase-wc-color-picker--readonly",!n&&"designbase-wc-color-picker--no-input"].filter(Boolean).join(" "),this.triggerInputEl&&(this.triggerInputEl.hidden=m||!n,this.triggerInputEl.disabled=s,this.triggerInputEl.readOnly=l),this.triggerCopyBtn&&(this.triggerCopyBtn.hidden=m||!(n&&r),this.triggerCopyBtn.disabled=s),this.toggleBtn&&(this.toggleBtn.hidden=m,this.toggleBtn.disabled=s),this.dropdownEl&&(this.dropdownEl.className=`designbase-wc-color-picker__dropdown designbase-wc-color-picker__dropdown--${i}`,this.dropdownEl.hidden=!("dropdown"===e&&this.open)),this.alphaSliderWrapEl&&(this.alphaSliderWrapEl.hidden=!o),this.panelAlphaWrapEl&&(this.panelAlphaWrapEl.hidden=!o),this.formatSelectEl&&(this.formatSelectEl.hidden=!a),this.panelCopyBtnEl&&(this.panelCopyBtnEl.hidden=!r),this.eyedropperBtnEl&&(this.eyedropperBtnEl.hidden=!(h&&d)),this.selectorEl){const t="modal"===e?this.modalBodyEl:this.dropdownEl;t&&this.selectorEl.parentElement!==t&&t.append(this.selectorEl)}this.modalEl&&("modal"===e&&this.open?this.modalEl.setAttribute("open","true"):this.modalEl.removeAttribute("open")),this.updateCopyButtons(),this.updateVisuals()}}customElements.get("db-color-picker")||customElements.define("db-color-picker",DbColorPicker);export{DbColorPicker};
1
+ import{hexToRgb as t,rgbToHsv as e,hsvToRgb as i,toHex as s,rgbToHsl as l,formatColor as n,normalizeHex as o,isHex as a,clamp as r}from"./color-picker-utils.js";import{getDbComponentIconSize as h,createDbIcon as d}from"./db-icons.js";import{rafThrottle as p}from"../core/dom.js";const u=["s","m","l"],c=["dropdown","modal"],g=["input","swatch"],E=["bottom-start","bottom-end","top-start","top-end"],m="#006FFF",b=t(m)??{r:0,g:111,b:255},v=e(b.r,b.g,b.b),y=JSON.stringify([{label:"HEX",value:"hex"},{label:"RGB",value:"rgb"},{label:"RGBA",value:"rgba"},{label:"HSL",value:"hsl"},{label:"HSLA",value:"hsla"}]);class DbColorPicker extends HTMLElement{constructor(){super(...arguments),this.h=v.h,this.s=v.s,this.v=v.v,this.a=100,this.open=!1,this.format="hex",this.colorInput=m,this.alphaInput="100",this.isCopied=!1,this.tempColor="",this.dragging=null,this.mounted=!1,this.copiedTimer=null,this.debounceTimer=null,this.lastEmittedHex="",this.suppressNextValueSync=!1,this.didMount=!1,this.triggerInputFocused=!1,this.panelInputFocused=!1,this.panelAlphaInputFocused=!1,this.handleOutsideClick=t=>{if(!this.open||"dropdown"!==this.getOption("type",c,"dropdown"))return;const e=t.target;this.contains(e)||this.formatSelectEl?.contains(e)||(this.open=!1,this.update())},this.handleDocumentMouseMove=p(t=>{"area"===this.dragging&&(this.getBool("disabled")||this.getBool("readonly")||this.updateFromArea(t.clientX,t.clientY))}),this.handleDocumentMouseUp=()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))},this.handleModalCancel=()=>{const i=t(this.tempColor);if(i){const t=e(i.r,i.g,i.b);this.h=t.h,this.s=t.s,this.v=t.v}this.open=!1,this.update(),this.dispatchEvent(new CustomEvent("db-cancel",{bubbles:!0,composed:!0}))},this.handleModalApply=()=>{this.open=!1,this.actuallyEmit(),this.dispatchEvent(new CustomEvent("db-apply",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})),this.update()}}static get observedAttributes(){return["size","type","trigger","position","value","default-value","show-input","show-alpha","show-format-selector","show-copy-button","show-eyedropper","disabled","readonly","full-width","error","on-change-format","change-debounce-ms","emit-during-drag"]}connectedCallback(){this.mounted||this.mount(),this.syncFromValueAttr(!0),this.update(),document.addEventListener("mousedown",this.handleOutsideClick),document.addEventListener("mousemove",this.handleDocumentMouseMove),document.addEventListener("mouseup",this.handleDocumentMouseUp)}disconnectedCallback(){document.removeEventListener("mousedown",this.handleOutsideClick),document.removeEventListener("mousemove",this.handleDocumentMouseMove),document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.copiedTimer&&clearTimeout(this.copiedTimer),this.debounceTimer&&clearTimeout(this.debounceTimer)}attributeChangedCallback(t){this.mounted&&("value"!==t&&"default-value"!==t||this.syncFromValueAttr(!1),this.update())}getBool(t,e=!1){if(!this.hasAttribute(t))return e;const i=this.getAttribute(t);return""===i||"true"===i}getOption(t,e,i){const s=this.getAttribute(t);return s&&e.includes(s)?s:i}getIconSize(){return h(this.getOption("size",u,"m"))}getRgb(){return i(this.h,this.s,this.v)}getHex(){const t=this.getRgb();return s(t.r,t.g,t.b)}getHsl(){const t=this.getRgb();return l(t.r,t.g,t.b)}getUiFormatted(){const t=this.getRgb(),e=this.getHex(),i=this.getHsl();return n(this.format,t,e,i,this.a)}getOutward(){return"hex"===("ui"===this.getAttribute("on-change-format")?"ui":"hex")?this.getHex():this.getUiFormatted()}syncFromValueAttr(i){const s=this.getAttribute("value")??(i?this.getAttribute("default-value"):null)??(i?m:null);if(null==s)return;const l=o(s);if(!a(l))return;if(!i&&this.suppressNextValueSync&&l===this.lastEmittedHex)return void(this.suppressNextValueSync=!1);const n=t(l);if(!n)return;const r=e(n.r,n.g,n.b);this.h=r.h,this.s=r.s,this.v=r.v,this.colorInput=l,this.lastEmittedHex=l}actuallyEmit(){const t=o(this.getHex()),e=this.hasAttribute("value")&&a(this.getAttribute("value")||"")?o(this.getAttribute("value")||""):null;e&&e===t||this.lastEmittedHex!==t&&(this.lastEmittedHex=t,this.suppressNextValueSync=!0,this.setAttribute("value",t),this.dispatchEvent(new CustomEvent("db-change",{detail:{value:this.getOutward()},bubbles:!0,composed:!0})))}scheduleEmit(){const t=this.getBool("emit-during-drag",!0);if(this.dragging&&!t)return;const e=Number(this.getAttribute("change-debounce-ms")||"0");if(e>0)return this.debounceTimer&&clearTimeout(this.debounceTimer),void(this.debounceTimer=setTimeout(()=>this.actuallyEmit(),e));this.actuallyEmit()}onColorStateChanged(t=!1){this.didMount?(!t||this.getBool("emit-during-drag",!0),this.scheduleEmit()):this.didMount=!0}updateFromArea(t,e){const i=this.colorFieldEl;if(!i)return;const s=i.getBoundingClientRect(),l=r(t-s.left,0,s.width),n=r(e-s.top,0,s.height);this.s=l/s.width*100,this.v=100-n/s.height*100,this.updateVisuals(),this.onColorStateChanged()}getInputValue(t){return t?t.getAttribute("value")??"":""}setInputValue(t,e){t&&void 0!==e&&t.setAttribute("value",e)}getPanelControlSize(){return"s"===this.getOption("size",u,"m")?"s":"m"}commitColorInput(i){const s=("trigger"===i?this.triggerInputEl?.value:this.getInputValue(this.panelValueInputEl)??"").trim();if(/^#([0-9A-Fa-f]{6})$/.test(s)){const i=t(s),l=e(i.r,i.g,i.b);return this.h=l.h,this.s=l.s,this.v=l.v,this.colorInput=o(s),this.updateVisuals(),void this.onColorStateChanged()}let l=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(s);if(l){const t=r(parseInt(l[1],10),0,255),i=r(parseInt(l[2],10),0,255),s=r(parseInt(l[3],10),0,255),n=e(t,i,s);return this.h=n.h,this.s=n.s,this.v=n.v,this.colorInput=`rgb(${t}, ${i}, ${s})`,this.updateVisuals(),void this.onColorStateChanged()}if(l=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i.exec(s),l){const t=r(parseInt(l[1],10),0,255),i=r(parseInt(l[2],10),0,255),s=r(parseInt(l[3],10),0,255),n=parseFloat(l[4]),o=e(t,i,s);this.h=o.h,this.s=o.s,this.v=o.v,this.a=Math.round(100*n),this.alphaInput=String(this.a),this.colorInput=`rgba(${t}, ${i}, ${s}, ${n})`,this.updateVisuals(),this.onColorStateChanged()}}commitAlphaInput(){const t=Number(this.getInputValue(this.panelAlphaInputEl).trim()||this.alphaInput);if(!Number.isNaN(t)&&t>=0&&t<=100){const e=Math.round(t);this.a=e,this.alphaInput=String(e),this.updateVisuals(),this.onColorStateChanged()}else this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput)}async onCopy(){try{await navigator.clipboard.writeText(this.getUiFormatted()),this.isCopied=!0,this.updateCopyButtons(),this.copiedTimer&&clearTimeout(this.copiedTimer),this.copiedTimer=setTimeout(()=>{this.isCopied=!1,this.updateCopyButtons()},1600)}catch{}}async onEyedrop(){try{if("EyeDropper"in window){const i=new window.EyeDropper,{sRGBHex:s}=await i.open(),l=t(s);if(!l)return;const n=e(l.r,l.g,l.b);this.h=n.h,this.s=n.s,this.v=n.v,this.updateVisuals(),this.onColorStateChanged()}}catch{}}toggleOpen(){if(this.getBool("disabled")||this.getBool("readonly"))return;if("modal"===this.getOption("type",c,"dropdown"))return this.tempColor=this.getHex(),this.open=!0,void this.update();this.open=!this.open,this.update()}close(){this.open&&"dropdown"===this.getOption("type",c,"dropdown")&&(this.open=!1,this.update())}mount(){this.mounted=!0;const t=this.getIconSize();this.triggerEl=document.createElement("div"),this.triggerEl.className="designbase-wc-color-picker__trigger",this.triggerEl.addEventListener("click",()=>this.toggleOpen());const e=document.createElement("div");e.className="designbase-wc-color-picker__color-display",this.colorBoxEl=document.createElement("div"),this.colorBoxEl.className="designbase-wc-color-picker__color-box",e.append(this.colorBoxEl),this.triggerInputEl=document.createElement("input"),this.triggerInputEl.type="text",this.triggerInputEl.className="designbase-wc-color-picker__input",this.triggerInputEl.placeholder="#000000",this.triggerInputEl.addEventListener("click",t=>t.stopPropagation()),this.triggerInputEl.addEventListener("focus",()=>{this.triggerInputFocused=!0}),this.triggerInputEl.addEventListener("blur",()=>{this.triggerInputFocused=!1;const t="hex"===this.format?o(this.getUiFormatted()):this.getUiFormatted();this.triggerInputEl&&this.triggerInputEl.value!==t&&(this.triggerInputEl.value=t,this.colorInput=t)}),this.triggerInputEl.addEventListener("input",()=>{this.triggerInputEl&&(this.colorInput=this.triggerInputEl.value)}),this.triggerInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("trigger")});const i=document.createElement("div");i.className="designbase-wc-color-picker__trigger-actions",this.triggerCopyBtn=document.createElement("button"),this.triggerCopyBtn.type="button",this.triggerCopyBtn.className="designbase-wc-color-picker__copy-button-inline",this.triggerCopyBtn.setAttribute("aria-label","Copy color value"),this.triggerCopyBtn.addEventListener("click",t=>{t.stopPropagation(),this.onCopy()}),this.toggleBtn=document.createElement("button"),this.toggleBtn.type="button",this.toggleBtn.className="designbase-wc-color-picker__toggle",this.toggleBtn.setAttribute("aria-label","Toggle color picker"),this.toggleBtn.append(d("chevron-down",t)),i.append(this.triggerCopyBtn,this.toggleBtn),this.triggerEl.append(e,this.triggerInputEl,i),this.dropdownEl=document.createElement("div"),this.dropdownEl.className="designbase-wc-color-picker__dropdown",this.dropdownEl.addEventListener("click",t=>t.stopPropagation()),this.dropdownEl.hidden=!0;const s=document.createElement("div");s.className="designbase-wc-color-picker__selector";const l=document.createElement("div");l.className="designbase-wc-color-picker__color-area",this.colorFieldEl=document.createElement("div"),this.colorFieldEl.className="designbase-wc-color-picker__color-field",this.colorPointerEl=document.createElement("div"),this.colorPointerEl.className="designbase-wc-color-picker__color-pointer",this.colorFieldEl.append(this.colorPointerEl),this.colorFieldEl.addEventListener("mousedown",t=>{this.getBool("disabled")||this.getBool("readonly")||(t.preventDefault(),this.dragging="area",this.updateFromArea(t.clientX,t.clientY))}),this.colorFieldEl.addEventListener("touchstart",t=>{if(this.getBool("disabled")||this.getBool("readonly"))return;this.dragging="area";const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchmove",t=>{if("area"!==this.dragging)return;const e=t.touches[0];this.updateFromArea(e.clientX,e.clientY)},{passive:!0}),this.colorFieldEl.addEventListener("touchend",()=>{"area"===this.dragging&&(this.dragging=null,this.onColorStateChanged(!0))}),l.append(this.colorFieldEl);const n=document.createElement("div");n.className="designbase-wc-color-picker__controls",this.eyedropperBtnEl=document.createElement("db-button"),this.eyedropperBtnEl.setAttribute("variant","tertiary"),this.eyedropperBtnEl.setAttribute("size",this.getPanelControlSize()),this.eyedropperBtnEl.setAttribute("icon-only",""),this.eyedropperBtnEl.setAttribute("start-icon","eyedropper"),this.eyedropperBtnEl.setAttribute("aria-label","Eyedropper tool"),this.eyedropperBtnEl.addEventListener("click",()=>{this.onEyedrop()});const a=document.createElement("div");a.className="designbase-wc-color-picker__slider-container";const h=document.createElement("div");h.className="designbase-wc-color-picker__hue-slider",this.hueSliderEl=document.createElement("input"),this.hueSliderEl.type="range",this.hueSliderEl.min="0",this.hueSliderEl.max="360",this.hueSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--hue",this.hueSliderEl.addEventListener("input",()=>{this.h=parseFloat(this.hueSliderEl.value),this.updateVisuals(),this.onColorStateChanged()}),h.append(this.hueSliderEl),this.alphaSliderWrapEl=document.createElement("div"),this.alphaSliderWrapEl.className="designbase-wc-color-picker__alpha-slider",this.alphaSliderEl=document.createElement("input"),this.alphaSliderEl.type="range",this.alphaSliderEl.min="0",this.alphaSliderEl.max="100",this.alphaSliderEl.className="designbase-wc-color-picker__slider designbase-wc-color-picker__slider--alpha",this.alphaSliderEl.addEventListener("input",()=>{this.a=r(parseInt(this.alphaSliderEl.value,10),0,100),this.alphaInput=String(this.a),this.panelAlphaInputEl&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.updateVisuals(),this.onColorStateChanged()}),this.alphaSliderWrapEl.append(this.alphaSliderEl),a.append(h,this.alphaSliderWrapEl),n.append(this.eyedropperBtnEl,a);const p=document.createElement("div");p.className="designbase-wc-color-picker__value-display",this.formatSelectEl=document.createElement("db-select"),this.formatSelectEl.setAttribute("size","s"),this.formatSelectEl.setAttribute("position","top"),this.formatSelectEl.setAttribute("show-clear-button","false"),this.formatSelectEl.setAttribute("options",y),this.formatSelectEl.addEventListener("db-change",t=>{const e=t.detail,i=e?.value;i&&(this.format=i,this.updateVisuals())}),this.panelValueInputEl=document.createElement("db-input"),this.panelValueInputEl.classList.add("designbase-wc-color-picker__value-input"),this.panelValueInputEl.setAttribute("size","s"),this.panelValueInputEl.setAttribute("placeholder","#000000"),this.panelValueInputEl.addEventListener("db-focus",()=>{this.panelInputFocused=!0}),this.panelValueInputEl.addEventListener("db-blur",()=>{this.panelInputFocused=!1;const t="hex"===this.format?o(this.getUiFormatted()):this.getUiFormatted();this.getInputValue(this.panelValueInputEl)!==t&&(this.setInputValue(this.panelValueInputEl,t),this.colorInput=t)}),this.panelValueInputEl.addEventListener("db-input",t=>{const e=t.detail;void 0!==e?.value&&(this.colorInput=e.value)}),this.panelValueInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitColorInput("panel")}),this.panelAlphaWrapEl=document.createElement("div"),this.panelAlphaWrapEl.className="designbase-wc-color-picker__alpha-input-wrap",this.panelAlphaInputEl=document.createElement("db-input"),this.panelAlphaInputEl.classList.add("designbase-wc-color-picker__alpha-input"),this.panelAlphaInputEl.setAttribute("size","s"),this.panelAlphaInputEl.setAttribute("placeholder","100"),this.panelAlphaInputEl.setAttribute("aria-label","Alpha percent"),this.panelAlphaInputEl.addEventListener("db-focus",()=>{this.panelAlphaInputFocused=!0}),this.panelAlphaInputEl.addEventListener("db-blur",()=>{this.panelAlphaInputFocused=!1,this.commitAlphaInput()}),this.panelAlphaInputEl.addEventListener("db-input",t=>{const e=t.detail,i=(e?.value??"").replace(/[^\d]/g,"").slice(0,3);i!==e?.value&&this.setInputValue(this.panelAlphaInputEl,i),this.alphaInput=i}),this.panelAlphaInputEl.addEventListener("keydown",t=>{"Enter"===t.key&&this.commitAlphaInput()});const u=document.createElement("span");u.className="designbase-wc-color-picker__alpha-suffix",u.textContent="%",this.panelAlphaWrapEl.append(this.panelAlphaInputEl,u),this.panelCopyBtnEl=document.createElement("db-button"),this.panelCopyBtnEl.setAttribute("variant","tertiary"),this.panelCopyBtnEl.setAttribute("size","s"),this.panelCopyBtnEl.setAttribute("icon-only",""),this.panelCopyBtnEl.setAttribute("start-icon","copy"),this.panelCopyBtnEl.setAttribute("aria-label","Copy color value"),this.panelCopyBtnEl.addEventListener("click",()=>{this.onCopy()}),p.append(this.formatSelectEl,this.panelValueInputEl,this.panelAlphaWrapEl,this.panelCopyBtnEl),s.append(l,n,p),this.selectorEl=s,this.dropdownEl.append(s),this.modalEl=document.createElement("db-modal"),this.modalEl.setAttribute("size","s"),this.modalEl.setAttribute("title","색상 선택"),this.modalEl.setAttribute("close-on-escape","true"),this.modalEl.addEventListener("db-close",this.handleModalCancel),this.modalBodyEl=document.createElement("div"),this.modalBodyEl.className="designbase-wc-modal__body designbase-wc-color-picker__modal-body",this.modalBodyEl.setAttribute("data-modal-part","body");const c=document.createElement("div");c.className="designbase-wc-modal__footer",c.setAttribute("data-modal-part","footer");const g=document.createElement("db-button");g.setAttribute("variant","tertiary"),g.setAttribute("size","m"),g.textContent="취소",g.addEventListener("click",this.handleModalCancel);const E=document.createElement("db-button");E.setAttribute("variant","primary"),E.setAttribute("size","m"),E.textContent="적용",E.addEventListener("click",this.handleModalApply),c.append(g,E),this.modalEl.append(this.modalBodyEl,c),this.replaceChildren(this.triggerEl,this.dropdownEl,this.modalEl)}updateCopyButtons(){const t=this.getIconSize(),e=this.isCopied?"done":"copy";this.triggerCopyBtn&&this.triggerCopyBtn.replaceChildren(d(e,t)),this.panelCopyBtnEl&&this.panelCopyBtnEl.setAttribute("start-icon",e)}updateVisuals(){const t=this.getRgb(),e=this.getHex(),i=this.getBool("show-alpha",!0),s=this.getUiFormatted(),l="hex"===this.format?o(s):s;!this.triggerInputFocused&&this.triggerInputEl&&(this.triggerInputEl.value=l),!this.panelInputFocused&&this.panelValueInputEl&&this.setInputValue(this.panelValueInputEl,l),this.colorBoxEl&&(this.colorBoxEl.style.backgroundColor=i?`rgba(${t.r}, ${t.g}, ${t.b}, ${this.a/100})`:e),this.colorFieldEl&&(this.colorFieldEl.style.backgroundImage=`\n linear-gradient(to top, rgba(0,0,0,1), rgba(0,0,0,0)),\n linear-gradient(to right, #ffffff, hsl(${this.h}, 100%, 50%))\n `),this.colorPointerEl&&(this.colorPointerEl.style.left=`${this.s}%`,this.colorPointerEl.style.top=100-this.v+"%",this.colorPointerEl.style.backgroundColor=`rgb(${t.r}, ${t.g}, ${t.b})`),this.hueSliderEl&&(this.hueSliderEl.value=String(this.h),this.hueSliderEl.style.background="linear-gradient(to right,\n hsl(0,100%,50%),\n hsl(60,100%,50%),\n hsl(120,100%,50%),\n hsl(180,100%,50%),\n hsl(240,100%,50%),\n hsl(300,100%,50%),\n hsl(360,100%,50%))"),this.alphaSliderEl&&(this.alphaSliderEl.value=String(this.a),this.alphaSliderEl.style.backgroundImage=`\n linear-gradient(45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(-45deg, var(--db-border-base) 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(-45deg, transparent 75%, var(--db-border-base) 75%),\n linear-gradient(to right, rgba(${t.r}, ${t.g}, ${t.b}, 0), rgba(${t.r}, ${t.g}, ${t.b}, 1))\n `,this.alphaSliderEl.style.backgroundSize="8px 8px,8px 8px,8px 8px,8px 8px,100% 100%",this.alphaSliderEl.style.backgroundPosition="0 0,0 4px,4px -4px,-4px 0,0 0",this.alphaSliderEl.style.backgroundColor="var(--db-surface-base)"),this.panelAlphaInputEl&&!this.panelAlphaInputFocused&&this.setInputValue(this.panelAlphaInputEl,this.alphaInput),this.formatSelectEl&&this.formatSelectEl.getAttribute("value")!==this.format&&this.formatSelectEl.setAttribute("value",this.format),this.colorInput=l}update(){if(!this.mounted)return;const t=this.getOption("size",u,"m"),e=this.getOption("type",c,"dropdown"),i=this.getOption("position",E,"bottom-start"),s=this.getBool("disabled"),l=this.getBool("readonly"),n=this.getBool("show-input",!0),o=this.getBool("show-alpha",!0),a=this.getBool("show-format-selector",!0),r=this.getBool("show-copy-button",!0),h=this.getBool("show-eyedropper",!0),d="undefined"!=typeof window&&"EyeDropper"in window,p=this.getOption("trigger",g,"input"),m="swatch"===p;if(this.className=["designbase-wc-color-picker",`designbase-wc-color-picker--${t}`,`designbase-wc-color-picker--${i}`,`designbase-wc-color-picker--trigger-${p}`,this.open&&"dropdown"===e&&"designbase-wc-color-picker--open",this.getBool("full-width")&&"designbase-wc-color-picker--full-width",this.getBool("error")&&"designbase-wc-color-picker--error",s&&"designbase-wc-color-picker--disabled",l&&"designbase-wc-color-picker--readonly",!n&&"designbase-wc-color-picker--no-input"].filter(Boolean).join(" "),this.triggerInputEl?.setAttribute("aria-invalid",String(this.getBool("error"))),this.triggerInputEl&&(this.triggerInputEl.hidden=m||!n,this.triggerInputEl.disabled=s,this.triggerInputEl.readOnly=l),this.triggerCopyBtn&&(this.triggerCopyBtn.hidden=m||!(n&&r),this.triggerCopyBtn.disabled=s),this.toggleBtn&&(this.toggleBtn.hidden=m,this.toggleBtn.disabled=s),this.dropdownEl&&(this.dropdownEl.className=`designbase-wc-color-picker__dropdown designbase-wc-color-picker__dropdown--${i}`,this.dropdownEl.hidden=!("dropdown"===e&&this.open)),this.alphaSliderWrapEl&&(this.alphaSliderWrapEl.hidden=!o),this.panelAlphaWrapEl&&(this.panelAlphaWrapEl.hidden=!o),this.formatSelectEl&&(this.formatSelectEl.hidden=!a),this.panelCopyBtnEl&&(this.panelCopyBtnEl.hidden=!r),this.eyedropperBtnEl&&(this.eyedropperBtnEl.hidden=!(h&&d)),this.selectorEl){const t="modal"===e?this.modalBodyEl:this.dropdownEl;t&&this.selectorEl.parentElement!==t&&t.append(this.selectorEl)}this.modalEl&&("modal"===e&&this.open?this.modalEl.setAttribute("open","true"):this.modalEl.removeAttribute("open")),this.updateCopyButtons(),this.updateVisuals()}}customElements.get("db-color-picker")||customElements.define("db-color-picker",DbColorPicker);export{DbColorPicker};