react-resizable-panels.cjs.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var React = require('react');
  4. function _interopNamespace(e) {
  5. if (e && e.__esModule) return e;
  6. var n = Object.create(null);
  7. if (e) {
  8. Object.keys(e).forEach(function (k) {
  9. if (k !== 'default') {
  10. var d = Object.getOwnPropertyDescriptor(e, k);
  11. Object.defineProperty(n, k, d.get ? d : {
  12. enumerable: true,
  13. get: function () { return e[k]; }
  14. });
  15. }
  16. });
  17. }
  18. n["default"] = e;
  19. return Object.freeze(n);
  20. }
  21. var React__namespace = /*#__PURE__*/_interopNamespace(React);
  22. const isBrowser = typeof window !== "undefined";
  23. // The "contextmenu" event is not supported as a PointerEvent in all browsers yet, so MouseEvent still need to be handled
  24. const PanelGroupContext = React.createContext(null);
  25. PanelGroupContext.displayName = "PanelGroupContext";
  26. const DATA_ATTRIBUTES = {
  27. group: "data-panel-group",
  28. groupDirection: "data-panel-group-direction",
  29. groupId: "data-panel-group-id",
  30. panel: "data-panel",
  31. panelCollapsible: "data-panel-collapsible",
  32. panelId: "data-panel-id",
  33. panelSize: "data-panel-size",
  34. resizeHandle: "data-resize-handle",
  35. resizeHandleActive: "data-resize-handle-active",
  36. resizeHandleEnabled: "data-panel-resize-handle-enabled",
  37. resizeHandleId: "data-panel-resize-handle-id",
  38. resizeHandleState: "data-resize-handle-state"
  39. };
  40. const PRECISION = 10;
  41. const useIsomorphicLayoutEffect = isBrowser ? React.useLayoutEffect : () => {};
  42. const useId = React__namespace["useId".toString()];
  43. const wrappedUseId = typeof useId === "function" ? useId : () => null;
  44. let counter = 0;
  45. function useUniqueId(idFromParams = null) {
  46. const idFromUseId = wrappedUseId();
  47. const idRef = React.useRef(idFromParams || idFromUseId || null);
  48. if (idRef.current === null) {
  49. idRef.current = "" + counter++;
  50. }
  51. return idFromParams !== null && idFromParams !== void 0 ? idFromParams : idRef.current;
  52. }
  53. function PanelWithForwardedRef({
  54. children,
  55. className: classNameFromProps = "",
  56. collapsedSize,
  57. collapsible,
  58. defaultSize,
  59. forwardedRef,
  60. id: idFromProps,
  61. maxSize,
  62. minSize,
  63. onCollapse,
  64. onExpand,
  65. onResize,
  66. order,
  67. style: styleFromProps,
  68. tagName: Type = "div",
  69. ...rest
  70. }) {
  71. const context = React.useContext(PanelGroupContext);
  72. if (context === null) {
  73. throw Error(`Panel components must be rendered within a PanelGroup container`);
  74. }
  75. const {
  76. collapsePanel,
  77. expandPanel,
  78. getPanelSize,
  79. getPanelStyle,
  80. groupId,
  81. isPanelCollapsed,
  82. reevaluatePanelConstraints,
  83. registerPanel,
  84. resizePanel,
  85. unregisterPanel
  86. } = context;
  87. const panelId = useUniqueId(idFromProps);
  88. const panelDataRef = React.useRef({
  89. callbacks: {
  90. onCollapse,
  91. onExpand,
  92. onResize
  93. },
  94. constraints: {
  95. collapsedSize,
  96. collapsible,
  97. defaultSize,
  98. maxSize,
  99. minSize
  100. },
  101. id: panelId,
  102. idIsFromProps: idFromProps !== undefined,
  103. order
  104. });
  105. React.useRef({
  106. didLogMissingDefaultSizeWarning: false
  107. });
  108. useIsomorphicLayoutEffect(() => {
  109. const {
  110. callbacks,
  111. constraints
  112. } = panelDataRef.current;
  113. const prevConstraints = {
  114. ...constraints
  115. };
  116. panelDataRef.current.id = panelId;
  117. panelDataRef.current.idIsFromProps = idFromProps !== undefined;
  118. panelDataRef.current.order = order;
  119. callbacks.onCollapse = onCollapse;
  120. callbacks.onExpand = onExpand;
  121. callbacks.onResize = onResize;
  122. constraints.collapsedSize = collapsedSize;
  123. constraints.collapsible = collapsible;
  124. constraints.defaultSize = defaultSize;
  125. constraints.maxSize = maxSize;
  126. constraints.minSize = minSize;
  127. // If constraints have changed, we should revisit panel sizes.
  128. // This is uncommon but may happen if people are trying to implement pixel based constraints.
  129. if (prevConstraints.collapsedSize !== constraints.collapsedSize || prevConstraints.collapsible !== constraints.collapsible || prevConstraints.maxSize !== constraints.maxSize || prevConstraints.minSize !== constraints.minSize) {
  130. reevaluatePanelConstraints(panelDataRef.current, prevConstraints);
  131. }
  132. });
  133. useIsomorphicLayoutEffect(() => {
  134. const panelData = panelDataRef.current;
  135. registerPanel(panelData);
  136. return () => {
  137. unregisterPanel(panelData);
  138. };
  139. }, [order, panelId, registerPanel, unregisterPanel]);
  140. React.useImperativeHandle(forwardedRef, () => ({
  141. collapse: () => {
  142. collapsePanel(panelDataRef.current);
  143. },
  144. expand: minSize => {
  145. expandPanel(panelDataRef.current, minSize);
  146. },
  147. getId() {
  148. return panelId;
  149. },
  150. getSize() {
  151. return getPanelSize(panelDataRef.current);
  152. },
  153. isCollapsed() {
  154. return isPanelCollapsed(panelDataRef.current);
  155. },
  156. isExpanded() {
  157. return !isPanelCollapsed(panelDataRef.current);
  158. },
  159. resize: size => {
  160. resizePanel(panelDataRef.current, size);
  161. }
  162. }), [collapsePanel, expandPanel, getPanelSize, isPanelCollapsed, panelId, resizePanel]);
  163. const style = getPanelStyle(panelDataRef.current, defaultSize);
  164. return React.createElement(Type, {
  165. ...rest,
  166. children,
  167. className: classNameFromProps,
  168. id: panelId,
  169. style: {
  170. ...style,
  171. ...styleFromProps
  172. },
  173. // CSS selectors
  174. [DATA_ATTRIBUTES.groupId]: groupId,
  175. [DATA_ATTRIBUTES.panel]: "",
  176. [DATA_ATTRIBUTES.panelCollapsible]: collapsible || undefined,
  177. [DATA_ATTRIBUTES.panelId]: panelId,
  178. [DATA_ATTRIBUTES.panelSize]: parseFloat("" + style.flexGrow).toFixed(1)
  179. });
  180. }
  181. const Panel = React.forwardRef((props, ref) => React.createElement(PanelWithForwardedRef, {
  182. ...props,
  183. forwardedRef: ref
  184. }));
  185. PanelWithForwardedRef.displayName = "Panel";
  186. Panel.displayName = "forwardRef(Panel)";
  187. let nonce;
  188. function getNonce() {
  189. return nonce;
  190. }
  191. function setNonce(value) {
  192. nonce = value;
  193. }
  194. let currentCursorStyle = null;
  195. let enabled = true;
  196. let prevRuleIndex = -1;
  197. let styleElement = null;
  198. function disableGlobalCursorStyles() {
  199. enabled = false;
  200. }
  201. function enableGlobalCursorStyles() {
  202. enabled = true;
  203. }
  204. function getCursorStyle(state, constraintFlags) {
  205. if (constraintFlags) {
  206. const horizontalMin = (constraintFlags & EXCEEDED_HORIZONTAL_MIN) !== 0;
  207. const horizontalMax = (constraintFlags & EXCEEDED_HORIZONTAL_MAX) !== 0;
  208. const verticalMin = (constraintFlags & EXCEEDED_VERTICAL_MIN) !== 0;
  209. const verticalMax = (constraintFlags & EXCEEDED_VERTICAL_MAX) !== 0;
  210. if (horizontalMin) {
  211. if (verticalMin) {
  212. return "se-resize";
  213. } else if (verticalMax) {
  214. return "ne-resize";
  215. } else {
  216. return "e-resize";
  217. }
  218. } else if (horizontalMax) {
  219. if (verticalMin) {
  220. return "sw-resize";
  221. } else if (verticalMax) {
  222. return "nw-resize";
  223. } else {
  224. return "w-resize";
  225. }
  226. } else if (verticalMin) {
  227. return "s-resize";
  228. } else if (verticalMax) {
  229. return "n-resize";
  230. }
  231. }
  232. switch (state) {
  233. case "horizontal":
  234. return "ew-resize";
  235. case "intersection":
  236. return "move";
  237. case "vertical":
  238. return "ns-resize";
  239. }
  240. }
  241. function resetGlobalCursorStyle() {
  242. if (styleElement !== null) {
  243. document.head.removeChild(styleElement);
  244. currentCursorStyle = null;
  245. styleElement = null;
  246. prevRuleIndex = -1;
  247. }
  248. }
  249. function setGlobalCursorStyle(state, constraintFlags) {
  250. var _styleElement$sheet$i, _styleElement$sheet2;
  251. if (!enabled) {
  252. return;
  253. }
  254. const style = getCursorStyle(state, constraintFlags);
  255. if (currentCursorStyle === style) {
  256. return;
  257. }
  258. currentCursorStyle = style;
  259. if (styleElement === null) {
  260. styleElement = document.createElement("style");
  261. const nonce = getNonce();
  262. if (nonce) {
  263. styleElement.setAttribute("nonce", nonce);
  264. }
  265. document.head.appendChild(styleElement);
  266. }
  267. if (prevRuleIndex >= 0) {
  268. var _styleElement$sheet;
  269. (_styleElement$sheet = styleElement.sheet) === null || _styleElement$sheet === void 0 ? void 0 : _styleElement$sheet.removeRule(prevRuleIndex);
  270. }
  271. prevRuleIndex = (_styleElement$sheet$i = (_styleElement$sheet2 = styleElement.sheet) === null || _styleElement$sheet2 === void 0 ? void 0 : _styleElement$sheet2.insertRule(`*{cursor: ${style} !important;}`)) !== null && _styleElement$sheet$i !== void 0 ? _styleElement$sheet$i : -1;
  272. }
  273. function isKeyDown(event) {
  274. return event.type === "keydown";
  275. }
  276. function isPointerEvent(event) {
  277. return event.type.startsWith("pointer");
  278. }
  279. function isMouseEvent(event) {
  280. return event.type.startsWith("mouse");
  281. }
  282. function getResizeEventCoordinates(event) {
  283. if (isPointerEvent(event)) {
  284. if (event.isPrimary) {
  285. return {
  286. x: event.clientX,
  287. y: event.clientY
  288. };
  289. }
  290. } else if (isMouseEvent(event)) {
  291. return {
  292. x: event.clientX,
  293. y: event.clientY
  294. };
  295. }
  296. return {
  297. x: Infinity,
  298. y: Infinity
  299. };
  300. }
  301. function getInputType() {
  302. if (typeof matchMedia === "function") {
  303. return matchMedia("(pointer:coarse)").matches ? "coarse" : "fine";
  304. }
  305. }
  306. function intersects(rectOne, rectTwo, strict) {
  307. if (strict) {
  308. return rectOne.x < rectTwo.x + rectTwo.width && rectOne.x + rectOne.width > rectTwo.x && rectOne.y < rectTwo.y + rectTwo.height && rectOne.y + rectOne.height > rectTwo.y;
  309. } else {
  310. return rectOne.x <= rectTwo.x + rectTwo.width && rectOne.x + rectOne.width >= rectTwo.x && rectOne.y <= rectTwo.y + rectTwo.height && rectOne.y + rectOne.height >= rectTwo.y;
  311. }
  312. }
  313. // Forked from NPM stacking-order@2.0.0
  314. /**
  315. * Determine which of two nodes appears in front of the other —
  316. * if `a` is in front, returns 1, otherwise returns -1
  317. * @param {HTMLElement | SVGElement} a
  318. * @param {HTMLElement | SVGElement} b
  319. */
  320. function compare(a, b) {
  321. if (a === b) throw new Error("Cannot compare node with itself");
  322. const ancestors = {
  323. a: get_ancestors(a),
  324. b: get_ancestors(b)
  325. };
  326. let common_ancestor;
  327. // remove shared ancestors
  328. while (ancestors.a.at(-1) === ancestors.b.at(-1)) {
  329. a = ancestors.a.pop();
  330. b = ancestors.b.pop();
  331. common_ancestor = a;
  332. }
  333. assert(common_ancestor, "Stacking order can only be calculated for elements with a common ancestor");
  334. const z_indexes = {
  335. a: get_z_index(find_stacking_context(ancestors.a)),
  336. b: get_z_index(find_stacking_context(ancestors.b))
  337. };
  338. if (z_indexes.a === z_indexes.b) {
  339. const children = common_ancestor.childNodes;
  340. const furthest_ancestors = {
  341. a: ancestors.a.at(-1),
  342. b: ancestors.b.at(-1)
  343. };
  344. let i = children.length;
  345. while (i--) {
  346. const child = children[i];
  347. if (child === furthest_ancestors.a) return 1;
  348. if (child === furthest_ancestors.b) return -1;
  349. }
  350. }
  351. return Math.sign(z_indexes.a - z_indexes.b);
  352. }
  353. const props = /\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;
  354. /** @param {HTMLElement | SVGElement} node */
  355. function is_flex_item(node) {
  356. var _get_parent;
  357. // @ts-ignore
  358. const display = getComputedStyle((_get_parent = get_parent(node)) !== null && _get_parent !== void 0 ? _get_parent : node).display;
  359. return display === "flex" || display === "inline-flex";
  360. }
  361. /** @param {HTMLElement | SVGElement} node */
  362. function creates_stacking_context(node) {
  363. const style = getComputedStyle(node);
  364. // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
  365. if (style.position === "fixed") return true;
  366. // Forked to fix upstream bug https://github.com/Rich-Harris/stacking-order/issues/3
  367. // if (
  368. // (style.zIndex !== "auto" && style.position !== "static") ||
  369. // is_flex_item(node)
  370. // )
  371. if (style.zIndex !== "auto" && (style.position !== "static" || is_flex_item(node))) return true;
  372. if (+style.opacity < 1) return true;
  373. if ("transform" in style && style.transform !== "none") return true;
  374. if ("webkitTransform" in style && style.webkitTransform !== "none") return true;
  375. if ("mixBlendMode" in style && style.mixBlendMode !== "normal") return true;
  376. if ("filter" in style && style.filter !== "none") return true;
  377. if ("webkitFilter" in style && style.webkitFilter !== "none") return true;
  378. if ("isolation" in style && style.isolation === "isolate") return true;
  379. if (props.test(style.willChange)) return true;
  380. // @ts-expect-error
  381. if (style.webkitOverflowScrolling === "touch") return true;
  382. return false;
  383. }
  384. /** @param {(HTMLElement| SVGElement)[]} nodes */
  385. function find_stacking_context(nodes) {
  386. let i = nodes.length;
  387. while (i--) {
  388. const node = nodes[i];
  389. assert(node, "Missing node");
  390. if (creates_stacking_context(node)) return node;
  391. }
  392. return null;
  393. }
  394. /** @param {HTMLElement | SVGElement} node */
  395. function get_z_index(node) {
  396. return node && Number(getComputedStyle(node).zIndex) || 0;
  397. }
  398. /** @param {HTMLElement} node */
  399. function get_ancestors(node) {
  400. const ancestors = [];
  401. while (node) {
  402. ancestors.push(node);
  403. // @ts-ignore
  404. node = get_parent(node);
  405. }
  406. return ancestors; // [ node, ... <body>, <html>, document ]
  407. }
  408. /** @param {HTMLElement} node */
  409. function get_parent(node) {
  410. const {
  411. parentNode
  412. } = node;
  413. if (parentNode && parentNode instanceof ShadowRoot) {
  414. return parentNode.host;
  415. }
  416. return parentNode;
  417. }
  418. const EXCEEDED_HORIZONTAL_MIN = 0b0001;
  419. const EXCEEDED_HORIZONTAL_MAX = 0b0010;
  420. const EXCEEDED_VERTICAL_MIN = 0b0100;
  421. const EXCEEDED_VERTICAL_MAX = 0b1000;
  422. const isCoarsePointer = getInputType() === "coarse";
  423. let intersectingHandles = [];
  424. let isPointerDown = false;
  425. let ownerDocumentCounts = new Map();
  426. let panelConstraintFlags = new Map();
  427. const registeredResizeHandlers = new Set();
  428. function registerResizeHandle(resizeHandleId, element, direction, hitAreaMargins, setResizeHandlerState) {
  429. var _ownerDocumentCounts$;
  430. const {
  431. ownerDocument
  432. } = element;
  433. const data = {
  434. direction,
  435. element,
  436. hitAreaMargins,
  437. setResizeHandlerState
  438. };
  439. const count = (_ownerDocumentCounts$ = ownerDocumentCounts.get(ownerDocument)) !== null && _ownerDocumentCounts$ !== void 0 ? _ownerDocumentCounts$ : 0;
  440. ownerDocumentCounts.set(ownerDocument, count + 1);
  441. registeredResizeHandlers.add(data);
  442. updateListeners();
  443. return function unregisterResizeHandle() {
  444. var _ownerDocumentCounts$2;
  445. panelConstraintFlags.delete(resizeHandleId);
  446. registeredResizeHandlers.delete(data);
  447. const count = (_ownerDocumentCounts$2 = ownerDocumentCounts.get(ownerDocument)) !== null && _ownerDocumentCounts$2 !== void 0 ? _ownerDocumentCounts$2 : 1;
  448. ownerDocumentCounts.set(ownerDocument, count - 1);
  449. updateListeners();
  450. if (count === 1) {
  451. ownerDocumentCounts.delete(ownerDocument);
  452. }
  453. // If the resize handle that is currently unmounting is intersecting with the pointer,
  454. // update the global pointer to account for the change
  455. if (intersectingHandles.includes(data)) {
  456. const index = intersectingHandles.indexOf(data);
  457. if (index >= 0) {
  458. intersectingHandles.splice(index, 1);
  459. }
  460. updateCursor();
  461. // Also instruct the handle to stop dragging; this prevents the parent group from being left in an inconsistent state
  462. // See github.com/bvaughn/react-resizable-panels/issues/402
  463. setResizeHandlerState("up", true, null);
  464. }
  465. };
  466. }
  467. function handlePointerDown(event) {
  468. const {
  469. target
  470. } = event;
  471. const {
  472. x,
  473. y
  474. } = getResizeEventCoordinates(event);
  475. isPointerDown = true;
  476. recalculateIntersectingHandles({
  477. target,
  478. x,
  479. y
  480. });
  481. updateListeners();
  482. if (intersectingHandles.length > 0) {
  483. updateResizeHandlerStates("down", event);
  484. event.preventDefault();
  485. if (!isWithinResizeHandle(target)) {
  486. event.stopImmediatePropagation();
  487. }
  488. }
  489. }
  490. function handlePointerMove(event) {
  491. const {
  492. x,
  493. y
  494. } = getResizeEventCoordinates(event);
  495. // Edge case (see #340)
  496. // Detect when the pointer has been released outside an iframe on a different domain
  497. if (isPointerDown && event.buttons === 0) {
  498. isPointerDown = false;
  499. updateResizeHandlerStates("up", event);
  500. }
  501. if (!isPointerDown) {
  502. const {
  503. target
  504. } = event;
  505. // Recalculate intersecting handles whenever the pointer moves, except if it has already been pressed
  506. // at that point, the handles may not move with the pointer (depending on constraints)
  507. // but the same set of active handles should be locked until the pointer is released
  508. recalculateIntersectingHandles({
  509. target,
  510. x,
  511. y
  512. });
  513. }
  514. updateResizeHandlerStates("move", event);
  515. // Update cursor based on return value(s) from active handles
  516. updateCursor();
  517. if (intersectingHandles.length > 0) {
  518. event.preventDefault();
  519. }
  520. }
  521. function handlePointerUp(event) {
  522. const {
  523. target
  524. } = event;
  525. const {
  526. x,
  527. y
  528. } = getResizeEventCoordinates(event);
  529. panelConstraintFlags.clear();
  530. isPointerDown = false;
  531. if (intersectingHandles.length > 0) {
  532. event.preventDefault();
  533. if (!isWithinResizeHandle(target)) {
  534. event.stopImmediatePropagation();
  535. }
  536. }
  537. updateResizeHandlerStates("up", event);
  538. recalculateIntersectingHandles({
  539. target,
  540. x,
  541. y
  542. });
  543. updateCursor();
  544. updateListeners();
  545. }
  546. function isWithinResizeHandle(element) {
  547. let currentElement = element;
  548. while (currentElement) {
  549. if (currentElement.hasAttribute(DATA_ATTRIBUTES.resizeHandle)) {
  550. return true;
  551. }
  552. currentElement = currentElement.parentElement;
  553. }
  554. return false;
  555. }
  556. function recalculateIntersectingHandles({
  557. target,
  558. x,
  559. y
  560. }) {
  561. intersectingHandles.splice(0);
  562. let targetElement = null;
  563. if (target instanceof HTMLElement || target instanceof SVGElement) {
  564. targetElement = target;
  565. }
  566. registeredResizeHandlers.forEach(data => {
  567. const {
  568. element: dragHandleElement,
  569. hitAreaMargins
  570. } = data;
  571. const dragHandleRect = dragHandleElement.getBoundingClientRect();
  572. const {
  573. bottom,
  574. left,
  575. right,
  576. top
  577. } = dragHandleRect;
  578. const margin = isCoarsePointer ? hitAreaMargins.coarse : hitAreaMargins.fine;
  579. const eventIntersects = x >= left - margin && x <= right + margin && y >= top - margin && y <= bottom + margin;
  580. if (eventIntersects) {
  581. // TRICKY
  582. // We listen for pointers events at the root in order to support hit area margins
  583. // (determining when the pointer is close enough to an element to be considered a "hit")
  584. // Clicking on an element "above" a handle (e.g. a modal) should prevent a hit though
  585. // so at this point we need to compare stacking order of a potentially intersecting drag handle,
  586. // and the element that was actually clicked/touched
  587. if (targetElement !== null && document.contains(targetElement) && dragHandleElement !== targetElement && !dragHandleElement.contains(targetElement) && !targetElement.contains(dragHandleElement) &&
  588. // Calculating stacking order has a cost, so we should avoid it if possible
  589. // That is why we only check potentially intersecting handles,
  590. // and why we skip if the event target is within the handle's DOM
  591. compare(targetElement, dragHandleElement) > 0) {
  592. // If the target is above the drag handle, then we also need to confirm they overlap
  593. // If they are beside each other (e.g. a panel and its drag handle) then the handle is still interactive
  594. //
  595. // It's not enough to compare only the target
  596. // The target might be a small element inside of a larger container
  597. // (For example, a SPAN or a DIV inside of a larger modal dialog)
  598. let currentElement = targetElement;
  599. let didIntersect = false;
  600. while (currentElement) {
  601. if (currentElement.contains(dragHandleElement)) {
  602. break;
  603. } else if (intersects(currentElement.getBoundingClientRect(), dragHandleRect, true)) {
  604. didIntersect = true;
  605. break;
  606. }
  607. currentElement = currentElement.parentElement;
  608. }
  609. if (didIntersect) {
  610. return;
  611. }
  612. }
  613. intersectingHandles.push(data);
  614. }
  615. });
  616. }
  617. function reportConstraintsViolation(resizeHandleId, flag) {
  618. panelConstraintFlags.set(resizeHandleId, flag);
  619. }
  620. function updateCursor() {
  621. let intersectsHorizontal = false;
  622. let intersectsVertical = false;
  623. intersectingHandles.forEach(data => {
  624. const {
  625. direction
  626. } = data;
  627. if (direction === "horizontal") {
  628. intersectsHorizontal = true;
  629. } else {
  630. intersectsVertical = true;
  631. }
  632. });
  633. let constraintFlags = 0;
  634. panelConstraintFlags.forEach(flag => {
  635. constraintFlags |= flag;
  636. });
  637. if (intersectsHorizontal && intersectsVertical) {
  638. setGlobalCursorStyle("intersection", constraintFlags);
  639. } else if (intersectsHorizontal) {
  640. setGlobalCursorStyle("horizontal", constraintFlags);
  641. } else if (intersectsVertical) {
  642. setGlobalCursorStyle("vertical", constraintFlags);
  643. } else {
  644. resetGlobalCursorStyle();
  645. }
  646. }
  647. let listenersAbortController = new AbortController();
  648. function updateListeners() {
  649. listenersAbortController.abort();
  650. listenersAbortController = new AbortController();
  651. const options = {
  652. capture: true,
  653. signal: listenersAbortController.signal
  654. };
  655. if (!registeredResizeHandlers.size) {
  656. return;
  657. }
  658. if (isPointerDown) {
  659. if (intersectingHandles.length > 0) {
  660. ownerDocumentCounts.forEach((count, ownerDocument) => {
  661. const {
  662. body
  663. } = ownerDocument;
  664. if (count > 0) {
  665. body.addEventListener("contextmenu", handlePointerUp, options);
  666. body.addEventListener("pointerleave", handlePointerMove, options);
  667. body.addEventListener("pointermove", handlePointerMove, options);
  668. }
  669. });
  670. }
  671. window.addEventListener("pointerup", handlePointerUp, options);
  672. window.addEventListener("pointercancel", handlePointerUp, options);
  673. } else {
  674. ownerDocumentCounts.forEach((count, ownerDocument) => {
  675. const {
  676. body
  677. } = ownerDocument;
  678. if (count > 0) {
  679. body.addEventListener("pointerdown", handlePointerDown, options);
  680. body.addEventListener("pointermove", handlePointerMove, options);
  681. }
  682. });
  683. }
  684. }
  685. function updateResizeHandlerStates(action, event) {
  686. registeredResizeHandlers.forEach(data => {
  687. const {
  688. setResizeHandlerState
  689. } = data;
  690. const isActive = intersectingHandles.includes(data);
  691. setResizeHandlerState(action, isActive, event);
  692. });
  693. }
  694. function useForceUpdate() {
  695. const [_, setCount] = React.useState(0);
  696. return React.useCallback(() => setCount(prevCount => prevCount + 1), []);
  697. }
  698. function assert(expectedCondition, message) {
  699. if (!expectedCondition) {
  700. console.error(message);
  701. throw Error(message);
  702. }
  703. }
  704. function fuzzyCompareNumbers(actual, expected, fractionDigits = PRECISION) {
  705. if (actual.toFixed(fractionDigits) === expected.toFixed(fractionDigits)) {
  706. return 0;
  707. } else {
  708. return actual > expected ? 1 : -1;
  709. }
  710. }
  711. function fuzzyNumbersEqual$1(actual, expected, fractionDigits = PRECISION) {
  712. return fuzzyCompareNumbers(actual, expected, fractionDigits) === 0;
  713. }
  714. function fuzzyNumbersEqual(actual, expected, fractionDigits) {
  715. return fuzzyCompareNumbers(actual, expected, fractionDigits) === 0;
  716. }
  717. function fuzzyLayoutsEqual(actual, expected, fractionDigits) {
  718. if (actual.length !== expected.length) {
  719. return false;
  720. }
  721. for (let index = 0; index < actual.length; index++) {
  722. const actualSize = actual[index];
  723. const expectedSize = expected[index];
  724. if (!fuzzyNumbersEqual(actualSize, expectedSize, fractionDigits)) {
  725. return false;
  726. }
  727. }
  728. return true;
  729. }
  730. // Panel size must be in percentages; pixel values should be pre-converted
  731. function resizePanel({
  732. panelConstraints: panelConstraintsArray,
  733. panelIndex,
  734. size
  735. }) {
  736. const panelConstraints = panelConstraintsArray[panelIndex];
  737. assert(panelConstraints != null, `Panel constraints not found for index ${panelIndex}`);
  738. let {
  739. collapsedSize = 0,
  740. collapsible,
  741. maxSize = 100,
  742. minSize = 0
  743. } = panelConstraints;
  744. if (fuzzyCompareNumbers(size, minSize) < 0) {
  745. if (collapsible) {
  746. // Collapsible panels should snap closed or open only once they cross the halfway point between collapsed and min size.
  747. const halfwayPoint = (collapsedSize + minSize) / 2;
  748. if (fuzzyCompareNumbers(size, halfwayPoint) < 0) {
  749. size = collapsedSize;
  750. } else {
  751. size = minSize;
  752. }
  753. } else {
  754. size = minSize;
  755. }
  756. }
  757. size = Math.min(maxSize, size);
  758. size = parseFloat(size.toFixed(PRECISION));
  759. return size;
  760. }
  761. // All units must be in percentages; pixel values should be pre-converted
  762. function adjustLayoutByDelta({
  763. delta,
  764. initialLayout,
  765. panelConstraints: panelConstraintsArray,
  766. pivotIndices,
  767. prevLayout,
  768. trigger
  769. }) {
  770. if (fuzzyNumbersEqual(delta, 0)) {
  771. return initialLayout;
  772. }
  773. const nextLayout = [...initialLayout];
  774. const [firstPivotIndex, secondPivotIndex] = pivotIndices;
  775. assert(firstPivotIndex != null, "Invalid first pivot index");
  776. assert(secondPivotIndex != null, "Invalid second pivot index");
  777. let deltaApplied = 0;
  778. // const DEBUG = [];
  779. // DEBUG.push(`adjustLayoutByDelta()`);
  780. // DEBUG.push(` initialLayout: ${initialLayout.join(", ")}`);
  781. // DEBUG.push(` prevLayout: ${prevLayout.join(", ")}`);
  782. // DEBUG.push(` delta: ${delta}`);
  783. // DEBUG.push(` pivotIndices: ${pivotIndices.join(", ")}`);
  784. // DEBUG.push(` trigger: ${trigger}`);
  785. // DEBUG.push("");
  786. // A resizing panel affects the panels before or after it.
  787. //
  788. // A negative delta means the panel(s) immediately after the resize handle should grow/expand by decreasing its offset.
  789. // Other panels may also need to shrink/contract (and shift) to make room, depending on the min weights.
  790. //
  791. // A positive delta means the panel(s) immediately before the resize handle should "expand".
  792. // This is accomplished by shrinking/contracting (and shifting) one or more of the panels after the resize handle.
  793. {
  794. // If this is a resize triggered by a keyboard event, our logic for expanding/collapsing is different.
  795. // We no longer check the halfway threshold because this may prevent the panel from expanding at all.
  796. if (trigger === "keyboard") {
  797. {
  798. // Check if we should expand a collapsed panel
  799. const index = delta < 0 ? secondPivotIndex : firstPivotIndex;
  800. const panelConstraints = panelConstraintsArray[index];
  801. assert(panelConstraints, `Panel constraints not found for index ${index}`);
  802. const {
  803. collapsedSize = 0,
  804. collapsible,
  805. minSize = 0
  806. } = panelConstraints;
  807. // DEBUG.push(`edge case check 1: ${index}`);
  808. // DEBUG.push(` -> collapsible? ${collapsible}`);
  809. if (collapsible) {
  810. const prevSize = initialLayout[index];
  811. assert(prevSize != null, `Previous layout not found for panel index ${index}`);
  812. if (fuzzyNumbersEqual(prevSize, collapsedSize)) {
  813. const localDelta = minSize - prevSize;
  814. // DEBUG.push(` -> expand delta: ${localDelta}`);
  815. if (fuzzyCompareNumbers(localDelta, Math.abs(delta)) > 0) {
  816. delta = delta < 0 ? 0 - localDelta : localDelta;
  817. // DEBUG.push(` -> delta: ${delta}`);
  818. }
  819. }
  820. }
  821. }
  822. {
  823. // Check if we should collapse a panel at its minimum size
  824. const index = delta < 0 ? firstPivotIndex : secondPivotIndex;
  825. const panelConstraints = panelConstraintsArray[index];
  826. assert(panelConstraints, `No panel constraints found for index ${index}`);
  827. const {
  828. collapsedSize = 0,
  829. collapsible,
  830. minSize = 0
  831. } = panelConstraints;
  832. // DEBUG.push(`edge case check 2: ${index}`);
  833. // DEBUG.push(` -> collapsible? ${collapsible}`);
  834. if (collapsible) {
  835. const prevSize = initialLayout[index];
  836. assert(prevSize != null, `Previous layout not found for panel index ${index}`);
  837. if (fuzzyNumbersEqual(prevSize, minSize)) {
  838. const localDelta = prevSize - collapsedSize;
  839. // DEBUG.push(` -> expand delta: ${localDelta}`);
  840. if (fuzzyCompareNumbers(localDelta, Math.abs(delta)) > 0) {
  841. delta = delta < 0 ? 0 - localDelta : localDelta;
  842. // DEBUG.push(` -> delta: ${delta}`);
  843. }
  844. }
  845. }
  846. }
  847. }
  848. // DEBUG.push("");
  849. }
  850. {
  851. // Pre-calculate max available delta in the opposite direction of our pivot.
  852. // This will be the maximum amount we're allowed to expand/contract the panels in the primary direction.
  853. // If this amount is less than the requested delta, adjust the requested delta.
  854. // If this amount is greater than the requested delta, that's useful information too–
  855. // as an expanding panel might change from collapsed to min size.
  856. const increment = delta < 0 ? 1 : -1;
  857. let index = delta < 0 ? secondPivotIndex : firstPivotIndex;
  858. let maxAvailableDelta = 0;
  859. // DEBUG.push("pre calc...");
  860. while (true) {
  861. const prevSize = initialLayout[index];
  862. assert(prevSize != null, `Previous layout not found for panel index ${index}`);
  863. const maxSafeSize = resizePanel({
  864. panelConstraints: panelConstraintsArray,
  865. panelIndex: index,
  866. size: 100
  867. });
  868. const delta = maxSafeSize - prevSize;
  869. // DEBUG.push(` ${index}: ${prevSize} -> ${maxSafeSize}`);
  870. maxAvailableDelta += delta;
  871. index += increment;
  872. if (index < 0 || index >= panelConstraintsArray.length) {
  873. break;
  874. }
  875. }
  876. // DEBUG.push(` -> max available delta: ${maxAvailableDelta}`);
  877. const minAbsDelta = Math.min(Math.abs(delta), Math.abs(maxAvailableDelta));
  878. delta = delta < 0 ? 0 - minAbsDelta : minAbsDelta;
  879. // DEBUG.push(` -> adjusted delta: ${delta}`);
  880. // DEBUG.push("");
  881. }
  882. {
  883. // Delta added to a panel needs to be subtracted from other panels (within the constraints that those panels allow).
  884. const pivotIndex = delta < 0 ? firstPivotIndex : secondPivotIndex;
  885. let index = pivotIndex;
  886. while (index >= 0 && index < panelConstraintsArray.length) {
  887. const deltaRemaining = Math.abs(delta) - Math.abs(deltaApplied);
  888. const prevSize = initialLayout[index];
  889. assert(prevSize != null, `Previous layout not found for panel index ${index}`);
  890. const unsafeSize = prevSize - deltaRemaining;
  891. const safeSize = resizePanel({
  892. panelConstraints: panelConstraintsArray,
  893. panelIndex: index,
  894. size: unsafeSize
  895. });
  896. if (!fuzzyNumbersEqual(prevSize, safeSize)) {
  897. deltaApplied += prevSize - safeSize;
  898. nextLayout[index] = safeSize;
  899. if (deltaApplied.toPrecision(3).localeCompare(Math.abs(delta).toPrecision(3), undefined, {
  900. numeric: true
  901. }) >= 0) {
  902. break;
  903. }
  904. }
  905. if (delta < 0) {
  906. index--;
  907. } else {
  908. index++;
  909. }
  910. }
  911. }
  912. // DEBUG.push(`after 1: ${nextLayout.join(", ")}`);
  913. // DEBUG.push(` deltaApplied: ${deltaApplied}`);
  914. // DEBUG.push("");
  915. // If we were unable to resize any of the panels panels, return the previous state.
  916. // This will essentially bailout and ignore e.g. drags past a panel's boundaries
  917. if (fuzzyLayoutsEqual(prevLayout, nextLayout)) {
  918. // DEBUG.push(`bailout to previous layout: ${prevLayout.join(", ")}`);
  919. // console.log(DEBUG.join("\n"));
  920. return prevLayout;
  921. }
  922. {
  923. // Now distribute the applied delta to the panels in the other direction
  924. const pivotIndex = delta < 0 ? secondPivotIndex : firstPivotIndex;
  925. const prevSize = initialLayout[pivotIndex];
  926. assert(prevSize != null, `Previous layout not found for panel index ${pivotIndex}`);
  927. const unsafeSize = prevSize + deltaApplied;
  928. const safeSize = resizePanel({
  929. panelConstraints: panelConstraintsArray,
  930. panelIndex: pivotIndex,
  931. size: unsafeSize
  932. });
  933. // Adjust the pivot panel before, but only by the amount that surrounding panels were able to shrink/contract.
  934. nextLayout[pivotIndex] = safeSize;
  935. // Edge case where expanding or contracting one panel caused another one to change collapsed state
  936. if (!fuzzyNumbersEqual(safeSize, unsafeSize)) {
  937. let deltaRemaining = unsafeSize - safeSize;
  938. const pivotIndex = delta < 0 ? secondPivotIndex : firstPivotIndex;
  939. let index = pivotIndex;
  940. while (index >= 0 && index < panelConstraintsArray.length) {
  941. const prevSize = nextLayout[index];
  942. assert(prevSize != null, `Previous layout not found for panel index ${index}`);
  943. const unsafeSize = prevSize + deltaRemaining;
  944. const safeSize = resizePanel({
  945. panelConstraints: panelConstraintsArray,
  946. panelIndex: index,
  947. size: unsafeSize
  948. });
  949. if (!fuzzyNumbersEqual(prevSize, safeSize)) {
  950. deltaRemaining -= safeSize - prevSize;
  951. nextLayout[index] = safeSize;
  952. }
  953. if (fuzzyNumbersEqual(deltaRemaining, 0)) {
  954. break;
  955. }
  956. if (delta > 0) {
  957. index--;
  958. } else {
  959. index++;
  960. }
  961. }
  962. }
  963. }
  964. // DEBUG.push(`after 2: ${nextLayout.join(", ")}`);
  965. // DEBUG.push(` deltaApplied: ${deltaApplied}`);
  966. // DEBUG.push("");
  967. const totalSize = nextLayout.reduce((total, size) => size + total, 0);
  968. // DEBUG.push(`total size: ${totalSize}`);
  969. // If our new layout doesn't add up to 100%, that means the requested delta can't be applied
  970. // In that case, fall back to our most recent valid layout
  971. if (!fuzzyNumbersEqual(totalSize, 100)) {
  972. // DEBUG.push(`bailout to previous layout: ${prevLayout.join(", ")}`);
  973. // console.log(DEBUG.join("\n"));
  974. return prevLayout;
  975. }
  976. // console.log(DEBUG.join("\n"));
  977. return nextLayout;
  978. }
  979. function calculateAriaValues({
  980. layout,
  981. panelsArray,
  982. pivotIndices
  983. }) {
  984. let currentMinSize = 0;
  985. let currentMaxSize = 100;
  986. let totalMinSize = 0;
  987. let totalMaxSize = 0;
  988. const firstIndex = pivotIndices[0];
  989. assert(firstIndex != null, "No pivot index found");
  990. // A panel's effective min/max sizes also need to account for other panel's sizes.
  991. panelsArray.forEach((panelData, index) => {
  992. const {
  993. constraints
  994. } = panelData;
  995. const {
  996. maxSize = 100,
  997. minSize = 0
  998. } = constraints;
  999. if (index === firstIndex) {
  1000. currentMinSize = minSize;
  1001. currentMaxSize = maxSize;
  1002. } else {
  1003. totalMinSize += minSize;
  1004. totalMaxSize += maxSize;
  1005. }
  1006. });
  1007. const valueMax = Math.min(currentMaxSize, 100 - totalMinSize);
  1008. const valueMin = Math.max(currentMinSize, 100 - totalMaxSize);
  1009. const valueNow = layout[firstIndex];
  1010. return {
  1011. valueMax,
  1012. valueMin,
  1013. valueNow
  1014. };
  1015. }
  1016. function getResizeHandleElementsForGroup(groupId, scope = document) {
  1017. return Array.from(scope.querySelectorAll(`[${DATA_ATTRIBUTES.resizeHandleId}][data-panel-group-id="${groupId}"]`));
  1018. }
  1019. function getResizeHandleElementIndex(groupId, id, scope = document) {
  1020. const handles = getResizeHandleElementsForGroup(groupId, scope);
  1021. const index = handles.findIndex(handle => handle.getAttribute(DATA_ATTRIBUTES.resizeHandleId) === id);
  1022. return index !== null && index !== void 0 ? index : null;
  1023. }
  1024. function determinePivotIndices(groupId, dragHandleId, panelGroupElement) {
  1025. const index = getResizeHandleElementIndex(groupId, dragHandleId, panelGroupElement);
  1026. return index != null ? [index, index + 1] : [-1, -1];
  1027. }
  1028. function getPanelGroupElement(id, rootElement = document) {
  1029. var _dataset;
  1030. //If the root element is the PanelGroup
  1031. if (rootElement instanceof HTMLElement && (rootElement === null || rootElement === void 0 ? void 0 : (_dataset = rootElement.dataset) === null || _dataset === void 0 ? void 0 : _dataset.panelGroupId) == id) {
  1032. return rootElement;
  1033. }
  1034. //Else query children
  1035. const element = rootElement.querySelector(`[data-panel-group][data-panel-group-id="${id}"]`);
  1036. if (element) {
  1037. return element;
  1038. }
  1039. return null;
  1040. }
  1041. function getResizeHandleElement(id, scope = document) {
  1042. const element = scope.querySelector(`[${DATA_ATTRIBUTES.resizeHandleId}="${id}"]`);
  1043. if (element) {
  1044. return element;
  1045. }
  1046. return null;
  1047. }
  1048. function getResizeHandlePanelIds(groupId, handleId, panelsArray, scope = document) {
  1049. var _panelsArray$index$id, _panelsArray$index, _panelsArray$id, _panelsArray;
  1050. const handle = getResizeHandleElement(handleId, scope);
  1051. const handles = getResizeHandleElementsForGroup(groupId, scope);
  1052. const index = handle ? handles.indexOf(handle) : -1;
  1053. const idBefore = (_panelsArray$index$id = (_panelsArray$index = panelsArray[index]) === null || _panelsArray$index === void 0 ? void 0 : _panelsArray$index.id) !== null && _panelsArray$index$id !== void 0 ? _panelsArray$index$id : null;
  1054. const idAfter = (_panelsArray$id = (_panelsArray = panelsArray[index + 1]) === null || _panelsArray === void 0 ? void 0 : _panelsArray.id) !== null && _panelsArray$id !== void 0 ? _panelsArray$id : null;
  1055. return [idBefore, idAfter];
  1056. }
  1057. // https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/
  1058. function useWindowSplitterPanelGroupBehavior({
  1059. committedValuesRef,
  1060. eagerValuesRef,
  1061. groupId,
  1062. layout,
  1063. panelDataArray,
  1064. panelGroupElement,
  1065. setLayout
  1066. }) {
  1067. React.useRef({
  1068. didWarnAboutMissingResizeHandle: false
  1069. });
  1070. useIsomorphicLayoutEffect(() => {
  1071. if (!panelGroupElement) {
  1072. return;
  1073. }
  1074. const resizeHandleElements = getResizeHandleElementsForGroup(groupId, panelGroupElement);
  1075. for (let index = 0; index < panelDataArray.length - 1; index++) {
  1076. const {
  1077. valueMax,
  1078. valueMin,
  1079. valueNow
  1080. } = calculateAriaValues({
  1081. layout,
  1082. panelsArray: panelDataArray,
  1083. pivotIndices: [index, index + 1]
  1084. });
  1085. const resizeHandleElement = resizeHandleElements[index];
  1086. if (resizeHandleElement == null) ; else {
  1087. const panelData = panelDataArray[index];
  1088. assert(panelData, `No panel data found for index "${index}"`);
  1089. resizeHandleElement.setAttribute("aria-controls", panelData.id);
  1090. resizeHandleElement.setAttribute("aria-valuemax", "" + Math.round(valueMax));
  1091. resizeHandleElement.setAttribute("aria-valuemin", "" + Math.round(valueMin));
  1092. resizeHandleElement.setAttribute("aria-valuenow", valueNow != null ? "" + Math.round(valueNow) : "");
  1093. }
  1094. }
  1095. return () => {
  1096. resizeHandleElements.forEach((resizeHandleElement, index) => {
  1097. resizeHandleElement.removeAttribute("aria-controls");
  1098. resizeHandleElement.removeAttribute("aria-valuemax");
  1099. resizeHandleElement.removeAttribute("aria-valuemin");
  1100. resizeHandleElement.removeAttribute("aria-valuenow");
  1101. });
  1102. };
  1103. }, [groupId, layout, panelDataArray, panelGroupElement]);
  1104. React.useEffect(() => {
  1105. if (!panelGroupElement) {
  1106. return;
  1107. }
  1108. const eagerValues = eagerValuesRef.current;
  1109. assert(eagerValues, `Eager values not found`);
  1110. const {
  1111. panelDataArray
  1112. } = eagerValues;
  1113. const groupElement = getPanelGroupElement(groupId, panelGroupElement);
  1114. assert(groupElement != null, `No group found for id "${groupId}"`);
  1115. const handles = getResizeHandleElementsForGroup(groupId, panelGroupElement);
  1116. assert(handles, `No resize handles found for group id "${groupId}"`);
  1117. const cleanupFunctions = handles.map(handle => {
  1118. const handleId = handle.getAttribute(DATA_ATTRIBUTES.resizeHandleId);
  1119. assert(handleId, `Resize handle element has no handle id attribute`);
  1120. const [idBefore, idAfter] = getResizeHandlePanelIds(groupId, handleId, panelDataArray, panelGroupElement);
  1121. if (idBefore == null || idAfter == null) {
  1122. return () => {};
  1123. }
  1124. const onKeyDown = event => {
  1125. if (event.defaultPrevented) {
  1126. return;
  1127. }
  1128. switch (event.key) {
  1129. case "Enter":
  1130. {
  1131. event.preventDefault();
  1132. const index = panelDataArray.findIndex(panelData => panelData.id === idBefore);
  1133. if (index >= 0) {
  1134. const panelData = panelDataArray[index];
  1135. assert(panelData, `No panel data found for index ${index}`);
  1136. const size = layout[index];
  1137. const {
  1138. collapsedSize = 0,
  1139. collapsible,
  1140. minSize = 0
  1141. } = panelData.constraints;
  1142. if (size != null && collapsible) {
  1143. const nextLayout = adjustLayoutByDelta({
  1144. delta: fuzzyNumbersEqual(size, collapsedSize) ? minSize - collapsedSize : collapsedSize - size,
  1145. initialLayout: layout,
  1146. panelConstraints: panelDataArray.map(panelData => panelData.constraints),
  1147. pivotIndices: determinePivotIndices(groupId, handleId, panelGroupElement),
  1148. prevLayout: layout,
  1149. trigger: "keyboard"
  1150. });
  1151. if (layout !== nextLayout) {
  1152. setLayout(nextLayout);
  1153. }
  1154. }
  1155. }
  1156. break;
  1157. }
  1158. }
  1159. };
  1160. handle.addEventListener("keydown", onKeyDown);
  1161. return () => {
  1162. handle.removeEventListener("keydown", onKeyDown);
  1163. };
  1164. });
  1165. return () => {
  1166. cleanupFunctions.forEach(cleanupFunction => cleanupFunction());
  1167. };
  1168. }, [panelGroupElement, committedValuesRef, eagerValuesRef, groupId, layout, panelDataArray, setLayout]);
  1169. }
  1170. function areEqual(arrayA, arrayB) {
  1171. if (arrayA.length !== arrayB.length) {
  1172. return false;
  1173. }
  1174. for (let index = 0; index < arrayA.length; index++) {
  1175. if (arrayA[index] !== arrayB[index]) {
  1176. return false;
  1177. }
  1178. }
  1179. return true;
  1180. }
  1181. function getResizeEventCursorPosition(direction, event) {
  1182. const isHorizontal = direction === "horizontal";
  1183. const {
  1184. x,
  1185. y
  1186. } = getResizeEventCoordinates(event);
  1187. return isHorizontal ? x : y;
  1188. }
  1189. function calculateDragOffsetPercentage(event, dragHandleId, direction, initialDragState, panelGroupElement) {
  1190. const isHorizontal = direction === "horizontal";
  1191. const handleElement = getResizeHandleElement(dragHandleId, panelGroupElement);
  1192. assert(handleElement, `No resize handle element found for id "${dragHandleId}"`);
  1193. const groupId = handleElement.getAttribute(DATA_ATTRIBUTES.groupId);
  1194. assert(groupId, `Resize handle element has no group id attribute`);
  1195. let {
  1196. initialCursorPosition
  1197. } = initialDragState;
  1198. const cursorPosition = getResizeEventCursorPosition(direction, event);
  1199. const groupElement = getPanelGroupElement(groupId, panelGroupElement);
  1200. assert(groupElement, `No group element found for id "${groupId}"`);
  1201. const groupRect = groupElement.getBoundingClientRect();
  1202. const groupSizeInPixels = isHorizontal ? groupRect.width : groupRect.height;
  1203. const offsetPixels = cursorPosition - initialCursorPosition;
  1204. const offsetPercentage = offsetPixels / groupSizeInPixels * 100;
  1205. return offsetPercentage;
  1206. }
  1207. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX
  1208. function calculateDeltaPercentage(event, dragHandleId, direction, initialDragState, keyboardResizeBy, panelGroupElement) {
  1209. if (isKeyDown(event)) {
  1210. const isHorizontal = direction === "horizontal";
  1211. let delta = 0;
  1212. if (event.shiftKey) {
  1213. delta = 100;
  1214. } else if (keyboardResizeBy != null) {
  1215. delta = keyboardResizeBy;
  1216. } else {
  1217. delta = 10;
  1218. }
  1219. let movement = 0;
  1220. switch (event.key) {
  1221. case "ArrowDown":
  1222. movement = isHorizontal ? 0 : delta;
  1223. break;
  1224. case "ArrowLeft":
  1225. movement = isHorizontal ? -delta : 0;
  1226. break;
  1227. case "ArrowRight":
  1228. movement = isHorizontal ? delta : 0;
  1229. break;
  1230. case "ArrowUp":
  1231. movement = isHorizontal ? 0 : -delta;
  1232. break;
  1233. case "End":
  1234. movement = 100;
  1235. break;
  1236. case "Home":
  1237. movement = -100;
  1238. break;
  1239. }
  1240. return movement;
  1241. } else {
  1242. if (initialDragState == null) {
  1243. return 0;
  1244. }
  1245. return calculateDragOffsetPercentage(event, dragHandleId, direction, initialDragState, panelGroupElement);
  1246. }
  1247. }
  1248. function calculateUnsafeDefaultLayout({
  1249. panelDataArray
  1250. }) {
  1251. const layout = Array(panelDataArray.length);
  1252. const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
  1253. let numPanelsWithSizes = 0;
  1254. let remainingSize = 100;
  1255. // Distribute default sizes first
  1256. for (let index = 0; index < panelDataArray.length; index++) {
  1257. const panelConstraints = panelConstraintsArray[index];
  1258. assert(panelConstraints, `Panel constraints not found for index ${index}`);
  1259. const {
  1260. defaultSize
  1261. } = panelConstraints;
  1262. if (defaultSize != null) {
  1263. numPanelsWithSizes++;
  1264. layout[index] = defaultSize;
  1265. remainingSize -= defaultSize;
  1266. }
  1267. }
  1268. // Remaining size should be distributed evenly between panels without default sizes
  1269. for (let index = 0; index < panelDataArray.length; index++) {
  1270. const panelConstraints = panelConstraintsArray[index];
  1271. assert(panelConstraints, `Panel constraints not found for index ${index}`);
  1272. const {
  1273. defaultSize
  1274. } = panelConstraints;
  1275. if (defaultSize != null) {
  1276. continue;
  1277. }
  1278. const numRemainingPanels = panelDataArray.length - numPanelsWithSizes;
  1279. const size = remainingSize / numRemainingPanels;
  1280. numPanelsWithSizes++;
  1281. layout[index] = size;
  1282. remainingSize -= size;
  1283. }
  1284. return layout;
  1285. }
  1286. // Layout should be pre-converted into percentages
  1287. function callPanelCallbacks(panelsArray, layout, panelIdToLastNotifiedSizeMap) {
  1288. layout.forEach((size, index) => {
  1289. const panelData = panelsArray[index];
  1290. assert(panelData, `Panel data not found for index ${index}`);
  1291. const {
  1292. callbacks,
  1293. constraints,
  1294. id: panelId
  1295. } = panelData;
  1296. const {
  1297. collapsedSize = 0,
  1298. collapsible
  1299. } = constraints;
  1300. const lastNotifiedSize = panelIdToLastNotifiedSizeMap[panelId];
  1301. if (lastNotifiedSize == null || size !== lastNotifiedSize) {
  1302. panelIdToLastNotifiedSizeMap[panelId] = size;
  1303. const {
  1304. onCollapse,
  1305. onExpand,
  1306. onResize
  1307. } = callbacks;
  1308. if (onResize) {
  1309. onResize(size, lastNotifiedSize);
  1310. }
  1311. if (collapsible && (onCollapse || onExpand)) {
  1312. if (onExpand && (lastNotifiedSize == null || fuzzyNumbersEqual$1(lastNotifiedSize, collapsedSize)) && !fuzzyNumbersEqual$1(size, collapsedSize)) {
  1313. onExpand();
  1314. }
  1315. if (onCollapse && (lastNotifiedSize == null || !fuzzyNumbersEqual$1(lastNotifiedSize, collapsedSize)) && fuzzyNumbersEqual$1(size, collapsedSize)) {
  1316. onCollapse();
  1317. }
  1318. }
  1319. }
  1320. });
  1321. }
  1322. function compareLayouts(a, b) {
  1323. if (a.length !== b.length) {
  1324. return false;
  1325. } else {
  1326. for (let index = 0; index < a.length; index++) {
  1327. if (a[index] != b[index]) {
  1328. return false;
  1329. }
  1330. }
  1331. }
  1332. return true;
  1333. }
  1334. // This method returns a number between 1 and 100 representing
  1335. // the % of the group's overall space this panel should occupy.
  1336. function computePanelFlexBoxStyle({
  1337. defaultSize,
  1338. dragState,
  1339. layout,
  1340. panelData,
  1341. panelIndex,
  1342. precision = 3
  1343. }) {
  1344. const size = layout[panelIndex];
  1345. let flexGrow;
  1346. if (size == null) {
  1347. // Initial render (before panels have registered themselves)
  1348. // In order to support server rendering, fall back to default size if provided
  1349. flexGrow = defaultSize != undefined ? defaultSize.toPrecision(precision) : "1";
  1350. } else if (panelData.length === 1) {
  1351. // Special case: Single panel group should always fill full width/height
  1352. flexGrow = "1";
  1353. } else {
  1354. flexGrow = size.toPrecision(precision);
  1355. }
  1356. return {
  1357. flexBasis: 0,
  1358. flexGrow,
  1359. flexShrink: 1,
  1360. // Without this, Panel sizes may be unintentionally overridden by their content
  1361. overflow: "hidden",
  1362. // Disable pointer events inside of a panel during resize
  1363. // This avoid edge cases like nested iframes
  1364. pointerEvents: dragState !== null ? "none" : undefined
  1365. };
  1366. }
  1367. function debounce(callback, durationMs = 10) {
  1368. let timeoutId = null;
  1369. let callable = (...args) => {
  1370. if (timeoutId !== null) {
  1371. clearTimeout(timeoutId);
  1372. }
  1373. timeoutId = setTimeout(() => {
  1374. callback(...args);
  1375. }, durationMs);
  1376. };
  1377. return callable;
  1378. }
  1379. // PanelGroup might be rendering in a server-side environment where localStorage is not available
  1380. // or on a browser with cookies/storage disabled.
  1381. // In either case, this function avoids accessing localStorage until needed,
  1382. // and avoids throwing user-visible errors.
  1383. function initializeDefaultStorage(storageObject) {
  1384. try {
  1385. if (typeof localStorage !== "undefined") {
  1386. // Bypass this check for future calls
  1387. storageObject.getItem = name => {
  1388. return localStorage.getItem(name);
  1389. };
  1390. storageObject.setItem = (name, value) => {
  1391. localStorage.setItem(name, value);
  1392. };
  1393. } else {
  1394. throw new Error("localStorage not supported in this environment");
  1395. }
  1396. } catch (error) {
  1397. console.error(error);
  1398. storageObject.getItem = () => null;
  1399. storageObject.setItem = () => {};
  1400. }
  1401. }
  1402. function getPanelGroupKey(autoSaveId) {
  1403. return `react-resizable-panels:${autoSaveId}`;
  1404. }
  1405. // Note that Panel ids might be user-provided (stable) or useId generated (non-deterministic)
  1406. // so they should not be used as part of the serialization key.
  1407. // Using the min/max size attributes should work well enough as a backup.
  1408. // Pre-sorting by minSize allows remembering layouts even if panels are re-ordered/dragged.
  1409. function getPanelKey(panels) {
  1410. return panels.map(panel => {
  1411. const {
  1412. constraints,
  1413. id,
  1414. idIsFromProps,
  1415. order
  1416. } = panel;
  1417. if (idIsFromProps) {
  1418. return id;
  1419. } else {
  1420. return order ? `${order}:${JSON.stringify(constraints)}` : JSON.stringify(constraints);
  1421. }
  1422. }).sort((a, b) => a.localeCompare(b)).join(",");
  1423. }
  1424. function loadSerializedPanelGroupState(autoSaveId, storage) {
  1425. try {
  1426. const panelGroupKey = getPanelGroupKey(autoSaveId);
  1427. const serialized = storage.getItem(panelGroupKey);
  1428. if (serialized) {
  1429. const parsed = JSON.parse(serialized);
  1430. if (typeof parsed === "object" && parsed != null) {
  1431. return parsed;
  1432. }
  1433. }
  1434. } catch (error) {}
  1435. return null;
  1436. }
  1437. function loadPanelGroupState(autoSaveId, panels, storage) {
  1438. var _loadSerializedPanelG, _state$panelKey;
  1439. const state = (_loadSerializedPanelG = loadSerializedPanelGroupState(autoSaveId, storage)) !== null && _loadSerializedPanelG !== void 0 ? _loadSerializedPanelG : {};
  1440. const panelKey = getPanelKey(panels);
  1441. return (_state$panelKey = state[panelKey]) !== null && _state$panelKey !== void 0 ? _state$panelKey : null;
  1442. }
  1443. function savePanelGroupState(autoSaveId, panels, panelSizesBeforeCollapse, sizes, storage) {
  1444. var _loadSerializedPanelG2;
  1445. const panelGroupKey = getPanelGroupKey(autoSaveId);
  1446. const panelKey = getPanelKey(panels);
  1447. const state = (_loadSerializedPanelG2 = loadSerializedPanelGroupState(autoSaveId, storage)) !== null && _loadSerializedPanelG2 !== void 0 ? _loadSerializedPanelG2 : {};
  1448. state[panelKey] = {
  1449. expandToSizes: Object.fromEntries(panelSizesBeforeCollapse.entries()),
  1450. layout: sizes
  1451. };
  1452. try {
  1453. storage.setItem(panelGroupKey, JSON.stringify(state));
  1454. } catch (error) {
  1455. console.error(error);
  1456. }
  1457. }
  1458. // All units must be in percentages; pixel values should be pre-converted
  1459. function validatePanelGroupLayout({
  1460. layout: prevLayout,
  1461. panelConstraints
  1462. }) {
  1463. const nextLayout = [...prevLayout];
  1464. const nextLayoutTotalSize = nextLayout.reduce((accumulated, current) => accumulated + current, 0);
  1465. // Validate layout expectations
  1466. if (nextLayout.length !== panelConstraints.length) {
  1467. throw Error(`Invalid ${panelConstraints.length} panel layout: ${nextLayout.map(size => `${size}%`).join(", ")}`);
  1468. } else if (!fuzzyNumbersEqual(nextLayoutTotalSize, 100) && nextLayout.length > 0) {
  1469. for (let index = 0; index < panelConstraints.length; index++) {
  1470. const unsafeSize = nextLayout[index];
  1471. assert(unsafeSize != null, `No layout data found for index ${index}`);
  1472. const safeSize = 100 / nextLayoutTotalSize * unsafeSize;
  1473. nextLayout[index] = safeSize;
  1474. }
  1475. }
  1476. let remainingSize = 0;
  1477. // First pass: Validate the proposed layout given each panel's constraints
  1478. for (let index = 0; index < panelConstraints.length; index++) {
  1479. const unsafeSize = nextLayout[index];
  1480. assert(unsafeSize != null, `No layout data found for index ${index}`);
  1481. const safeSize = resizePanel({
  1482. panelConstraints,
  1483. panelIndex: index,
  1484. size: unsafeSize
  1485. });
  1486. if (unsafeSize != safeSize) {
  1487. remainingSize += unsafeSize - safeSize;
  1488. nextLayout[index] = safeSize;
  1489. }
  1490. }
  1491. // If there is additional, left over space, assign it to any panel(s) that permits it
  1492. // (It's not worth taking multiple additional passes to evenly distribute)
  1493. if (!fuzzyNumbersEqual(remainingSize, 0)) {
  1494. for (let index = 0; index < panelConstraints.length; index++) {
  1495. const prevSize = nextLayout[index];
  1496. assert(prevSize != null, `No layout data found for index ${index}`);
  1497. const unsafeSize = prevSize + remainingSize;
  1498. const safeSize = resizePanel({
  1499. panelConstraints,
  1500. panelIndex: index,
  1501. size: unsafeSize
  1502. });
  1503. if (prevSize !== safeSize) {
  1504. remainingSize -= safeSize - prevSize;
  1505. nextLayout[index] = safeSize;
  1506. // Once we've used up the remainder, bail
  1507. if (fuzzyNumbersEqual(remainingSize, 0)) {
  1508. break;
  1509. }
  1510. }
  1511. }
  1512. }
  1513. return nextLayout;
  1514. }
  1515. const LOCAL_STORAGE_DEBOUNCE_INTERVAL = 100;
  1516. const defaultStorage = {
  1517. getItem: name => {
  1518. initializeDefaultStorage(defaultStorage);
  1519. return defaultStorage.getItem(name);
  1520. },
  1521. setItem: (name, value) => {
  1522. initializeDefaultStorage(defaultStorage);
  1523. defaultStorage.setItem(name, value);
  1524. }
  1525. };
  1526. const debounceMap = {};
  1527. function PanelGroupWithForwardedRef({
  1528. autoSaveId = null,
  1529. children,
  1530. className: classNameFromProps = "",
  1531. direction,
  1532. forwardedRef,
  1533. id: idFromProps = null,
  1534. onLayout = null,
  1535. keyboardResizeBy = null,
  1536. storage = defaultStorage,
  1537. style: styleFromProps,
  1538. tagName: Type = "div",
  1539. ...rest
  1540. }) {
  1541. const groupId = useUniqueId(idFromProps);
  1542. const panelGroupElementRef = React.useRef(null);
  1543. const [dragState, setDragState] = React.useState(null);
  1544. const [layout, setLayout] = React.useState([]);
  1545. const forceUpdate = useForceUpdate();
  1546. const panelIdToLastNotifiedSizeMapRef = React.useRef({});
  1547. const panelSizeBeforeCollapseRef = React.useRef(new Map());
  1548. const prevDeltaRef = React.useRef(0);
  1549. const committedValuesRef = React.useRef({
  1550. autoSaveId,
  1551. direction,
  1552. dragState,
  1553. id: groupId,
  1554. keyboardResizeBy,
  1555. onLayout,
  1556. storage
  1557. });
  1558. const eagerValuesRef = React.useRef({
  1559. layout,
  1560. panelDataArray: [],
  1561. panelDataArrayChanged: false
  1562. });
  1563. React.useRef({
  1564. didLogIdAndOrderWarning: false,
  1565. didLogPanelConstraintsWarning: false,
  1566. prevPanelIds: []
  1567. });
  1568. React.useImperativeHandle(forwardedRef, () => ({
  1569. getId: () => committedValuesRef.current.id,
  1570. getLayout: () => {
  1571. const {
  1572. layout
  1573. } = eagerValuesRef.current;
  1574. return layout;
  1575. },
  1576. setLayout: unsafeLayout => {
  1577. const {
  1578. onLayout
  1579. } = committedValuesRef.current;
  1580. const {
  1581. layout: prevLayout,
  1582. panelDataArray
  1583. } = eagerValuesRef.current;
  1584. const safeLayout = validatePanelGroupLayout({
  1585. layout: unsafeLayout,
  1586. panelConstraints: panelDataArray.map(panelData => panelData.constraints)
  1587. });
  1588. if (!areEqual(prevLayout, safeLayout)) {
  1589. setLayout(safeLayout);
  1590. eagerValuesRef.current.layout = safeLayout;
  1591. if (onLayout) {
  1592. onLayout(safeLayout);
  1593. }
  1594. callPanelCallbacks(panelDataArray, safeLayout, panelIdToLastNotifiedSizeMapRef.current);
  1595. }
  1596. }
  1597. }), []);
  1598. useIsomorphicLayoutEffect(() => {
  1599. committedValuesRef.current.autoSaveId = autoSaveId;
  1600. committedValuesRef.current.direction = direction;
  1601. committedValuesRef.current.dragState = dragState;
  1602. committedValuesRef.current.id = groupId;
  1603. committedValuesRef.current.onLayout = onLayout;
  1604. committedValuesRef.current.storage = storage;
  1605. });
  1606. useWindowSplitterPanelGroupBehavior({
  1607. committedValuesRef,
  1608. eagerValuesRef,
  1609. groupId,
  1610. layout,
  1611. panelDataArray: eagerValuesRef.current.panelDataArray,
  1612. setLayout,
  1613. panelGroupElement: panelGroupElementRef.current
  1614. });
  1615. React.useEffect(() => {
  1616. const {
  1617. panelDataArray
  1618. } = eagerValuesRef.current;
  1619. // If this panel has been configured to persist sizing information, save sizes to local storage.
  1620. if (autoSaveId) {
  1621. if (layout.length === 0 || layout.length !== panelDataArray.length) {
  1622. return;
  1623. }
  1624. let debouncedSave = debounceMap[autoSaveId];
  1625. // Limit the frequency of localStorage updates.
  1626. if (debouncedSave == null) {
  1627. debouncedSave = debounce(savePanelGroupState, LOCAL_STORAGE_DEBOUNCE_INTERVAL);
  1628. debounceMap[autoSaveId] = debouncedSave;
  1629. }
  1630. // Clone mutable data before passing to the debounced function,
  1631. // else we run the risk of saving an incorrect combination of mutable and immutable values to state.
  1632. const clonedPanelDataArray = [...panelDataArray];
  1633. const clonedPanelSizesBeforeCollapse = new Map(panelSizeBeforeCollapseRef.current);
  1634. debouncedSave(autoSaveId, clonedPanelDataArray, clonedPanelSizesBeforeCollapse, layout, storage);
  1635. }
  1636. }, [autoSaveId, layout, storage]);
  1637. // DEV warnings
  1638. React.useEffect(() => {
  1639. });
  1640. // External APIs are safe to memoize via committed values ref
  1641. const collapsePanel = React.useCallback(panelData => {
  1642. const {
  1643. onLayout
  1644. } = committedValuesRef.current;
  1645. const {
  1646. layout: prevLayout,
  1647. panelDataArray
  1648. } = eagerValuesRef.current;
  1649. if (panelData.constraints.collapsible) {
  1650. const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
  1651. const {
  1652. collapsedSize = 0,
  1653. panelSize,
  1654. pivotIndices
  1655. } = panelDataHelper(panelDataArray, panelData, prevLayout);
  1656. assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
  1657. if (!fuzzyNumbersEqual$1(panelSize, collapsedSize)) {
  1658. // Store size before collapse;
  1659. // This is the size that gets restored if the expand() API is used.
  1660. panelSizeBeforeCollapseRef.current.set(panelData.id, panelSize);
  1661. const isLastPanel = findPanelDataIndex(panelDataArray, panelData) === panelDataArray.length - 1;
  1662. const delta = isLastPanel ? panelSize - collapsedSize : collapsedSize - panelSize;
  1663. const nextLayout = adjustLayoutByDelta({
  1664. delta,
  1665. initialLayout: prevLayout,
  1666. panelConstraints: panelConstraintsArray,
  1667. pivotIndices,
  1668. prevLayout,
  1669. trigger: "imperative-api"
  1670. });
  1671. if (!compareLayouts(prevLayout, nextLayout)) {
  1672. setLayout(nextLayout);
  1673. eagerValuesRef.current.layout = nextLayout;
  1674. if (onLayout) {
  1675. onLayout(nextLayout);
  1676. }
  1677. callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
  1678. }
  1679. }
  1680. }
  1681. }, []);
  1682. // External APIs are safe to memoize via committed values ref
  1683. const expandPanel = React.useCallback((panelData, minSizeOverride) => {
  1684. const {
  1685. onLayout
  1686. } = committedValuesRef.current;
  1687. const {
  1688. layout: prevLayout,
  1689. panelDataArray
  1690. } = eagerValuesRef.current;
  1691. if (panelData.constraints.collapsible) {
  1692. const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
  1693. const {
  1694. collapsedSize = 0,
  1695. panelSize = 0,
  1696. minSize: minSizeFromProps = 0,
  1697. pivotIndices
  1698. } = panelDataHelper(panelDataArray, panelData, prevLayout);
  1699. const minSize = minSizeOverride !== null && minSizeOverride !== void 0 ? minSizeOverride : minSizeFromProps;
  1700. if (fuzzyNumbersEqual$1(panelSize, collapsedSize)) {
  1701. // Restore this panel to the size it was before it was collapsed, if possible.
  1702. const prevPanelSize = panelSizeBeforeCollapseRef.current.get(panelData.id);
  1703. const baseSize = prevPanelSize != null && prevPanelSize >= minSize ? prevPanelSize : minSize;
  1704. const isLastPanel = findPanelDataIndex(panelDataArray, panelData) === panelDataArray.length - 1;
  1705. const delta = isLastPanel ? panelSize - baseSize : baseSize - panelSize;
  1706. const nextLayout = adjustLayoutByDelta({
  1707. delta,
  1708. initialLayout: prevLayout,
  1709. panelConstraints: panelConstraintsArray,
  1710. pivotIndices,
  1711. prevLayout,
  1712. trigger: "imperative-api"
  1713. });
  1714. if (!compareLayouts(prevLayout, nextLayout)) {
  1715. setLayout(nextLayout);
  1716. eagerValuesRef.current.layout = nextLayout;
  1717. if (onLayout) {
  1718. onLayout(nextLayout);
  1719. }
  1720. callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
  1721. }
  1722. }
  1723. }
  1724. }, []);
  1725. // External APIs are safe to memoize via committed values ref
  1726. const getPanelSize = React.useCallback(panelData => {
  1727. const {
  1728. layout,
  1729. panelDataArray
  1730. } = eagerValuesRef.current;
  1731. const {
  1732. panelSize
  1733. } = panelDataHelper(panelDataArray, panelData, layout);
  1734. assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
  1735. return panelSize;
  1736. }, []);
  1737. // This API should never read from committedValuesRef
  1738. const getPanelStyle = React.useCallback((panelData, defaultSize) => {
  1739. const {
  1740. panelDataArray
  1741. } = eagerValuesRef.current;
  1742. const panelIndex = findPanelDataIndex(panelDataArray, panelData);
  1743. return computePanelFlexBoxStyle({
  1744. defaultSize,
  1745. dragState,
  1746. layout,
  1747. panelData: panelDataArray,
  1748. panelIndex
  1749. });
  1750. }, [dragState, layout]);
  1751. // External APIs are safe to memoize via committed values ref
  1752. const isPanelCollapsed = React.useCallback(panelData => {
  1753. const {
  1754. layout,
  1755. panelDataArray
  1756. } = eagerValuesRef.current;
  1757. const {
  1758. collapsedSize = 0,
  1759. collapsible,
  1760. panelSize
  1761. } = panelDataHelper(panelDataArray, panelData, layout);
  1762. assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
  1763. return collapsible === true && fuzzyNumbersEqual$1(panelSize, collapsedSize);
  1764. }, []);
  1765. // External APIs are safe to memoize via committed values ref
  1766. const isPanelExpanded = React.useCallback(panelData => {
  1767. const {
  1768. layout,
  1769. panelDataArray
  1770. } = eagerValuesRef.current;
  1771. const {
  1772. collapsedSize = 0,
  1773. collapsible,
  1774. panelSize
  1775. } = panelDataHelper(panelDataArray, panelData, layout);
  1776. assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
  1777. return !collapsible || fuzzyCompareNumbers(panelSize, collapsedSize) > 0;
  1778. }, []);
  1779. const registerPanel = React.useCallback(panelData => {
  1780. const {
  1781. panelDataArray
  1782. } = eagerValuesRef.current;
  1783. panelDataArray.push(panelData);
  1784. panelDataArray.sort((panelA, panelB) => {
  1785. const orderA = panelA.order;
  1786. const orderB = panelB.order;
  1787. if (orderA == null && orderB == null) {
  1788. return 0;
  1789. } else if (orderA == null) {
  1790. return -1;
  1791. } else if (orderB == null) {
  1792. return 1;
  1793. } else {
  1794. return orderA - orderB;
  1795. }
  1796. });
  1797. eagerValuesRef.current.panelDataArrayChanged = true;
  1798. forceUpdate();
  1799. }, [forceUpdate]);
  1800. // (Re)calculate group layout whenever panels are registered or unregistered.
  1801. // eslint-disable-next-line react-hooks/exhaustive-deps
  1802. useIsomorphicLayoutEffect(() => {
  1803. if (eagerValuesRef.current.panelDataArrayChanged) {
  1804. eagerValuesRef.current.panelDataArrayChanged = false;
  1805. const {
  1806. autoSaveId,
  1807. onLayout,
  1808. storage
  1809. } = committedValuesRef.current;
  1810. const {
  1811. layout: prevLayout,
  1812. panelDataArray
  1813. } = eagerValuesRef.current;
  1814. // If this panel has been configured to persist sizing information,
  1815. // default size should be restored from local storage if possible.
  1816. let unsafeLayout = null;
  1817. if (autoSaveId) {
  1818. const state = loadPanelGroupState(autoSaveId, panelDataArray, storage);
  1819. if (state) {
  1820. panelSizeBeforeCollapseRef.current = new Map(Object.entries(state.expandToSizes));
  1821. unsafeLayout = state.layout;
  1822. }
  1823. }
  1824. if (unsafeLayout == null) {
  1825. unsafeLayout = calculateUnsafeDefaultLayout({
  1826. panelDataArray
  1827. });
  1828. }
  1829. // Validate even saved layouts in case something has changed since last render
  1830. // e.g. for pixel groups, this could be the size of the window
  1831. const nextLayout = validatePanelGroupLayout({
  1832. layout: unsafeLayout,
  1833. panelConstraints: panelDataArray.map(panelData => panelData.constraints)
  1834. });
  1835. if (!areEqual(prevLayout, nextLayout)) {
  1836. setLayout(nextLayout);
  1837. eagerValuesRef.current.layout = nextLayout;
  1838. if (onLayout) {
  1839. onLayout(nextLayout);
  1840. }
  1841. callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
  1842. }
  1843. }
  1844. });
  1845. // Reset the cached layout if hidden by the Activity/Offscreen API
  1846. useIsomorphicLayoutEffect(() => {
  1847. const eagerValues = eagerValuesRef.current;
  1848. return () => {
  1849. eagerValues.layout = [];
  1850. };
  1851. }, []);
  1852. const registerResizeHandle = React.useCallback(dragHandleId => {
  1853. let isRTL = false;
  1854. const panelGroupElement = panelGroupElementRef.current;
  1855. if (panelGroupElement) {
  1856. const style = window.getComputedStyle(panelGroupElement, null);
  1857. if (style.getPropertyValue("direction") === "rtl") {
  1858. isRTL = true;
  1859. }
  1860. }
  1861. return function resizeHandler(event) {
  1862. event.preventDefault();
  1863. const panelGroupElement = panelGroupElementRef.current;
  1864. if (!panelGroupElement) {
  1865. return () => null;
  1866. }
  1867. const {
  1868. direction,
  1869. dragState,
  1870. id: groupId,
  1871. keyboardResizeBy,
  1872. onLayout
  1873. } = committedValuesRef.current;
  1874. const {
  1875. layout: prevLayout,
  1876. panelDataArray
  1877. } = eagerValuesRef.current;
  1878. const {
  1879. initialLayout
  1880. } = dragState !== null && dragState !== void 0 ? dragState : {};
  1881. const pivotIndices = determinePivotIndices(groupId, dragHandleId, panelGroupElement);
  1882. let delta = calculateDeltaPercentage(event, dragHandleId, direction, dragState, keyboardResizeBy, panelGroupElement);
  1883. const isHorizontal = direction === "horizontal";
  1884. if (isHorizontal && isRTL) {
  1885. delta = -delta;
  1886. }
  1887. const panelConstraints = panelDataArray.map(panelData => panelData.constraints);
  1888. const nextLayout = adjustLayoutByDelta({
  1889. delta,
  1890. initialLayout: initialLayout !== null && initialLayout !== void 0 ? initialLayout : prevLayout,
  1891. panelConstraints,
  1892. pivotIndices,
  1893. prevLayout,
  1894. trigger: isKeyDown(event) ? "keyboard" : "mouse-or-touch"
  1895. });
  1896. const layoutChanged = !compareLayouts(prevLayout, nextLayout);
  1897. // Only update the cursor for layout changes triggered by touch/mouse events (not keyboard)
  1898. // Update the cursor even if the layout hasn't changed (we may need to show an invalid cursor state)
  1899. if (isPointerEvent(event) || isMouseEvent(event)) {
  1900. // Watch for multiple subsequent deltas; this might occur for tiny cursor movements.
  1901. // In this case, Panel sizes might not change–
  1902. // but updating cursor in this scenario would cause a flicker.
  1903. if (prevDeltaRef.current != delta) {
  1904. prevDeltaRef.current = delta;
  1905. if (!layoutChanged && delta !== 0) {
  1906. // If the pointer has moved too far to resize the panel any further, note this so we can update the cursor.
  1907. // This mimics VS Code behavior.
  1908. if (isHorizontal) {
  1909. reportConstraintsViolation(dragHandleId, delta < 0 ? EXCEEDED_HORIZONTAL_MIN : EXCEEDED_HORIZONTAL_MAX);
  1910. } else {
  1911. reportConstraintsViolation(dragHandleId, delta < 0 ? EXCEEDED_VERTICAL_MIN : EXCEEDED_VERTICAL_MAX);
  1912. }
  1913. } else {
  1914. reportConstraintsViolation(dragHandleId, 0);
  1915. }
  1916. }
  1917. }
  1918. if (layoutChanged) {
  1919. setLayout(nextLayout);
  1920. eagerValuesRef.current.layout = nextLayout;
  1921. if (onLayout) {
  1922. onLayout(nextLayout);
  1923. }
  1924. callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
  1925. }
  1926. };
  1927. }, []);
  1928. // External APIs are safe to memoize via committed values ref
  1929. const resizePanel = React.useCallback((panelData, unsafePanelSize) => {
  1930. const {
  1931. onLayout
  1932. } = committedValuesRef.current;
  1933. const {
  1934. layout: prevLayout,
  1935. panelDataArray
  1936. } = eagerValuesRef.current;
  1937. const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
  1938. const {
  1939. panelSize,
  1940. pivotIndices
  1941. } = panelDataHelper(panelDataArray, panelData, prevLayout);
  1942. assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
  1943. const isLastPanel = findPanelDataIndex(panelDataArray, panelData) === panelDataArray.length - 1;
  1944. const delta = isLastPanel ? panelSize - unsafePanelSize : unsafePanelSize - panelSize;
  1945. const nextLayout = adjustLayoutByDelta({
  1946. delta,
  1947. initialLayout: prevLayout,
  1948. panelConstraints: panelConstraintsArray,
  1949. pivotIndices,
  1950. prevLayout,
  1951. trigger: "imperative-api"
  1952. });
  1953. if (!compareLayouts(prevLayout, nextLayout)) {
  1954. setLayout(nextLayout);
  1955. eagerValuesRef.current.layout = nextLayout;
  1956. if (onLayout) {
  1957. onLayout(nextLayout);
  1958. }
  1959. callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
  1960. }
  1961. }, []);
  1962. const reevaluatePanelConstraints = React.useCallback((panelData, prevConstraints) => {
  1963. const {
  1964. layout,
  1965. panelDataArray
  1966. } = eagerValuesRef.current;
  1967. const {
  1968. collapsedSize: prevCollapsedSize = 0,
  1969. collapsible: prevCollapsible
  1970. } = prevConstraints;
  1971. const {
  1972. collapsedSize: nextCollapsedSize = 0,
  1973. collapsible: nextCollapsible,
  1974. maxSize: nextMaxSize = 100,
  1975. minSize: nextMinSize = 0
  1976. } = panelData.constraints;
  1977. const {
  1978. panelSize: prevPanelSize
  1979. } = panelDataHelper(panelDataArray, panelData, layout);
  1980. if (prevPanelSize == null) {
  1981. // It's possible that the panels in this group have changed since the last render
  1982. return;
  1983. }
  1984. if (prevCollapsible && nextCollapsible && fuzzyNumbersEqual$1(prevPanelSize, prevCollapsedSize)) {
  1985. if (!fuzzyNumbersEqual$1(prevCollapsedSize, nextCollapsedSize)) {
  1986. resizePanel(panelData, nextCollapsedSize);
  1987. }
  1988. } else if (prevPanelSize < nextMinSize) {
  1989. resizePanel(panelData, nextMinSize);
  1990. } else if (prevPanelSize > nextMaxSize) {
  1991. resizePanel(panelData, nextMaxSize);
  1992. }
  1993. }, [resizePanel]);
  1994. // TODO Multiple drag handles can be active at the same time so this API is a bit awkward now
  1995. const startDragging = React.useCallback((dragHandleId, event) => {
  1996. const {
  1997. direction
  1998. } = committedValuesRef.current;
  1999. const {
  2000. layout
  2001. } = eagerValuesRef.current;
  2002. if (!panelGroupElementRef.current) {
  2003. return;
  2004. }
  2005. const handleElement = getResizeHandleElement(dragHandleId, panelGroupElementRef.current);
  2006. assert(handleElement, `Drag handle element not found for id "${dragHandleId}"`);
  2007. const initialCursorPosition = getResizeEventCursorPosition(direction, event);
  2008. setDragState({
  2009. dragHandleId,
  2010. dragHandleRect: handleElement.getBoundingClientRect(),
  2011. initialCursorPosition,
  2012. initialLayout: layout
  2013. });
  2014. }, []);
  2015. const stopDragging = React.useCallback(() => {
  2016. setDragState(null);
  2017. }, []);
  2018. const unregisterPanel = React.useCallback(panelData => {
  2019. const {
  2020. panelDataArray
  2021. } = eagerValuesRef.current;
  2022. const index = findPanelDataIndex(panelDataArray, panelData);
  2023. if (index >= 0) {
  2024. panelDataArray.splice(index, 1);
  2025. // TRICKY
  2026. // When a panel is removed from the group, we should delete the most recent prev-size entry for it.
  2027. // If we don't do this, then a conditionally rendered panel might not call onResize when it's re-mounted.
  2028. // Strict effects mode makes this tricky though because all panels will be registered, unregistered, then re-registered on mount.
  2029. delete panelIdToLastNotifiedSizeMapRef.current[panelData.id];
  2030. eagerValuesRef.current.panelDataArrayChanged = true;
  2031. forceUpdate();
  2032. }
  2033. }, [forceUpdate]);
  2034. const context = React.useMemo(() => ({
  2035. collapsePanel,
  2036. direction,
  2037. dragState,
  2038. expandPanel,
  2039. getPanelSize,
  2040. getPanelStyle,
  2041. groupId,
  2042. isPanelCollapsed,
  2043. isPanelExpanded,
  2044. reevaluatePanelConstraints,
  2045. registerPanel,
  2046. registerResizeHandle,
  2047. resizePanel,
  2048. startDragging,
  2049. stopDragging,
  2050. unregisterPanel,
  2051. panelGroupElement: panelGroupElementRef.current
  2052. }), [collapsePanel, dragState, direction, expandPanel, getPanelSize, getPanelStyle, groupId, isPanelCollapsed, isPanelExpanded, reevaluatePanelConstraints, registerPanel, registerResizeHandle, resizePanel, startDragging, stopDragging, unregisterPanel]);
  2053. const style = {
  2054. display: "flex",
  2055. flexDirection: direction === "horizontal" ? "row" : "column",
  2056. height: "100%",
  2057. overflow: "hidden",
  2058. width: "100%"
  2059. };
  2060. return React.createElement(PanelGroupContext.Provider, {
  2061. value: context
  2062. }, React.createElement(Type, {
  2063. ...rest,
  2064. children,
  2065. className: classNameFromProps,
  2066. id: idFromProps,
  2067. ref: panelGroupElementRef,
  2068. style: {
  2069. ...style,
  2070. ...styleFromProps
  2071. },
  2072. // CSS selectors
  2073. [DATA_ATTRIBUTES.group]: "",
  2074. [DATA_ATTRIBUTES.groupDirection]: direction,
  2075. [DATA_ATTRIBUTES.groupId]: groupId
  2076. }));
  2077. }
  2078. const PanelGroup = React.forwardRef((props, ref) => React.createElement(PanelGroupWithForwardedRef, {
  2079. ...props,
  2080. forwardedRef: ref
  2081. }));
  2082. PanelGroupWithForwardedRef.displayName = "PanelGroup";
  2083. PanelGroup.displayName = "forwardRef(PanelGroup)";
  2084. function findPanelDataIndex(panelDataArray, panelData) {
  2085. return panelDataArray.findIndex(prevPanelData => prevPanelData === panelData || prevPanelData.id === panelData.id);
  2086. }
  2087. function panelDataHelper(panelDataArray, panelData, layout) {
  2088. const panelIndex = findPanelDataIndex(panelDataArray, panelData);
  2089. const isLastPanel = panelIndex === panelDataArray.length - 1;
  2090. const pivotIndices = isLastPanel ? [panelIndex - 1, panelIndex] : [panelIndex, panelIndex + 1];
  2091. const panelSize = layout[panelIndex];
  2092. return {
  2093. ...panelData.constraints,
  2094. panelSize,
  2095. pivotIndices
  2096. };
  2097. }
  2098. // https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/
  2099. function useWindowSplitterResizeHandlerBehavior({
  2100. disabled,
  2101. handleId,
  2102. resizeHandler,
  2103. panelGroupElement
  2104. }) {
  2105. React.useEffect(() => {
  2106. if (disabled || resizeHandler == null || panelGroupElement == null) {
  2107. return;
  2108. }
  2109. const handleElement = getResizeHandleElement(handleId, panelGroupElement);
  2110. if (handleElement == null) {
  2111. return;
  2112. }
  2113. const onKeyDown = event => {
  2114. if (event.defaultPrevented) {
  2115. return;
  2116. }
  2117. switch (event.key) {
  2118. case "ArrowDown":
  2119. case "ArrowLeft":
  2120. case "ArrowRight":
  2121. case "ArrowUp":
  2122. case "End":
  2123. case "Home":
  2124. {
  2125. event.preventDefault();
  2126. resizeHandler(event);
  2127. break;
  2128. }
  2129. case "F6":
  2130. {
  2131. event.preventDefault();
  2132. const groupId = handleElement.getAttribute(DATA_ATTRIBUTES.groupId);
  2133. assert(groupId, `No group element found for id "${groupId}"`);
  2134. const handles = getResizeHandleElementsForGroup(groupId, panelGroupElement);
  2135. const index = getResizeHandleElementIndex(groupId, handleId, panelGroupElement);
  2136. assert(index !== null, `No resize element found for id "${handleId}"`);
  2137. const nextIndex = event.shiftKey ? index > 0 ? index - 1 : handles.length - 1 : index + 1 < handles.length ? index + 1 : 0;
  2138. const nextHandle = handles[nextIndex];
  2139. nextHandle.focus();
  2140. break;
  2141. }
  2142. }
  2143. };
  2144. handleElement.addEventListener("keydown", onKeyDown);
  2145. return () => {
  2146. handleElement.removeEventListener("keydown", onKeyDown);
  2147. };
  2148. }, [panelGroupElement, disabled, handleId, resizeHandler]);
  2149. }
  2150. function PanelResizeHandle({
  2151. children = null,
  2152. className: classNameFromProps = "",
  2153. disabled = false,
  2154. hitAreaMargins,
  2155. id: idFromProps,
  2156. onBlur,
  2157. onClick,
  2158. onDragging,
  2159. onFocus,
  2160. onPointerDown,
  2161. onPointerUp,
  2162. style: styleFromProps = {},
  2163. tabIndex = 0,
  2164. tagName: Type = "div",
  2165. ...rest
  2166. }) {
  2167. var _hitAreaMargins$coars, _hitAreaMargins$fine;
  2168. const elementRef = React.useRef(null);
  2169. // Use a ref to guard against users passing inline props
  2170. const callbacksRef = React.useRef({
  2171. onClick,
  2172. onDragging,
  2173. onPointerDown,
  2174. onPointerUp
  2175. });
  2176. React.useEffect(() => {
  2177. callbacksRef.current.onClick = onClick;
  2178. callbacksRef.current.onDragging = onDragging;
  2179. callbacksRef.current.onPointerDown = onPointerDown;
  2180. callbacksRef.current.onPointerUp = onPointerUp;
  2181. });
  2182. const panelGroupContext = React.useContext(PanelGroupContext);
  2183. if (panelGroupContext === null) {
  2184. throw Error(`PanelResizeHandle components must be rendered within a PanelGroup container`);
  2185. }
  2186. const {
  2187. direction,
  2188. groupId,
  2189. registerResizeHandle: registerResizeHandleWithParentGroup,
  2190. startDragging,
  2191. stopDragging,
  2192. panelGroupElement
  2193. } = panelGroupContext;
  2194. const resizeHandleId = useUniqueId(idFromProps);
  2195. const [state, setState] = React.useState("inactive");
  2196. const [isFocused, setIsFocused] = React.useState(false);
  2197. const [resizeHandler, setResizeHandler] = React.useState(null);
  2198. const committedValuesRef = React.useRef({
  2199. state
  2200. });
  2201. useIsomorphicLayoutEffect(() => {
  2202. committedValuesRef.current.state = state;
  2203. });
  2204. React.useEffect(() => {
  2205. if (disabled) {
  2206. setResizeHandler(null);
  2207. } else {
  2208. const resizeHandler = registerResizeHandleWithParentGroup(resizeHandleId);
  2209. setResizeHandler(() => resizeHandler);
  2210. }
  2211. }, [disabled, resizeHandleId, registerResizeHandleWithParentGroup]);
  2212. // Extract hit area margins before passing them to the effect's dependency array
  2213. // so that inline object values won't trigger re-renders
  2214. const coarseHitAreaMargins = (_hitAreaMargins$coars = hitAreaMargins === null || hitAreaMargins === void 0 ? void 0 : hitAreaMargins.coarse) !== null && _hitAreaMargins$coars !== void 0 ? _hitAreaMargins$coars : 15;
  2215. const fineHitAreaMargins = (_hitAreaMargins$fine = hitAreaMargins === null || hitAreaMargins === void 0 ? void 0 : hitAreaMargins.fine) !== null && _hitAreaMargins$fine !== void 0 ? _hitAreaMargins$fine : 5;
  2216. React.useEffect(() => {
  2217. if (disabled || resizeHandler == null) {
  2218. return;
  2219. }
  2220. const element = elementRef.current;
  2221. assert(element, "Element ref not attached");
  2222. let didMove = false;
  2223. const setResizeHandlerState = (action, isActive, event) => {
  2224. if (!isActive) {
  2225. setState("inactive");
  2226. return;
  2227. }
  2228. switch (action) {
  2229. case "down":
  2230. {
  2231. setState("drag");
  2232. didMove = false;
  2233. assert(event, 'Expected event to be defined for "down" action');
  2234. startDragging(resizeHandleId, event);
  2235. const {
  2236. onDragging,
  2237. onPointerDown
  2238. } = callbacksRef.current;
  2239. onDragging === null || onDragging === void 0 ? void 0 : onDragging(true);
  2240. onPointerDown === null || onPointerDown === void 0 ? void 0 : onPointerDown();
  2241. break;
  2242. }
  2243. case "move":
  2244. {
  2245. const {
  2246. state
  2247. } = committedValuesRef.current;
  2248. didMove = true;
  2249. if (state !== "drag") {
  2250. setState("hover");
  2251. }
  2252. assert(event, 'Expected event to be defined for "move" action');
  2253. resizeHandler(event);
  2254. break;
  2255. }
  2256. case "up":
  2257. {
  2258. setState("hover");
  2259. stopDragging();
  2260. const {
  2261. onClick,
  2262. onDragging,
  2263. onPointerUp
  2264. } = callbacksRef.current;
  2265. onDragging === null || onDragging === void 0 ? void 0 : onDragging(false);
  2266. onPointerUp === null || onPointerUp === void 0 ? void 0 : onPointerUp();
  2267. if (!didMove) {
  2268. onClick === null || onClick === void 0 ? void 0 : onClick();
  2269. }
  2270. break;
  2271. }
  2272. }
  2273. };
  2274. return registerResizeHandle(resizeHandleId, element, direction, {
  2275. coarse: coarseHitAreaMargins,
  2276. fine: fineHitAreaMargins
  2277. }, setResizeHandlerState);
  2278. }, [coarseHitAreaMargins, direction, disabled, fineHitAreaMargins, registerResizeHandleWithParentGroup, resizeHandleId, resizeHandler, startDragging, stopDragging]);
  2279. useWindowSplitterResizeHandlerBehavior({
  2280. disabled,
  2281. handleId: resizeHandleId,
  2282. resizeHandler,
  2283. panelGroupElement
  2284. });
  2285. const style = {
  2286. touchAction: "none",
  2287. userSelect: "none"
  2288. };
  2289. return React.createElement(Type, {
  2290. ...rest,
  2291. children,
  2292. className: classNameFromProps,
  2293. id: idFromProps,
  2294. onBlur: () => {
  2295. setIsFocused(false);
  2296. onBlur === null || onBlur === void 0 ? void 0 : onBlur();
  2297. },
  2298. onFocus: () => {
  2299. setIsFocused(true);
  2300. onFocus === null || onFocus === void 0 ? void 0 : onFocus();
  2301. },
  2302. ref: elementRef,
  2303. role: "separator",
  2304. style: {
  2305. ...style,
  2306. ...styleFromProps
  2307. },
  2308. tabIndex,
  2309. // CSS selectors
  2310. [DATA_ATTRIBUTES.groupDirection]: direction,
  2311. [DATA_ATTRIBUTES.groupId]: groupId,
  2312. [DATA_ATTRIBUTES.resizeHandle]: "",
  2313. [DATA_ATTRIBUTES.resizeHandleActive]: state === "drag" ? "pointer" : isFocused ? "keyboard" : undefined,
  2314. [DATA_ATTRIBUTES.resizeHandleEnabled]: !disabled,
  2315. [DATA_ATTRIBUTES.resizeHandleId]: resizeHandleId,
  2316. [DATA_ATTRIBUTES.resizeHandleState]: state
  2317. });
  2318. }
  2319. PanelResizeHandle.displayName = "PanelResizeHandle";
  2320. function getPanelElement(id, scope = document) {
  2321. const element = scope.querySelector(`[data-panel-id="${id}"]`);
  2322. if (element) {
  2323. return element;
  2324. }
  2325. return null;
  2326. }
  2327. function getPanelElementsForGroup(groupId, scope = document) {
  2328. return Array.from(scope.querySelectorAll(`[data-panel][data-panel-group-id="${groupId}"]`));
  2329. }
  2330. function getIntersectingRectangle(rectOne, rectTwo, strict) {
  2331. if (!intersects(rectOne, rectTwo, strict)) {
  2332. return {
  2333. x: 0,
  2334. y: 0,
  2335. width: 0,
  2336. height: 0
  2337. };
  2338. }
  2339. return {
  2340. x: Math.max(rectOne.x, rectTwo.x),
  2341. y: Math.max(rectOne.y, rectTwo.y),
  2342. width: Math.min(rectOne.x + rectOne.width, rectTwo.x + rectTwo.width) - Math.max(rectOne.x, rectTwo.x),
  2343. height: Math.min(rectOne.y + rectOne.height, rectTwo.y + rectTwo.height) - Math.max(rectOne.y, rectTwo.y)
  2344. };
  2345. }
  2346. exports.DATA_ATTRIBUTES = DATA_ATTRIBUTES;
  2347. exports.Panel = Panel;
  2348. exports.PanelGroup = PanelGroup;
  2349. exports.PanelResizeHandle = PanelResizeHandle;
  2350. exports.assert = assert;
  2351. exports.disableGlobalCursorStyles = disableGlobalCursorStyles;
  2352. exports.enableGlobalCursorStyles = enableGlobalCursorStyles;
  2353. exports.getIntersectingRectangle = getIntersectingRectangle;
  2354. exports.getPanelElement = getPanelElement;
  2355. exports.getPanelElementsForGroup = getPanelElementsForGroup;
  2356. exports.getPanelGroupElement = getPanelGroupElement;
  2357. exports.getResizeHandleElement = getResizeHandleElement;
  2358. exports.getResizeHandleElementIndex = getResizeHandleElementIndex;
  2359. exports.getResizeHandleElementsForGroup = getResizeHandleElementsForGroup;
  2360. exports.getResizeHandlePanelIds = getResizeHandlePanelIds;
  2361. exports.intersects = intersects;
  2362. exports.setNonce = setNonce;