@ahrowe/ui 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/esm/common/accordion/accordion.mjs +1 -1
  2. package/dist/esm/common/accordion/accordion.mjs.map +1 -1
  3. package/dist/esm/common/colorPicker/colorPicker.mjs +1 -1
  4. package/dist/esm/common/colorPicker/colorPicker.mjs.map +1 -1
  5. package/dist/esm/common/confirmModal/confirmModal.mjs +1 -1
  6. package/dist/esm/common/confirmModal/confirmModal.mjs.map +1 -1
  7. package/dist/esm/common/dropZone/dropZone.mjs +1 -1
  8. package/dist/esm/common/dropZone/dropZone.mjs.map +1 -1
  9. package/dist/esm/common/floatingMenu/useFloatingPosition.mjs +1 -1
  10. package/dist/esm/common/floatingMenu/useFloatingPosition.mjs.map +1 -1
  11. package/dist/esm/common/floorPlan/floorPlan.geometry.mjs +1 -1
  12. package/dist/esm/common/floorPlan/floorPlan.geometry.mjs.map +1 -1
  13. package/dist/esm/common/floorPlan/floorPlan.graph.mjs +1 -1
  14. package/dist/esm/common/floorPlan/floorPlan.graph.mjs.map +1 -1
  15. package/dist/esm/common/floorPlan/floorPlan.mesh.mjs +2 -0
  16. package/dist/esm/common/floorPlan/floorPlan.mesh.mjs.map +1 -0
  17. package/dist/esm/common/floorPlan/floorPlan.triangulate.mjs +2 -0
  18. package/dist/esm/common/floorPlan/floorPlan.triangulate.mjs.map +1 -0
  19. package/dist/esm/common/hooks/useAnchorTracking.mjs +2 -0
  20. package/dist/esm/common/hooks/useAnchorTracking.mjs.map +1 -0
  21. package/dist/esm/common/idleManager/idleManager.mjs +1 -1
  22. package/dist/esm/common/idleManager/idleManager.mjs.map +1 -1
  23. package/dist/esm/common/input/input.mjs +1 -1
  24. package/dist/esm/common/input/input.mjs.map +1 -1
  25. package/dist/esm/common/inputDropdown/inputDropdown.mjs +1 -1
  26. package/dist/esm/common/inputDropdown/inputDropdown.mjs.map +1 -1
  27. package/dist/esm/common/klipyPicker/components/gifView/gifView.mjs +1 -1
  28. package/dist/esm/common/klipyPicker/components/gifView/gifView.mjs.map +1 -1
  29. package/dist/esm/common/multiSelect/multiSelect.mjs +2 -0
  30. package/dist/esm/common/multiSelect/multiSelect.mjs.map +1 -0
  31. package/dist/esm/common/multiSelect/multiSelect.module.mjs +2 -0
  32. package/dist/esm/common/multiSelect/multiSelect.module.mjs.map +1 -0
  33. package/dist/esm/common/overscroll/overscroll.mjs +1 -1
  34. package/dist/esm/common/overscroll/overscroll.mjs.map +1 -1
  35. package/dist/esm/common/pagination/pagination.mjs +2 -0
  36. package/dist/esm/common/pagination/pagination.mjs.map +1 -0
  37. package/dist/esm/common/pagination/pagination.module.mjs +2 -0
  38. package/dist/esm/common/pagination/pagination.module.mjs.map +1 -0
  39. package/dist/esm/common/popover/usePopoverPosition.mjs +1 -1
  40. package/dist/esm/common/popover/usePopoverPosition.mjs.map +1 -1
  41. package/dist/esm/common/roomDrawer/roomDrawer.mjs +1 -1
  42. package/dist/esm/common/roomDrawer/roomDrawer.mjs.map +1 -1
  43. package/dist/esm/common/roomDrawer/roomDrawer.module.mjs.map +1 -1
  44. package/dist/esm/common/roomViewer/roomViewer.module.mjs.map +1 -1
  45. package/dist/esm/common/timer/timer.mjs.map +1 -1
  46. package/dist/esm/common/tree/flattenTree.mjs +2 -0
  47. package/dist/esm/common/tree/flattenTree.mjs.map +1 -0
  48. package/dist/esm/common/tree/tree.mjs +2 -0
  49. package/dist/esm/common/tree/tree.mjs.map +1 -0
  50. package/dist/esm/common/tree/tree.module.mjs +2 -0
  51. package/dist/esm/common/tree/tree.module.mjs.map +1 -0
  52. package/dist/esm/common/virtualList/virtualList.mjs +1 -1
  53. package/dist/esm/common/virtualList/virtualList.mjs.map +1 -1
  54. package/dist/esm/common/virtualList/virtualRow.mjs.map +1 -1
  55. package/dist/esm/index.mjs +1 -1
  56. package/dist/esm/services/formValidation/validatableComponent.mjs.map +1 -1
  57. package/dist/index.cjs +3 -3
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/style.css +1 -1
  60. package/dist/types/package/common/configProvider/configProvider.types.d.ts +6 -0
  61. package/dist/types/package/common/floatingMenu/useFloatingPosition.d.ts +4 -6
  62. package/dist/types/package/common/floorPlan/floorPlan.graph.d.ts +45 -0
  63. package/dist/types/package/common/floorPlan/floorPlan.mesh.d.ts +36 -0
  64. package/dist/types/package/common/floorPlan/floorPlan.triangulate.d.ts +11 -0
  65. package/dist/types/package/common/floorPlan/index.d.ts +4 -2
  66. package/dist/types/package/common/hooks/useAnchorTracking.d.ts +40 -0
  67. package/dist/types/package/common/inputDropdown/inputDropdown.types.d.ts +6 -0
  68. package/dist/types/package/common/multiSelect/index.d.ts +2 -0
  69. package/dist/types/package/common/multiSelect/multiSelect.d.ts +4 -0
  70. package/dist/types/package/common/multiSelect/multiSelect.types.d.ts +62 -0
  71. package/dist/types/package/common/pagination/index.d.ts +2 -0
  72. package/dist/types/package/common/pagination/pagination.d.ts +4 -0
  73. package/dist/types/package/common/pagination/pagination.types.d.ts +30 -0
  74. package/dist/types/package/common/popover/usePopoverPosition.d.ts +4 -2
  75. package/dist/types/package/common/tree/flattenTree.d.ts +3 -0
  76. package/dist/types/package/common/tree/index.d.ts +3 -0
  77. package/dist/types/package/common/tree/tree.d.ts +4 -0
  78. package/dist/types/package/common/tree/tree.types.d.ts +62 -0
  79. package/dist/types/package/common/virtualList/virtualList.types.d.ts +8 -0
  80. package/dist/types/package/common/virtualList/virtualRow.d.ts +1 -1
  81. package/dist/types/package/index.d.ts +6 -0
  82. package/docs/CLAUDE.md +3 -0
  83. package/docs/FloorPlan.md +39 -1
  84. package/docs/InputDropdown.md +3 -0
  85. package/docs/MultiSelect.md +100 -0
  86. package/docs/Pagination.md +72 -0
  87. package/docs/RoomDrawer.md +14 -0
  88. package/docs/Tree.md +95 -0
  89. package/docs/VirtualList.md +1 -0
  90. package/package.json +4 -2
@@ -1,2 +1,2 @@
1
- import{AccordionStyleType as e}from"./accordion.types.mjs";import t from"./accordion.module.mjs";import n from"./accordion.primary.module.mjs";import r from"./accordion.plain.module.mjs";import{useComponentDefaults as i}from"../configProvider/useComponentDefaults.mjs";import{useEffect as a,useRef as o,useState as s}from"react";import c from"classnames";import{FontAwesomeIcon as l}from"@fortawesome/react-fontawesome";import{faChevronDown as u}from"@fortawesome/free-solid-svg-icons";import{jsx as d,jsxs as f}from"react/jsx-runtime";var p={[e.Default]:t,[e.Primary]:n,[e.Plain]:r};function m(t){let{id:n=``,title:r=``,children:m=null,expanded:h=null,onHeaderClicked:g=()=>{},styleType:_=e.Default,startOpen:v=!1,hideHeader:y=!1,className:b,style:x,classNames:S,styles:C,...w}=i(`Accordion`,t),T=p[_],E=o(null),[D,O]=s(h??v),[k,A]=s(null);a(()=>{h!==null&&O(h)},[h]),a(()=>{let e=E.current;if(!e)return;let t=new ResizeObserver(()=>A(e.offsetHeight));return t.observe(e),()=>t.unobserve(e)},[]);function j(){let e=!D;g(n,e),h===null&&O(e)}let M={height:`${D?32:24}px`},N={height:D?k??`auto`:`0px`};return f(`div`,{...w,id:n||void 0,className:c(T.accordion,D&&T.accordionActive,b,S?.root),style:{...x,...C?.root},children:[!y&&f(`div`,{className:c(T.accordionHeader,D&&T.accordionHeaderActive,S?.header),style:{...M,...C?.header},onClick:j,role:`button`,tabIndex:0,onKeyDown:({key:e})=>{e===`Enter`&&j()},children:[d(`div`,{className:c(T.accordionTitle,S?.title),style:C?.title,children:r}),d(l,{icon:u,className:c(T.accordionIcon,D&&T.accordionIconActive,S?.icon),style:C?.icon})]}),d(`div`,{className:c(T.accordionBody,D&&T.accordionBodyActive,S?.body),style:{...N,...C?.body},children:d(`div`,{className:c(T.accordionBodyInner,S?.bodyInner),style:C?.bodyInner,ref:E,children:m})})]})}export{m as default};
1
+ import{AccordionStyleType as e}from"./accordion.types.mjs";import t from"./accordion.module.mjs";import n from"./accordion.primary.module.mjs";import r from"./accordion.plain.module.mjs";import{useComponentDefaults as i}from"../configProvider/useComponentDefaults.mjs";import{useEffect as a,useRef as o,useState as s}from"react";import c from"classnames";import{FontAwesomeIcon as l}from"@fortawesome/react-fontawesome";import{faChevronDown as u}from"@fortawesome/free-solid-svg-icons";import{jsx as d,jsxs as f}from"react/jsx-runtime";var p={[e.Default]:t,[e.Primary]:n,[e.Plain]:r};function m(t){let{id:n=``,title:r=``,children:m=null,expanded:h=null,onHeaderClicked:g=()=>{},styleType:_=e.Default,startOpen:v=!1,hideHeader:y=!1,className:b,style:x,classNames:S,styles:C,...w}=i(`Accordion`,t),T=p[_],E=o(null),D=o(null),[O,k]=s(h??v),[A,j]=s(null);a(()=>{h!==null&&k(h)},[h]),a(()=>{let e=E.current;e&&(e.inert=!O)},[O]),a(()=>{let e=D.current;if(!e)return;let t=new ResizeObserver(()=>j(e.offsetHeight));return t.observe(e),()=>t.unobserve(e)},[]);function M(){let e=!O;g(n,e),h===null&&k(e)}let N={height:`${O?32:24}px`},P={height:O?A??`auto`:`0px`};return f(`div`,{...w,id:n||void 0,className:c(T.accordion,O&&T.accordionActive,b,S?.root),style:{...x,...C?.root},children:[!y&&f(`div`,{className:c(T.accordionHeader,O&&T.accordionHeaderActive,S?.header),style:{...N,...C?.header},onClick:M,role:`button`,tabIndex:0,onKeyDown:({key:e})=>{e===`Enter`&&M()},children:[d(`div`,{className:c(T.accordionTitle,S?.title),style:C?.title,children:r}),d(l,{icon:u,className:c(T.accordionIcon,O&&T.accordionIconActive,S?.icon),style:C?.icon})]}),d(`div`,{ref:E,className:c(T.accordionBody,O&&T.accordionBodyActive,S?.body),style:{...P,...C?.body},children:d(`div`,{className:c(T.accordionBodyInner,S?.bodyInner),style:C?.bodyInner,ref:D,children:m})})]})}export{m as default};
2
2
  //# sourceMappingURL=accordion.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"accordion.mjs","names":[],"sources":["../../../../package/common/accordion/accordion.tsx"],"sourcesContent":["import React, { useState, useEffect, useRef, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faChevronDown as arrowIcon } from '@fortawesome/free-solid-svg-icons';\n\nimport { AccordionStyleType, type AccordionProps } from './accordion.types';\n\nimport defaultStyles from './accordion.module.pcss';\nimport primaryStyles from './accordion.primary.module.pcss';\nimport plainStyles from './accordion.plain.module.pcss';\nimport { useComponentDefaults } from '../configProvider';\n\nconst STYLES_BY_TYPE: Record<AccordionStyleType, typeof defaultStyles> = {\n [AccordionStyleType.Default]: defaultStyles,\n [AccordionStyleType.Primary]: primaryStyles,\n [AccordionStyleType.Plain]: plainStyles,\n};\n\nfunction Accordion(props: AccordionProps): ReactElement {\n const {\n id = '',\n title = '',\n children = null,\n expanded = null,\n onHeaderClicked = () => {},\n styleType = AccordionStyleType.Default,\n startOpen = false,\n hideHeader = false,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Accordion', props);\n const s = STYLES_BY_TYPE[styleType];\n const bodyRef = useRef<HTMLDivElement>(null);\n\n const [isExpanded, setIsExpanded] = useState(expanded ?? startOpen);\n const [bodyHeight, setBodyHeight] = useState<number | null>(null);\n\n // Sync controlled expanded prop\n useEffect(() => {\n // eslint-disable-next-line react-hooks/set-state-in-effect\n if (expanded !== null) setIsExpanded(expanded);\n }, [expanded]);\n\n // Measure body height via ResizeObserver\n useEffect(() => {\n const el = bodyRef.current;\n if (!el) return;\n const observer = new ResizeObserver(() => setBodyHeight(el.offsetHeight));\n observer.observe(el);\n return () => observer.unobserve(el);\n }, []);\n\n function toggleExpanded() {\n const next = !isExpanded;\n onHeaderClicked(id, next);\n if (expanded === null) setIsExpanded(next);\n }\n\n const headerHeight = 24;\n const headerStyle = { height: `${isExpanded ? headerHeight + headerHeight / 3 : headerHeight}px` };\n const bodyStyle = { height: isExpanded ? (bodyHeight ?? 'auto') : '0px' };\n\n return (\n <div {...rest} id={id || undefined} className={cx(s.accordion, isExpanded && s.accordionActive, className, classNames?.root)} style={{ ...style, ...slotStyles?.root }}>\n {!hideHeader && (\n <div\n className={cx(s.accordionHeader, isExpanded && s.accordionHeaderActive, classNames?.header)}\n style={{ ...headerStyle, ...slotStyles?.header }}\n onClick={toggleExpanded}\n role=\"button\"\n tabIndex={0}\n onKeyDown={({ key }) => { if (key === 'Enter') toggleExpanded(); }}\n >\n <div className={cx(s.accordionTitle, classNames?.title)} style={slotStyles?.title}>{title}</div>\n <FontAwesomeIcon\n icon={arrowIcon}\n className={cx(s.accordionIcon, isExpanded && s.accordionIconActive, classNames?.icon)}\n style={slotStyles?.icon as React.CSSProperties & Record<`--fa-font-${string}`, string>}\n />\n </div>\n )}\n <div\n className={cx(s.accordionBody, isExpanded && s.accordionBodyActive, classNames?.body)}\n style={{ ...bodyStyle, ...slotStyles?.body }}\n >\n <div className={cx(s.accordionBodyInner, classNames?.bodyInner)} style={slotStyles?.bodyInner} ref={bodyRef}>\n {children}\n </div>\n </div>\n </div>\n );\n}\n\nexport default Accordion;\n"],"mappings":"whBAYA,IAAM,EAAmE,EACtE,EAAmB,SAAU,GAC7B,EAAmB,SAAU,GAC7B,EAAmB,OAAQ,CAC9B,EAEA,SAAS,EAAU,EAAqC,CACtD,GAAM,CACN,KAAK,GACL,QAAQ,GACR,WAAW,KACX,WAAW,KACX,sBAAwB,CAAC,EACzB,YAAY,EAAmB,QAC/B,YAAY,GACZ,aAAa,GACb,YACA,QACA,aACA,OAAQ,EACR,GAAG,GACC,EAAqB,YAAa,CAAK,EACrC,EAAI,EAAe,GACnB,EAAU,EAAuB,IAAI,EAErC,CAAC,EAAY,GAAiB,EAAS,GAAY,CAAS,EAC5D,CAAC,EAAY,GAAiB,EAAwB,IAAI,EAGhE,MAAgB,CAEV,IAAa,MAAM,EAAc,CAAQ,CAC/C,EAAG,CAAC,CAAQ,CAAC,EAGb,MAAgB,CACd,IAAM,EAAK,EAAQ,QACnB,GAAI,CAAC,EAAI,OACT,IAAM,EAAW,IAAI,mBAAqB,EAAc,EAAG,YAAY,CAAC,EAEx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../../../../package/common/accordion/accordion.tsx"],"sourcesContent":["import React, { useState, useEffect, useRef, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faChevronDown as arrowIcon } from '@fortawesome/free-solid-svg-icons';\n\nimport { AccordionStyleType, type AccordionProps } from './accordion.types';\n\nimport defaultStyles from './accordion.module.pcss';\nimport primaryStyles from './accordion.primary.module.pcss';\nimport plainStyles from './accordion.plain.module.pcss';\nimport { useComponentDefaults } from '../configProvider';\n\nconst STYLES_BY_TYPE: Record<AccordionStyleType, typeof defaultStyles> = {\n [AccordionStyleType.Default]: defaultStyles,\n [AccordionStyleType.Primary]: primaryStyles,\n [AccordionStyleType.Plain]: plainStyles,\n};\n\nfunction Accordion(props: AccordionProps): ReactElement {\n const {\n id = '',\n title = '',\n children = null,\n expanded = null,\n onHeaderClicked = () => {},\n styleType = AccordionStyleType.Default,\n startOpen = false,\n hideHeader = false,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Accordion', props);\n const s = STYLES_BY_TYPE[styleType];\n const bodyRef = useRef<HTMLDivElement>(null);\n const bodyInnerRef = useRef<HTMLDivElement>(null);\n\n const [isExpanded, setIsExpanded] = useState(expanded ?? startOpen);\n const [bodyHeight, setBodyHeight] = useState<number | null>(null);\n\n useEffect(() => {\n // eslint-disable-next-line react-hooks/set-state-in-effect\n if (expanded !== null) setIsExpanded(expanded);\n }, [expanded]);\n\n useEffect(() => {\n const el = bodyRef.current;\n if (el) el.inert = !isExpanded;\n }, [isExpanded]);\n\n useEffect(() => {\n const el = bodyInnerRef.current;\n if (!el) return;\n const observer = new ResizeObserver(() => setBodyHeight(el.offsetHeight));\n observer.observe(el);\n return () => observer.unobserve(el);\n }, []);\n\n function toggleExpanded() {\n const next = !isExpanded;\n onHeaderClicked(id, next);\n if (expanded === null) setIsExpanded(next);\n }\n\n const headerHeight = 24;\n const headerStyle = { height: `${isExpanded ? headerHeight + headerHeight / 3 : headerHeight}px` };\n const bodyStyle = { height: isExpanded ? (bodyHeight ?? 'auto') : '0px' };\n\n return (\n <div {...rest} id={id || undefined} className={cx(s.accordion, isExpanded && s.accordionActive, className, classNames?.root)} style={{ ...style, ...slotStyles?.root }}>\n {!hideHeader && (\n <div\n className={cx(s.accordionHeader, isExpanded && s.accordionHeaderActive, classNames?.header)}\n style={{ ...headerStyle, ...slotStyles?.header }}\n onClick={toggleExpanded}\n role=\"button\"\n tabIndex={0}\n onKeyDown={({ key }) => { if (key === 'Enter') toggleExpanded(); }}\n >\n <div className={cx(s.accordionTitle, classNames?.title)} style={slotStyles?.title}>{title}</div>\n <FontAwesomeIcon\n icon={arrowIcon}\n className={cx(s.accordionIcon, isExpanded && s.accordionIconActive, classNames?.icon)}\n style={slotStyles?.icon as React.CSSProperties & Record<`--fa-font-${string}`, string>}\n />\n </div>\n )}\n <div\n ref={bodyRef}\n className={cx(s.accordionBody, isExpanded && s.accordionBodyActive, classNames?.body)}\n style={{ ...bodyStyle, ...slotStyles?.body }}\n >\n <div className={cx(s.accordionBodyInner, classNames?.bodyInner)} style={slotStyles?.bodyInner} ref={bodyInnerRef}>\n {children}\n </div>\n </div>\n </div>\n );\n}\n\nexport default Accordion;\n"],"mappings":"whBAYA,IAAM,EAAmE,EACtE,EAAmB,SAAU,GAC7B,EAAmB,SAAU,GAC7B,EAAmB,OAAQ,CAC9B,EAEA,SAAS,EAAU,EAAqC,CACtD,GAAM,CACN,KAAK,GACL,QAAQ,GACR,WAAW,KACX,WAAW,KACX,sBAAwB,CAAC,EACzB,YAAY,EAAmB,QAC/B,YAAY,GACZ,aAAa,GACb,YACA,QACA,aACA,OAAQ,EACR,GAAG,GACC,EAAqB,YAAa,CAAK,EACrC,EAAI,EAAe,GACnB,EAAU,EAAuB,IAAI,EACrC,EAAe,EAAuB,IAAI,EAE1C,CAAC,EAAY,GAAiB,EAAS,GAAY,CAAS,EAC5D,CAAC,EAAY,GAAiB,EAAwB,IAAI,EAEh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AC,MAAD,CACE,IAAK,EACL,UAAW,EAAG,EAAE,cAAe,GAAc,EAAE,oBAAqB,GAAY,IAAI,EACpF,MAAO,CAAE,GAAG,EAAW,GAAG,GAAY,IAAK,WAE3C,EAAC,MAAD,CAAK,UAAW,EAAG,EAAE,mBAAoB,GAAY,SAAS,EAAG,MAAO,GAAY,UAAW,IAAK,EACjG,UACE,CAAA,CACF,CAAA,CACF,GAET"}
@@ -1,2 +1,2 @@
1
- import e from"../interactableDiv/index.mjs";import{Align as t}from"../floatingMenu/floatingMenu.types.mjs";import n from"../floatingMenu/floatingMenu.mjs";import r from"../input/input.mjs";import i from"./colorPicker.module.mjs";import{useRef as a,useState as o}from"react";import s from"classnames";import{FontAwesomeIcon as c}from"@fortawesome/react-fontawesome";import{faEyeDropper as l}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var f=typeof window<`u`&&`EyeDropper`in window;async function p(){let e=window.EyeDropper;if(!e)return null;try{return(await new e().open()).sRGBHex}catch{return null}}function m(e){return/^#[0-9a-fA-F]{6}$/.test(e)||/^#[0-9a-fA-F]{8}$/.test(e)}function h(e){return/^#[0-9a-fA-F]{8}$/.test(e)?{hex6:e.slice(0,7),alpha:Math.round(parseInt(e.slice(7,9),16)/255*100)}:{hex6:e.slice(0,7),alpha:100}}function g(e,t,n){return!n||t>=100?e:`${e}${Math.round(t/100*255).toString(16).padStart(2,`0`)}`}function _(e,t){return`rgba(${parseInt(e.slice(1,3),16)}, ${parseInt(e.slice(3,5),16)}, ${parseInt(e.slice(5,7),16)}, ${t/100})`}function v(e){let t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,r=parseInt(e.slice(5,7),16)/255,i=Math.max(t,n,r),a=i-Math.min(t,n,r),o=0;a!==0&&(o=i===t?(n-r)/a%6:i===n?(r-t)/a+2:(t-n)/a+4,o=Math.round(o*60),o<0&&(o+=360));let s=i===0?0:Math.round(a/i*100),c=Math.round(i*100);return{h:o,s,v:c}}function y(e,t,n){let r=t/100,i=n/100,a=i*r,o=a*(1-Math.abs(e/60%2-1)),s=i-a,c=0,l=0,u=0;e<60?(c=a,l=o,u=0):e<120?(c=o,l=a,u=0):e<180?(c=0,l=a,u=o):e<240?(c=0,l=o,u=a):e<300?(c=o,l=0,u=a):(c=a,l=0,u=o);let d=e=>Math.round((e+s)*255).toString(16).padStart(2,`0`);return`#${d(c)}${d(l)}${d(u)}`}function b({hex:e,onChange:t,useInputComponent:n=!1}){let[a,s]=o(e),[c,l]=o(e);e!==c&&(l(e),s(e));function d(e){s(e);let n=e.startsWith(`#`)?e:`#${e}`;m(n)&&t(n)}function f(){m(a.startsWith(`#`)?a:`#${a}`)||s(e)}return n?u(r,{value:a,onChange:e=>d(e),onBlur:f}):u(`input`,{type:`text`,value:a,onChange:e=>d(e.target.value),onBlur:f,className:i.hexInput,spellCheck:!1})}function x({hue:e,sat:t,val:n,alpha:r,onHueChange:o,onSVChange:s,onAlphaChange:m,showInput:_=!0,showAlpha:x=!1}){let S=a(null);function C(e){let t=S.current.getBoundingClientRect(),n=Math.max(0,Math.min(1,(e.clientX-t.left)/t.width)),r=Math.max(0,Math.min(1,(e.clientY-t.top)/t.height));return{s:n*100,v:(1-r)*100}}function w(e){e.currentTarget.setPointerCapture(e.pointerId);let{s:t,v:n}=C(e);s(t,n);let r=e=>{let{s:t,v:n}=C(e);s(t,n)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i)};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)}function T(e){let{hex6:t,alpha:n}=h(e),{h:r,s:i,v:a}=v(t);o(r),s(i,a),x&&m(n)}let E=y(e,t,n),D=x?g(E,r,!0):E;return d(`div`,{className:i.panel,children:[d(`div`,{ref:S,className:i.gradientArea,style:{"--hue":e},onPointerDown:w,children:[u(`div`,{className:i.gradientOverlay}),u(`div`,{className:i.cursor,style:{left:`${t}%`,top:`${100-n}%`}})]}),u(`input`,{type:`range`,min:0,max:359,value:e,onChange:e=>o(Number(e.target.value)),className:i.hueSlider}),x&&u(`input`,{type:`range`,min:0,max:100,value:r,onChange:e=>m(Number(e.target.value)),className:i.alphaSlider,style:{"--alpha-color":E}}),(_||f)&&d(`div`,{className:i.hexRow,children:[_&&u(b,{hex:D,onChange:T}),f&&u(`button`,{type:`button`,className:i.eyeDropperButton,onClick:async()=>{let e=await p();e&&T(e)},"aria-label":`Pick color from screen`,children:u(c,{icon:l})})]})]})}var S=`#3b82f6`;function C({className:r,value:c=S,onChange:l,showInput:f=!1,showAlpha:p=!1,inline:C=!1,...w}){let[T,E]=o(!1),{hex6:D,alpha:O}=h(m(c)?c:S),k=v(D),[A,j]=o({h:k.h,s:k.s,v:k.v,a:O}),M=a(A),[N,P]=o(c);if(c!==N){P(c);let{hex6:e,alpha:t}=h(m(c)?c:S);if(e!==y(A.h,A.s,A.v)||t!==A.a){let n=v(e);j({h:n.h,s:n.s,v:n.v,a:t})}}let{h:F,s:I,v:L,a:R}=A;function z(e,t,n,r){l?.(g(y(e,t,n),r,p))}function B(e){M.current.h=e,j(t=>({...t,h:e})),z(e,M.current.s,M.current.v,M.current.a)}function V(e,t){M.current.s=e,M.current.v=t,j(n=>({...n,s:e,v:t})),z(M.current.h,e,t,M.current.a)}function H(e){M.current.a=e,j(t=>({...t,a:e})),z(M.current.h,M.current.s,M.current.v,e)}let U=y(F,I,L),W=p?_(U,R):U,G=g(U,R,p),K={hue:F,sat:I,val:L,alpha:R,onHueChange:B,onSVChange:V,onAlphaChange:H,showAlpha:p};return C?u(`div`,{...w,className:s(i.colorPicker,r),children:u(x,{...K,showInput:f})}):d(`div`,{...w,className:s(i.colorPicker,r),children:[u(n,{isOpen:T,onOpenChange:E,dontCloseOnChildClick:!0,align:t.Left,content:u(x,{...K}),children:d(e,{className:i.swatch,children:[u(`div`,{className:i.swatchFill,style:{background:W}}),u(`span`,{className:i.swatchHex,children:G})]})}),f&&u(b,{hex:G,onChange:e=>l?.(e),useInputComponent:!0})]})}export{C as default};
1
+ import e from"../interactableDiv/index.mjs";import{Align as t}from"../floatingMenu/floatingMenu.types.mjs";import n from"../floatingMenu/floatingMenu.mjs";import r from"../input/input.mjs";import i from"./colorPicker.module.mjs";import{useRef as a,useState as o}from"react";import s from"classnames";import{FontAwesomeIcon as c}from"@fortawesome/react-fontawesome";import{faEyeDropper as l}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var f=typeof window<`u`&&`EyeDropper`in window;async function p(){let e=window.EyeDropper;if(!e)return null;try{return(await new e().open()).sRGBHex}catch{return null}}function m(e){return/^#[0-9a-fA-F]{6}$/.test(e)||/^#[0-9a-fA-F]{8}$/.test(e)}function h(e){return/^#[0-9a-fA-F]{8}$/.test(e)?{hex6:e.slice(0,7),alpha:parseInt(e.slice(7,9),16)/255*100}:{hex6:e.slice(0,7),alpha:100}}function g(e,t,n){return!n||t>=100?e:`${e}${Math.round(t/100*255).toString(16).padStart(2,`0`)}`}function _(e,t){return`rgba(${parseInt(e.slice(1,3),16)}, ${parseInt(e.slice(3,5),16)}, ${parseInt(e.slice(5,7),16)}, ${t/100})`}function v(e){let t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,r=parseInt(e.slice(5,7),16)/255,i=Math.max(t,n,r),a=i-Math.min(t,n,r),o=0;a!==0&&(o=i===t?(n-r)/a%6:i===n?(r-t)/a+2:(t-n)/a+4,o*=60,o<0&&(o+=360));let s=i===0?0:a/i*100,c=i*100;return{h:o,s,v:c}}function y(e,t,n){let r=t/100,i=n/100,a=i*r,o=a*(1-Math.abs(e/60%2-1)),s=i-a,c=0,l=0,u=0;e<60?(c=a,l=o,u=0):e<120?(c=o,l=a,u=0):e<180?(c=0,l=a,u=o):e<240?(c=0,l=o,u=a):e<300?(c=o,l=0,u=a):(c=a,l=0,u=o);let d=e=>Math.round((e+s)*255).toString(16).padStart(2,`0`);return`#${d(c)}${d(l)}${d(u)}`}function b({hex:e,onChange:t,useInputComponent:n=!1}){let[a,s]=o(e),[c,l]=o(e);e!==c&&(l(e),s(e));function d(e){s(e);let n=e.startsWith(`#`)?e:`#${e}`;m(n)&&t(n)}function f(){m(a.startsWith(`#`)?a:`#${a}`)||s(e)}return n?u(r,{value:a,onChange:e=>d(e),onBlur:f}):u(`input`,{type:`text`,value:a,onChange:e=>d(e.target.value),onBlur:f,className:i.hexInput,spellCheck:!1})}function x({hue:e,sat:t,val:n,alpha:r,onHueChange:o,onSVChange:s,onAlphaChange:m,showInput:_=!0,showAlpha:x=!1}){let S=a(null);function C(e){let t=S.current.getBoundingClientRect(),n=Math.max(0,Math.min(1,(e.clientX-t.left)/t.width)),r=Math.max(0,Math.min(1,(e.clientY-t.top)/t.height));return{s:n*100,v:(1-r)*100}}function w(e){e.currentTarget.setPointerCapture(e.pointerId);let{s:t,v:n}=C(e);s(t,n);let r=e=>{let{s:t,v:n}=C(e);s(t,n)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i)};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)}function T(e){let{hex6:t,alpha:n}=h(e),{h:r,s:i,v:a}=v(t);o(r),s(i,a),x&&m(n)}let E=y(e,t,n),D=x?g(E,r,!0):E;return d(`div`,{className:i.panel,children:[d(`div`,{ref:S,className:i.gradientArea,style:{"--hue":e},onPointerDown:w,children:[u(`div`,{className:i.gradientOverlay}),u(`div`,{className:i.cursor,style:{left:`${t}%`,top:`${100-n}%`}})]}),u(`input`,{type:`range`,min:0,max:359,value:Math.round(e),onChange:e=>o(Number(e.target.value)),className:i.hueSlider}),x&&u(`input`,{type:`range`,min:0,max:100,value:Math.round(r),onChange:e=>m(Number(e.target.value)),className:i.alphaSlider,style:{"--alpha-color":E}}),(_||f)&&d(`div`,{className:i.hexRow,children:[_&&u(b,{hex:D,onChange:T}),f&&u(`button`,{type:`button`,className:i.eyeDropperButton,onClick:async()=>{let e=await p();e&&T(e)},"aria-label":`Pick color from screen`,children:u(c,{icon:l})})]})]})}var S=`#3b82f6`;function C({className:r,value:c=S,onChange:l,showInput:f=!1,showAlpha:p=!1,inline:C=!1,...w}){let[T,E]=o(!1),{hex6:D,alpha:O}=h(m(c)?c:S),k=v(D),[A,j]=o({h:k.h,s:k.s,v:k.v,a:O}),M=a(A),[N,P]=o(c);if(c!==N){P(c);let{hex6:e,alpha:t}=h(m(c)?c:S);if(e!==y(A.h,A.s,A.v)||t!==A.a){let n=v(e);j({h:n.h,s:n.s,v:n.v,a:t})}}let{h:F,s:I,v:L,a:R}=A;function z(e,t,n,r){l?.(g(y(e,t,n),r,p))}function B(e){M.current.h=e,j(t=>({...t,h:e})),z(e,M.current.s,M.current.v,M.current.a)}function V(e,t){M.current.s=e,M.current.v=t,j(n=>({...n,s:e,v:t})),z(M.current.h,e,t,M.current.a)}function H(e){M.current.a=e,j(t=>({...t,a:e})),z(M.current.h,M.current.s,M.current.v,e)}let U=y(F,I,L),W=p?_(U,R):U,G=g(U,R,p),K={hue:F,sat:I,val:L,alpha:R,onHueChange:B,onSVChange:V,onAlphaChange:H,showAlpha:p};return C?u(`div`,{...w,className:s(i.colorPicker,r),children:u(x,{...K,showInput:f})}):d(`div`,{...w,className:s(i.colorPicker,r),children:[u(n,{isOpen:T,onOpenChange:E,dontCloseOnChildClick:!0,align:t.Left,content:u(x,{...K}),children:d(e,{className:i.swatch,children:[u(`div`,{className:i.swatchFill,style:{background:W}}),u(`span`,{className:i.swatchHex,children:G})]})}),f&&u(b,{hex:G,onChange:e=>l?.(e),useInputComponent:!0})]})}export{C as default};
2
2
  //# sourceMappingURL=colorPicker.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"colorPicker.mjs","names":[],"sources":["../../../../package/common/colorPicker/colorPicker.tsx"],"sourcesContent":["import { useState, useRef, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faEyeDropper } from '@fortawesome/free-solid-svg-icons';\n\nimport InteractableDiv from 'components/common/interactableDiv';\nimport FloatingMenu from 'components/common/floatingMenu';\nimport Input from 'components/common/input';\nimport { Align } from 'components/common/floatingMenu/floatingMenu.types';\nimport type { ColorPickerProps } from './colorPicker.types';\n\nimport styles from './colorPicker.module.pcss';\n\ninterface EyeDropperConstructor {\n new (): { open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }> };\n}\n\nconst eyeDropperSupported = typeof window !== 'undefined' && 'EyeDropper' in window;\n\nasync function pickColorFromScreen(): Promise<string | null> {\n const EyeDropperCtor = (window as unknown as { EyeDropper?: EyeDropperConstructor }).EyeDropper;\n if (!EyeDropperCtor) return null;\n try {\n const result = await new EyeDropperCtor().open();\n return result.sRGBHex;\n } catch {\n return null; // user cancelled or picker failed\n }\n}\n\n// ── Color utilities ──────────────────────────────────────────────────────────\n\nfunction isValidHex(s: string): boolean {\n return /^#[0-9a-fA-F]{6}$/.test(s) || /^#[0-9a-fA-F]{8}$/.test(s);\n}\n\n/** Split any valid hex into its 6-digit base and 0-100 alpha. */\nfunction parseHex(hex: string): { hex6: string; alpha: number } {\n if (/^#[0-9a-fA-F]{8}$/.test(hex)) {\n return {\n hex6: hex.slice(0, 7),\n alpha: Math.round((parseInt(hex.slice(7, 9), 16) / 255) * 100),\n };\n }\n return { hex6: hex.slice(0, 7), alpha: 100 };\n}\n\n/** Combine a 6-digit hex + 0-100 alpha into the right output format.\n * Full opacity (alpha === 100) is omitted — 6-digit hex implies opaque. */\nfunction buildValue(hex6: string, alpha: number, showAlpha: boolean): string {\n if (!showAlpha || alpha >= 100) return hex6;\n const a = Math.round((alpha / 100) * 255).toString(16).padStart(2, '0');\n return `${hex6}${a}`;\n}\n\nfunction hexToRgba(hex6: string, alpha: number): string {\n const r = parseInt(hex6.slice(1, 3), 16);\n const g = parseInt(hex6.slice(3, 5), 16);\n const b = parseInt(hex6.slice(5, 7), 16);\n return `rgba(${r}, ${g}, ${b}, ${alpha / 100})`;\n}\n\nfunction hexToHsv(hex6: string): { h: number; s: number; v: number } {\n const r = parseInt(hex6.slice(1, 3), 16) / 255;\n const g = parseInt(hex6.slice(3, 5), 16) / 255;\n const b = parseInt(hex6.slice(5, 7), 16) / 255;\n\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const delta = max - min;\n\n let h = 0;\n if (delta !== 0) {\n if (max === r) h = ((g - b) / delta) % 6;\n else if (max === g) h = (b - r) / delta + 2;\n else h = (r - g) / delta + 4;\n h = Math.round(h * 60);\n if (h < 0) h += 360;\n }\n\n const s = max === 0 ? 0 : Math.round((delta / max) * 100);\n const v = Math.round(max * 100);\n\n return { h, s, v };\n}\n\nfunction hsvToHex(h: number, s: number, v: number): string {\n const sv = s / 100;\n const vv = v / 100;\n const c = vv * sv;\n const x = c * (1 - Math.abs(((h / 60) % 2) - 1));\n const m = vv - c;\n\n let r = 0, g = 0, b = 0;\n if (h < 60) { r = c; g = x; b = 0; }\n else if (h < 120) { r = x; g = c; b = 0; }\n else if (h < 180) { r = 0; g = c; b = x; }\n else if (h < 240) { r = 0; g = x; b = c; }\n else if (h < 300) { r = x; g = 0; b = c; }\n else { r = c; g = 0; b = x; }\n\n const toHex = (n: number) => Math.round((n + m) * 255).toString(16).padStart(2, '0');\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n}\n\n// ── HexInput ─────────────────────────────────────────────────────────────────\n\ninterface HexInputProps {\n hex: string;\n onChange: (hex: string) => void;\n useInputComponent?: boolean;\n}\n\nfunction HexInput({ hex, onChange, useInputComponent = false }: HexInputProps): ReactElement {\n const [draft, setDraft] = useState(hex);\n\n const [prevHex, setPrevHex] = useState(hex);\n if (hex !== prevHex) {\n setPrevHex(hex);\n setDraft(hex);\n }\n\n function handleChange(raw: string) {\n setDraft(raw);\n const normalized = raw.startsWith('#') ? raw : `#${raw}`;\n if (isValidHex(normalized)) onChange(normalized);\n }\n\n function handleBlur() {\n const normalized = draft.startsWith('#') ? draft : `#${draft}`;\n if (!isValidHex(normalized)) setDraft(hex);\n }\n\n if (useInputComponent) {\n return (\n <Input\n value={draft}\n onChange={(value: string) => handleChange(value)}\n onBlur={handleBlur}\n />\n );\n }\n\n return (\n <input\n type=\"text\"\n value={draft}\n onChange={(e) => handleChange(e.target.value)}\n onBlur={handleBlur}\n className={styles.hexInput}\n spellCheck={false}\n />\n );\n}\n\n// ── Picker panel ─────────────────────────────────────────────────────────────\n\ninterface PickerPanelProps {\n hue: number;\n sat: number;\n val: number;\n alpha: number;\n onHueChange: (h: number) => void;\n onSVChange: (s: number, v: number) => void;\n onAlphaChange: (a: number) => void;\n showInput?: boolean;\n showAlpha?: boolean;\n}\n\nfunction PickerPanel({\n hue, sat, val, alpha,\n onHueChange, onSVChange, onAlphaChange,\n showInput = true, showAlpha = false,\n}: PickerPanelProps): ReactElement {\n const gradientRef = useRef<HTMLDivElement>(null);\n\n function getSVFromEvent(e: { clientX: number; clientY: number }): { s: number; v: number } {\n const rect = gradientRef.current!.getBoundingClientRect();\n const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));\n const y = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));\n return { s: x * 100, v: (1 - y) * 100 };\n }\n\n // Pointer Events (not mouse events) so dragging works for touch/pen too.\n function onGradientPointerDown(e: React.PointerEvent) {\n e.currentTarget.setPointerCapture(e.pointerId);\n const { s, v } = getSVFromEvent(e);\n onSVChange(s, v);\n\n const onMove = (ev: PointerEvent) => {\n const { s, v } = getSVFromEvent(ev);\n onSVChange(s, v);\n };\n const onUp = () => {\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onUp);\n };\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onUp);\n }\n\n function onHexChange(normalized: string) {\n const { hex6, alpha: parsedAlpha } = parseHex(normalized);\n const { h, s, v } = hexToHsv(hex6);\n onHueChange(h);\n onSVChange(s, v);\n if (showAlpha) onAlphaChange(parsedAlpha);\n }\n\n const hex6 = hsvToHex(hue, sat, val);\n const hexInputValue = showAlpha ? buildValue(hex6, alpha, true) : hex6;\n\n return (\n <div className={styles.panel}>\n <div\n ref={gradientRef}\n className={styles.gradientArea}\n style={{ '--hue': hue } as React.CSSProperties}\n onPointerDown={onGradientPointerDown}\n >\n <div className={styles.gradientOverlay} />\n <div\n className={styles.cursor}\n style={{ left: `${sat}%`, top: `${100 - val}%` }}\n />\n </div>\n\n <input\n type=\"range\"\n min={0}\n max={359}\n value={hue}\n onChange={(e) => onHueChange(Number(e.target.value))}\n className={styles.hueSlider}\n />\n\n {showAlpha && (\n <input\n type=\"range\"\n min={0}\n max={100}\n value={alpha}\n onChange={(e) => onAlphaChange(Number(e.target.value))}\n className={styles.alphaSlider}\n style={{ '--alpha-color': hex6 } as React.CSSProperties}\n />\n )}\n\n {(showInput || eyeDropperSupported) && (\n <div className={styles.hexRow}>\n {showInput && <HexInput hex={hexInputValue} onChange={onHexChange} />}\n {eyeDropperSupported && (\n <button\n type=\"button\"\n className={styles.eyeDropperButton}\n onClick={async () => {\n const hex = await pickColorFromScreen();\n if (hex) onHexChange(hex);\n }}\n aria-label=\"Pick color from screen\"\n >\n <FontAwesomeIcon icon={faEyeDropper} />\n </button>\n )}\n </div>\n )}\n </div>\n );\n}\n\n// ── ColorPicker ───────────────────────────────────────────────────────────────\n\nconst DEFAULT_COLOR = '#3b82f6';\n\nfunction ColorPicker({\n className,\n value = DEFAULT_COLOR,\n onChange,\n showInput = false,\n showAlpha = false,\n inline = false,\n ...rest\n}: ColorPickerProps): ReactElement {\n const [isOpen, setIsOpen] = useState(false);\n\n const initSafe = isValidHex(value) ? value : DEFAULT_COLOR;\n const { hex6: initHex6, alpha: initAlpha } = parseHex(initSafe);\n const initHsv = hexToHsv(initHex6);\n\n // Single state object so hue survives when saturation/value hit 0\n // (hexToHsv of any grey returns h=0, which would corrupt hue if derived from props).\n const [hsva, setHsva] = useState({ h: initHsv.h, s: initHsv.s, v: initHsv.v, a: initAlpha });\n\n // Ref mirrors state so drag callbacks never read stale closure values.\n const cur = useRef(hsva);\n\n // Sync from external prop changes: \"derive state during render\" pattern\n // avoids setState-in-effect. We compare the incoming hex against what our\n // current state produces — if they match, the change came from us and we skip.\n const [prevValue, setPrevValue] = useState(value);\n if (value !== prevValue) {\n setPrevValue(value);\n const safe = isValidHex(value) ? value : DEFAULT_COLOR;\n const { hex6: incomingHex6, alpha: incomingA } = parseHex(safe);\n const currentHex6 = hsvToHex(hsva.h, hsva.s, hsva.v);\n if (incomingHex6 !== currentHex6 || incomingA !== hsva.a) {\n const hsv = hexToHsv(incomingHex6);\n const next = { h: hsv.h, s: hsv.s, v: hsv.v, a: incomingA };\n setHsva(next);\n }\n }\n\n const { h: hue, s: sat, v: val, a: alpha } = hsva;\n\n function emit(h: number, s: number, v: number, a: number) {\n onChange?.(buildValue(hsvToHex(h, s, v), a, showAlpha));\n }\n\n function handleHueChange(h: number) {\n cur.current.h = h;\n setHsva(prev => ({ ...prev, h }));\n emit(h, cur.current.s, cur.current.v, cur.current.a);\n }\n\n function handleSVChange(s: number, v: number) {\n cur.current.s = s;\n cur.current.v = v;\n setHsva(prev => ({ ...prev, s, v }));\n emit(cur.current.h, s, v, cur.current.a);\n }\n\n function handleAlphaChange(a: number) {\n cur.current.a = a;\n setHsva(prev => ({ ...prev, a }));\n emit(cur.current.h, cur.current.s, cur.current.v, a);\n }\n\n const hex6 = hsvToHex(hue, sat, val);\n const swatchBackground = showAlpha ? hexToRgba(hex6, alpha) : hex6;\n const displayValue = buildValue(hex6, alpha, showAlpha);\n\n const pickerPanelProps: PickerPanelProps = {\n hue, sat, val, alpha,\n onHueChange: handleHueChange,\n onSVChange: handleSVChange,\n onAlphaChange: handleAlphaChange,\n showAlpha,\n };\n\n if (inline) {\n return (\n <div {...rest} className={cx(styles.colorPicker, className)}>\n <PickerPanel {...pickerPanelProps} showInput={showInput} />\n </div>\n );\n }\n\n return (\n <div {...rest} className={cx(styles.colorPicker, className)}>\n <FloatingMenu\n isOpen={isOpen}\n onOpenChange={setIsOpen}\n dontCloseOnChildClick\n align={Align.Left}\n content={<PickerPanel {...pickerPanelProps} />}\n >\n <InteractableDiv className={styles.swatch}>\n <div className={styles.swatchFill} style={{ background: swatchBackground }} />\n <span className={styles.swatchHex}>{displayValue}</span>\n </InteractableDiv>\n </FloatingMenu>\n\n {showInput && (\n <HexInput\n hex={displayValue}\n onChange={(v) => onChange?.(v)}\n useInputComponent\n />\n )}\n </div>\n );\n}\n\nexport default ColorPicker;\n"],"mappings":"geAiBA,IAAM,EAAsB,OAAO,OAAW,KAAe,eAAgB,OAE7E,eAAe,GAA8C,CAC3D,IAAM,EAAkB,OAA6D,WACrF,GAAI,CAAC,EAAgB,OAAO,KAC5B,GAAI,CAEF,OAAO,MADc,IAAI,EAAe,EAAE,KAAK,GACjC,OAChB,MAAQ,CACN,OAAO,IACT,CACF,CAIA,SAAS,EAAW,EAAoB,CACtC,MAAO,oBAAoB,KAAK,CAAC,GAAK,oBAAoB,KAAK,CAAC,CAClE,CAGA,SAAS,EAAS,EAA8C,CAO9D,MANI,oBAAoB,KAAK,CAAG,EACvB,CACL,KAAM,EAAI,MAAM,EAAG,CAAC,EACpB,MAAO,KAAK,MAAO,SAAS,EAAI,MAAM,EAAG,CAAC,EAAG,EAAE,EAAI,IAAO,GAAG,CAC/D,EAEK,CAAE,KAAM,EAAI,MAAM,EAAG,CAAC,EAAG,MAAO,GAAI,CAC7C,CAIA,SAAS,EAAW,EAAc,EAAe,EAA4B,CAG3E,MAFI,CAAC,GAAa,GAAS,IAAY,EAEhC,GAAG,IADA,KAAK,MAAO,EAAQ,IAAO,GAAG,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAClD,GACnB,CAEA,SAAS,EAAU,EAAc,EAAuB,CAItD,MAAO,QAHG,SAAS,EAAK,MAAM,EAAG,CAAC,EAAG,EAGtB,EAAE,IAFP,SAAS,EAAK,MAAM,EAAG,CAAC,EAAG,EAEhB,EAAE,IADb,SAAS,EAAK,MAAM,EAAG,CAAC,EAAG,EACV,EAAE,IAAI,EAAQ,IAAI,EA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CAAK,UAAW,EAAO,WAAY,MAAO,CAAE,WAAY,CAAiB,CAAI,CAAA,EAC7E,EAAC,OAAD,CAAM,UAAW,EAAO,mBAAY,CAAmB,CAAA,CACxC,GACL,CAAA,EAEb,GACC,EAAC,EAAD,CACE,IAAK,EACL,SAAW,GAAM,IAAW,CAAC,EAC7B,kBAAA,EACD,CAAA,CAEA,GAET"}
1
+ {"version":3,"file":"colorPicker.mjs","names":[],"sources":["../../../../package/common/colorPicker/colorPicker.tsx"],"sourcesContent":["import { useState, useRef, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faEyeDropper } from '@fortawesome/free-solid-svg-icons';\n\nimport InteractableDiv from 'components/common/interactableDiv';\nimport FloatingMenu from 'components/common/floatingMenu';\nimport Input from 'components/common/input';\nimport { Align } from 'components/common/floatingMenu/floatingMenu.types';\nimport type { ColorPickerProps } from './colorPicker.types';\n\nimport styles from './colorPicker.module.pcss';\n\ninterface EyeDropperConstructor {\n new (): { open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }> };\n}\n\nconst eyeDropperSupported = typeof window !== 'undefined' && 'EyeDropper' in window;\n\nasync function pickColorFromScreen(): Promise<string | null> {\n const EyeDropperCtor = (window as unknown as { EyeDropper?: EyeDropperConstructor }).EyeDropper;\n if (!EyeDropperCtor) return null;\n try {\n const result = await new EyeDropperCtor().open();\n return result.sRGBHex;\n } catch {\n return null; // user cancelled or picker failed\n }\n}\n\n// ── Color utilities ──────────────────────────────────────────────────────────\n\nfunction isValidHex(s: string): boolean {\n return /^#[0-9a-fA-F]{6}$/.test(s) || /^#[0-9a-fA-F]{8}$/.test(s);\n}\n\n/** Split any valid hex into its 6-digit base and 0-100 alpha. */\nfunction parseHex(hex: string): { hex6: string; alpha: number } {\n if (/^#[0-9a-fA-F]{8}$/.test(hex)) {\n return {\n hex6: hex.slice(0, 7),\n alpha: (parseInt(hex.slice(7, 9), 16) / 255) * 100,\n };\n }\n return { hex6: hex.slice(0, 7), alpha: 100 };\n}\n\n/** Combine a 6-digit hex + 0-100 alpha into the right output format.\n * Full opacity (alpha === 100) is omitted — 6-digit hex implies opaque. */\nfunction buildValue(hex6: string, alpha: number, showAlpha: boolean): string {\n if (!showAlpha || alpha >= 100) return hex6;\n const a = Math.round((alpha / 100) * 255).toString(16).padStart(2, '0');\n return `${hex6}${a}`;\n}\n\nfunction hexToRgba(hex6: string, alpha: number): string {\n const r = parseInt(hex6.slice(1, 3), 16);\n const g = parseInt(hex6.slice(3, 5), 16);\n const b = parseInt(hex6.slice(5, 7), 16);\n return `rgba(${r}, ${g}, ${b}, ${alpha / 100})`;\n}\n\nfunction hexToHsv(hex6: string): { h: number; s: number; v: number } {\n const r = parseInt(hex6.slice(1, 3), 16) / 255;\n const g = parseInt(hex6.slice(3, 5), 16) / 255;\n const b = parseInt(hex6.slice(5, 7), 16) / 255;\n\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const delta = max - min;\n\n let h = 0;\n if (delta !== 0) {\n if (max === r) h = ((g - b) / delta) % 6;\n else if (max === g) h = (b - r) / delta + 2;\n else h = (r - g) / delta + 4;\n h *= 60;\n if (h < 0) h += 360;\n }\n\n // Deliberately unrounded: hsvToHex rounds once, at the byte. Rounding here too costs up to a\n // unit per channel, so a value handed in would come back out changed (#3b82f6 -> #3b82f5).\n const s = max === 0 ? 0 : (delta / max) * 100;\n const v = max * 100;\n\n return { h, s, v };\n}\n\nfunction hsvToHex(h: number, s: number, v: number): string {\n const sv = s / 100;\n const vv = v / 100;\n const c = vv * sv;\n const x = c * (1 - Math.abs(((h / 60) % 2) - 1));\n const m = vv - c;\n\n let r = 0, g = 0, b = 0;\n if (h < 60) { r = c; g = x; b = 0; }\n else if (h < 120) { r = x; g = c; b = 0; }\n else if (h < 180) { r = 0; g = c; b = x; }\n else if (h < 240) { r = 0; g = x; b = c; }\n else if (h < 300) { r = x; g = 0; b = c; }\n else { r = c; g = 0; b = x; }\n\n const toHex = (n: number) => Math.round((n + m) * 255).toString(16).padStart(2, '0');\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n}\n\n// ── HexInput ─────────────────────────────────────────────────────────────────\n\ninterface HexInputProps {\n hex: string;\n onChange: (hex: string) => void;\n useInputComponent?: boolean;\n}\n\nfunction HexInput({ hex, onChange, useInputComponent = false }: HexInputProps): ReactElement {\n const [draft, setDraft] = useState(hex);\n\n const [prevHex, setPrevHex] = useState(hex);\n if (hex !== prevHex) {\n setPrevHex(hex);\n setDraft(hex);\n }\n\n function handleChange(raw: string) {\n setDraft(raw);\n const normalized = raw.startsWith('#') ? raw : `#${raw}`;\n if (isValidHex(normalized)) onChange(normalized);\n }\n\n function handleBlur() {\n const normalized = draft.startsWith('#') ? draft : `#${draft}`;\n if (!isValidHex(normalized)) setDraft(hex);\n }\n\n if (useInputComponent) {\n return (\n <Input\n value={draft}\n onChange={(value: string) => handleChange(value)}\n onBlur={handleBlur}\n />\n );\n }\n\n return (\n <input\n type=\"text\"\n value={draft}\n onChange={(e) => handleChange(e.target.value)}\n onBlur={handleBlur}\n className={styles.hexInput}\n spellCheck={false}\n />\n );\n}\n\n// ── Picker panel ─────────────────────────────────────────────────────────────\n\ninterface PickerPanelProps {\n hue: number;\n sat: number;\n val: number;\n alpha: number;\n onHueChange: (h: number) => void;\n onSVChange: (s: number, v: number) => void;\n onAlphaChange: (a: number) => void;\n showInput?: boolean;\n showAlpha?: boolean;\n}\n\nfunction PickerPanel({\n hue, sat, val, alpha,\n onHueChange, onSVChange, onAlphaChange,\n showInput = true, showAlpha = false,\n}: PickerPanelProps): ReactElement {\n const gradientRef = useRef<HTMLDivElement>(null);\n\n function getSVFromEvent(e: { clientX: number; clientY: number }): { s: number; v: number } {\n const rect = gradientRef.current!.getBoundingClientRect();\n const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));\n const y = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));\n return { s: x * 100, v: (1 - y) * 100 };\n }\n\n // Pointer Events (not mouse events) so dragging works for touch/pen too.\n function onGradientPointerDown(e: React.PointerEvent) {\n e.currentTarget.setPointerCapture(e.pointerId);\n const { s, v } = getSVFromEvent(e);\n onSVChange(s, v);\n\n const onMove = (ev: PointerEvent) => {\n const { s, v } = getSVFromEvent(ev);\n onSVChange(s, v);\n };\n const onUp = () => {\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onUp);\n };\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onUp);\n }\n\n function onHexChange(normalized: string) {\n const { hex6, alpha: parsedAlpha } = parseHex(normalized);\n const { h, s, v } = hexToHsv(hex6);\n onHueChange(h);\n onSVChange(s, v);\n if (showAlpha) onAlphaChange(parsedAlpha);\n }\n\n const hex6 = hsvToHex(hue, sat, val);\n const hexInputValue = showAlpha ? buildValue(hex6, alpha, true) : hex6;\n\n return (\n <div className={styles.panel}>\n <div\n ref={gradientRef}\n className={styles.gradientArea}\n style={{ '--hue': hue } as React.CSSProperties}\n onPointerDown={onGradientPointerDown}\n >\n <div className={styles.gradientOverlay} />\n <div\n className={styles.cursor}\n style={{ left: `${sat}%`, top: `${100 - val}%` }}\n />\n </div>\n\n <input\n type=\"range\"\n min={0}\n max={359}\n value={Math.round(hue)}\n onChange={(e) => onHueChange(Number(e.target.value))}\n className={styles.hueSlider}\n />\n\n {showAlpha && (\n <input\n type=\"range\"\n min={0}\n max={100}\n value={Math.round(alpha)}\n onChange={(e) => onAlphaChange(Number(e.target.value))}\n className={styles.alphaSlider}\n style={{ '--alpha-color': hex6 } as React.CSSProperties}\n />\n )}\n\n {(showInput || eyeDropperSupported) && (\n <div className={styles.hexRow}>\n {showInput && <HexInput hex={hexInputValue} onChange={onHexChange} />}\n {eyeDropperSupported && (\n <button\n type=\"button\"\n className={styles.eyeDropperButton}\n onClick={async () => {\n const hex = await pickColorFromScreen();\n if (hex) onHexChange(hex);\n }}\n aria-label=\"Pick color from screen\"\n >\n <FontAwesomeIcon icon={faEyeDropper} />\n </button>\n )}\n </div>\n )}\n </div>\n );\n}\n\n// ── ColorPicker ───────────────────────────────────────────────────────────────\n\nconst DEFAULT_COLOR = '#3b82f6';\n\nfunction ColorPicker({\n className,\n value = DEFAULT_COLOR,\n onChange,\n showInput = false,\n showAlpha = false,\n inline = false,\n ...rest\n}: ColorPickerProps): ReactElement {\n const [isOpen, setIsOpen] = useState(false);\n\n const initSafe = isValidHex(value) ? value : DEFAULT_COLOR;\n const { hex6: initHex6, alpha: initAlpha } = parseHex(initSafe);\n const initHsv = hexToHsv(initHex6);\n\n // Single state object so hue survives when saturation/value hit 0\n // (hexToHsv of any grey returns h=0, which would corrupt hue if derived from props).\n const [hsva, setHsva] = useState({ h: initHsv.h, s: initHsv.s, v: initHsv.v, a: initAlpha });\n\n // Ref mirrors state so drag callbacks never read stale closure values.\n const cur = useRef(hsva);\n\n // Sync from external prop changes: \"derive state during render\" pattern\n // avoids setState-in-effect. We compare the incoming hex against what our\n // current state produces — if they match, the change came from us and we skip.\n const [prevValue, setPrevValue] = useState(value);\n if (value !== prevValue) {\n setPrevValue(value);\n const safe = isValidHex(value) ? value : DEFAULT_COLOR;\n const { hex6: incomingHex6, alpha: incomingA } = parseHex(safe);\n const currentHex6 = hsvToHex(hsva.h, hsva.s, hsva.v);\n if (incomingHex6 !== currentHex6 || incomingA !== hsva.a) {\n const hsv = hexToHsv(incomingHex6);\n const next = { h: hsv.h, s: hsv.s, v: hsv.v, a: incomingA };\n setHsva(next);\n }\n }\n\n const { h: hue, s: sat, v: val, a: alpha } = hsva;\n\n function emit(h: number, s: number, v: number, a: number) {\n onChange?.(buildValue(hsvToHex(h, s, v), a, showAlpha));\n }\n\n function handleHueChange(h: number) {\n cur.current.h = h;\n setHsva(prev => ({ ...prev, h }));\n emit(h, cur.current.s, cur.current.v, cur.current.a);\n }\n\n function handleSVChange(s: number, v: number) {\n cur.current.s = s;\n cur.current.v = v;\n setHsva(prev => ({ ...prev, s, v }));\n emit(cur.current.h, s, v, cur.current.a);\n }\n\n function handleAlphaChange(a: number) {\n cur.current.a = a;\n setHsva(prev => ({ ...prev, a }));\n emit(cur.current.h, cur.current.s, cur.current.v, a);\n }\n\n const hex6 = hsvToHex(hue, sat, val);\n const swatchBackground = showAlpha ? hexToRgba(hex6, alpha) : hex6;\n const displayValue = buildValue(hex6, alpha, showAlpha);\n\n const pickerPanelProps: PickerPanelProps = {\n hue, sat, val, alpha,\n onHueChange: handleHueChange,\n onSVChange: handleSVChange,\n onAlphaChange: handleAlphaChange,\n showAlpha,\n };\n\n if (inline) {\n return (\n <div {...rest} className={cx(styles.colorPicker, className)}>\n <PickerPanel {...pickerPanelProps} showInput={showInput} />\n </div>\n );\n }\n\n return (\n <div {...rest} className={cx(styles.colorPicker, className)}>\n <FloatingMenu\n isOpen={isOpen}\n onOpenChange={setIsOpen}\n dontCloseOnChildClick\n align={Align.Left}\n content={<PickerPanel {...pickerPanelProps} />}\n >\n <InteractableDiv className={styles.swatch}>\n <div className={styles.swatchFill} style={{ background: swatchBackground }} />\n <span className={styles.swatchHex}>{displayValue}</span>\n </InteractableDiv>\n </FloatingMenu>\n\n {showInput && (\n <HexInput\n hex={displayValue}\n onChange={(v) => onChange?.(v)}\n useInputComponent\n />\n )}\n </div>\n );\n}\n\nexport default ColorPicker;\n"],"mappings":"geAiBA,IAAM,EAAsB,OAAO,OAAW,KAAe,eAAgB,OAE7E,eAAe,GAA8C,CAC3D,IAAM,EAAkB,OAA6D,WACrF,GAAI,CAAC,EAAgB,OAAO,KAC5B,GAAI,CAEF,OAAO,MADc,IAAI,EAAe,EAAE,KAAK,GACjC,OAChB,MAAQ,CACN,OAAO,IACT,CACF,CAIA,SAAS,EAAW,EAAoB,CACtC,MAAO,oBAAoB,KAAK,CAAC,GAAK,oBAAoB,KAAK,CAAC,CAClE,CAGA,SAAS,EAAS,EAA8C,CAO9D,MANI,oBAAoB,KAAK,CAAG,EACvB,CACL,KAAM,EAAI,MAAM,EAAG,CAAC,EACpB,MAAQ,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,EACxD,EAAe,EAAW,EAAM,EAAO,CAAS,EAEhD,EAAqC,CACzC,MAAK,MAAK,MAAK,QACf,YAAa,EACb,WAAY,EACZ,cAAe,EACf,WACF,EAUA,OARI,EAEA,EAAC,MAAD,CAAK,GAAI,EAAM,UAAW,EAAG,EAAO,YAAa,CAAS,WACxD,EAAC,EAAD,CAAa,GAAI,EAA6B,WAAY,CAAA,CACvD,CAAA,EAKP,EAAC,MAAD,CAAK,GAAI,EAAM,UAAW,EAAG,EAAO,YAAa,CAAS,WAA1D,CACE,EAAC,EAAD,CACU,SACR,aAAc,EACd,sBAAA,GACA,MAAO,EAAM,KACb,QAAS,EAAC,EAAD,CAAa,GAAI,CAAmB,CAAA,WAE7C,EAAC,EAAD,CAAiB,UAAW,EAAO,gBAAnC,CACE,EAAC,MAAD,CAAK,UAAW,EAAO,WAAY,MAAO,CAAE,WAAY,CAAiB,CAAI,CAAA,EAC7E,EAAC,OAAD,CAAM,UAAW,EAAO,mBAAY,CAAmB,CAAA,CACxC,GACL,CAAA,EAEb,GACC,EAAC,EAAD,CACE,IAAK,EACL,SAAW,GAAM,IAAW,CAAC,EAC7B,kBAAA,EACD,CAAA,CAEA,GAET"}
@@ -1,2 +1,2 @@
1
- import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{ButtonStyleType as t}from"../button/button.types.mjs";import n from"../actionButtons/actionButtons.mjs";import r from"../modal/modal.mjs";import{useState as i}from"react";import{jsx as a,jsxs as o}from"react/jsx-runtime";function s(s){let{children:c=null,className:l=``,onClose:u=()=>{},onConfirm:d=()=>{},title:f=``,content:p=null,isOpen:m=void 0,submitLabel:h=`Confirm`,cancelLabel:g=`Cancel`,isDelete:_=!1,actionButtonsProps:v={}}=e(`ConfirmModal`,s),[y,b]=i(!1),[x,S]=i(!1);function C(e=!1){b(!1),u(e)}async function w(){S(!0);try{await d(),C(!0)}finally{S(!1)}}let T=o(r,{title:f,isOpen:m===void 0?y:m,onClose:()=>C(),className:c?void 0:l,children:[p,a(n,{onClose:()=>C(),onSubmit:w,submitLabel:h,cancelLabel:g,submitButtonStyle:_?t.Delete:void 0,isSubmitButtonLoading:x,...v})]});return c?o(`div`,{className:l,children:[a(`span`,{onClick:()=>b(!0),children:c}),T]}):T}export{s as default};
1
+ import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{ButtonStyleType as t}from"../button/button.types.mjs";import n from"../actionButtons/actionButtons.mjs";import r from"../modal/modal.mjs";import{useState as i}from"react";import{jsx as a,jsxs as o}from"react/jsx-runtime";function s(s){let{children:c=null,className:l=``,onClose:u=()=>{},onConfirm:d=()=>{},title:f=``,content:p=null,isOpen:m=void 0,submitLabel:h=`Confirm`,cancelLabel:g=`Cancel`,isDelete:_=!1,actionButtonsProps:v={}}=e(`ConfirmModal`,s),[y,b]=i(!1),[x,S]=i(!1);function C(e=!1){b(!1),u(e)}async function w(){S(!0);try{await d(),C(!0)}catch{}finally{S(!1)}}let T=o(r,{title:f,isOpen:m===void 0?y:m,onClose:()=>C(),className:c?void 0:l,children:[p,a(n,{onClose:()=>C(),onSubmit:w,submitLabel:h,cancelLabel:g,submitButtonStyle:_?t.Delete:void 0,isSubmitButtonLoading:x,...v})]});return c?o(`div`,{className:l,children:[a(`span`,{onClick:()=>b(!0),children:c}),T]}):T}export{s as default};
2
2
  //# sourceMappingURL=confirmModal.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"confirmModal.mjs","names":[],"sources":["../../../../package/common/confirmModal/confirmModal.tsx"],"sourcesContent":["import { useState, type ReactElement } from 'react';\n\nimport Modal from '../modal';\nimport { ActionButtons } from '../actionButtons';\nimport { ButtonStyleType } from '../button';\nimport { useComponentDefaults } from '../configProvider';\nimport type { ConfirmModalProps } from './confirmModal.types';\n\nfunction ConfirmModal(props: ConfirmModalProps): ReactElement {\n const {\n children = null,\n className = '',\n onClose = () => {},\n onConfirm = () => {},\n title = '',\n content = null,\n isOpen: propIsOpen = undefined,\n submitLabel = 'Confirm',\n cancelLabel = 'Cancel',\n isDelete = false,\n actionButtonsProps = {},\n } = useComponentDefaults('ConfirmModal', props);\n const [internalOpen, setInternalOpen] = useState(false);\n const [isSubmitting, setIsSubmitting] = useState(false);\n\n function handleClose(didSubmit = false) {\n setInternalOpen(false);\n onClose(didSubmit);\n }\n\n async function handleConfirm() {\n setIsSubmitting(true);\n try {\n await onConfirm();\n handleClose(true);\n } finally {\n setIsSubmitting(false);\n }\n }\n\n const isOpen = propIsOpen === undefined ? internalOpen : propIsOpen;\n\n const modal = (\n <Modal title={title} isOpen={isOpen} onClose={() => handleClose()} className={children ? undefined : className}>\n {content}\n <ActionButtons\n onClose={() => handleClose()}\n onSubmit={handleConfirm}\n submitLabel={submitLabel}\n cancelLabel={cancelLabel}\n submitButtonStyle={isDelete ? ButtonStyleType.Delete : undefined}\n isSubmitButtonLoading={isSubmitting}\n {...actionButtonsProps}\n />\n </Modal>\n );\n\n if (!children) return modal;\n\n return (\n <div className={className}>\n <span onClick={() => setInternalOpen(true)}>{children}</span>\n {modal}\n </div>\n );\n}\n\nexport default ConfirmModal;\n"],"mappings":"sTAQA,SAAS,EAAa,EAAwC,CAC5D,GAAM,CACN,WAAW,KACX,YAAY,GACZ,cAAgB,CAAC,EACjB,gBAAkB,CAAC,EACnB,QAAQ,GACR,UAAU,KACV,OAAQ,EAAa,IAAA,GACrB,cAAc,UACd,cAAc,SACd,WAAW,GACX,qBAAqB,CAAC,GAClB,EAAqB,eAAgB,CAAK,EACxC,CAAC,EAAc,GAAmB,EAAS,EAAK,EAChD,CAAC,EAAc,GAAmB,EAAS,EAAK,EAEtD,SAAS,EAAY,EAAY,GAAO,CACtC,EAAgB,EAAK,EACrB,EAAQ,CAAS,CACnB,CAEA,eAAe,GAAgB,CAC7B,EAAgB,EAAI,EACpB,GAAI,CACF,MAAM,EAAU,EAChB,EAAY,EAAI,CAClB,QAAU,CACR,EAAgB,EAAK,CACvB,CACF,CAIA,IAAM,EACJ,EAAC,EAAD,CAAc,QAAe,OAHhB,IAAe,IAAA,GAAY,EAAe,EAGlB,YAAe,EAAY,EAAG,UAAW,EAAW,IAAA,GAAY,WAArG,CACG,EACD,EAAC,EAAD,CACE,YAAe,EAAY,EAC3B,SAAU,EACG,cACA,cACb,kBAAmB,EAAW,EAAgB,OAAS,IAAA,GACvD,sBAAuB,EACvB,GAAI,CACL,CAAA,CACI,IAKT,OAFK,EAGH,EAAC,MAAD,CAAgB,qBAAhB,CACE,EAAC,OAAD,CAAM,YAAe,EAAgB,EAAI,EAAI,UAAe,CAAA,EAC3D,CACE,IANe,CAQxB"}
1
+ {"version":3,"file":"confirmModal.mjs","names":[],"sources":["../../../../package/common/confirmModal/confirmModal.tsx"],"sourcesContent":["import { useState, type ReactElement } from 'react';\n\nimport Modal from '../modal';\nimport { ActionButtons } from '../actionButtons';\nimport { ButtonStyleType } from '../button';\nimport { useComponentDefaults } from '../configProvider';\nimport type { ConfirmModalProps } from './confirmModal.types';\n\nfunction ConfirmModal(props: ConfirmModalProps): ReactElement {\n const {\n children = null,\n className = '',\n onClose = () => {},\n onConfirm = () => {},\n title = '',\n content = null,\n isOpen: propIsOpen = undefined,\n submitLabel = 'Confirm',\n cancelLabel = 'Cancel',\n isDelete = false,\n actionButtonsProps = {},\n } = useComponentDefaults('ConfirmModal', props);\n const [internalOpen, setInternalOpen] = useState(false);\n const [isSubmitting, setIsSubmitting] = useState(false);\n\n function handleClose(didSubmit = false) {\n setInternalOpen(false);\n onClose(didSubmit);\n }\n\n async function handleConfirm() {\n setIsSubmitting(true);\n try {\n await onConfirm();\n handleClose(true);\n } catch {\n // Nothing is awaiting this handler, so a rejection would surface as an unhandled one.\n // The dialog staying open is the signal that the action did not go through; reporting\n // the failure itself belongs to whoever wrote `onConfirm`.\n } finally {\n setIsSubmitting(false);\n }\n }\n\n const isOpen = propIsOpen === undefined ? internalOpen : propIsOpen;\n\n const modal = (\n <Modal title={title} isOpen={isOpen} onClose={() => handleClose()} className={children ? undefined : className}>\n {content}\n <ActionButtons\n onClose={() => handleClose()}\n onSubmit={handleConfirm}\n submitLabel={submitLabel}\n cancelLabel={cancelLabel}\n submitButtonStyle={isDelete ? ButtonStyleType.Delete : undefined}\n isSubmitButtonLoading={isSubmitting}\n {...actionButtonsProps}\n />\n </Modal>\n );\n\n if (!children) return modal;\n\n return (\n <div className={className}>\n <span onClick={() => setInternalOpen(true)}>{children}</span>\n {modal}\n </div>\n );\n}\n\nexport default ConfirmModal;\n"],"mappings":"sTAQA,SAAS,EAAa,EAAwC,CAC5D,GAAM,CACN,WAAW,KACX,YAAY,GACZ,cAAgB,CAAC,EACjB,gBAAkB,CAAC,EACnB,QAAQ,GACR,UAAU,KACV,OAAQ,EAAa,IAAA,GACrB,cAAc,UACd,cAAc,SACd,WAAW,GACX,qBAAqB,CAAC,GAClB,EAAqB,eAAgB,CAAK,EACxC,CAAC,EAAc,GAAmB,EAAS,EAAK,EAChD,CAAC,EAAc,GAAmB,EAAS,EAAK,EAEtD,SAAS,EAAY,EAAY,GAAO,CACtC,EAAgB,EAAK,EACrB,EAAQ,CAAS,CACnB,CAEA,eAAe,GAAgB,CAC7B,EAAgB,EAAI,EACpB,GAAI,CACF,MAAM,EAAU,EAChB,EAAY,EAAI,CAClB,MAAQ,CAIR,QAAU,CACR,EAAgB,EAAK,CACvB,CACF,CAIA,IAAM,EACJ,EAAC,EAAD,CAAc,QAAe,OAHhB,IAAe,IAAA,GAAY,EAAe,EAGlB,YAAe,EAAY,EAAG,UAAW,EAAW,IAAA,GAAY,WAArG,CACG,EACD,EAAC,EAAD,CACE,YAAe,EAAY,EAC3B,SAAU,EACG,cACA,cACb,kBAAmB,EAAW,EAAgB,OAAS,IAAA,GACvD,sBAAuB,EACvB,GAAI,CACL,CAAA,CACI,IAKT,OAFK,EAGH,EAAC,MAAD,CAAgB,qBAAhB,CACE,EAAC,OAAD,CAAM,YAAe,EAAgB,EAAI,EAAI,UAAe,CAAA,EAC3D,CACE,IANe,CAQxB"}
@@ -1,2 +1,2 @@
1
- import{DropZoneReturnType as e,DropZoneStatus as t}from"./dropZone.types.mjs";import n from"./dropZone.module.mjs";import{useCallback as r,useEffect as i,useId as a,useRef as o,useState as s}from"react";import c from"classnames";import{jsx as l,jsxs as u}from"react/jsx-runtime";function d(e,t){if(!t.length)return!0;let n=e.name.toLowerCase(),r=e.type.toLowerCase();return t.some(e=>{let t=e.trim().toLowerCase();return t?t.startsWith(`.`)?n.endsWith(t):t.endsWith(`/*`)?r.startsWith(t.slice(0,-1)):r===t:!1})}function f(t,n){return n===e.File?Promise.resolve({ok:!0,value:t}):new Promise(r=>{let i=new FileReader;i.onload=e=>{let n=e.target?.result;if(typeof n!=`string`){r({ok:!1});return}r({ok:!0,value:{name:t.name,size:t.size,type:t.type,lastModified:t.lastModified,data:n}})},i.onerror=()=>r({ok:!1}),n===e.Base64?i.readAsDataURL(t):i.readAsText(t)})}function p(e){return new Promise(t=>{if(e.isFile)e.file(e=>t([e]),()=>t([]));else if(e.isDirectory){let n=e.createReader(),r=[],i=()=>{n.readEntries(e=>{e.length?(r.push(...e),i()):Promise.all(r.map(p)).then(e=>t(e.flat()))},()=>t([]))};i()}else t([])})}function m(e,t){let n=e.items;if(n&&n.length){if(t&&typeof n[0].webkitGetAsEntry==`function`){let e=[];for(let t=0;t<n.length;t+=1)if(n[t].kind===`file`){let r=n[t].webkitGetAsEntry();r&&e.push(r)}if(e.length)return Promise.all(e.map(p)).then(e=>e.flat())}let e=[];for(let t=0;t<n.length;t+=1)if(n[t].kind===`file`){let r=n[t].getAsFile();r&&e.push(r)}return Promise.resolve(e)}return Promise.resolve(Array.from(e.files||[]))}function h({children:p,acceptedTypes:h=[],returnType:g=e.File,openPickerOnClick:_=!1,multiple:v=!0,maxFiles:y,maxSize:b,enablePaste:x=!1,allowDirectories:S=!0,capture:C,disabled:w=!1,unstyled:T=!1,showFileNames:E=!1,files:D,onFilesChanged:O,onReject:k,onStatusChanged:A,className:j,style:M,classNames:N,styles:P,...F}){let[I,L]=s(t.Idle),R=o(null),z=a(),B=o(I),V=o(0),H=o(0),U=o({acceptedTypes:h,returnType:g,multiple:v,maxFiles:y,maxSize:b,allowDirectories:S,disabled:w,onFilesChanged:O,onReject:k,onStatusChanged:A});U.current={acceptedTypes:h,returnType:g,multiple:v,maxFiles:y,maxSize:b,allowDirectories:S,disabled:w,onFilesChanged:O,onReject:k,onStatusChanged:A};let W=r(e=>{B.current!==e&&(B.current=e,L(e),U.current.onStatusChanged?.(e))},[]),G=r(async e=>{let n=U.current,r=[],i=[];for(let t of e)d(t,n.acceptedTypes)?n.maxSize!=null&&t.size>n.maxSize?r.push({file:t,reason:`tooLarge`}):i.push(t):r.push({file:t,reason:`unacceptedType`});n.multiple||(i=i.slice(0,1)),n.maxFiles!=null&&i.length>n.maxFiles&&(i.slice(n.maxFiles).forEach(e=>r.push({file:e,reason:`tooMany`})),i=i.slice(0,n.maxFiles));let a=await Promise.all(i.map(e=>f(e,n.returnType))),o=[];a.forEach((e,t)=>{e.ok?o.push(e.value):r.push({file:i[t],reason:`readError`})}),r.length&&n.onReject?.(r),W(r.length&&!o.length?t.Error:t.Idle),o.length&&n.onFilesChanged?.(o)},[W]);i(()=>{let e=e=>!e||Array.from(e.types||[]).includes(`Files`),n=n=>{U.current.disabled||!e(n.dataTransfer)||(V.current+=1,(B.current===t.Idle||B.current===t.Error)&&W(t.Dragging))},r=()=>{V.current=Math.max(0,V.current-1),V.current===0&&B.current===t.Dragging&&W(t.Idle)},i=()=>{V.current=0,H.current=0,B.current===t.Dragging&&W(t.Idle)};return window.addEventListener(`dragenter`,n),window.addEventListener(`dragleave`,r),window.addEventListener(`drop`,i),()=>{window.removeEventListener(`dragenter`,n),window.removeEventListener(`dragleave`,r),window.removeEventListener(`drop`,i)}},[W]);let K=r(e=>{e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect=w?`none`:`copy`)},[w]),q=r(e=>{e.preventDefault(),e.stopPropagation(),!w&&(H.current+=1,W(t.Active))},[w,W]),J=r(e=>{e.preventDefault(),e.stopPropagation(),H.current=Math.max(0,H.current-1),H.current===0&&W(V.current>0?t.Dragging:t.Idle)},[W]),Y=r(e=>{if(e.preventDefault(),e.stopPropagation(),H.current=0,V.current=0,w||!e.dataTransfer){W(t.Idle);return}W(t.Idle),m(e.dataTransfer,U.current.allowDirectories).then(e=>{e.length&&G(e)})},[w,W,G]),X=r(()=>{w||!_||R.current?.click()},[w,_]),Z=r(e=>{let t=Array.from(e.target.files||[]);e.target.value=``,t.length&&G(t)},[G]),Q=r(e=>{if(!x||w)return;let t=Array.from(e.clipboardData?.files||[]);t.length&&(e.preventDefault(),G(t))},[x,w,G]),ee=r(e=>{!_||w||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),X())},[_,w,X]),$=I===t.Dragging||I===t.Active,te={status:I,isDragging:$,isActive:I===t.Active,disabled:w},ne=h.length?h.join(`,`):void 0;return u(`div`,{...F,className:c(n.dropZone,_&&n.dropZoneClickable,w&&n.dropZoneDisabled,!T&&n.dropZoneDefault,!T&&I===t.Dragging&&n.dropZoneDragging,!T&&I===t.Active&&n.dropZoneActive,!T&&I===t.Error&&n.dropZoneError,N?.root,j),style:{...P?.root,...M},onDragEnter:q,onDragLeave:J,onDragOver:K,onDrop:Y,onClick:X,onKeyDown:ee,onPaste:x?Q:void 0,role:_?`button`:void 0,tabIndex:_&&!w?0:void 0,"aria-disabled":w||void 0,children:[l(`div`,{className:c(n.dropZoneContent,$&&n.dropZoneContentDragging,N?.content),style:P?.content,children:typeof p==`function`?p(te):p}),E&&D&&D.length>0&&l(`div`,{className:c(n.dropZoneFileList,N?.fileList),style:P?.fileList,children:D.map((e,t)=>l(`div`,{className:c(n.dropZoneFileItem,N?.fileItem),style:P?.fileItem,children:e.name},`${e.name}-${t}`))}),l(`input`,{ref:R,id:z,type:`file`,className:c(n.dropZoneInput,N?.input),style:P?.input,accept:ne,multiple:v,capture:C,disabled:w,onChange:Z,tabIndex:-1,"aria-hidden":`true`})]})}export{h as default};
1
+ import{DropZoneReturnType as e,DropZoneStatus as t}from"./dropZone.types.mjs";import n from"./dropZone.module.mjs";import{useCallback as r,useEffect as i,useId as a,useRef as o,useState as s}from"react";import c from"classnames";import{jsx as l,jsxs as u}from"react/jsx-runtime";function d(e,t){if(!t.length)return!0;let n=e.name.toLowerCase(),r=e.type.toLowerCase();return t.some(e=>{let t=e.trim().toLowerCase();return t?t.startsWith(`.`)?n.endsWith(t):t.endsWith(`/*`)?r.startsWith(t.slice(0,-1)):r===t:!1})}function f(t,n){return n===e.File?Promise.resolve({ok:!0,value:t}):new Promise(r=>{let i=new FileReader;i.onload=e=>{let n=e.target?.result;if(typeof n!=`string`){r({ok:!1});return}r({ok:!0,value:{name:t.name,size:t.size,type:t.type,lastModified:t.lastModified,data:n}})},i.onerror=()=>r({ok:!1}),n===e.Base64?i.readAsDataURL(t):i.readAsText(t)})}function p(e){return new Promise(t=>{if(e.isFile)e.file(e=>t([e]),()=>t([]));else if(e.isDirectory){let n=e.createReader(),r=[],i=()=>{n.readEntries(e=>{e.length?(r.push(...e),i()):Promise.all(r.map(p)).then(e=>t(e.flat()))},()=>t([]))};i()}else t([])})}function m(e,t){let n=e.items;if(n&&n.length){if(t&&typeof n[0].webkitGetAsEntry==`function`){let e=[];for(let t=0;t<n.length;t+=1)if(n[t].kind===`file`){let r=n[t].webkitGetAsEntry();r&&e.push(r)}if(e.length)return Promise.all(e.map(p)).then(e=>e.flat())}let e=[];for(let t=0;t<n.length;t+=1)if(n[t].kind===`file`){let r=n[t].getAsFile();r&&e.push(r)}return Promise.resolve(e)}return Promise.resolve(Array.from(e.files||[]))}function h({children:p,acceptedTypes:h=[],returnType:g=e.File,openPickerOnClick:_=!1,multiple:v=!0,maxFiles:y,maxSize:b,enablePaste:x=!1,allowDirectories:S=!0,capture:C,disabled:w=!1,unstyled:T=!1,showFileNames:E=!1,files:D,onFilesChanged:O,onReject:k,onStatusChanged:A,className:j,style:M,classNames:N,styles:P,...F}){let[I,L]=s(t.Idle),R=o(null),z=a(),B=o(I),V=o(0),H=o(0),U=o({acceptedTypes:h,returnType:g,multiple:v,maxFiles:y,maxSize:b,allowDirectories:S,disabled:w,onFilesChanged:O,onReject:k,onStatusChanged:A});i(()=>{U.current={acceptedTypes:h,returnType:g,multiple:v,maxFiles:y,maxSize:b,allowDirectories:S,disabled:w,onFilesChanged:O,onReject:k,onStatusChanged:A}});let W=r(e=>{B.current!==e&&(B.current=e,L(e),U.current.onStatusChanged?.(e))},[]),G=r(async e=>{let n=U.current,r=[],i=[];for(let t of e)d(t,n.acceptedTypes)?n.maxSize!=null&&t.size>n.maxSize?r.push({file:t,reason:`tooLarge`}):i.push(t):r.push({file:t,reason:`unacceptedType`});n.multiple||(i=i.slice(0,1)),n.maxFiles!=null&&i.length>n.maxFiles&&(i.slice(n.maxFiles).forEach(e=>r.push({file:e,reason:`tooMany`})),i=i.slice(0,n.maxFiles));let a=await Promise.all(i.map(e=>f(e,n.returnType))),o=[];a.forEach((e,t)=>{e.ok?o.push(e.value):r.push({file:i[t],reason:`readError`})}),r.length&&n.onReject?.(r),W(r.length&&!o.length?t.Error:t.Idle),o.length&&n.onFilesChanged?.(o)},[W]);i(()=>{let e=e=>!e||Array.from(e.types||[]).includes(`Files`),n=n=>{U.current.disabled||!e(n.dataTransfer)||(V.current+=1,(B.current===t.Idle||B.current===t.Error)&&W(t.Dragging))},r=()=>{V.current=Math.max(0,V.current-1),V.current===0&&B.current===t.Dragging&&W(t.Idle)},i=()=>{V.current=0,H.current=0,B.current===t.Dragging&&W(t.Idle)};return window.addEventListener(`dragenter`,n),window.addEventListener(`dragleave`,r),window.addEventListener(`drop`,i),()=>{window.removeEventListener(`dragenter`,n),window.removeEventListener(`dragleave`,r),window.removeEventListener(`drop`,i)}},[W]);let K=r(e=>{e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect=w?`none`:`copy`)},[w]),q=r(e=>{e.preventDefault(),e.stopPropagation(),!w&&(H.current+=1,W(t.Active))},[w,W]),J=r(e=>{e.preventDefault(),e.stopPropagation(),H.current=Math.max(0,H.current-1),H.current===0&&W(V.current>0?t.Dragging:t.Idle)},[W]),Y=r(e=>{if(e.preventDefault(),e.stopPropagation(),H.current=0,V.current=0,w||!e.dataTransfer){W(t.Idle);return}W(t.Idle),m(e.dataTransfer,U.current.allowDirectories).then(e=>{e.length&&G(e)})},[w,W,G]),X=r(()=>{w||!_||R.current?.click()},[w,_]),Z=r(e=>{let t=Array.from(e.target.files||[]);e.target.value=``,t.length&&G(t)},[G]),Q=r(e=>{if(!x||w)return;let t=Array.from(e.clipboardData?.files||[]);t.length&&(e.preventDefault(),G(t))},[x,w,G]),ee=r(e=>{!_||w||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),X())},[_,w,X]),$=I===t.Dragging||I===t.Active,te={status:I,isDragging:$,isActive:I===t.Active,disabled:w},ne=h.length?h.join(`,`):void 0;return u(`div`,{...F,className:c(n.dropZone,_&&n.dropZoneClickable,w&&n.dropZoneDisabled,!T&&n.dropZoneDefault,!T&&I===t.Dragging&&n.dropZoneDragging,!T&&I===t.Active&&n.dropZoneActive,!T&&I===t.Error&&n.dropZoneError,N?.root,j),style:{...P?.root,...M},onDragEnter:q,onDragLeave:J,onDragOver:K,onDrop:Y,onClick:X,onKeyDown:ee,onPaste:x?Q:void 0,role:_?`button`:void 0,tabIndex:_&&!w?0:void 0,"aria-disabled":w||void 0,children:[l(`div`,{className:c(n.dropZoneContent,$&&n.dropZoneContentDragging,N?.content),style:P?.content,children:typeof p==`function`?p(te):p}),E&&D&&D.length>0&&l(`div`,{className:c(n.dropZoneFileList,N?.fileList),style:P?.fileList,children:D.map((e,t)=>l(`div`,{className:c(n.dropZoneFileItem,N?.fileItem),style:P?.fileItem,children:e.name},`${e.name}-${t}`))}),l(`input`,{ref:R,id:z,type:`file`,className:c(n.dropZoneInput,N?.input),style:P?.input,accept:ne,multiple:v,capture:C,disabled:w,onChange:Z,tabIndex:-1,"aria-hidden":`true`})]})}export{h as default};
2
2
  //# sourceMappingURL=dropZone.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dropZone.mjs","names":[],"sources":["../../../../package/common/dropZone/dropZone.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport cx from 'classnames';\n\nimport {\n DropZoneProps,\n DropZoneReturnType,\n DropZoneStatus,\n DropZoneRejection,\n DropZoneRenderState,\n LoadedFile,\n} from './dropZone.types';\n\nimport styles from './dropZone.module.pcss';\n\n// ── Pure helpers ──────────────────────────────────────────────────────────────\n\n/** True when a file matches one of the accepted tokens (extension, mime, or wildcard). */\nfunction matchesAccepted(file: File, acceptedTypes: string[]): boolean {\n if (!acceptedTypes.length) return true;\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return acceptedTypes.some((raw) => {\n const accept = raw.trim().toLowerCase();\n if (!accept) return false;\n if (accept.startsWith('.')) return name.endsWith(accept); // extension\n if (accept.endsWith('/*')) return type.startsWith(accept.slice(0, -1)); // wildcard e.g. image/\n return type === accept; // exact mime type\n });\n}\n\ntype ReadResult = { ok: true; value: File | LoadedFile } | { ok: false };\n\n/** Read a single file into the requested return shape. Never rejects — failures resolve to `{ ok: false }`. */\nfunction readFile(file: File, returnType: DropZoneReturnType): Promise<ReadResult> {\n if (returnType === DropZoneReturnType.File) {\n return Promise.resolve({ ok: true, value: file });\n }\n return new Promise<ReadResult>((resolve) => {\n const reader = new FileReader();\n reader.onload = (event) => {\n const data = event.target?.result;\n if (typeof data !== 'string') {\n resolve({ ok: false });\n return;\n }\n resolve({\n ok: true,\n value: { name: file.name, size: file.size, type: file.type, lastModified: file.lastModified, data },\n });\n };\n reader.onerror = () => resolve({ ok: false });\n if (returnType === DropZoneReturnType.Base64) reader.readAsDataURL(file);\n else reader.readAsText(file);\n });\n}\n\n/** Recursively flatten a dropped file-system entry into a list of Files. */\nfunction readEntry(entry: FileSystemEntry): Promise<File[]> {\n return new Promise((resolve) => {\n if (entry.isFile) {\n (entry as FileSystemFileEntry).file(\n (file) => resolve([file]),\n () => resolve([])\n );\n } else if (entry.isDirectory) {\n const reader = (entry as FileSystemDirectoryEntry).createReader();\n const collected: FileSystemEntry[] = [];\n const readBatch = () => {\n // readEntries yields entries in chunks — keep calling until it returns empty.\n reader.readEntries((batch) => {\n if (!batch.length) {\n Promise.all(collected.map(readEntry)).then((nested) => resolve(nested.flat()));\n } else {\n collected.push(...batch);\n readBatch();\n }\n }, () => resolve([]));\n };\n readBatch();\n } else {\n resolve([]);\n }\n });\n}\n\n/**\n * Extract Files from a drop's DataTransfer. `webkitGetAsEntry()` must be called\n * synchronously within the drop handler, so all entries are captured before any await.\n */\nfunction gatherFiles(dataTransfer: DataTransfer, allowDirectories: boolean): Promise<File[]> {\n const items = dataTransfer.items;\n if (items && items.length) {\n if (allowDirectories && typeof items[0].webkitGetAsEntry === 'function') {\n const entries: FileSystemEntry[] = [];\n for (let i = 0; i < items.length; i += 1) {\n if (items[i].kind === 'file') {\n const entry = items[i].webkitGetAsEntry();\n if (entry) entries.push(entry);\n }\n }\n if (entries.length) {\n return Promise.all(entries.map(readEntry)).then((nested) => nested.flat());\n }\n }\n const files: File[] = [];\n for (let i = 0; i < items.length; i += 1) {\n if (items[i].kind === 'file') {\n const file = items[i].getAsFile();\n if (file) files.push(file);\n }\n }\n return Promise.resolve(files);\n }\n return Promise.resolve(Array.from(dataTransfer.files || []));\n}\n\n// ── Component ───────────────────────────────────────────────────────────────\n\nfunction DropZone({\n children,\n acceptedTypes = [],\n returnType = DropZoneReturnType.File,\n openPickerOnClick = false,\n multiple = true,\n maxFiles,\n maxSize,\n enablePaste = false,\n allowDirectories = true,\n capture,\n disabled = false,\n unstyled = false,\n showFileNames = false,\n files,\n onFilesChanged,\n onReject,\n onStatusChanged,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n}: DropZoneProps) {\n const [status, setStatus] = useState<DropZoneStatus>(DropZoneStatus.Idle);\n\n const inputRef = useRef<HTMLInputElement>(null);\n const inputId = useId();\n const statusRef = useRef(status);\n const windowDragDepth = useRef(0);\n const zoneDragDepth = useRef(0);\n\n // Latest props/callbacks, so the once-mounted window listeners never read stale values.\n const cfg = useRef({\n acceptedTypes, returnType, multiple, maxFiles, maxSize, allowDirectories,\n disabled, onFilesChanged, onReject, onStatusChanged,\n });\n cfg.current = {\n acceptedTypes, returnType, multiple, maxFiles, maxSize, allowDirectories,\n disabled, onFilesChanged, onReject, onStatusChanged,\n };\n\n const changeStatus = useCallback((next: DropZoneStatus) => {\n if (statusRef.current === next) return;\n statusRef.current = next;\n setStatus(next);\n cfg.current.onStatusChanged?.(next);\n }, []);\n\n const processFiles = useCallback(async (incoming: File[]) => {\n const c = cfg.current;\n const rejections: DropZoneRejection[] = [];\n let accepted: File[] = [];\n\n for (const file of incoming) {\n if (!matchesAccepted(file, c.acceptedTypes)) {\n rejections.push({ file, reason: 'unacceptedType' });\n } else if (c.maxSize != null && file.size > c.maxSize) {\n rejections.push({ file, reason: 'tooLarge' });\n } else {\n accepted.push(file);\n }\n }\n\n if (!c.multiple) accepted = accepted.slice(0, 1);\n if (c.maxFiles != null && accepted.length > c.maxFiles) {\n accepted.slice(c.maxFiles).forEach((file) => rejections.push({ file, reason: 'tooMany' }));\n accepted = accepted.slice(0, c.maxFiles);\n }\n\n // Read in input order — Promise.all preserves index regardless of completion order.\n const results = await Promise.all(accepted.map((file) => readFile(file, c.returnType)));\n const loaded: (File | LoadedFile)[] = [];\n results.forEach((result, index) => {\n if (result.ok) loaded.push(result.value);\n else rejections.push({ file: accepted[index], reason: 'readError' });\n });\n\n if (rejections.length) c.onReject?.(rejections);\n changeStatus(rejections.length && !loaded.length ? DropZoneStatus.Error : DropZoneStatus.Idle);\n if (loaded.length) c.onFilesChanged?.(loaded);\n }, [changeStatus]);\n\n // Window-level drag tracking via an enter/leave depth counter (robust against bubbling).\n useEffect(() => {\n const hasFiles = (dt: DataTransfer | null) =>\n !dt || Array.from(dt.types || []).includes('Files');\n\n const onWindowDragEnter = (e: DragEvent) => {\n if (cfg.current.disabled || !hasFiles(e.dataTransfer)) return;\n windowDragDepth.current += 1;\n if (statusRef.current === DropZoneStatus.Idle || statusRef.current === DropZoneStatus.Error) {\n changeStatus(DropZoneStatus.Dragging);\n }\n };\n const onWindowDragLeave = () => {\n windowDragDepth.current = Math.max(0, windowDragDepth.current - 1);\n if (windowDragDepth.current === 0 && statusRef.current === DropZoneStatus.Dragging) {\n changeStatus(DropZoneStatus.Idle);\n }\n };\n const onWindowDrop = () => {\n windowDragDepth.current = 0;\n zoneDragDepth.current = 0;\n if (statusRef.current === DropZoneStatus.Dragging) changeStatus(DropZoneStatus.Idle);\n };\n\n window.addEventListener('dragenter', onWindowDragEnter);\n window.addEventListener('dragleave', onWindowDragLeave);\n window.addEventListener('drop', onWindowDrop);\n return () => {\n window.removeEventListener('dragenter', onWindowDragEnter);\n window.removeEventListener('dragleave', onWindowDragLeave);\n window.removeEventListener('drop', onWindowDrop);\n };\n }, [changeStatus]);\n\n const onDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n if (e.dataTransfer) e.dataTransfer.dropEffect = disabled ? 'none' : 'copy';\n }, [disabled]);\n\n const onDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n if (disabled) return;\n zoneDragDepth.current += 1;\n changeStatus(DropZoneStatus.Active);\n }, [disabled, changeStatus]);\n\n const onDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n zoneDragDepth.current = Math.max(0, zoneDragDepth.current - 1);\n if (zoneDragDepth.current === 0) {\n // Left the zone, but a drag may still be active elsewhere in the window.\n changeStatus(windowDragDepth.current > 0 ? DropZoneStatus.Dragging : DropZoneStatus.Idle);\n }\n }, [changeStatus]);\n\n const onDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n zoneDragDepth.current = 0;\n windowDragDepth.current = 0;\n if (disabled || !e.dataTransfer) {\n changeStatus(DropZoneStatus.Idle);\n return;\n }\n changeStatus(DropZoneStatus.Idle);\n // gatherFiles captures any directory entries synchronously before awaiting.\n gatherFiles(e.dataTransfer, cfg.current.allowDirectories).then((collected) => {\n if (collected.length) processFiles(collected);\n });\n }, [disabled, changeStatus, processFiles]);\n\n const openPicker = useCallback(() => {\n if (disabled || !openPickerOnClick) return;\n inputRef.current?.click();\n }, [disabled, openPickerOnClick]);\n\n const onInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const selected = Array.from(e.target.files || []);\n // Reset so picking the same file again still fires onChange.\n e.target.value = '';\n if (selected.length) processFiles(selected);\n }, [processFiles]);\n\n const onPaste = useCallback((e: React.ClipboardEvent<HTMLDivElement>) => {\n if (!enablePaste || disabled) return;\n const pasted = Array.from(e.clipboardData?.files || []);\n if (pasted.length) {\n e.preventDefault();\n processFiles(pasted);\n }\n }, [enablePaste, disabled, processFiles]);\n\n const onKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {\n if (!openPickerOnClick || disabled) return;\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n openPicker();\n }\n }, [openPickerOnClick, disabled, openPicker]);\n\n const isDragging = status === DropZoneStatus.Dragging || status === DropZoneStatus.Active;\n const renderState: DropZoneRenderState = {\n status,\n isDragging,\n isActive: status === DropZoneStatus.Active,\n disabled,\n };\n\n const acceptAttr = acceptedTypes.length ? acceptedTypes.join(',') : undefined;\n\n return (\n <div\n {...rest}\n className={cx(\n styles.dropZone,\n openPickerOnClick && styles.dropZoneClickable,\n disabled && styles.dropZoneDisabled,\n !unstyled && styles.dropZoneDefault,\n !unstyled && status === DropZoneStatus.Dragging && styles.dropZoneDragging,\n !unstyled && status === DropZoneStatus.Active && styles.dropZoneActive,\n !unstyled && status === DropZoneStatus.Error && styles.dropZoneError,\n classNames?.root,\n className\n )}\n style={{ ...slotStyles?.root, ...style }}\n onDragEnter={onDragEnter}\n onDragLeave={onDragLeave}\n onDragOver={onDragOver}\n onDrop={onDrop}\n onClick={openPicker}\n onKeyDown={onKeyDown}\n onPaste={enablePaste ? onPaste : undefined}\n role={openPickerOnClick ? 'button' : undefined}\n tabIndex={openPickerOnClick && !disabled ? 0 : undefined}\n aria-disabled={disabled || undefined}\n >\n <div\n className={cx(styles.dropZoneContent, isDragging && styles.dropZoneContentDragging, classNames?.content)}\n style={slotStyles?.content}\n >\n {typeof children === 'function' ? children(renderState) : children}\n </div>\n\n {showFileNames && files && files.length > 0 && (\n <div className={cx(styles.dropZoneFileList, classNames?.fileList)} style={slotStyles?.fileList}>\n {files.map((file, index) => (\n <div\n key={`${file.name}-${index}`}\n className={cx(styles.dropZoneFileItem, classNames?.fileItem)}\n style={slotStyles?.fileItem}\n >\n {file.name}\n </div>\n ))}\n </div>\n )}\n\n <input\n ref={inputRef}\n id={inputId}\n type=\"file\"\n className={cx(styles.dropZoneInput, classNames?.input)}\n style={slotStyles?.input}\n accept={acceptAttr}\n multiple={multiple}\n capture={capture}\n disabled={disabled}\n onChange={onInputChange}\n tabIndex={-1}\n aria-hidden=\"true\"\n />\n </div>\n );\n}\n\nexport default DropZone;\n"],"mappings":"uRAiBA,SAAS,EAAgB,EAAY,EAAkC,CACrE,GAAI,CAAC,EAAc,OAAQ,MAAO,GAClC,IAAM,EAAO,EAAK,KAAK,YAAY,EAC7B,EAAO,EAAK,KAAK,YAAY,EACnC,OAAO,EAAc,KAAM,GAAQ,CACjC,IAAM,EAAS,EAAI,KAAK,EAAE,YAAY,EAItC,OAHK,EACD,EAAO,WAAW,GAAG,EAAU,EAAK,SAAS,CAAM,EACnD,EAAO,SAAS,IAAI,EAAU,EAAK,WAAW,EAAO,MAAM,EAAG,EAAE,CAAC,EAC9D,IAAS,EAHI,EAItB,CAAC,CACH,CAKA,SAAS,EAAS,EAAY,EAAqD,CAIjF,OAHI,IAAe,EAAmB,KAC7B,QAAQ,QAAQ,CAAE,GAAI,GAAM,MAAO,CAAK,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EAAO,cACvD,GAAY,KACZ,CACF,EACA,MAAO,CAAE,GAAG,GAAY,KAAM,GAAG,CAAM,EAC1B,cACA,cACD,aACJ,SACR,QAAS,EACE,aACX,QAAS,EAAc,EAAU,IAAA,GACjC,KAAM,EAAoB,SAAW,IAAA,GACrC,SAAU,GAAqB,CAAC,EAAW,EAAI,IAAA,GAC/C,gBAAe,GAAY,IAAA,YAvB7B,CAyBE,EAAC,MAAD,CACE,UAAW,EAAG,EAAO,gBAAiB,GAAc,EAAO,wBAAyB,GAAY,OAAO,EACvG,MAAO,GAAY,iBAElB,OAAO,GAAa,WAAa,EAAS,EAAW,EAAI,CACvD,CAAA,EAEJ,GAAiB,GAAS,EAAM,OAAS,GACxC,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,iBAAkB,GAAY,QAAQ,EAAG,MAAO,GAAY,kBACnF,EAAM,KAAK,EAAM,IAChB,EAAC,MAAD,CAEE,UAAW,EAAG,EAAO,iBAAkB,GAAY,QAAQ,EAC3D,MAAO,GAAY,kBAElB,EAAK,IACH,EALE,GAAG,EAAK,KAAK,GAAG,GAKlB,CACN,CACE,CAAA,EAGP,EAAC,QAAD,CACE,IAAK,EACL,GAAI,EACJ,KAAK,OACL,UAAW,EAAG,EAAO,cAAe,GAAY,KAAK,EACrD,MAAO,GAAY,MACnB,OAAQ,GACE,WACD,UACC,WACV,SAAU,EACV,SAAU,GACV,cAAY,MACb,CAAA,CACE,GAET"}
1
+ {"version":3,"file":"dropZone.mjs","names":[],"sources":["../../../../package/common/dropZone/dropZone.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport cx from 'classnames';\n\nimport {\n DropZoneProps,\n DropZoneReturnType,\n DropZoneStatus,\n DropZoneRejection,\n DropZoneRenderState,\n LoadedFile,\n} from './dropZone.types';\n\nimport styles from './dropZone.module.pcss';\n\n// ── Pure helpers ──────────────────────────────────────────────────────────────\n\n/** True when a file matches one of the accepted tokens (extension, mime, or wildcard). */\nfunction matchesAccepted(file: File, acceptedTypes: string[]): boolean {\n if (!acceptedTypes.length) return true;\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return acceptedTypes.some((raw) => {\n const accept = raw.trim().toLowerCase();\n if (!accept) return false;\n if (accept.startsWith('.')) return name.endsWith(accept); // extension\n if (accept.endsWith('/*')) return type.startsWith(accept.slice(0, -1)); // wildcard e.g. image/\n return type === accept; // exact mime type\n });\n}\n\ntype ReadResult = { ok: true; value: File | LoadedFile } | { ok: false };\n\n/** Read a single file into the requested return shape. Never rejects — failures resolve to `{ ok: false }`. */\nfunction readFile(file: File, returnType: DropZoneReturnType): Promise<ReadResult> {\n if (returnType === DropZoneReturnType.File) {\n return Promise.resolve({ ok: true, value: file });\n }\n return new Promise<ReadResult>((resolve) => {\n const reader = new FileReader();\n reader.onload = (event) => {\n const data = event.target?.result;\n if (typeof data !== 'string') {\n resolve({ ok: false });\n return;\n }\n resolve({\n ok: true,\n value: { name: file.name, size: file.size, type: file.type, lastModified: file.lastModified, data },\n });\n };\n reader.onerror = () => resolve({ ok: false });\n if (returnType === DropZoneReturnType.Base64) reader.readAsDataURL(file);\n else reader.readAsText(file);\n });\n}\n\n/** Recursively flatten a dropped file-system entry into a list of Files. */\nfunction readEntry(entry: FileSystemEntry): Promise<File[]> {\n return new Promise((resolve) => {\n if (entry.isFile) {\n (entry as FileSystemFileEntry).file(\n (file) => resolve([file]),\n () => resolve([])\n );\n } else if (entry.isDirectory) {\n const reader = (entry as FileSystemDirectoryEntry).createReader();\n const collected: FileSystemEntry[] = [];\n const readBatch = () => {\n // readEntries yields entries in chunks — keep calling until it returns empty.\n reader.readEntries((batch) => {\n if (!batch.length) {\n Promise.all(collected.map(readEntry)).then((nested) => resolve(nested.flat()));\n } else {\n collected.push(...batch);\n readBatch();\n }\n }, () => resolve([]));\n };\n readBatch();\n } else {\n resolve([]);\n }\n });\n}\n\n/**\n * Extract Files from a drop's DataTransfer. `webkitGetAsEntry()` must be called\n * synchronously within the drop handler, so all entries are captured before any await.\n */\nfunction gatherFiles(dataTransfer: DataTransfer, allowDirectories: boolean): Promise<File[]> {\n const items = dataTransfer.items;\n if (items && items.length) {\n if (allowDirectories && typeof items[0].webkitGetAsEntry === 'function') {\n const entries: FileSystemEntry[] = [];\n for (let i = 0; i < items.length; i += 1) {\n if (items[i].kind === 'file') {\n const entry = items[i].webkitGetAsEntry();\n if (entry) entries.push(entry);\n }\n }\n if (entries.length) {\n return Promise.all(entries.map(readEntry)).then((nested) => nested.flat());\n }\n }\n const files: File[] = [];\n for (let i = 0; i < items.length; i += 1) {\n if (items[i].kind === 'file') {\n const file = items[i].getAsFile();\n if (file) files.push(file);\n }\n }\n return Promise.resolve(files);\n }\n return Promise.resolve(Array.from(dataTransfer.files || []));\n}\n\n// ── Component ───────────────────────────────────────────────────────────────\n\nfunction DropZone({\n children,\n acceptedTypes = [],\n returnType = DropZoneReturnType.File,\n openPickerOnClick = false,\n multiple = true,\n maxFiles,\n maxSize,\n enablePaste = false,\n allowDirectories = true,\n capture,\n disabled = false,\n unstyled = false,\n showFileNames = false,\n files,\n onFilesChanged,\n onReject,\n onStatusChanged,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n}: DropZoneProps) {\n const [status, setStatus] = useState<DropZoneStatus>(DropZoneStatus.Idle);\n\n const inputRef = useRef<HTMLInputElement>(null);\n const inputId = useId();\n const statusRef = useRef(status);\n const windowDragDepth = useRef(0);\n const zoneDragDepth = useRef(0);\n\n // Latest props/callbacks, so the once-mounted window listeners never read stale values.\n const cfg = useRef({\n acceptedTypes, returnType, multiple, maxFiles, maxSize, allowDirectories,\n disabled, onFilesChanged, onReject, onStatusChanged,\n });\n useEffect(() => {\n cfg.current = {\n acceptedTypes, returnType, multiple, maxFiles, maxSize, allowDirectories,\n disabled, onFilesChanged, onReject, onStatusChanged,\n };\n });\n\n const changeStatus = useCallback((next: DropZoneStatus) => {\n if (statusRef.current === next) return;\n statusRef.current = next;\n setStatus(next);\n cfg.current.onStatusChanged?.(next);\n }, []);\n\n const processFiles = useCallback(async (incoming: File[]) => {\n const c = cfg.current;\n const rejections: DropZoneRejection[] = [];\n let accepted: File[] = [];\n\n for (const file of incoming) {\n if (!matchesAccepted(file, c.acceptedTypes)) {\n rejections.push({ file, reason: 'unacceptedType' });\n } else if (c.maxSize != null && file.size > c.maxSize) {\n rejections.push({ file, reason: 'tooLarge' });\n } else {\n accepted.push(file);\n }\n }\n\n if (!c.multiple) accepted = accepted.slice(0, 1);\n if (c.maxFiles != null && accepted.length > c.maxFiles) {\n accepted.slice(c.maxFiles).forEach((file) => rejections.push({ file, reason: 'tooMany' }));\n accepted = accepted.slice(0, c.maxFiles);\n }\n\n // Read in input order — Promise.all preserves index regardless of completion order.\n const results = await Promise.all(accepted.map((file) => readFile(file, c.returnType)));\n const loaded: (File | LoadedFile)[] = [];\n results.forEach((result, index) => {\n if (result.ok) loaded.push(result.value);\n else rejections.push({ file: accepted[index], reason: 'readError' });\n });\n\n if (rejections.length) c.onReject?.(rejections);\n changeStatus(rejections.length && !loaded.length ? DropZoneStatus.Error : DropZoneStatus.Idle);\n if (loaded.length) c.onFilesChanged?.(loaded);\n }, [changeStatus]);\n\n // Window-level drag tracking via an enter/leave depth counter (robust against bubbling).\n useEffect(() => {\n const hasFiles = (dt: DataTransfer | null) =>\n !dt || Array.from(dt.types || []).includes('Files');\n\n const onWindowDragEnter = (e: DragEvent) => {\n if (cfg.current.disabled || !hasFiles(e.dataTransfer)) return;\n windowDragDepth.current += 1;\n if (statusRef.current === DropZoneStatus.Idle || statusRef.current === DropZoneStatus.Error) {\n changeStatus(DropZoneStatus.Dragging);\n }\n };\n const onWindowDragLeave = () => {\n windowDragDepth.current = Math.max(0, windowDragDepth.current - 1);\n if (windowDragDepth.current === 0 && statusRef.current === DropZoneStatus.Dragging) {\n changeStatus(DropZoneStatus.Idle);\n }\n };\n const onWindowDrop = () => {\n windowDragDepth.current = 0;\n zoneDragDepth.current = 0;\n if (statusRef.current === DropZoneStatus.Dragging) changeStatus(DropZoneStatus.Idle);\n };\n\n window.addEventListener('dragenter', onWindowDragEnter);\n window.addEventListener('dragleave', onWindowDragLeave);\n window.addEventListener('drop', onWindowDrop);\n return () => {\n window.removeEventListener('dragenter', onWindowDragEnter);\n window.removeEventListener('dragleave', onWindowDragLeave);\n window.removeEventListener('drop', onWindowDrop);\n };\n }, [changeStatus]);\n\n const onDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n if (e.dataTransfer) e.dataTransfer.dropEffect = disabled ? 'none' : 'copy';\n }, [disabled]);\n\n const onDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n if (disabled) return;\n zoneDragDepth.current += 1;\n changeStatus(DropZoneStatus.Active);\n }, [disabled, changeStatus]);\n\n const onDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n zoneDragDepth.current = Math.max(0, zoneDragDepth.current - 1);\n if (zoneDragDepth.current === 0) {\n // Left the zone, but a drag may still be active elsewhere in the window.\n changeStatus(windowDragDepth.current > 0 ? DropZoneStatus.Dragging : DropZoneStatus.Idle);\n }\n }, [changeStatus]);\n\n const onDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n zoneDragDepth.current = 0;\n windowDragDepth.current = 0;\n if (disabled || !e.dataTransfer) {\n changeStatus(DropZoneStatus.Idle);\n return;\n }\n changeStatus(DropZoneStatus.Idle);\n // gatherFiles captures any directory entries synchronously before awaiting.\n gatherFiles(e.dataTransfer, cfg.current.allowDirectories).then((collected) => {\n if (collected.length) processFiles(collected);\n });\n }, [disabled, changeStatus, processFiles]);\n\n const openPicker = useCallback(() => {\n if (disabled || !openPickerOnClick) return;\n inputRef.current?.click();\n }, [disabled, openPickerOnClick]);\n\n const onInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const selected = Array.from(e.target.files || []);\n // Reset so picking the same file again still fires onChange.\n e.target.value = '';\n if (selected.length) processFiles(selected);\n }, [processFiles]);\n\n const onPaste = useCallback((e: React.ClipboardEvent<HTMLDivElement>) => {\n if (!enablePaste || disabled) return;\n const pasted = Array.from(e.clipboardData?.files || []);\n if (pasted.length) {\n e.preventDefault();\n processFiles(pasted);\n }\n }, [enablePaste, disabled, processFiles]);\n\n const onKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {\n if (!openPickerOnClick || disabled) return;\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n openPicker();\n }\n }, [openPickerOnClick, disabled, openPicker]);\n\n const isDragging = status === DropZoneStatus.Dragging || status === DropZoneStatus.Active;\n const renderState: DropZoneRenderState = {\n status,\n isDragging,\n isActive: status === DropZoneStatus.Active,\n disabled,\n };\n\n const acceptAttr = acceptedTypes.length ? acceptedTypes.join(',') : undefined;\n\n return (\n <div\n {...rest}\n className={cx(\n styles.dropZone,\n openPickerOnClick && styles.dropZoneClickable,\n disabled && styles.dropZoneDisabled,\n !unstyled && styles.dropZoneDefault,\n !unstyled && status === DropZoneStatus.Dragging && styles.dropZoneDragging,\n !unstyled && status === DropZoneStatus.Active && styles.dropZoneActive,\n !unstyled && status === DropZoneStatus.Error && styles.dropZoneError,\n classNames?.root,\n className\n )}\n style={{ ...slotStyles?.root, ...style }}\n onDragEnter={onDragEnter}\n onDragLeave={onDragLeave}\n onDragOver={onDragOver}\n onDrop={onDrop}\n onClick={openPicker}\n onKeyDown={onKeyDown}\n onPaste={enablePaste ? onPaste : undefined}\n role={openPickerOnClick ? 'button' : undefined}\n tabIndex={openPickerOnClick && !disabled ? 0 : undefined}\n aria-disabled={disabled || undefined}\n >\n <div\n className={cx(styles.dropZoneContent, isDragging && styles.dropZoneContentDragging, classNames?.content)}\n style={slotStyles?.content}\n >\n {typeof children === 'function' ? children(renderState) : children}\n </div>\n\n {showFileNames && files && files.length > 0 && (\n <div className={cx(styles.dropZoneFileList, classNames?.fileList)} style={slotStyles?.fileList}>\n {files.map((file, index) => (\n <div\n key={`${file.name}-${index}`}\n className={cx(styles.dropZoneFileItem, classNames?.fileItem)}\n style={slotStyles?.fileItem}\n >\n {file.name}\n </div>\n ))}\n </div>\n )}\n\n <input\n ref={inputRef}\n id={inputId}\n type=\"file\"\n className={cx(styles.dropZoneInput, classNames?.input)}\n style={slotStyles?.input}\n accept={acceptAttr}\n multiple={multiple}\n capture={capture}\n disabled={disabled}\n onChange={onInputChange}\n tabIndex={-1}\n aria-hidden=\"true\"\n />\n </div>\n );\n}\n\nexport default DropZone;\n"],"mappings":"uRAiBA,SAAS,EAAgB,EAAY,EAAkC,CACrE,GAAI,CAAC,EAAc,OAAQ,MAAO,GAClC,IAAM,EAAO,EAAK,KAAK,YAAY,EAC7B,EAAO,EAAK,KAAK,YAAY,EACnC,OAAO,EAAc,KAAM,GAAQ,CACjC,IAAM,EAAS,EAAI,KAAK,EAAE,YAAY,EAItC,OAHK,EACD,EAAO,WAAW,GAAG,EAAU,EAAK,SAAS,CAAM,EACnD,EAAO,SAAS,IAAI,EAAU,EAAK,WAAW,EAAO,MAAM,EAAG,EAAE,CAAC,EAC9D,IAAS,EAHI,EAItB,CAAC,CACH,CAKA,SAAS,EAAS,EAAY,EAAqD,CAIjF,OAHI,IAAe,EAAmB,KAC7B,QAAQ,QAAQ,CAAE,GAAI,GAAM,MAAO,CAAK,CAAC,EAE3C,IAAI,QAAqB,GAAY,CAC1C,IAAM,EAAS,IAAI,WACnB,EAAO,OAAU,GAAU,CACzB,IAAM,EAAO,EAAM,QAAQ,OAC3B,GAAI,OAAO,GAAS,SAAU,CAC5B,EAAQ,CAAE,GAAI,EAAM,CAAC,EACrB,MACF,CACA,EAAQ,CACN,GAAI,GACJ,MAAO,CAAE,KAAM,EAAK,KAAM,KAAM,EAAK,KAAM,KAAM,EAAK,KAAM,aAAc,EAAK,aAAc,MAAK,CACpG,CAAC,CACH,EACA,EAAO,YAAgB,EAAQ,CAAE,GAAI,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O,GAAY,iBAElB,OAAO,GAAa,WAAa,EAAS,EAAW,EAAI,CACvD,CAAA,EAEJ,GAAiB,GAAS,EAAM,OAAS,GACxC,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,iBAAkB,GAAY,QAAQ,EAAG,MAAO,GAAY,kBACnF,EAAM,KAAK,EAAM,IAChB,EAAC,MAAD,CAEE,UAAW,EAAG,EAAO,iBAAkB,GAAY,QAAQ,EAC3D,MAAO,GAAY,kBAElB,EAAK,IACH,EALE,GAAG,EAAK,KAAK,GAAG,GAKlB,CACN,CACE,CAAA,EAGP,EAAC,QAAD,CACE,IAAK,EACL,GAAI,EACJ,KAAK,OACL,UAAW,EAAG,EAAO,cAAe,GAAY,KAAK,EACrD,MAAO,GAAY,MACnB,OAAQ,GACE,WACD,UACC,WACV,SAAU,EACV,SAAU,GACV,cAAY,MACb,CAAA,CACE,GAET"}
@@ -1,2 +1,2 @@
1
- import{getScrollableAncestors as e,isHiddenByAnyAncestor as t}from"../utils/scrollAncestors.mjs";import{getVisualViewportRect as n}from"../utils/visualViewport.mjs";import{useLayoutEffect as r}from"react";var i=8;function a({isOpen:a,triggerRef:o,anchorRef:s,panelRef:c,flipClassName:l,placement:u=`bottom`}){r(()=>{if(!a)return;let r,d;function f(){let a=o.current,p=s.current;if(!a||!p){r=requestAnimationFrame(f);return}let m=e(a);function h(){let e=a.getBoundingClientRect(),r=c.current?.offsetHeight??0,o=n(),s=o.top+o.height-e.bottom,d=e.top-o.top,f=u===`top`?d:s,h=f<r&&(u===`top`?s:d)>f,g=u===`top`?!h:h;p.classList.toggle(l,h),p.style.top=`${g?e.top-p.offsetHeight:e.bottom}px`,p.style.left=`${e.left}px`;let y=c.current;if(y){let t=y===p?0:y.offsetLeft,n=e.left+t,r=n+y.offsetWidth-(o.left+o.width-i),a=o.left+i-n;r>0?p.style.left=`${e.left-r}px`:a>0&&(p.style.left=`${e.left+a}px`)}p.style.visibility=t(e,m)?`hidden`:``;let b=c.current;b&&!_.has(b)&&v()}let g=new ResizeObserver(()=>h()),_=new Set;function v(){[p,c.current].forEach(e=>{!e||_.has(e)||(_.add(e),g.observe(e))})}h();let y=[window,...m];y.forEach(e=>e.addEventListener(`scroll`,h,{passive:!0})),window.addEventListener(`resize`,h),window.visualViewport?.addEventListener(`resize`,h),window.visualViewport?.addEventListener(`scroll`,h),d=()=>{y.forEach(e=>e.removeEventListener(`scroll`,h)),window.removeEventListener(`resize`,h),window.visualViewport?.removeEventListener(`resize`,h),window.visualViewport?.removeEventListener(`scroll`,h),g.disconnect(),p.style.top=``,p.style.left=``,p.style.visibility=``,p.classList.remove(l)}}return f(),()=>{r!==void 0&&cancelAnimationFrame(r),d?.()}},[a,o,s,c,l,u])}export{a as useFloatingPosition};
1
+ import{isHiddenByAnyAncestor as e}from"../utils/scrollAncestors.mjs";import{getVisualViewportRect as t}from"../utils/visualViewport.mjs";import{useAnchorTracking as n}from"../hooks/useAnchorTracking.mjs";var r=8;function i({isOpen:i,triggerRef:a,anchorRef:o,panelRef:s,flipClassName:c,placement:l=`bottom`}){n({isOpen:i,triggerRef:a,elementRefs:[o],resizeRefs:[o,s],deps:[o,s,c,l],update:(n,i)=>{let a=o.current;if(!a)return;let u=n.getBoundingClientRect(),d=s.current?.offsetHeight??0,f=t(),p=f.top+f.height-u.bottom,m=u.top-f.top,h=l===`top`?m:p,g=h<d&&(l===`top`?p:m)>h,_=l===`top`?!g:g;a.classList.toggle(c,g),a.style.top=`${_?u.top-a.offsetHeight:u.bottom}px`,a.style.left=`${u.left}px`;let v=s.current;if(v){let e=v===a?0:v.offsetLeft,t=u.left+e,n=t+v.offsetWidth-(f.left+f.width-r),i=f.left+r-t;n>0?a.style.left=`${u.left-n}px`:i>0&&(a.style.left=`${u.left+i}px`)}a.style.visibility=e(u,i)?`hidden`:``},teardown:()=>{let e=o.current;e&&(e.style.top=``,e.style.left=``,e.style.visibility=``,e.classList.remove(c))}})}export{i as useFloatingPosition};
2
2
  //# sourceMappingURL=useFloatingPosition.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"useFloatingPosition.mjs","names":[],"sources":["../../../../package/common/floatingMenu/useFloatingPosition.ts"],"sourcesContent":["import { useLayoutEffect, type RefObject } from 'react';\nimport { getScrollableAncestors, isHiddenByAnyAncestor } from 'components/common/utils/scrollAncestors';\nimport { getVisualViewportRect } from 'components/common/utils/visualViewport';\n\nexport interface UseFloatingPositionArgs {\n isOpen: boolean;\n /** The element the popup is anchored to. */\n triggerRef: RefObject<HTMLElement | null>;\n /** The `position: fixed` element that gets `top`/`left`/`visibility` written to it directly. */\n anchorRef: RefObject<HTMLElement | null>;\n /** The visible panel whose height decides whether there's room to render on the preferred side. */\n panelRef: RefObject<HTMLElement | null>;\n /** Class toggled on `anchorRef` when flipped to the non-preferred side. */\n flipClassName: string;\n /** Preferred side relative to the trigger (default `'bottom'`) — flips to the other side when there's no room. */\n placement?: 'top' | 'bottom';\n}\n\n/** Minimum gap kept between the panel and the viewport edge when horizontally clamped. */\nconst EDGE_MARGIN = 8;\n\n/**\n * Keeps a portaled, `position: fixed` popup anchored to a trigger element: tracks the\n * trigger across scroll/resize on every real scrolling ancestor, flips above the trigger\n * when there's no room below, and hides (not closes) the popup when the trigger itself\n * scrolls behind a clipping ancestor — matching Floating UI's autoUpdate + hide middleware.\n * It also shifts the popup horizontally to stay within the viewport: `align`/RTL-style CSS\n * only positions the panel relative to the anchor's own box and has no awareness of where\n * that box actually sits on screen, so a trigger near a screen edge would otherwise let the\n * panel overflow it with no correction.\n *\n * Position/visibility are written straight to the DOM via refs, not through React state:\n * going through setState -> re-render -> commit adds a round-trip that lags behind the\n * browser's own scroll painting by at least a frame.\n */\nexport function useFloatingPosition({ isOpen, triggerRef, anchorRef, panelRef, flipClassName, placement = 'bottom' }: UseFloatingPositionArgs) {\n useLayoutEffect(() => {\n if (!isOpen) return;\n\n let rafId: number | undefined;\n let teardown: (() => void) | undefined;\n\n // The anchor/trigger may not be mounted yet on the very first invocation of this\n // effect: a portal target (e.g. BodyEnd's `#bodyEnd` div) can still be missing on\n // the initial render, in which case the portaled content — and this ref — commits\n // one render later. Since refs never change identity, that later commit doesn't\n // re-trigger this effect on its own, so retry on the next frame until it's there.\n function trySetup() {\n const trigger = triggerRef.current;\n const anchor = anchorRef.current;\n if (!trigger || !anchor) {\n rafId = requestAnimationFrame(trySetup);\n return;\n }\n const ancestors = getScrollableAncestors(trigger);\n\n function updatePos() {\n const rect = trigger!.getBoundingClientRect();\n const panelHeight = panelRef.current?.offsetHeight ?? 0;\n // The visible area, not the full layout viewport — shrinks on mobile when a keyboard is\n // open, so flip/clamp react to what's actually on screen instead of the keyboard hiding\n // a panel that \"fit\" against the unshrunk layout viewport.\n const vv = getVisualViewportRect();\n const spaceBelow = vv.top + vv.height - rect.bottom;\n const spaceAbove = rect.top - vv.top;\n const preferredSpace = placement === 'top' ? spaceAbove : spaceBelow;\n const alternateSpace = placement === 'top' ? spaceBelow : spaceAbove;\n const flip = preferredSpace < panelHeight && alternateSpace > preferredSpace;\n const renderAbove = placement === 'top' ? !flip : flip;\n anchor!.classList.toggle(flipClassName, flip);\n // Shift up by the anchor's own height when rendering above, so this works whether\n // the anchor is a zero-height decorative wrapper (FloatingMenu, whose real panel\n // hangs off it via absolute-positioned CSS) or the visible panel itself\n // (Dropdown) — for the former the shift is a no-op (height 0).\n anchor!.style.top = `${renderAbove ? rect.top - anchor!.offsetHeight : rect.bottom}px`;\n anchor!.style.left = `${rect.left}px`;\n\n // Horizontal clamp: shift the anchor so the panel stays within the viewport, since\n // `align` CSS only positions it relative to the anchor's own box. Use offsetWidth/\n // offsetLeft (untransformed layout geometry), not getBoundingClientRect — both this\n // anchor and Dropdown's animate in via a CSS `transform: scale(...)`, which\n // getBoundingClientRect reflects but the box-model offsets don't, so measuring via\n // the transformed rect would under- or over-correct while that entrance animation runs.\n const panelForClamp = panelRef.current;\n if (panelForClamp) {\n const relativeLeft = panelForClamp === anchor ? 0 : panelForClamp.offsetLeft;\n const panelLeft = rect.left + relativeLeft;\n const panelRight = panelLeft + panelForClamp.offsetWidth;\n const overflowRight = panelRight - (vv.left + vv.width - EDGE_MARGIN);\n const overflowLeft = vv.left + EDGE_MARGIN - panelLeft;\n if (overflowRight > 0) {\n anchor!.style.left = `${rect.left - overflowRight}px`;\n } else if (overflowLeft > 0) {\n anchor!.style.left = `${rect.left + overflowLeft}px`;\n }\n }\n\n anchor!.style.visibility = isHiddenByAnyAncestor(rect, ancestors) ? 'hidden' : '';\n // The panel can mount a commit later than the anchor; once it's observed this\n // is a single Set lookup, so it costs nothing on the scroll path.\n const panel = panelRef.current;\n if (panel && !observed.has(panel)) observeSizeTargets();\n }\n\n // The panel's own height feeds both the flip decision and, when rendering above,\n // the top offset — so a popup whose content changes size while open (a filtered\n // list shrinking, an async list loading in) has to be re-measured, or it keeps a\n // top computed for its old height and ends up detached from the trigger.\n const resizeObserver = new ResizeObserver(() => updatePos());\n const observed = new Set<Element>();\n function observeSizeTargets() {\n // Both, since they're the same element for a panel-as-anchor consumer (Dropdown)\n // but not for a zero-height wrapper whose content sits inside it (FloatingMenu).\n // Called from updatePos too: the panel can mount a commit later than the anchor.\n [anchor, panelRef.current].forEach((el) => {\n if (!el || observed.has(el)) return;\n observed.add(el);\n resizeObserver.observe(el);\n });\n }\n\n updatePos();\n\n const scrollTargets: (Window | HTMLElement)[] = [window, ...ancestors];\n scrollTargets.forEach((t) => t.addEventListener('scroll', updatePos, { passive: true }));\n window.addEventListener('resize', updatePos);\n // `window.resize` doesn't reliably fire when a mobile keyboard opens/closes — visualViewport\n // does, and is what the space/clamp math above is measured against.\n window.visualViewport?.addEventListener('resize', updatePos);\n window.visualViewport?.addEventListener('scroll', updatePos);\n teardown = () => {\n scrollTargets.forEach((t) => t.removeEventListener('scroll', updatePos));\n window.removeEventListener('resize', updatePos);\n window.visualViewport?.removeEventListener('resize', updatePos);\n window.visualViewport?.removeEventListener('scroll', updatePos);\n resizeObserver.disconnect();\n // Positioning is written as inline styles, which outrank any class the popup might switch\n // to while it stays mounted — a popup turning into a bottom sheet (`useSheet`) would keep\n // the coordinates computed for its anchored self. Hand the element back as we found it.\n anchor!.style.top = '';\n anchor!.style.left = '';\n anchor!.style.visibility = '';\n anchor!.classList.remove(flipClassName);\n };\n }\n\n trySetup();\n\n return () => {\n if (rafId !== undefined) cancelAnimationFrame(rafId);\n teardown?.();\n };\n }, [isOpen, triggerRef, anchorRef, panelRef, flipClassName, placement]);\n}"],"mappings":"6MAmBA,IAAM,EAAc,EAgBpB,SAAgB,EAAoB,CAAE,SAAQ,aAAY,YAAW,WAAU,gBAAe,YAAY,UAAqC,CAC7I,MAAsB,CACpB,GAAI,CAAC,EAAQ,OAEb,IAAI,EACA,EAOJ,SAAS,GAAW,CAClB,IAAM,EAAU,EAAW,QACrB,EAAS,EAAU,QACzB,GAAI,CAAC,GAAW,CAAC,EAAQ,CACvB,EAAQ,sBAAsB,CAAQ,EACtC,MACF,CACA,IAAM,EAAY,EAAuB,CAAO,EAEhD,SAAS,GAAY,CACnB,IAAM,EAAO,EAAS,sBAAsB,EACtC,EAAc,EAAS,SAAS,cAAgB,EAIhD,EAAK,EAAsB,EAC3B,EAAa,EAAG,IAAM,EAAG,OAAS,EAAK,OACvC,EAAa,EAAK,IAAM,EAAG,IAC3B,EAAiB,IAAc,MAAQ,EAAa,EAEpD,EAAO,EAAiB,IADP,IAAc,MAAQ,EAAa,GACI,EACxD,EAAc,IAAc,MAAQ,CAAC,EAAO,EAClD,EAAQ,UAAU,OAAO,EAAe,CAAI,EAK5C,EAAQ,MAAM,IAAM,GAAG,EAAc,EAAK,IAAM,EAAQ,aAAe,EAAK,OAAO,IACnF,EAAQ,MAAM,KAAO,GAAG,EAAK,KAAK,IAQlC,IAAM,EAAgB,EAAS,QAC/B,GAAI,EAAe,CACjB,IAAM,EAAe,IAAkB,EAAS,EAAI,EAAc,WAC5D,EAAY,EAAK,KAAO,EAExB,EADa,EAAY,EAAc,aACT,EAAG,KAAO,EAAG,MAAQ,GACnD,EAAe,EA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,CAAC,CACxE"}
1
+ {"version":3,"file":"useFloatingPosition.mjs","names":[],"sources":["../../../../package/common/floatingMenu/useFloatingPosition.ts"],"sourcesContent":["import { type RefObject } from 'react';\nimport { isHiddenByAnyAncestor } from 'components/common/utils/scrollAncestors';\nimport { getVisualViewportRect } from 'components/common/utils/visualViewport';\nimport { useAnchorTracking } from '../hooks/useAnchorTracking';\n\nexport interface UseFloatingPositionArgs {\n isOpen: boolean;\n /** The element the popup is anchored to. */\n triggerRef: RefObject<HTMLElement | null>;\n /** The `position: fixed` element that gets `top`/`left`/`visibility` written to it directly. */\n anchorRef: RefObject<HTMLElement | null>;\n /** The visible panel whose height decides whether there's room to render on the preferred side. */\n panelRef: RefObject<HTMLElement | null>;\n /** Class toggled on `anchorRef` when flipped to the non-preferred side. */\n flipClassName: string;\n /** Preferred side relative to the trigger (default `'bottom'`) — flips to the other side when there's no room. */\n placement?: 'top' | 'bottom';\n}\n\n/** Minimum gap kept between the panel and the viewport edge when horizontally clamped. */\nconst EDGE_MARGIN = 8;\n\n/**\n * Keeps a portaled, `position: fixed` popup anchored to a trigger element: flips above the\n * trigger when there's no room below, and hides (not closes) the popup when the trigger itself\n * scrolls behind a clipping ancestor — matching Floating UI's autoUpdate + hide middleware.\n * It also shifts the popup horizontally to stay within the viewport: `align`/RTL-style CSS\n * only positions the panel relative to the anchor's own box and has no awareness of where\n * that box actually sits on screen, so a trigger near a screen edge would otherwise let the\n * panel overflow it with no correction.\n *\n * `useAnchorTracking` supplies the lifecycle around this: mount wait, ancestor resolution, and\n * re-running on scroll, viewport resize and panel size changes.\n */\nexport function useFloatingPosition({ isOpen, triggerRef, anchorRef, panelRef, flipClassName, placement = 'bottom' }: UseFloatingPositionArgs) {\n useAnchorTracking({\n isOpen,\n triggerRef,\n elementRefs: [anchorRef],\n // Both, since they're the same element for a panel-as-anchor consumer (Dropdown) but not for\n // a zero-height wrapper whose content sits inside it (FloatingMenu).\n resizeRefs: [anchorRef, panelRef],\n deps: [anchorRef, panelRef, flipClassName, placement],\n\n update: (trigger, ancestors) => {\n const anchor = anchorRef.current;\n if (!anchor) return;\n\n const rect = trigger.getBoundingClientRect();\n const panelHeight = panelRef.current?.offsetHeight ?? 0;\n // The visible area, not the full layout viewport — shrinks on mobile when a keyboard is\n // open, so flip/clamp react to what's actually on screen instead of the keyboard hiding\n // a panel that \"fit\" against the unshrunk layout viewport.\n const vv = getVisualViewportRect();\n const spaceBelow = vv.top + vv.height - rect.bottom;\n const spaceAbove = rect.top - vv.top;\n const preferredSpace = placement === 'top' ? spaceAbove : spaceBelow;\n const alternateSpace = placement === 'top' ? spaceBelow : spaceAbove;\n const flip = preferredSpace < panelHeight && alternateSpace > preferredSpace;\n const renderAbove = placement === 'top' ? !flip : flip;\n anchor.classList.toggle(flipClassName, flip);\n // Shift up by the anchor's own height when rendering above, so this works whether\n // the anchor is a zero-height decorative wrapper (FloatingMenu, whose real panel\n // hangs off it via absolute-positioned CSS) or the visible panel itself\n // (Dropdown) — for the former the shift is a no-op (height 0).\n anchor.style.top = `${renderAbove ? rect.top - anchor.offsetHeight : rect.bottom}px`;\n anchor.style.left = `${rect.left}px`;\n\n // Horizontal clamp: shift the anchor so the panel stays within the viewport, since\n // `align` CSS only positions it relative to the anchor's own box. Use offsetWidth/\n // offsetLeft (untransformed layout geometry), not getBoundingClientRect — both this\n // anchor and Dropdown's animate in via a CSS `transform: scale(...)`, which\n // getBoundingClientRect reflects but the box-model offsets don't, so measuring via\n // the transformed rect would under- or over-correct while that entrance animation runs.\n const panelForClamp = panelRef.current;\n if (panelForClamp) {\n const relativeLeft = panelForClamp === anchor ? 0 : panelForClamp.offsetLeft;\n const panelLeft = rect.left + relativeLeft;\n const panelRight = panelLeft + panelForClamp.offsetWidth;\n const overflowRight = panelRight - (vv.left + vv.width - EDGE_MARGIN);\n const overflowLeft = vv.left + EDGE_MARGIN - panelLeft;\n if (overflowRight > 0) {\n anchor.style.left = `${rect.left - overflowRight}px`;\n } else if (overflowLeft > 0) {\n anchor.style.left = `${rect.left + overflowLeft}px`;\n }\n }\n\n anchor.style.visibility = isHiddenByAnyAncestor(rect, ancestors) ? 'hidden' : '';\n },\n\n teardown: () => {\n // Positioning is written as inline styles, which outrank any class the popup might switch\n // to while it stays mounted — a popup turning into a bottom sheet (`useSheet`) would keep\n // the coordinates computed for its anchored self. Hand the element back as we found it.\n const anchor = anchorRef.current;\n if (!anchor) return;\n anchor.style.top = '';\n anchor.style.left = '';\n anchor.style.visibility = '';\n anchor.classList.remove(flipClassName);\n },\n });\n}\n"],"mappings":"4MAoBA,IAAM,EAAc,EAcpB,SAAgB,EAAoB,CAAE,SAAQ,aAAY,YAAW,WAAU,gBAAe,YAAY,UAAqC,CAC7I,EAAkB,CAChB,SACA,aACA,YAAa,CAAC,CAAS,EAGvB,WAAY,CAAC,EAAW,CAAQ,EAChC,KAAM,CAAC,EAAW,EAAU,EAAe,CAAS,EAEpD,QAAS,EAAS,IAAc,CAC9B,IAAM,EAAS,EAAU,QACzB,GAAI,CAAC,EAAQ,OAEb,IAAM,EAAO,EAAQ,sBAAsB,EACrC,EAAc,EAAS,SAAS,cAAgB,EAIhD,EAAK,EAAsB,EAC3B,EAAa,EAAG,IAAM,EAAG,OAAS,EAAK,OACvC,EAAa,EAAK,IAAM,EAAG,IAC3B,EAAiB,IAAc,MAAQ,EAAa,EAEpD,EAAO,EAAiB,IADP,IAAc,MAAQ,EAAa,GACI,EACxD,EAAc,IAAc,MAAQ,CAAC,EAAO,EAClD,EAAO,UAAU,OAAO,EAAe,CAAI,EAK3C,EAAO,MAAM,IAAM,GAAG,EAAc,EAAK,IAAM,EAAO,aAAe,EAAK,OAAO,IACjF,EAAO,MAAM,KAAO,GAAG,EAAK,KAAK,IAQjC,IAAM,EAAgB,EAAS,QAC/B,GAAI,EAAe,CACjB,IAAM,EAAe,IAAkB,EAAS,EAAI,EAAc,WAC5D,EAAY,EAAK,KAAO,EAExB,EADa,EAAY,EAAc,aACT,EAAG,KAAO,EAAG,MAAQ,GACnD,EAAe,EAAG,KAAO,EAAc,EACzC,EAAgB,EAClB,EAAO,MAAM,KAAO,GAAG,EAAK,KAAO,EAAc,IACxC,EAAe,IACxB,EAAO,MAAM,KAAO,GAAG,EAAK,KAAO,EAAa,IAEpD,CAEA,EAAO,MAAM,WAAa,EAAsB,EAAM,CAAS,EAAI,SAAW,EAChF,EAEA,aAAgB,CAId,IAAM,EAAS,EAAU,QACpB,IACL,EAAO,MAAM,IAAM,GACnB,EAAO,MAAM,KAAO,GACpB,EAAO,MAAM,WAAa,GAC1B,EAAO,UAAU,OAAO,CAAa,EACvC,CACF,CAAC,CACH"}
@@ -1,2 +1,2 @@
1
- var e=10,t=1e-4,n=100;function r(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function i(e,t,n){return(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x)}function a(e,t,n){let i=n.x-t.x,a=n.y-t.y,o=i*i+a*a;if(o===0)return{dist:r(e,t),t:0,point:{x:t.x,y:t.y}};let s=((e.x-t.x)*i+(e.y-t.y)*a)/o,c=s<0?0:s>1?1:s,l={x:t.x+c*i,y:t.y+c*a};return{dist:r(e,l),t:c,point:l}}function o(e,t,n){return a(e,t,n).point}function s(e,t,n,a,o=1){let s=r(e,t),c=r(n,a);if(s<1e-9||c<1e-9)return{kind:`none`};let l=t.x-e.x,u=t.y-e.y,d=a.x-n.x,f=a.y-n.y,p=l*f-u*d,m=Math.abs(i(e,t,n))/s,h=Math.abs(i(e,t,a))/s;if(Math.abs(p)<1e-12||m<o&&h<o){if(m>=o||h>=o)return{kind:`none`};let t=l*l+u*u,r=((n.x-e.x)*l+(n.y-e.y)*u)/t,i=((a.x-e.x)*l+(a.y-e.y)*u)/t,c=Math.min(r,i),d=Math.max(r,i),f=o/s;return d<f||c>1-f||Math.min(d,1)-Math.max(c,0)<f?{kind:`collinearDisjoint`}:{kind:`collinearOverlap`}}let g=((n.x-e.x)*f-(n.y-e.y)*d)/p,_=((n.x-e.x)*u-(n.y-e.y)*l)/p,v=o/s,y=o/c;if(g<-v||g>1+v||_<-y||_>1+y)return{kind:`none`};let b={x:e.x+g*l,y:e.y+g*u},x=g<=v||g>=1-v,S=_<=y||_>=1-y;return x||S?{kind:`touch`,t:g,s:_,point:b}:{kind:`proper`,t:g,s:_,point:b}}function c(e){let t=e.length;if(t<3)return 0;let n=0;for(let r=0,i=t-1;r<t;i=r++)n+=e[i].x*e[r].y-e[r].x*e[i].y;return n/2}function l(e){let t=e.length;if(t<2)return 0;let n=0;for(let i=0,a=t-1;i<t;a=i++)n+=r(e[a],e[i]);return n}function u(e){let t=e.length;if(t===0)return{x:0,y:0};if(t<3)return{x:e.reduce((e,t)=>e+t.x,0)/t,y:e.reduce((e,t)=>e+t.y,0)/t};let n=0,r=0,i=0;for(let a=0,o=t-1;a<t;o=a++){let t=e[o].x*e[a].y-e[a].x*e[o].y;n+=t,r+=(e[o].x+e[a].x)*t,i+=(e[o].y+e[a].y)*t}return Math.abs(n)<1e-9?{x:e.reduce((e,t)=>e+t.x,0)/t,y:e.reduce((e,t)=>e+t.y,0)/t}:{x:r/(3*n),y:i/(3*n)}}function d(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r++){let a=t[r].x,o=t[r].y,s=t[i].x,c=t[i].y;o>e.y!=c>e.y&&e.x<(s-a)*(e.y-o)/(c-o)+a&&(n=!n)}return n}function f(e,t,n=[]){if(!d(e,t))return!1;for(let t of n)if(d(e,t))return!1;return!0}function p(e,t=[]){if(e.length===0)return{x:0,y:0};let n=u(e);if(f(n,e,t))return n;let r=1/0,i=-1/0;for(let t of e)t.y<r&&(r=t.y),t.y>i&&(i=t.y);if(!Number.isFinite(r)||i-r<1e-9)return n;let a=[e,...t],o=null;for(let e=1;e<=7;e++){let t=r+(i-r)*e/8,n=[];for(let e of a)for(let r=0,i=e.length-1;r<e.length;i=r++){let a=e[i],o=e[r];a.y>t!=o.y>t&&n.push(a.x+(t-a.y)*(o.x-a.x)/(o.y-a.y))}n.sort((e,t)=>e-t);for(let e=0;e+1<n.length;e+=2){let r=n[e+1]-n[e];r>2&&(!o||r>o.width)&&(o={point:{x:(n[e]+n[e+1])/2,y:t},width:r})}}return o?o.point:n}function m(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)a.x<t&&(t=a.x),a.y<n&&(n=a.y),a.x>r&&(r=a.x),a.y>i&&(i=a.y);return{minX:t,minY:n,maxX:r,maxY:i}}export{t as EPS_ANGLE,n as MIN_OPENING_WIDTH,e as MIN_WALL_LENGTH,u as areaCentroid,m as boundsOf,i as cross,r as dist,l as perimeter,d as pointInRing,f as pointInRings,a as pointToSegment,o as projectOnSegment,p as representativePoint,s as segmentIntersection,c as signedArea};
1
+ var e=10,t=1e-4,n=100;function r(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function i(e,t,n){return(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x)}function a(e,t,n){let i=n.x-t.x,a=n.y-t.y,o=i*i+a*a;if(o===0)return{dist:r(e,t),t:0,point:{x:t.x,y:t.y}};let s=((e.x-t.x)*i+(e.y-t.y)*a)/o,c=s<0?0:s>1?1:s,l={x:t.x+c*i,y:t.y+c*a};return{dist:r(e,l),t:c,point:l}}function o(e,t,n){return a(e,t,n).point}function s(e,t,n,a,o=1){let s=r(e,t),c=r(n,a);if(s<1e-9||c<1e-9)return{kind:`none`};let l=t.x-e.x,u=t.y-e.y,d=a.x-n.x,f=a.y-n.y,p=l*f-u*d,m=Math.abs(i(e,t,n))/s,h=Math.abs(i(e,t,a))/s;if(Math.abs(p)<1e-12||m<o&&h<o){if(m>=o||h>=o)return{kind:`none`};let t=l*l+u*u,r=((n.x-e.x)*l+(n.y-e.y)*u)/t,i=((a.x-e.x)*l+(a.y-e.y)*u)/t,c=Math.min(r,i),d=Math.max(r,i),f=o/s;return d<f||c>1-f||Math.min(d,1)-Math.max(c,0)<f?{kind:`collinearDisjoint`}:{kind:`collinearOverlap`}}let g=((n.x-e.x)*f-(n.y-e.y)*d)/p,_=((n.x-e.x)*u-(n.y-e.y)*l)/p,v=o/s,y=o/c;if(g<-v||g>1+v||_<-y||_>1+y)return{kind:`none`};let b={x:e.x+g*l,y:e.y+g*u},x=g<=v||g>=1-v,S=_<=y||_>=1-y;return x||S?{kind:`touch`,t:g,s:_,point:b}:{kind:`proper`,t:g,s:_,point:b}}function c(e){let t=e.length;if(t<3)return 0;let n=0;for(let r=0,i=t-1;r<t;i=r++)n+=e[i].x*e[r].y-e[r].x*e[i].y;return n/2}function l(e){let t=e.length;if(t<2)return 0;let n=0;for(let i=0,a=t-1;i<t;a=i++)n+=r(e[a],e[i]);return n}function u(e){let t=e.length;if(t===0)return{x:0,y:0};if(t<3)return{x:e.reduce((e,t)=>e+t.x,0)/t,y:e.reduce((e,t)=>e+t.y,0)/t};let n=0,r=0,i=0;for(let a=0,o=t-1;a<t;o=a++){let t=e[o].x*e[a].y-e[a].x*e[o].y;n+=t,r+=(e[o].x+e[a].x)*t,i+=(e[o].y+e[a].y)*t}return Math.abs(n)<1e-9?{x:e.reduce((e,t)=>e+t.x,0)/t,y:e.reduce((e,t)=>e+t.y,0)/t}:{x:r/(3*n),y:i/(3*n)}}function d(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r++){let a=t[r].x,o=t[r].y,s=t[i].x,c=t[i].y;o>e.y!=c>e.y&&e.x<(s-a)*(e.y-o)/(c-o)+a&&(n=!n)}return n}function f(e,t,n=[]){if(!d(e,t))return!1;for(let t of n)if(d(e,t))return!1;return!0}function p(e,t=[]){if(e.length===0)return{x:0,y:0};let n=u(e);if(f(n,e,t))return n;let r=1/0,i=-1/0;for(let t of e)t.y<r&&(r=t.y),t.y>i&&(i=t.y);if(!Number.isFinite(r)||i-r<1e-9)return n;let a=[e,...t],o=null;for(let e=1;e<=7;e++){let t=r+(i-r)*e/8,n=[];for(let e of a)for(let r=0,i=e.length-1;r<e.length;i=r++){let a=e[i],o=e[r];a.y>t!=o.y>t&&n.push(a.x+(t-a.y)*(o.x-a.x)/(o.y-a.y))}n.sort((e,t)=>e-t);for(let e=0;e+1<n.length;e+=2){let r=n[e+1]-n[e];r>2&&(!o||r>o.width)&&(o={point:{x:(n[e]+n[e+1])/2,y:t},width:r})}}return o?o.point:n}function m(e){let t=e.slice(),n=!0;for(;n&&t.length>3;){n=!1;let e=[],i=t.length;for(let a=0;a<i;a++){let o=t[(a-1+i)%i],s=t[(a+1)%i];if(r(o,s)<1){n=!0;continue}e.push(t[a])}n&&(t=e.filter((t,n)=>r(t,e[(n+1)%e.length])>=1))}return t}function h(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)a.x<t&&(t=a.x),a.y<n&&(n=a.y),a.x>r&&(r=a.x),a.y>i&&(i=a.y);return{minX:t,minY:n,maxX:r,maxY:i}}export{t as EPS_ANGLE,n as MIN_OPENING_WIDTH,e as MIN_WALL_LENGTH,u as areaCentroid,h as boundsOf,i as cross,r as dist,l as perimeter,d as pointInRing,f as pointInRings,a as pointToSegment,o as projectOnSegment,p as representativePoint,s as segmentIntersection,c as signedArea,m as stripSpurs};
2
2
  //# sourceMappingURL=floorPlan.geometry.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"floorPlan.geometry.mjs","names":[],"sources":["../../../../package/common/floorPlan/floorPlan.geometry.ts"],"sourcesContent":["/**\n * Pure vector and polygon primitives. Nothing here knows about the plan model.\n *\n * All lengths are millimetres (see floorPlan.types.ts).\n */\n\nimport type { PlanPoint } from './floorPlan.types';\n\n// ─── Model-integrity epsilons ──────────────────────────────────────────────────\n// These are FIXED millimetre values describing when the model itself is degenerate.\n// They are a separate family from the user-intent tolerances in floorPlan.snap.ts,\n// which are screen pixels converted through the current zoom. Conflating the two\n// gives you either a model that accumulates 0.2mm walls, or snapping that stops\n// working when zoomed in.\n\n/** Shortest wall the graph will accept. Keeps zero-length walls out entirely. */\nexport const MIN_WALL_LENGTH = 10;\n/** Two points closer than this are the same point. */\nexport const EPS_COINCIDENT = 1;\n/** A ring with |area| below this encloses nothing (0.0001 m²). */\nexport const EPS_AREA = 100;\n/** Angular tolerance for \"these two walls are collinear\", in radians. */\nexport const EPS_ANGLE = 1e-4;\n/** Narrowest scanline span that counts as room interior rather than a slit. */\nexport const EPS_SPAN = 2;\n/** Narrowest opening worth keeping when a wall shortens under it. */\nexport const MIN_OPENING_WIDTH = 100;\n\n// ─── Vectors ───────────────────────────────────────────────────────────────────\n\nexport function dist(a: PlanPoint, b: PlanPoint): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nexport function distSq(a: PlanPoint, b: PlanPoint): number {\n const dx = a.x - b.x;\n const dy = a.y - b.y;\n return dx * dx + dy * dy;\n}\n\n/** Cross product of ab and ac. Positive when c is clockwise of b in SVG's y-down space. */\nexport function cross(a: PlanPoint, b: PlanPoint, c: PlanPoint): number {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\n}\n\nexport function lerp(a: PlanPoint, b: PlanPoint, t: number): PlanPoint {\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n}\n\n/** Unit vector from a to b, or null when they are coincident. */\nexport function direction(a: PlanPoint, b: PlanPoint): PlanPoint | null {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.hypot(dx, dy);\n if (len < 1e-9) return null;\n return { x: dx / len, y: dy / len };\n}\n\n/** Left-hand normal of the direction from a to b, or null when coincident. */\nexport function normal(a: PlanPoint, b: PlanPoint): PlanPoint | null {\n const d = direction(a, b);\n return d ? { x: -d.y, y: d.x } : null;\n}\n\n// ─── Point / segment ───────────────────────────────────────────────────────────\n\n/**\n * Distance from p to segment ab, plus the clamped parameter t of the closest point.\n * `t` is clamped to [0, 1], so the closest point is always on the segment.\n */\nexport function pointToSegment(\n p: PlanPoint,\n a: PlanPoint,\n b: PlanPoint,\n): { dist: number; t: number; point: PlanPoint } {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len2 = dx * dx + dy * dy;\n if (len2 === 0) return { dist: dist(p, a), t: 0, point: { x: a.x, y: a.y } };\n const raw = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;\n const t = raw < 0 ? 0 : raw > 1 ? 1 : raw;\n const point = { x: a.x + t * dx, y: a.y + t * dy };\n return { dist: dist(p, point), t, point };\n}\n\n/**\n * Exact projection of p onto segment ab, clamped to the segment.\n *\n * Used after a fuzzy hit tolerance has decided that p belongs to this segment: intent\n * is allowed to be approximate, the stored model never is.\n */\nexport function projectOnSegment(p: PlanPoint, a: PlanPoint, b: PlanPoint): PlanPoint {\n return pointToSegment(p, a, b).point;\n}\n\nexport type SegmentIntersectionKind =\n /** The segments cross strictly inside both. */\n | 'proper'\n /** They are parallel and do not touch. */\n | 'none'\n /** They lie on the same line and overlap over a non-zero length. */\n | 'collinearOverlap'\n /** They lie on the same line but do not overlap. */\n | 'collinearDisjoint'\n /** An endpoint of one lies on the other, or they share an endpoint. */\n | 'touch';\n\nexport interface SegmentIntersection {\n kind: SegmentIntersectionKind;\n /** Parameter along ab, for 'proper' and 'touch'. */\n t?: number;\n /** Parameter along cd, for 'proper' and 'touch'. */\n s?: number;\n point?: PlanPoint;\n}\n\n/**\n * Classifies how segments ab and cd meet.\n *\n * `eps` is a millimetre distance tolerance, not a parameter tolerance, so the result\n * does not change with segment length.\n */\nexport function segmentIntersection(\n a: PlanPoint,\n b: PlanPoint,\n c: PlanPoint,\n d: PlanPoint,\n eps = EPS_COINCIDENT,\n): SegmentIntersection {\n const abLen = dist(a, b);\n const cdLen = dist(c, d);\n if (abLen < 1e-9 || cdLen < 1e-9) return { kind: 'none' };\n\n const rx = b.x - a.x;\n const ry = b.y - a.y;\n const sx = d.x - c.x;\n const sy = d.y - c.y;\n const denom = rx * sy - ry * sx;\n\n // Perpendicular distance of c and d from line ab, used to tell parallel from collinear.\n const distC = Math.abs(cross(a, b, c)) / abLen;\n const distD = Math.abs(cross(a, b, d)) / abLen;\n\n if (Math.abs(denom) < 1e-12 || (distC < eps && distD < eps)) {\n if (distC >= eps || distD >= eps) return { kind: 'none' };\n // Collinear: compare parameters along ab.\n const len2 = rx * rx + ry * ry;\n const tc = ((c.x - a.x) * rx + (c.y - a.y) * ry) / len2;\n const td = ((d.x - a.x) * rx + (d.y - a.y) * ry) / len2;\n const lo = Math.min(tc, td);\n const hi = Math.max(tc, td);\n const epsT = eps / abLen;\n if (hi < epsT || lo > 1 - epsT) return { kind: 'collinearDisjoint' };\n if (Math.min(hi, 1) - Math.max(lo, 0) < epsT) return { kind: 'collinearDisjoint' };\n return { kind: 'collinearOverlap' };\n }\n\n const t = ((c.x - a.x) * sy - (c.y - a.y) * sx) / denom;\n const s = ((c.x - a.x) * ry - (c.y - a.y) * rx) / denom;\n const epsT = eps / abLen;\n const epsS = eps / cdLen;\n\n if (t < -epsT || t > 1 + epsT || s < -epsS || s > 1 + epsS) return { kind: 'none' };\n\n const point = { x: a.x + t * rx, y: a.y + t * ry };\n const atAbEnd = t <= epsT || t >= 1 - epsT;\n const atCdEnd = s <= epsS || s >= 1 - epsS;\n if (atAbEnd || atCdEnd) return { kind: 'touch', t, s, point };\n return { kind: 'proper', t, s, point };\n}\n\n// ─── Rings ─────────────────────────────────────────────────────────────────────\n\n/**\n * Shoelace area of a closed ring (first vertex not repeated).\n *\n * Positive means visually clockwise in SVG's y-down space. See `PlanFace.outer`.\n */\nexport function signedArea(ring: readonly PlanPoint[]): number {\n const n = ring.length;\n if (n < 3) return 0;\n let sum = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n sum += ring[j].x * ring[i].y - ring[i].x * ring[j].y;\n }\n return sum / 2;\n}\n\nexport function perimeter(ring: readonly PlanPoint[]): number {\n const n = ring.length;\n if (n < 2) return 0;\n let sum = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) sum += dist(ring[j], ring[i]);\n return sum;\n}\n\n/**\n * Area-weighted centroid of a ring.\n *\n * Deliberately not the vertex mean: a dangling wall adds an out-and-back vertex pair\n * that skews the mean but contributes nothing to the area moment. Falls back to the\n * vertex mean only for a degenerate (zero-area) ring.\n */\nexport function areaCentroid(ring: readonly PlanPoint[]): PlanPoint {\n const n = ring.length;\n if (n === 0) return { x: 0, y: 0 };\n if (n < 3) {\n return {\n x: ring.reduce((s, p) => s + p.x, 0) / n,\n y: ring.reduce((s, p) => s + p.y, 0) / n,\n };\n }\n let a = 0;\n let cx = 0;\n let cy = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const f = ring[j].x * ring[i].y - ring[i].x * ring[j].y;\n a += f;\n cx += (ring[j].x + ring[i].x) * f;\n cy += (ring[j].y + ring[i].y) * f;\n }\n if (Math.abs(a) < 1e-9) {\n return {\n x: ring.reduce((s, p) => s + p.x, 0) / n,\n y: ring.reduce((s, p) => s + p.y, 0) / n,\n };\n }\n return { x: cx / (3 * a), y: cy / (3 * a) };\n}\n\n/** Ray-casting point-in-ring test. Points exactly on an edge are unspecified. */\nexport function pointInRing(p: PlanPoint, ring: readonly PlanPoint[]): boolean {\n let inside = false;\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const xi = ring[i].x;\n const yi = ring[i].y;\n const xj = ring[j].x;\n const yj = ring[j].y;\n if (yi > p.y !== yj > p.y && p.x < ((xj - xi) * (p.y - yi)) / (yj - yi) + xi) {\n inside = !inside;\n }\n }\n return inside;\n}\n\n/** Inside `outer` and outside every hole. */\nexport function pointInRings(\n p: PlanPoint,\n outer: readonly PlanPoint[],\n holes: readonly (readonly PlanPoint[])[] = [],\n): boolean {\n if (!pointInRing(p, outer)) return false;\n for (const hole of holes) if (pointInRing(p, hole)) return false;\n return true;\n}\n\n/**\n * A point guaranteed to lie strictly inside the ring set, placed somewhere visually\n * central where possible.\n *\n * The area centroid is preferred, but it is not guaranteed to be inside a concave\n * polygon (an L-shaped room's centroid can land in the notch), so a scanline fallback\n * picks the widest interior span across several horizontal lines. The EPS_SPAN test on\n * that span is what stops an anchor landing inside the zero-width slit that a dangling\n * wall leaves in a face.\n */\nexport function representativePoint(\n outer: readonly PlanPoint[],\n holes: readonly (readonly PlanPoint[])[] = [],\n): PlanPoint {\n if (outer.length === 0) return { x: 0, y: 0 };\n\n const centre = areaCentroid(outer);\n if (pointInRings(centre, outer, holes)) return centre;\n\n let ymin = Infinity;\n let ymax = -Infinity;\n for (const p of outer) {\n if (p.y < ymin) ymin = p.y;\n if (p.y > ymax) ymax = p.y;\n }\n if (!Number.isFinite(ymin) || ymax - ymin < 1e-9) return centre;\n\n const rings: readonly (readonly PlanPoint[])[] = [outer, ...holes];\n let best: { point: PlanPoint; width: number } | null = null;\n\n const SAMPLES = 7;\n for (let k = 1; k <= SAMPLES; k++) {\n const y = ymin + ((ymax - ymin) * k) / (SAMPLES + 1);\n const xs: number[] = [];\n // One crossing list across ALL rings, so even-odd pairing yields interior spans\n // directly. Running the scanline per ring would not compose with holes.\n for (const ring of rings) {\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const p = ring[j];\n const q = ring[i];\n if (p.y > y !== q.y > y) {\n xs.push(p.x + ((y - p.y) * (q.x - p.x)) / (q.y - p.y));\n }\n }\n }\n xs.sort((m, n) => m - n);\n for (let i = 0; i + 1 < xs.length; i += 2) {\n const width = xs[i + 1] - xs[i];\n if (width > EPS_SPAN && (!best || width > best.width)) {\n best = { point: { x: (xs[i] + xs[i + 1]) / 2, y }, width };\n }\n }\n }\n\n return best ? best.point : centre;\n}\n\n/**\n * Removes out-and-back spurs (`... P, Q, P ...`) from a ring, repeatedly until none\n * remain.\n *\n * A face containing a dangling wall is a valid fill but is not a simple polygon, which\n * breaks polygon offsetting and makes some triangulators emit zero-area triangles. Run\n * this before triangulating a floor slab; keep the raw ring for the 2D fill, where the\n * slit is harmless and `wallIds` alignment matters.\n */\nexport function stripSpurs(ring: readonly PlanPoint[]): PlanPoint[] {\n let out = ring.slice();\n let changed = true;\n while (changed && out.length > 3) {\n changed = false;\n const next: PlanPoint[] = [];\n const n = out.length;\n for (let i = 0; i < n; i++) {\n const prev = out[(i - 1 + n) % n];\n const nextPt = out[(i + 1) % n];\n // The middle of an out-and-back is the vertex whose neighbours coincide.\n if (dist(prev, nextPt) < EPS_COINCIDENT) {\n changed = true;\n continue;\n }\n next.push(out[i]);\n }\n if (changed) {\n // Drop the now-duplicated turning point left behind by each removed spur tip.\n out = next.filter((p, i) => dist(p, next[(i + 1) % next.length]) >= EPS_COINCIDENT);\n }\n }\n return out;\n}\n\nexport function rectToPoints(x: number, y: number, w: number, h: number): PlanPoint[] {\n return [\n { x, y },\n { x: x + w, y },\n { x: x + w, y: y + h },\n { x, y: y + h },\n ];\n}\n\nexport function boundsOf(points: readonly PlanPoint[]): {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n} | null {\n if (points.length === 0) return null;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of points) {\n if (p.x < minX) minX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.x > maxX) maxX = p.x;\n if (p.y > maxY) maxY = p.y;\n }\n return { minX, minY, maxX, maxY };\n}\n"],"mappings":"AAgBA,IAAa,EAAkB,GAMlB,EAAY,KAIZ,EAAoB,IAIjC,SAAgB,EAAK,EAAc,EAAsB,CACvD,OAAO,KAAK,MAAM,EAAE,EAAI,EAAE,EAAG,EAAE,EAAI,EAAE,CAAC,CACxC,CASA,SAAgB,EAAM,EAAc,EAAc,EAAsB,CACtE,OAAQ,EAAE,EAAI,EAAE,IAAM,EAAE,EAAI,EAAE,IAAM,EAAE,EAAI,EAAE,IAAM,EAAE,EAAI,EAAE,EAC5D,CA2BA,SAAgB,EACd,EACA,EACA,EAC+C,CAC/C,IAAM,EAAK,EAAE,EAAI,EAAE,EACb,EAAK,EAAE,EAAI,EAAE,EACb,EAAO,EAAK,EAAK,EAAK,EAC5B,GAAI,IAAS,EAAG,MAAO,CAAE,KAAM,EAAK,EAAG,CAAC,EAAG,EAAG,EAAG,MAAO,CAAE,EAAG,EAAE,EAAG,EAAG,EAAE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G,GAAK,EAAG,EAAI,IAAM,EAAG,GAAE,EAAG,OAAM,EAE7D,CACF,CAEA,OAAO,EAAO,EAAK,MAAQ,CAC7B,CA6CA,SAAgB,EAAS,EAKhB,CACP,GAAI,EAAO,SAAW,EAAG,OAAO,KAChC,IAAI,EAAO,IACP,EAAO,IACP,EAAO,KACP,EAAO,KACX,IAAK,IAAM,KAAK,EACV,EAAE,EAAI,IAAM,EAAO,EAAE,GACrB,EAAE,EAAI,IAAM,EAAO,EAAE,GACrB,EAAE,EAAI,IAAM,EAAO,EAAE,GACrB,EAAE,EAAI,IAAM,EAAO,EAAE,GAE3B,MAAO,CAAE,OAAM,OAAM,OAAM,MAAK,CAClC"}
1
+ {"version":3,"file":"floorPlan.geometry.mjs","names":[],"sources":["../../../../package/common/floorPlan/floorPlan.geometry.ts"],"sourcesContent":["/**\n * Pure vector and polygon primitives. Nothing here knows about the plan model.\n *\n * All lengths are millimetres (see floorPlan.types.ts).\n */\n\nimport type { PlanPoint } from './floorPlan.types';\n\n// ─── Model-integrity epsilons ──────────────────────────────────────────────────\n// These are FIXED millimetre values describing when the model itself is degenerate.\n// They are a separate family from the user-intent tolerances in floorPlan.snap.ts,\n// which are screen pixels converted through the current zoom. Conflating the two\n// gives you either a model that accumulates 0.2mm walls, or snapping that stops\n// working when zoomed in.\n\n/** Shortest wall the graph will accept. Keeps zero-length walls out entirely. */\nexport const MIN_WALL_LENGTH = 10;\n/** Two points closer than this are the same point. */\nexport const EPS_COINCIDENT = 1;\n/** A ring with |area| below this encloses nothing (0.0001 m²). */\nexport const EPS_AREA = 100;\n/** Angular tolerance for \"these two walls are collinear\", in radians. */\nexport const EPS_ANGLE = 1e-4;\n/** Narrowest scanline span that counts as room interior rather than a slit. */\nexport const EPS_SPAN = 2;\n/** Narrowest opening worth keeping when a wall shortens under it. */\nexport const MIN_OPENING_WIDTH = 100;\n\n// ─── Vectors ───────────────────────────────────────────────────────────────────\n\nexport function dist(a: PlanPoint, b: PlanPoint): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nexport function distSq(a: PlanPoint, b: PlanPoint): number {\n const dx = a.x - b.x;\n const dy = a.y - b.y;\n return dx * dx + dy * dy;\n}\n\n/** Cross product of ab and ac. Positive when c is clockwise of b in SVG's y-down space. */\nexport function cross(a: PlanPoint, b: PlanPoint, c: PlanPoint): number {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\n}\n\nexport function lerp(a: PlanPoint, b: PlanPoint, t: number): PlanPoint {\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n}\n\n/** Unit vector from a to b, or null when they are coincident. */\nexport function direction(a: PlanPoint, b: PlanPoint): PlanPoint | null {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.hypot(dx, dy);\n if (len < 1e-9) return null;\n return { x: dx / len, y: dy / len };\n}\n\n/** Left-hand normal of the direction from a to b, or null when coincident. */\nexport function normal(a: PlanPoint, b: PlanPoint): PlanPoint | null {\n const d = direction(a, b);\n return d ? { x: -d.y, y: d.x } : null;\n}\n\n// ─── Point / segment ───────────────────────────────────────────────────────────\n\n/**\n * Distance from p to segment ab, plus the clamped parameter t of the closest point.\n * `t` is clamped to [0, 1], so the closest point is always on the segment.\n */\nexport function pointToSegment(\n p: PlanPoint,\n a: PlanPoint,\n b: PlanPoint,\n): { dist: number; t: number; point: PlanPoint } {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len2 = dx * dx + dy * dy;\n if (len2 === 0) return { dist: dist(p, a), t: 0, point: { x: a.x, y: a.y } };\n const raw = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;\n const t = raw < 0 ? 0 : raw > 1 ? 1 : raw;\n const point = { x: a.x + t * dx, y: a.y + t * dy };\n return { dist: dist(p, point), t, point };\n}\n\n/**\n * Exact projection of p onto segment ab, clamped to the segment.\n *\n * Used after a fuzzy hit tolerance has decided that p belongs to this segment: intent\n * is allowed to be approximate, the stored model never is.\n */\nexport function projectOnSegment(p: PlanPoint, a: PlanPoint, b: PlanPoint): PlanPoint {\n return pointToSegment(p, a, b).point;\n}\n\nexport type SegmentIntersectionKind =\n /** The segments cross strictly inside both. */\n | 'proper'\n /** They are parallel and do not touch. */\n | 'none'\n /** They lie on the same line and overlap over a non-zero length. */\n | 'collinearOverlap'\n /** They lie on the same line but do not overlap. */\n | 'collinearDisjoint'\n /** An endpoint of one lies on the other, or they share an endpoint. */\n | 'touch';\n\nexport interface SegmentIntersection {\n kind: SegmentIntersectionKind;\n /** Parameter along ab, for 'proper' and 'touch'. */\n t?: number;\n /** Parameter along cd, for 'proper' and 'touch'. */\n s?: number;\n point?: PlanPoint;\n}\n\n/**\n * Classifies how segments ab and cd meet.\n *\n * `eps` is a millimetre distance tolerance, not a parameter tolerance, so the result\n * does not change with segment length.\n */\nexport function segmentIntersection(\n a: PlanPoint,\n b: PlanPoint,\n c: PlanPoint,\n d: PlanPoint,\n eps = EPS_COINCIDENT,\n): SegmentIntersection {\n const abLen = dist(a, b);\n const cdLen = dist(c, d);\n if (abLen < 1e-9 || cdLen < 1e-9) return { kind: 'none' };\n\n const rx = b.x - a.x;\n const ry = b.y - a.y;\n const sx = d.x - c.x;\n const sy = d.y - c.y;\n const denom = rx * sy - ry * sx;\n\n // Perpendicular distance of c and d from line ab, used to tell parallel from collinear.\n const distC = Math.abs(cross(a, b, c)) / abLen;\n const distD = Math.abs(cross(a, b, d)) / abLen;\n\n if (Math.abs(denom) < 1e-12 || (distC < eps && distD < eps)) {\n if (distC >= eps || distD >= eps) return { kind: 'none' };\n // Collinear: compare parameters along ab.\n const len2 = rx * rx + ry * ry;\n const tc = ((c.x - a.x) * rx + (c.y - a.y) * ry) / len2;\n const td = ((d.x - a.x) * rx + (d.y - a.y) * ry) / len2;\n const lo = Math.min(tc, td);\n const hi = Math.max(tc, td);\n const epsT = eps / abLen;\n if (hi < epsT || lo > 1 - epsT) return { kind: 'collinearDisjoint' };\n if (Math.min(hi, 1) - Math.max(lo, 0) < epsT) return { kind: 'collinearDisjoint' };\n return { kind: 'collinearOverlap' };\n }\n\n const t = ((c.x - a.x) * sy - (c.y - a.y) * sx) / denom;\n const s = ((c.x - a.x) * ry - (c.y - a.y) * rx) / denom;\n const epsT = eps / abLen;\n const epsS = eps / cdLen;\n\n if (t < -epsT || t > 1 + epsT || s < -epsS || s > 1 + epsS) return { kind: 'none' };\n\n const point = { x: a.x + t * rx, y: a.y + t * ry };\n const atAbEnd = t <= epsT || t >= 1 - epsT;\n const atCdEnd = s <= epsS || s >= 1 - epsS;\n if (atAbEnd || atCdEnd) return { kind: 'touch', t, s, point };\n return { kind: 'proper', t, s, point };\n}\n\n// ─── Rings ─────────────────────────────────────────────────────────────────────\n\n/**\n * Shoelace area of a closed ring (first vertex not repeated).\n *\n * Positive means visually clockwise in SVG's y-down space. See `PlanFace.outer`.\n */\nexport function signedArea(ring: readonly PlanPoint[]): number {\n const n = ring.length;\n if (n < 3) return 0;\n let sum = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n sum += ring[j].x * ring[i].y - ring[i].x * ring[j].y;\n }\n return sum / 2;\n}\n\nexport function perimeter(ring: readonly PlanPoint[]): number {\n const n = ring.length;\n if (n < 2) return 0;\n let sum = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) sum += dist(ring[j], ring[i]);\n return sum;\n}\n\n/**\n * Area-weighted centroid of a ring.\n *\n * Deliberately not the vertex mean: a dangling wall adds an out-and-back vertex pair\n * that skews the mean but contributes nothing to the area moment. Falls back to the\n * vertex mean only for a degenerate (zero-area) ring.\n */\nexport function areaCentroid(ring: readonly PlanPoint[]): PlanPoint {\n const n = ring.length;\n if (n === 0) return { x: 0, y: 0 };\n if (n < 3) {\n return {\n x: ring.reduce((s, p) => s + p.x, 0) / n,\n y: ring.reduce((s, p) => s + p.y, 0) / n,\n };\n }\n let a = 0;\n let cx = 0;\n let cy = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const f = ring[j].x * ring[i].y - ring[i].x * ring[j].y;\n a += f;\n cx += (ring[j].x + ring[i].x) * f;\n cy += (ring[j].y + ring[i].y) * f;\n }\n if (Math.abs(a) < 1e-9) {\n return {\n x: ring.reduce((s, p) => s + p.x, 0) / n,\n y: ring.reduce((s, p) => s + p.y, 0) / n,\n };\n }\n return { x: cx / (3 * a), y: cy / (3 * a) };\n}\n\n/** Ray-casting point-in-ring test. Points exactly on an edge are unspecified. */\nexport function pointInRing(p: PlanPoint, ring: readonly PlanPoint[]): boolean {\n let inside = false;\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const xi = ring[i].x;\n const yi = ring[i].y;\n const xj = ring[j].x;\n const yj = ring[j].y;\n if (yi > p.y !== yj > p.y && p.x < ((xj - xi) * (p.y - yi)) / (yj - yi) + xi) {\n inside = !inside;\n }\n }\n return inside;\n}\n\n/** Inside `outer` and outside every hole. */\nexport function pointInRings(\n p: PlanPoint,\n outer: readonly PlanPoint[],\n holes: readonly (readonly PlanPoint[])[] = [],\n): boolean {\n if (!pointInRing(p, outer)) return false;\n for (const hole of holes) if (pointInRing(p, hole)) return false;\n return true;\n}\n\n/**\n * A point guaranteed to lie strictly inside the ring set, placed somewhere visually\n * central where possible.\n *\n * The area centroid is preferred, but it is not guaranteed to be inside a concave\n * polygon (an L-shaped room's centroid can land in the notch), so a scanline fallback\n * picks the widest interior span across several horizontal lines. The EPS_SPAN test on\n * that span is what stops an anchor landing inside the zero-width slit that a dangling\n * wall leaves in a face.\n */\nexport function representativePoint(\n outer: readonly PlanPoint[],\n holes: readonly (readonly PlanPoint[])[] = [],\n): PlanPoint {\n if (outer.length === 0) return { x: 0, y: 0 };\n\n const centre = areaCentroid(outer);\n if (pointInRings(centre, outer, holes)) return centre;\n\n let ymin = Infinity;\n let ymax = -Infinity;\n for (const p of outer) {\n if (p.y < ymin) ymin = p.y;\n if (p.y > ymax) ymax = p.y;\n }\n if (!Number.isFinite(ymin) || ymax - ymin < 1e-9) return centre;\n\n const rings: readonly (readonly PlanPoint[])[] = [outer, ...holes];\n let best: { point: PlanPoint; width: number } | null = null;\n\n const SAMPLES = 7;\n for (let k = 1; k <= SAMPLES; k++) {\n const y = ymin + ((ymax - ymin) * k) / (SAMPLES + 1);\n const xs: number[] = [];\n // One crossing list across ALL rings, so even-odd pairing yields interior spans\n // directly. Running the scanline per ring would not compose with holes.\n for (const ring of rings) {\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const p = ring[j];\n const q = ring[i];\n if (p.y > y !== q.y > y) {\n xs.push(p.x + ((y - p.y) * (q.x - p.x)) / (q.y - p.y));\n }\n }\n }\n xs.sort((m, n) => m - n);\n for (let i = 0; i + 1 < xs.length; i += 2) {\n const width = xs[i + 1] - xs[i];\n if (width > EPS_SPAN && (!best || width > best.width)) {\n best = { point: { x: (xs[i] + xs[i + 1]) / 2, y }, width };\n }\n }\n }\n\n return best ? best.point : centre;\n}\n\n/**\n * Removes out-and-back spurs (`... P, Q, P ...`) from a ring, repeatedly until none\n * remain.\n *\n * A face containing a dangling wall is a valid fill but is not a simple polygon, which\n * breaks polygon offsetting and makes some triangulators emit zero-area triangles. Run\n * this before triangulating a floor slab; keep the raw ring for the 2D fill, where the\n * slit is harmless and `wallIds` alignment matters.\n */\nexport function stripSpurs(ring: readonly PlanPoint[]): PlanPoint[] {\n let out = ring.slice();\n let changed = true;\n while (changed && out.length > 3) {\n changed = false;\n const next: PlanPoint[] = [];\n const n = out.length;\n for (let i = 0; i < n; i++) {\n const prev = out[(i - 1 + n) % n];\n const nextPt = out[(i + 1) % n];\n // The middle of an out-and-back is the vertex whose neighbours coincide.\n if (dist(prev, nextPt) < EPS_COINCIDENT) {\n changed = true;\n continue;\n }\n next.push(out[i]);\n }\n if (changed) {\n // Drop the now-duplicated turning point left behind by each removed spur tip.\n out = next.filter((p, i) => dist(p, next[(i + 1) % next.length]) >= EPS_COINCIDENT);\n }\n }\n return out;\n}\n\nexport function rectToPoints(x: number, y: number, w: number, h: number): PlanPoint[] {\n return [\n { x, y },\n { x: x + w, y },\n { x: x + w, y: y + h },\n { x, y: y + h },\n ];\n}\n\nexport function boundsOf(points: readonly PlanPoint[]): {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n} | null {\n if (points.length === 0) return null;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of points) {\n if (p.x < minX) minX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.x > maxX) maxX = p.x;\n if (p.y > maxY) maxY = p.y;\n }\n return { minX, minY, maxX, maxY };\n}\n"],"mappings":"AAgBA,IAAa,EAAkB,GAMlB,EAAY,KAIZ,EAAoB,IAIjC,SAAgB,EAAK,EAAc,EAAsB,CACvD,OAAO,KAAK,MAAM,EAAE,EAAI,EAAE,EAAG,EAAE,EAAI,EAAE,CAAC,CACxC,CASA,SAAgB,EAAM,EAAc,EAAc,EAAsB,CACtE,OAAQ,EAAE,EAAI,EAAE,IAAM,EAAE,EAAI,EAAE,IAAM,EAAE,EAAI,EAAE,IAAM,EAAE,EAAI,EAAE,EAC5D,CA2BA,SAAgB,EACd,EACA,EACA,EAC+C,CAC/C,IAAM,EAAK,EAAE,EAAI,EAAE,EACb,EAAK,EAAE,EAAI,EAAE,EACb,EAAO,EAAK,EAAK,EAAK,EAC5B,GAAI,IAAS,EAAG,MAAO,CAAE,KAAM,EAAK,EAAG,CAAC,EAAG,EAAG,EAAG,MAAO,CAAE,EAAG,EAAE,EAAG,EAAG,EAAE,CAAE,CAAE,EAC3E,IAAM,IAAQ,EAAE,EAAI,EAAE,GAAK,GAAM,EAAE,EAAI,EAAE,GAAK,GAAM,EAC9C,EAAI,EAAM,EAAI,EAAI,EAAM,EAAI,EAAI,EAChC,EAAQ,CAAE,EAAG,EAAE,EAAI,EAAI,EAAI,EAAG,EAAE,EAAI,EAAI,CAAG,EACjD,MAAO,CAAE,KAAM,EAAK,EAAG,CAAK,EAAG,IAAG,OAAM,CAC1C,CAQA,SAAgB,EAAiB,EAAc,EAAc,E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,GAAK,EAAI,EAAI,GAAK,GACzB,EAAS,GAAK,EAAI,GAAK,GAE7B,GAAI,EAAK,EAAM,CAAM,EAAA,EAAoB,CACvC,EAAU,GACV,QACF,CACA,EAAK,KAAK,EAAI,EAAE,CAClB,CACI,IAEF,EAAM,EAAK,QAAQ,EAAG,IAAM,EAAK,EAAG,GAAM,EAAI,GAAK,EAAK,OAAO,GAAA,CAAmB,EAEtF,CACA,OAAO,CACT,CAWA,SAAgB,EAAS,EAKhB,CACP,GAAI,EAAO,SAAW,EAAG,OAAO,KAChC,IAAI,EAAO,IACP,EAAO,IACP,EAAO,KACP,EAAO,KACX,IAAK,IAAM,KAAK,EACV,EAAE,EAAI,IAAM,EAAO,EAAE,GACrB,EAAE,EAAI,IAAM,EAAO,EAAE,GACrB,EAAE,EAAI,IAAM,EAAO,EAAE,GACrB,EAAE,EAAI,IAAM,EAAO,EAAE,GAE3B,MAAO,CAAE,OAAM,OAAM,OAAM,MAAK,CAClC"}
@@ -1,2 +1,2 @@
1
- import{PlanIssueKind as e,WallType as t}from"./floorPlan.types.mjs";import{cross as n,dist as r,pointToSegment as i,projectOnSegment as a,segmentIntersection as o}from"./floorPlan.geometry.mjs";var s=0;function c(e){return s+=1,`${e}_${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID().slice(0,8):Math.random().toString(36).slice(2,10)}${s.toString(36)}`}function l(e){return{...e,nodes:{...e.nodes},walls:{...e.walls},openings:{...e.openings},rooms:{...e.rooms}}}function u(e,t,n={}){return{kind:e,message:t,...n}}function d(e,t){let n=e.nodes[t.a],i=e.nodes[t.b];return!n||!i?0:r(n,i)}function f(e,t){return Object.values(e.walls).filter(e=>e.a===t||e.b===t)}function p(e,t,n){for(let r of Object.values(e.walls))if(r.a===t&&r.b===n||r.a===n&&r.b===t)return r;return null}var m=250;function h(e,t){return`${Math.round(e/m)}|${Math.round(t/m)}`}function g(e){let t=new Map;for(let n of Object.values(e.nodes)){let e=h(n.x,n.y),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function _(e,t,n){let i=g(e),a=Math.round(t.x/m),o=Math.round(t.y/m),s=null,c=n,l=Math.max(1,Math.ceil(n/m));for(let e=-l;e<=l;e++)for(let n=-l;n<=l;n++)for(let l of i.get(`${a+e}|${o+n}`)??[]){let e=r(t,l);e<=c&&(s=l,c=e)}return s}function v(e,t,n,r){let a=null;for(let o of Object.values(e.walls)){if(r?.has(o.id))continue;let s=e.nodes[o.a],c=e.nodes[o.b];if(!s||!c)continue;let l=i(t,s,c);l.dist<=n&&(!a||l.dist<a.dist)&&(a={wall:o,t:l.t,point:l.point,dist:l.dist})}return a}function y(t,n,i){let o=t.walls[n];if(!o)return{floor:t,result:{nodeId:``,wallIds:null,droppedOpeningIds:[]},issues:[]};let s=t.nodes[o.a],d=t.nodes[o.b];if(!s||!d)return{floor:t,result:{nodeId:``,wallIds:null,droppedOpeningIds:[]},issues:[]};let f=r(s,d),p=a(typeof i==`number`?{x:s.x+(d.x-s.x)*i,y:s.y+(d.y-s.y)*i}:i,s,d),m=r(s,p);if(m<10)return{floor:t,result:{nodeId:o.a,wallIds:null,droppedOpeningIds:[]},issues:[]};if(f-m<10)return{floor:t,result:{nodeId:o.b,wallIds:null,droppedOpeningIds:[]},issues:[]};let h=l(t),g=c(`n`);h.nodes[g]={id:g,x:p.x,y:p.y};let _=c(`w`),v=c(`w`),y={thickness:o.thickness,type:o.type,height:o.height,baseHeight:o.baseHeight};h.walls[_]={...y,id:_,a:o.a,b:g},h.walls[v]={...y,id:v,a:g,b:o.b},delete h.walls[n];let b=[],x=[];for(let r of Object.values(t.openings)){if(r.wallId!==n)continue;let t=r.offset<=m,i=t?_:v,a=t?m:f-m,o=t?r.offset:r.offset-m,s=Math.min(r.width,a-2,o*2,(a-o)*2);if(s<100){delete h.openings[r.id],b.push(r.id),x.push(u(e.OpeningDropped,`An opening was removed: the wall it sat on became too short for it.`,{openingIds:[r.id],wallIds:[n]}));continue}h.openings[r.id]={...r,wallId:i,offset:o,width:s}}return{floor:h,result:{nodeId:g,wallIds:[_,v],droppedOpeningIds:b},issues:x}}function b(e,t,n){let r=_(e,t,n);if(r)return{floor:e,result:{nodeId:r.id,createdNode:!1,splitWallId:null},issues:[]};let i=v(e,t,n);if(i){let t=y(e,i.wall.id,i.point);if(t.result.nodeId)return{floor:t.floor,result:{nodeId:t.result.nodeId,createdNode:t.result.wallIds!==null,splitWallId:t.result.wallIds?i.wall.id:null},issues:t.issues}}let a=l(e),o=c(`n`);return a.nodes[o]={id:o,x:t.x,y:t.y},{floor:a,result:{nodeId:o,createdNode:!0,splitWallId:null},issues:[]}}var x={thickness:200,type:t.Interior};function S(t,n,a,s=x,l=1){let d=[];if(r(n,a)<10)return{floor:t,result:{wallIds:[],nodeIds:[]},issues:d};let f=b(t,n,l),m=f.floor;d.push(...f.issues);let h=b(m,a,l);m=h.floor,d.push(...h.issues);let g=f.result.nodeId,_=h.result.nodeId;if(g===_)return{floor:t,result:{wallIds:[],nodeIds:[]},issues:d};let v=m.nodes[g],S=m.nodes[_],C=r(v,S);if(C<10)return{floor:t,result:{wallIds:[],nodeIds:[]},issues:d};let w=[{t:0,nodeId:g},{t:1,nodeId:_}],T=new Map,E=[],D=e=>i(e,v,S).t;for(let e of Object.values(m.walls)){let t=m.nodes[e.a],n=m.nodes[e.b];if(!t||!n)continue;let r=o(v,S,t,n,l);if(r.kind===`collinearOverlap`){let e=D(t),r=D(n);E.push([Math.min(e,r),Math.max(e,r)]);for(let[i,a]of[[t,e],[n,r]])a*C>10&&(1-a)*C>10&&w.push({t:a,nodeId:i.id});continue}if(r.kind===`proper`&&r.t!==void 0&&r.s!==void 0){let t=T.get(e.id);t?t.push(r.s):T.set(e.id,[r.s]),w.push({t:r.t,nodeId:null,pending:{wallId:e.id,s:r.s}});continue}if(r.kind===`touch`&&r.t!==void 0&&r.s!==void 0){let e=r.s<=.5?t:n,a=D(e);i(e,v,S).dist<=l&&a*C>10&&(1-a)*C>10&&w.push({t:a,nodeId:e.id})}}for(let e of Object.values(m.nodes)){if(e.id===g||e.id===_)continue;let t=i(e,v,S);t.dist>l||t.t*C<=10||(1-t.t)*C<=10||w.push({t:t.t,nodeId:e.id})}for(let[e,n]of T){let r=[...n].sort((e,t)=>t-e),i=e,a=new Set(r);for(let n of r){let r=m.walls[i];if(!r)break;let o=m.nodes[r.a],s=m.nodes[r.b];if(!o||!s)break;let c=t.walls[e],l=m.nodes[c?.a??r.a]??o,u=m.nodes[c?.b??r.b]??s,f={x:l.x+(u.x-l.x)*n,y:l.y+(u.y-l.y)*n},p=y(m,i,f);m=p.floor,d.push(...p.issues),a.delete(n);for(let t of w)t.pending&&t.pending.wallId===e&&t.pending.s===n&&(t.nodeId=p.result.nodeId,t.pending=void 0);if(p.result.wallIds){let[e,t]=p.result.wallIds,r=Math.max(...a,-1);i=r>=0&&r>n?t:e}}}let O=w.filter(e=>!!e.nodeId);O.sort((e,t)=>e.t-t.t);let k=[];for(let e of O){let t=k[k.length-1];if(!t){k.push(e);continue}if(t.nodeId!==e.nodeId){if((e.t-t.t)*C<10){e.t>=.999999999&&(k[k.length-1]=e);continue}k.push(e)}}let A=[];for(let e=0;e+1<k.length;e++){let t=k[e],n=k[e+1],i=(t.t+n.t)/2;if(E.some(([e,t])=>i>e+1e-9&&i<t-1e-9)||p(m,t.nodeId,n.nodeId))continue;let a=m.nodes[t.nodeId],o=m.nodes[n.nodeId];if(!a||!o||r(a,o)<10)continue;let l=c(`w`);m={...m,walls:{...m.walls,[l]:{...s,id:l,a:t.nodeId,b:n.nodeId}}},A.push(l)}return A.length===0&&E.length>0&&d.push(u(e.DuplicateWall,`A wall already covers that span, so nothing was added.`)),{floor:m,result:{wallIds:A,nodeIds:k.map(e=>e.nodeId)},issues:d}}function C(e,t,n,r=x,i=1){let a=Math.min(t.x,n.x),o=Math.max(t.x,n.x),s=Math.min(t.y,n.y),c=Math.max(t.y,n.y);if(o-a<10||c-s<10)return{floor:e,result:{wallIds:[]},issues:[]};let l=[{x:a,y:s},{x:o,y:s},{x:o,y:c},{x:a,y:c}],u=e,d=[],f=[];for(let e=0;e<4;e++){let t=S(u,l[e],l[(e+1)%4],r,i);u=t.floor,d.push(...t.result.wallIds),f.push(...t.issues)}return{floor:u,result:{wallIds:d},issues:f}}function w(t,n,r){if(n===r||!t.nodes[n]||!t.nodes[r])return{floor:t,result:{removedWallIds:[]},issues:[]};let i=l(t),a=[],o=[];for(let e of Object.values(i.walls))e.a===r&&(i.walls[e.id]={...i.walls[e.id],a:n}),e.b===r&&(i.walls[e.id]={...i.walls[e.id],b:n});for(let e of Object.values(i.walls))if(e.a===e.b){delete i.walls[e.id],a.push(e.id);for(let t of Object.values(i.openings))t.wallId===e.id&&delete i.openings[t.id]}let s=new Map;for(let t of Object.values(i.walls)){let n=t.a<t.b?`${t.a}|${t.b}`:`${t.b}|${t.a}`,r=s.get(n);if(!r){s.set(n,t);continue}let c=t.thickness>=r.thickness?t:r,l=c===t?r:t;for(let e of Object.values(i.openings))e.wallId===l.id&&(i.openings[e.id]={...e,wallId:c.id});delete i.walls[l.id],a.push(l.id),s.set(n,c),o.push(u(e.DuplicateWall,`Two walls became the same wall and were merged.`,{wallIds:[c.id,l.id]}))}return delete i.nodes[r],{floor:i,result:{removedWallIds:a},issues:o}}function T(t,i,a={}){let{force:o=!1}=a,s=t.nodes[i];if(!s)return{floor:t,result:null,issues:[]};let p=f(t,i);if(p.length!==2)return{floor:t,result:null,issues:[]};let[m,h]=p,g=m.thickness===h.thickness&&m.type===h.type&&m.height===h.height&&m.baseHeight===h.baseHeight;if(!g&&!o)return{floor:t,result:null,issues:[]};let _=m.a===i?m.b:m.a,v=h.a===i?h.b:h.a;if(_===v)return{floor:t,result:null,issues:[]};let y=t.nodes[_],b=t.nodes[v];if(!y||!b)return{floor:t,result:null,issues:[]};let x=r(y,b);if(x<10||!o&&Math.abs(n(y,b,s))/x>Math.max(1,x*1e-4))return{floor:t,result:null,issues:[]};let S=!g&&m.thickness<h.thickness?h:m,C=l(t),w=c(`w`);C.walls[w]={id:w,a:_,b:v,thickness:S.thickness,type:S.type,height:S.height,baseHeight:S.baseHeight};let T=r(y,s),E=r(s,b),D=T+E>0?x/(T+E):1,O=[];for(let n of Object.values(t.openings)){if(n.wallId!==m.id&&n.wallId!==h.id)continue;let r=n.wallId===m.id,a=r?m:h,o=a.a===i,s=d(t,a),c=o?n.offset:s-n.offset,l=(r?T-c:T+c)*D,f=Math.min(n.width*D,x-2);if(f<100){O.push(u(e.OpeningDropped,`An opening was removed: the wall it sat on became too short for it.`,{openingIds:[n.id],wallIds:[a.id]})),delete C.openings[n.id];continue}C.openings[n.id]={...n,wallId:w,width:f,offset:Math.min(Math.max(l,f/2),x-f/2)}}return delete C.walls[m.id],delete C.walls[h.id],delete C.nodes[i],{floor:C,result:{wallId:w},issues:O}}function E(e,t,n={}){let{pruneOrphanNodes:r=!0,dissolveCollinear:i=!0}=n,a=e.walls[t];if(!a)return{floor:e,result:{removedNodeIds:[],dissolvedWallIds:[]},issues:[]};let o=l(e);delete o.walls[t];for(let e of Object.values(o.openings))e.wallId===t&&delete o.openings[e.id];let s=[],c=[],u=[];for(let e of[a.a,a.b]){let t=f(o,e).length;if(t===0&&r)delete o.nodes[e],s.push(e);else if(t===2&&i){let t=T(o,e);t.result&&(o=t.floor,c.push(t.result.wallId),s.push(e),u.push(...t.issues))}}return{floor:o,result:{removedNodeIds:s,dissolvedWallIds:c},issues:u}}function D(e,t,n){let r=e.nodes[t];if(!r)return{floor:e,result:void 0,issues:[]};let i=l(e);return i.nodes[t]={...r,x:n.x,y:n.y},{floor:i,result:void 0,issues:[]}}function O(e,t,n){let r=l(e);for(let i of Object.values(e.nodes))r.nodes[i.id]={...i,x:i.x+t,y:i.y+n};for(let i of Object.values(e.rooms))r.rooms[i.id]={...i,anchor:{x:i.anchor.x+t,y:i.anchor.y+n}};return r}function k(e,t){let n=l(e);for(let r of Object.values(e.nodes))n.nodes[r.id]={...r,x:r.x*t,y:r.y*t};for(let r of Object.values(e.walls))n.walls[r.id]={...r,thickness:r.thickness*t,height:r.height===void 0?void 0:r.height*t,baseHeight:r.baseHeight===void 0?void 0:r.baseHeight*t};for(let r of Object.values(e.openings))n.openings[r.id]={...r,offset:r.offset*t,width:r.width*t,sill:r.sill*t,head:r.head*t};for(let r of Object.values(e.rooms))n.rooms[r.id]={...r,anchor:{x:r.anchor.x*t,y:r.anchor.y*t},area:r.area*t*t};return n}function A(t,n){let r=t.walls[n.wallId];if(!r)return{floor:t,result:{openingId:null},issues:[]};let i=d(t,r),a=Math.min(n.width,i-2);if(a<100)return{floor:t,result:{openingId:null},issues:[u(e.OpeningDropped,`That wall is too short for an opening.`,{wallIds:[r.id]})]};let o=Math.min(Math.max(n.offset,a/2),i-a/2),s=l(t),f=c(`o`);return s.openings[f]={...n,id:f,offset:o,width:a},{floor:s,result:{openingId:f},issues:[]}}function j(e,t,n){let r=e.openings[t];if(!r)return{floor:e,result:void 0,issues:[]};let i=e.walls[r.wallId];if(!i)return{floor:e,result:void 0,issues:[]};let a=d(e,i),o={...r,...n},s=Math.min(Math.max(o.width,100),Math.max(a-2,100)),c=Math.min(Math.max(o.offset,s/2),Math.max(a-s/2,s/2)),u=l(e);return u.openings[t]={...o,width:s,offset:c},{floor:u,result:void 0,issues:[]}}function M(e,t){if(!e.openings[t])return{floor:e,result:void 0,issues:[]};let n=l(e);return delete n.openings[t],{floor:n,result:void 0,issues:[]}}function N(t){let n=[],a=Object.values(t.walls);for(let i of a){let a=t.nodes[i.a],o=t.nodes[i.b];if(i.a===i.b){n.push(u(e.SelfLoopWall,`A wall starts and ends at the same node.`,{wallIds:[i.id]}));continue}if(!a||!o){n.push(u(e.ZeroLengthWall,`A wall references a missing node.`,{wallIds:[i.id]}));continue}r(a,o)<10&&n.push(u(e.ZeroLengthWall,`A wall is shorter than the minimum length.`,{wallIds:[i.id]}))}let s=new Map;for(let t of a){let r=t.a<t.b?`${t.a}|${t.b}`:`${t.b}|${t.a}`,i=s.get(r);i?n.push(u(e.DuplicateWall,`Two walls connect the same pair of nodes.`,{wallIds:[i,t.id]})):s.set(r,t.id)}let c=Object.values(t.nodes);for(let t=0;t<c.length;t++)for(let i=t+1;i<c.length;i++)r(c[t],c[i])<1&&n.push(u(e.CoincidentNodes,`Two nodes occupy the same position.`,{nodeIds:[c[t].id,c[i].id]}));for(let r=0;r<a.length;r++)for(let i=r+1;i<a.length;i++){let s=a[r],c=a[i],l=t.nodes[s.a],d=t.nodes[s.b],f=t.nodes[c.a],p=t.nodes[c.b];if(!l||!d||!f||!p)continue;let m=o(l,d,f,p);m.kind===`proper`?n.push(u(e.UnsplitCrossing,`Two walls cross with no node at the intersection.`,{wallIds:[s.id,c.id]})):m.kind===`collinearOverlap`&&n.push(u(e.OverlappingWalls,`Two walls overlap along the same line.`,{wallIds:[s.id,c.id]}))}for(let r of a){let a=t.nodes[r.a],o=t.nodes[r.b];if(!(!a||!o))for(let t of c){if(t.id===r.a||t.id===r.b)continue;let s=i(t,a,o);s.dist<1&&s.t>0&&s.t<1&&n.push(u(e.UnsplitNodeOnWall,`A node sits on a wall that was never split there.`,{wallIds:[r.id],nodeIds:[t.id]}))}}for(let r of Object.values(t.openings))t.walls[r.wallId]||n.push(u(e.DanglingOpening,`An opening references a wall that no longer exists.`,{openingIds:[r.id]}));let l=new Set;for(let e of a)l.add(e.a),l.add(e.b);for(let t of c)l.has(t.id)||n.push(u(e.OrphanNode,`A node has no walls.`,{nodeIds:[t.id]}));return n}function P(t){let n=l(t),i=[];for(let t of Object.values(n.walls)){let a=n.nodes[t.a],o=n.nodes[t.b];(t.a===t.b||!a||!o||r(a,o)<10)&&(delete n.walls[t.id],i.push(u(e.ZeroLengthWall,`Removed a degenerate wall.`,{wallIds:[t.id]})))}let a=new Map;for(let t of Object.values(n.walls)){let r=t.a<t.b?`${t.a}|${t.b}`:`${t.b}|${t.a}`,o=a.get(r);if(!o){a.set(r,t);continue}let s=t.thickness>=o.thickness?t:o,c=s===t?o:t;for(let e of Object.values(n.openings))e.wallId===c.id&&(n.openings[e.id]={...e,wallId:s.id});delete n.walls[c.id],a.set(r,s),i.push(u(e.DuplicateWall,`Removed a duplicate wall.`,{wallIds:[c.id]}))}for(let t of Object.values(n.openings))n.walls[t.wallId]||(delete n.openings[t.id],i.push(u(e.DanglingOpening,`Removed an opening with no wall.`,{openingIds:[t.id]})));let o=new Set;for(let e of Object.values(n.walls))o.add(e.a),o.add(e.b);for(let t of Object.values(n.nodes))o.has(t.id)||(delete n.nodes[t.id],i.push(u(e.OrphanNode,`Removed a node with no walls.`,{nodeIds:[t.id]})));return{floor:n,result:i,issues:i}}export{x as DEFAULT_WALL_ATTRS,A as addOpening,C as addRect,S as addWall,P as cleanupPlan,T as dissolveNode,w as mergeNodes,D as moveNode,c as newId,M as removeOpening,E as removeWall,k as scalePlan,y as splitWall,O as transformPlan,j as updateOpening,N as validatePlan,d as wallLength};
1
+ import{PlanIssueKind as e,WallType as t}from"./floorPlan.types.mjs";import{cross as n,dist as r,pointToSegment as i,projectOnSegment as a,segmentIntersection as o}from"./floorPlan.geometry.mjs";var s=0;function c(e){return s+=1,`${e}_${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID().slice(0,8):Math.random().toString(36).slice(2,10)}${s.toString(36)}`}function l(e){return{...e,nodes:{...e.nodes},walls:{...e.walls},openings:{...e.openings},rooms:{...e.rooms}}}function u(e,t,n={}){return{kind:e,message:t,...n}}function d(e,t){let n=e.nodes[t.a],i=e.nodes[t.b];return!n||!i?0:r(n,i)}function f(e,t){return Object.values(e.walls).filter(e=>e.a===t||e.b===t)}function p(e,t,n){for(let r of Object.values(e.walls))if(r.a===t&&r.b===n||r.a===n&&r.b===t)return r;return null}var m=250;function h(e,t){return`${Math.round(e/m)}|${Math.round(t/m)}`}function g(e){let t=new Map;for(let n of Object.values(e.nodes)){let e=h(n.x,n.y),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function _(e,t,n){let i=g(e),a=Math.round(t.x/m),o=Math.round(t.y/m),s=null,c=n,l=Math.max(1,Math.ceil(n/m));for(let e=-l;e<=l;e++)for(let n=-l;n<=l;n++)for(let l of i.get(`${a+e}|${o+n}`)??[]){let e=r(t,l);e<=c&&(s=l,c=e)}return s}function v(e,t,n,r){let a=null;for(let o of Object.values(e.walls)){if(r?.has(o.id))continue;let s=e.nodes[o.a],c=e.nodes[o.b];if(!s||!c)continue;let l=i(t,s,c);l.dist<=n&&(!a||l.dist<a.dist)&&(a={wall:o,t:l.t,point:l.point,dist:l.dist})}return a}function y(t,n,i){let o=t.walls[n];if(!o)return{floor:t,result:{nodeId:``,wallIds:null,droppedOpeningIds:[]},issues:[]};let s=t.nodes[o.a],d=t.nodes[o.b];if(!s||!d)return{floor:t,result:{nodeId:``,wallIds:null,droppedOpeningIds:[]},issues:[]};let f=r(s,d),p=a(typeof i==`number`?{x:s.x+(d.x-s.x)*i,y:s.y+(d.y-s.y)*i}:i,s,d),m=r(s,p);if(m<10)return{floor:t,result:{nodeId:o.a,wallIds:null,droppedOpeningIds:[]},issues:[]};if(f-m<10)return{floor:t,result:{nodeId:o.b,wallIds:null,droppedOpeningIds:[]},issues:[]};let h=l(t),g=c(`n`);h.nodes[g]={id:g,x:p.x,y:p.y};let _=c(`w`),v=c(`w`),y={thickness:o.thickness,type:o.type,height:o.height,baseHeight:o.baseHeight};h.walls[_]={...y,id:_,a:o.a,b:g},h.walls[v]={...y,id:v,a:g,b:o.b},delete h.walls[n];let b=[],x=[];for(let r of Object.values(t.openings)){if(r.wallId!==n)continue;let t=r.offset<=m,i=t?_:v,a=t?m:f-m,o=t?r.offset:r.offset-m,s=Math.min(r.width,a-2,o*2,(a-o)*2);if(s<100){delete h.openings[r.id],b.push(r.id),x.push(u(e.OpeningDropped,`An opening was removed: the wall it sat on became too short for it.`,{openingIds:[r.id],wallIds:[n]}));continue}h.openings[r.id]={...r,wallId:i,offset:o,width:s}}return{floor:h,result:{nodeId:g,wallIds:[_,v],droppedOpeningIds:b},issues:x}}function b(e,t,n){let r=_(e,t,n);if(r)return{floor:e,result:{nodeId:r.id,createdNode:!1,splitWallId:null},issues:[]};let i=v(e,t,n);if(i){let t=y(e,i.wall.id,i.point);if(t.result.nodeId)return{floor:t.floor,result:{nodeId:t.result.nodeId,createdNode:t.result.wallIds!==null,splitWallId:t.result.wallIds?i.wall.id:null},issues:t.issues}}let a=l(e),o=c(`n`);return a.nodes[o]={id:o,x:t.x,y:t.y},{floor:a,result:{nodeId:o,createdNode:!0,splitWallId:null},issues:[]}}var x={thickness:200,type:t.Interior};function S(t,n,a,s=x,l=1){let d=[];if(r(n,a)<10)return{floor:t,result:{wallIds:[],nodeIds:[]},issues:d};let f=b(t,n,l),m=f.floor;d.push(...f.issues);let h=b(m,a,l);m=h.floor,d.push(...h.issues);let g=f.result.nodeId,_=h.result.nodeId;if(g===_)return{floor:t,result:{wallIds:[],nodeIds:[]},issues:d};let v=m.nodes[g],S=m.nodes[_],C=r(v,S);if(C<10)return{floor:t,result:{wallIds:[],nodeIds:[]},issues:d};let w=[{t:0,nodeId:g},{t:1,nodeId:_}],T=new Map,E=[],D=e=>i(e,v,S).t;for(let e of Object.values(m.walls)){let t=m.nodes[e.a],n=m.nodes[e.b];if(!t||!n)continue;let r=o(v,S,t,n,l);if(r.kind===`collinearOverlap`){let e=D(t),r=D(n);E.push([Math.min(e,r),Math.max(e,r)]);for(let[i,a]of[[t,e],[n,r]])a*C>10&&(1-a)*C>10&&w.push({t:a,nodeId:i.id});continue}if(r.kind===`proper`&&r.t!==void 0&&r.s!==void 0){let t=T.get(e.id);t?t.push(r.s):T.set(e.id,[r.s]),w.push({t:r.t,nodeId:null,pending:{wallId:e.id,s:r.s}});continue}if(r.kind===`touch`&&r.t!==void 0&&r.s!==void 0){let e=r.s<=.5?t:n,a=D(e);i(e,v,S).dist<=l&&a*C>10&&(1-a)*C>10&&w.push({t:a,nodeId:e.id})}}for(let e of Object.values(m.nodes)){if(e.id===g||e.id===_)continue;let t=i(e,v,S);t.dist>l||t.t*C<=10||(1-t.t)*C<=10||w.push({t:t.t,nodeId:e.id})}for(let[e,n]of T){let r=[...n].sort((e,t)=>t-e),i=e,a=new Set(r);for(let n of r){let r=m.walls[i];if(!r)break;let o=m.nodes[r.a],s=m.nodes[r.b];if(!o||!s)break;let c=t.walls[e],l=m.nodes[c?.a??r.a]??o,u=m.nodes[c?.b??r.b]??s,f={x:l.x+(u.x-l.x)*n,y:l.y+(u.y-l.y)*n},p=y(m,i,f);m=p.floor,d.push(...p.issues),a.delete(n);for(let t of w)t.pending&&t.pending.wallId===e&&t.pending.s===n&&(t.nodeId=p.result.nodeId,t.pending=void 0);if(p.result.wallIds){let[e,t]=p.result.wallIds,r=Math.max(...a,-1);i=r>=0&&r>n?t:e}}}let O=w.filter(e=>!!e.nodeId);O.sort((e,t)=>e.t-t.t);let k=[];for(let e of O){let t=k[k.length-1];if(!t){k.push(e);continue}if(t.nodeId!==e.nodeId){if((e.t-t.t)*C<10){e.t>=.999999999&&(k[k.length-1]=e);continue}k.push(e)}}let A=[];for(let e=0;e+1<k.length;e++){let t=k[e],n=k[e+1],i=(t.t+n.t)/2;if(E.some(([e,t])=>i>e+1e-9&&i<t-1e-9)||p(m,t.nodeId,n.nodeId))continue;let a=m.nodes[t.nodeId],o=m.nodes[n.nodeId];if(!a||!o||r(a,o)<10)continue;let l=c(`w`);m={...m,walls:{...m.walls,[l]:{...s,id:l,a:t.nodeId,b:n.nodeId}}},A.push(l)}return A.length===0&&E.length>0&&d.push(u(e.DuplicateWall,`A wall already covers that span, so nothing was added.`)),{floor:m,result:{wallIds:A,nodeIds:k.map(e=>e.nodeId)},issues:d}}function C(e,t,n,r=x,i=1){let a=Math.min(t.x,n.x),o=Math.max(t.x,n.x),s=Math.min(t.y,n.y),c=Math.max(t.y,n.y);if(o-a<10||c-s<10)return{floor:e,result:{wallIds:[]},issues:[]};let l=[{x:a,y:s},{x:o,y:s},{x:o,y:c},{x:a,y:c}],u=e,d=[],f=[];for(let e=0;e<4;e++){let t=S(u,l[e],l[(e+1)%4],r,i);u=t.floor,d.push(...t.result.wallIds),f.push(...t.issues)}return{floor:u,result:{wallIds:d},issues:f}}function w(t,n,r){if(n===r||!t.nodes[n]||!t.nodes[r])return{floor:t,result:{removedWallIds:[]},issues:[]};let i=l(t),a=[],o=[];for(let e of Object.values(i.walls))e.a===r&&(i.walls[e.id]={...i.walls[e.id],a:n}),e.b===r&&(i.walls[e.id]={...i.walls[e.id],b:n});for(let e of Object.values(i.walls))if(e.a===e.b){delete i.walls[e.id],a.push(e.id);for(let t of Object.values(i.openings))t.wallId===e.id&&delete i.openings[t.id]}let s=new Map;for(let t of Object.values(i.walls)){let n=t.a<t.b?`${t.a}|${t.b}`:`${t.b}|${t.a}`,r=s.get(n);if(!r){s.set(n,t);continue}let c=t.thickness>=r.thickness?t:r,l=c===t?r:t;for(let e of Object.values(i.openings))e.wallId===l.id&&(i.openings[e.id]={...e,wallId:c.id});delete i.walls[l.id],a.push(l.id),s.set(n,c),o.push(u(e.DuplicateWall,`Two walls became the same wall and were merged.`,{wallIds:[c.id,l.id]}))}return delete i.nodes[r],{floor:i,result:{removedWallIds:a},issues:o}}function T(t,i,a={}){let{force:o=!1}=a,s=t.nodes[i];if(!s)return{floor:t,result:null,issues:[]};let p=f(t,i);if(p.length!==2)return{floor:t,result:null,issues:[]};let[m,h]=p,g=m.thickness===h.thickness&&m.type===h.type&&m.height===h.height&&m.baseHeight===h.baseHeight;if(!g&&!o)return{floor:t,result:null,issues:[]};let _=m.a===i?m.b:m.a,v=h.a===i?h.b:h.a;if(_===v)return{floor:t,result:null,issues:[]};let y=t.nodes[_],b=t.nodes[v];if(!y||!b)return{floor:t,result:null,issues:[]};let x=r(y,b);if(x<10||!o&&Math.abs(n(y,b,s))/x>Math.max(1,x*1e-4))return{floor:t,result:null,issues:[]};let S=!g&&m.thickness<h.thickness?h:m,C=l(t),w=c(`w`);C.walls[w]={id:w,a:_,b:v,thickness:S.thickness,type:S.type,height:S.height,baseHeight:S.baseHeight};let T=r(y,s),E=r(s,b),D=T+E>0?x/(T+E):1,O=[];for(let n of Object.values(t.openings)){if(n.wallId!==m.id&&n.wallId!==h.id)continue;let r=n.wallId===m.id,a=r?m:h,o=a.a===i,s=d(t,a),c=o?n.offset:s-n.offset,l=(r?T-c:T+c)*D,f=Math.min(n.width*D,x-2);if(f<100){O.push(u(e.OpeningDropped,`An opening was removed: the wall it sat on became too short for it.`,{openingIds:[n.id],wallIds:[a.id]})),delete C.openings[n.id];continue}C.openings[n.id]={...n,wallId:w,width:f,offset:Math.min(Math.max(l,f/2),x-f/2)}}return delete C.walls[m.id],delete C.walls[h.id],delete C.nodes[i],{floor:C,result:{wallId:w},issues:O}}function E(e,t,n){let r=e.walls[t];if(!r||r.a===r.b||Math.hypot(n.x,n.y)<10)return{floor:e,result:null,issues:[]};let i=[r.a,r.b],a=[r.a,r.b],o=[null,null],s=[],c=[],u=e;i.forEach((i,s)=>{let c=e.nodes[i];if(!c)return;let d={x:c.x+n.x,y:c.y+n.y},p=f(e,i).filter(e=>e.id!==t);if(p.length===0){let e=l(u);e.nodes[i]={...e.nodes[i],x:d.x,y:d.y},u=e;return}let m=b(u,d,1);u=m.floor,a[s]=m.result.nodeId,o[s]=p.length===1?p[0]:r});let d=l(u);d.walls[t]={...d.walls[t],a:a[0],b:a[1]},u=d,i.forEach((e,t)=>{let n=o[t],r=u.nodes[e],i=u.nodes[a[t]];if(!n||!r||!i)return;let l=S(u,r,i,{thickness:n.thickness,type:n.type,height:n.height,baseHeight:n.baseHeight});u=l.floor,s.push(...l.result.wallIds),c.push(...l.issues)});let p=[];return i.forEach((e,t)=>{if(a[t]===e)return;let n=T(u,e);n.result&&(u=n.floor,p.push(e),c.push(...n.issues))}),{floor:u,result:{nodeIds:a,connectorIds:s,dissolvedNodeIds:p},issues:c}}function D(e,t=10){let n=e,i=[],a=[];for(let o=Object.keys(e.walls).length;o>0;o--){let e=Object.values(n.walls).find(e=>{if(e.a===e.b)return!1;let i=n.nodes[e.a],a=n.nodes[e.b];return i&&a&&r(i,a)<t});if(!e)break;let o=f(n,e.b).length>f(n,e.a).length?e.b:e.a,s=w(n,o,o===e.a?e.b:e.a);if(s.floor===n)break;n=s.floor,i.push(e.id),a.push(...s.issues)}return{floor:n,result:{weldedWallIds:i},issues:a}}function O(e,t,n={}){let{pruneOrphanNodes:r=!0,dissolveCollinear:i=!0}=n,a=e.walls[t];if(!a)return{floor:e,result:{removedNodeIds:[],dissolvedWallIds:[]},issues:[]};let o=l(e);delete o.walls[t];for(let e of Object.values(o.openings))e.wallId===t&&delete o.openings[e.id];let s=[],c=[],u=[];for(let e of[a.a,a.b]){let t=f(o,e).length;if(t===0&&r)delete o.nodes[e],s.push(e);else if(t===2&&i){let t=T(o,e);t.result&&(o=t.floor,c.push(t.result.wallId),s.push(e),u.push(...t.issues))}}return{floor:o,result:{removedNodeIds:s,dissolvedWallIds:c},issues:u}}function k(e,t,n){let r=e.nodes[t];if(!r)return{floor:e,result:void 0,issues:[]};let i=l(e);return i.nodes[t]={...r,x:n.x,y:n.y},{floor:i,result:void 0,issues:[]}}function A(e,t,n){let r=l(e);for(let i of Object.values(e.nodes))r.nodes[i.id]={...i,x:i.x+t,y:i.y+n};for(let i of Object.values(e.rooms))r.rooms[i.id]={...i,anchor:{x:i.anchor.x+t,y:i.anchor.y+n}};return r}function j(e,t){let n=l(e);for(let r of Object.values(e.nodes))n.nodes[r.id]={...r,x:r.x*t,y:r.y*t};for(let r of Object.values(e.walls))n.walls[r.id]={...r,thickness:r.thickness*t,height:r.height===void 0?void 0:r.height*t,baseHeight:r.baseHeight===void 0?void 0:r.baseHeight*t};for(let r of Object.values(e.openings))n.openings[r.id]={...r,offset:r.offset*t,width:r.width*t,sill:r.sill*t,head:r.head*t};for(let r of Object.values(e.rooms))n.rooms[r.id]={...r,anchor:{x:r.anchor.x*t,y:r.anchor.y*t},area:r.area*t*t};return n}function M(t,n){let r=t.walls[n.wallId];if(!r)return{floor:t,result:{openingId:null},issues:[]};let i=d(t,r),a=Math.min(n.width,i-2);if(a<100)return{floor:t,result:{openingId:null},issues:[u(e.OpeningDropped,`That wall is too short for an opening.`,{wallIds:[r.id]})]};let o=Math.min(Math.max(n.offset,a/2),i-a/2),s=l(t),f=c(`o`);return s.openings[f]={...n,id:f,offset:o,width:a},{floor:s,result:{openingId:f},issues:[]}}function N(e,t,n){let r=e.openings[t];if(!r)return{floor:e,result:void 0,issues:[]};let i=e.walls[r.wallId];if(!i)return{floor:e,result:void 0,issues:[]};let a=d(e,i),o={...r,...n},s=Math.min(Math.max(o.width,100),Math.max(a-2,100)),c=Math.min(Math.max(o.offset,s/2),Math.max(a-s/2,s/2)),u=l(e);return u.openings[t]={...o,width:s,offset:c},{floor:u,result:void 0,issues:[]}}function P(e,t){if(!e.openings[t])return{floor:e,result:void 0,issues:[]};let n=l(e);return delete n.openings[t],{floor:n,result:void 0,issues:[]}}function F(t){let n=[],a=Object.values(t.walls);for(let i of a){let a=t.nodes[i.a],o=t.nodes[i.b];if(i.a===i.b){n.push(u(e.SelfLoopWall,`A wall starts and ends at the same node.`,{wallIds:[i.id]}));continue}if(!a||!o){n.push(u(e.ZeroLengthWall,`A wall references a missing node.`,{wallIds:[i.id]}));continue}r(a,o)<10&&n.push(u(e.ZeroLengthWall,`A wall is shorter than the minimum length.`,{wallIds:[i.id]}))}let s=new Map;for(let t of a){let r=t.a<t.b?`${t.a}|${t.b}`:`${t.b}|${t.a}`,i=s.get(r);i?n.push(u(e.DuplicateWall,`Two walls connect the same pair of nodes.`,{wallIds:[i,t.id]})):s.set(r,t.id)}let c=Object.values(t.nodes);for(let t=0;t<c.length;t++)for(let i=t+1;i<c.length;i++)r(c[t],c[i])<1&&n.push(u(e.CoincidentNodes,`Two nodes occupy the same position.`,{nodeIds:[c[t].id,c[i].id]}));for(let r=0;r<a.length;r++)for(let i=r+1;i<a.length;i++){let s=a[r],c=a[i],l=t.nodes[s.a],d=t.nodes[s.b],f=t.nodes[c.a],p=t.nodes[c.b];if(!l||!d||!f||!p)continue;let m=o(l,d,f,p);m.kind===`proper`?n.push(u(e.UnsplitCrossing,`Two walls cross with no node at the intersection.`,{wallIds:[s.id,c.id]})):m.kind===`collinearOverlap`&&n.push(u(e.OverlappingWalls,`Two walls overlap along the same line.`,{wallIds:[s.id,c.id]}))}for(let r of a){let a=t.nodes[r.a],o=t.nodes[r.b];if(!(!a||!o))for(let t of c){if(t.id===r.a||t.id===r.b)continue;let s=i(t,a,o);s.dist<1&&s.t>0&&s.t<1&&n.push(u(e.UnsplitNodeOnWall,`A node sits on a wall that was never split there.`,{wallIds:[r.id],nodeIds:[t.id]}))}}for(let r of Object.values(t.openings))t.walls[r.wallId]||n.push(u(e.DanglingOpening,`An opening references a wall that no longer exists.`,{openingIds:[r.id]}));let l=new Set;for(let e of a)l.add(e.a),l.add(e.b);for(let t of c)l.has(t.id)||n.push(u(e.OrphanNode,`A node has no walls.`,{nodeIds:[t.id]}));return n}function I(t){let n=[],i=D(t),a=l(i.floor);for(let t of i.result.weldedWallIds)n.push(u(e.ZeroLengthWall,`Welded the two ends of a wall with no length.`,{wallIds:[t]}));for(let t of Object.values(a.walls)){let i=a.nodes[t.a],o=a.nodes[t.b];(t.a===t.b||!i||!o||r(i,o)<10)&&(delete a.walls[t.id],n.push(u(e.ZeroLengthWall,`Removed a degenerate wall.`,{wallIds:[t.id]})))}let o=new Map;for(let t of Object.values(a.walls)){let r=t.a<t.b?`${t.a}|${t.b}`:`${t.b}|${t.a}`,i=o.get(r);if(!i){o.set(r,t);continue}let s=t.thickness>=i.thickness?t:i,c=s===t?i:t;for(let e of Object.values(a.openings))e.wallId===c.id&&(a.openings[e.id]={...e,wallId:s.id});delete a.walls[c.id],o.set(r,s),n.push(u(e.DuplicateWall,`Removed a duplicate wall.`,{wallIds:[c.id]}))}for(let t of Object.values(a.openings))a.walls[t.wallId]||(delete a.openings[t.id],n.push(u(e.DanglingOpening,`Removed an opening with no wall.`,{openingIds:[t.id]})));let s=new Set;for(let e of Object.values(a.walls))s.add(e.a),s.add(e.b);for(let t of Object.values(a.nodes))s.has(t.id)||(delete a.nodes[t.id],n.push(u(e.OrphanNode,`Removed a node with no walls.`,{nodeIds:[t.id]})));return{floor:a,result:n,issues:n}}export{x as DEFAULT_WALL_ATTRS,M as addOpening,C as addRect,S as addWall,I as cleanupPlan,E as detachWall,T as dissolveNode,w as mergeNodes,k as moveNode,c as newId,P as removeOpening,O as removeWall,j as scalePlan,y as splitWall,A as transformPlan,N as updateOpening,F as validatePlan,d as wallLength,D as weldShortWalls};
2
2
  //# sourceMappingURL=floorPlan.graph.mjs.map