react-simple-dock 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Perceval Wajsbürt
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # React-Simple-Dock
2
+
3
+ A set of React components to create a dockable interface, allowing to arrange and resize tabs.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install react-simple-dock
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```tsx
14
+ import React from "react";
15
+ import { Layout, Panel } from "react-simple-dock";
16
+ import { DndProvider } from "react-dnd";
17
+ import { HTML5Backend } from "react-dnd-html5-backend";
18
+
19
+ const DEFAULT_CONFIG = {
20
+ kind: "row",
21
+ size: 100,
22
+ children: [
23
+ {
24
+ kind: "column",
25
+ size: 50,
26
+ children: [
27
+ { kind: "leaf", tabs: ["Panel 1"], tabIndex: 0, size: 50 },
28
+ { kind: "leaf", tabs: ["Panel 2"], tabIndex: 0, size: 50 },
29
+ ],
30
+ },
31
+ { kind: "leaf", tabs: ["Panel 3"], tabIndex: 0, size: 50 },
32
+ ],
33
+ };
34
+
35
+ const App = () => (
36
+ <DndProvider backend={HTML5Backend}>
37
+ <div style={{ background: "#bdbdbd", width: "100vw", height: "100vh" }}>
38
+ <Layout
39
+ /* optional initial layout config */
40
+ defaultConfig={DEFAULT_CONFIG}
41
+ >
42
+ <Panel key="Panel 1">
43
+ <p>Content 1</p>
44
+ </Panel>
45
+ <Panel key="Panel 2" header={<i>Italic title</i>}>
46
+ <p>Content 2</p>
47
+ </Panel>
48
+ <Panel key="Panel 3">
49
+ <p>Content 3</p>
50
+ </Panel>
51
+ </Layout>
52
+ </div>
53
+ </DndProvider>
54
+ );
55
+
56
+ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(<App />);
57
+ ```
58
+
59
+ ## Demo
60
+
61
+ [![Edit react-simple-dock](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/react-simple-dock-1j2j2?fontsize=14&hidenavigation=1&theme=dark)
package/dist/index.css ADDED
@@ -0,0 +1,192 @@
1
+ /* Light Theme, feel free to override */
2
+ :root {
3
+ --sd-grid-gap: 3px;
4
+ }
5
+
6
+ :root[data-theme="light"] {
7
+ --sd-background-color: #fff;
8
+ --sd-text-color: #000;
9
+ --sd-tab-border-color: #bdbdbd;
10
+ --sd-tab-background-color: white;
11
+ --sd-header-background-color: white;
12
+ --sd-header-border-color: #cecece;
13
+ --sd-overlay-color: rgba(69, 159, 232, 0.51);
14
+ --sd-highlight-color: #4591e8;
15
+ }
16
+
17
+ /* Dark Theme, feel free to override */
18
+ :root[data-theme="dark"] {
19
+ --sd-background-color: #22272e;
20
+ --sd-text-color: #fff;
21
+ --sd-border-color: #666;
22
+ --sd-tab-border-color: #111;
23
+ --sd-highlight-color: #4591e8;
24
+ --sd-tab-background-color: #1c2128;
25
+ --sd-header-background-color: #333;
26
+ --sd-header-border-color: #444;
27
+ --sd-overlay-color: rgba(105, 159, 232, 0.51);
28
+ }
29
+
30
+ body[data-jp-theme-light] {
31
+ /* don't care about the theme, just that we're in JupyterLab */
32
+ --sd-grid-gap: 7px;
33
+ --sd-background-color: var(--jp-layout-color3);
34
+ }
35
+
36
+ .resize-border {
37
+ position: absolute;
38
+ background-color: var(--sd-background-color, #fff);
39
+ opacity: 0;
40
+ z-index: 10;
41
+ }
42
+
43
+ .resize-border:hover {
44
+ opacity: 0.8;
45
+ }
46
+
47
+ .resize-border.bottom {
48
+ bottom: calc(0px - var(--sd-grid-gap));
49
+ left: 0;
50
+ right: 0;
51
+ height: calc((var(--sd-grid-gap)));
52
+ cursor: row-resize;
53
+ }
54
+
55
+ .resize-border.right {
56
+ top: 0;
57
+ bottom: 0;
58
+ right: calc(0px - var(--sd-grid-gap));
59
+ width: calc((var(--sd-grid-gap)));
60
+ cursor: col-resize;
61
+ }
62
+
63
+ .container {
64
+ width: 100%;
65
+ height: 100%;
66
+ }
67
+
68
+ .tab-handle-overlay {
69
+ position: absolute;
70
+ box-sizing: border-box;
71
+ display: none;
72
+ top: 0;
73
+ left: 0;
74
+ right: 0;
75
+ bottom: 0;
76
+ z-index: 100;
77
+ background: var(--sd-overlay-color, rgba(69, 159, 232, 0.51));
78
+ border: 2px dashed var(--sd-highlight-color, #4591e8);
79
+
80
+ pointer-events: none;
81
+ transition: 0s linear;
82
+ transition-property: left, right, top, bottom, width, height;
83
+ }
84
+
85
+ .panel {
86
+ position: relative;
87
+ display: flex;
88
+ flex: 1 100000000 0;
89
+ align-self: stretch;
90
+ height: 100%;
91
+ width: 100%;
92
+ background: var(--sd-background-color);
93
+ }
94
+
95
+ .panel.leaf {
96
+ flex-direction: column;
97
+ }
98
+
99
+ .row > .panel-content,
100
+ .column > .panel-content {
101
+ display: grid;
102
+ grid-gap: var(--sd-grid-gap);
103
+ position: absolute;
104
+ left: 0;
105
+ top: 0;
106
+ width: 100%;
107
+ height: 100%;
108
+ }
109
+
110
+ .leaf > .panel-content {
111
+ position: relative;
112
+ flex: 1;
113
+ }
114
+
115
+ .leaf > .panel-content > div {
116
+ background: var(--sd-tab-background-color);
117
+ position: absolute;
118
+ top: 0;
119
+ left: 0;
120
+ width: 100%;
121
+ height: 100%;
122
+ overflow: scroll;
123
+ }
124
+
125
+ /* TAB HEADER */
126
+
127
+ .tab-header {
128
+ display: flex;
129
+ flex-direction: row;
130
+ height: var(--sd-header-height);
131
+ }
132
+
133
+ .tab-header-border {
134
+ position: relative;
135
+ height: 1px;
136
+ background: var(--sd-tab-border-color, #cecece);
137
+ margin-top: -2px;
138
+ z-index: 0;
139
+ }
140
+
141
+ .tab-header-bottom {
142
+ position: relative;
143
+ background: var(--sd-tab-background-color, white);
144
+ height: 3px;
145
+ z-index: 2;
146
+ border: solid var(--sd-tab-border-color, #bdbdbd);
147
+ border-width: 0 1px 1px 1px;
148
+ /*
149
+ Why did I put this ? It messes up the overall width of the layout
150
+ margin-left: -1px;
151
+ margin-right: -1px;
152
+ */
153
+ }
154
+
155
+ .tab-placeholder {
156
+ width: 0;
157
+ transition: width 0.1s linear;
158
+ height: 0;
159
+ }
160
+
161
+ .tab-handle {
162
+ position: relative;
163
+ box-sizing: border-box;
164
+ padding: 5px;
165
+ color: var(--sd-text-color, #000);
166
+ background: var(--sd-tab-background-color, white);
167
+ font-size: calc((var(--sd-header-height) - 12px) * 0.8);
168
+ border: solid var(--sd-tab-border-color, #bdbdbd);
169
+ border-width: 1px 1px 1px 1px;
170
+ /* Too overlap the border of the next handle and avoid double borders */
171
+ margin-right: -1px;
172
+ z-index: 1;
173
+ }
174
+
175
+ .tab-handle:nth-child(2) {
176
+ border-left-width: 1px;
177
+ }
178
+
179
+ .tab-handle.tab-handle__hidden {
180
+ z-index: 0;
181
+ }
182
+
183
+ .tab-handle.tab-handle__visible:before {
184
+ content: "";
185
+ display: block;
186
+ background: var(--sd-highlight-color, #4591e8);
187
+ position: absolute;
188
+ top: 0;
189
+ left: 0;
190
+ right: 0;
191
+ height: 2px;
192
+ }
@@ -0,0 +1,9 @@
1
+ import React from "react";
2
+ import "./index.css";
3
+ import { LayoutConfig, PanelProps } from "./types";
4
+ export declare const Panel: (props: PanelProps) => any;
5
+ export declare function Layout(props: {
6
+ children: React.ReactElement<PanelProps>[] | React.ReactElement<PanelProps>;
7
+ defaultConfig?: LayoutConfig;
8
+ wrapDnd?: boolean;
9
+ }): import("react/jsx-runtime").JSX.Element;
package/dist/index.js ADDED
@@ -0,0 +1,380 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
3
+ import "./index.css";
4
+ import { DndProvider, useDrag, useDragDropManager, useDrop } from "react-dnd";
5
+ import { filterPanels, movePanel } from "./utils";
6
+ import { HTML5Backend } from "react-dnd-html5-backend";
7
+ export const Panel = (props) => {
8
+ return null;
9
+ };
10
+ function useForceUpdate() {
11
+ const [value, setValue] = useState(0); // integer state
12
+ return () => setValue((value) => value + 1); // update state to force render
13
+ }
14
+ const getPanelElementHeader = (node) => node.children[0];
15
+ const TabHandle = ({ name, index, visible, onClick, children, }) => {
16
+ const getItem = () => ({
17
+ name,
18
+ handleElement: targetRef.current,
19
+ width: targetRef.current.offsetWidth,
20
+ });
21
+ const targetRef = useRef(null);
22
+ const [{}, dragRef] = useDrag(() => ({
23
+ type: "TabHeader",
24
+ collect: () => ({}),
25
+ item: getItem,
26
+ }), [name]);
27
+ return (_jsx("div", { className: `tab-handle tab-handle__${visible ? "visible" : "hidden"}`, ref: (element) => {
28
+ dragRef(element);
29
+ targetRef.current = element;
30
+ }, onClick: () => onClick(index), children: children }));
31
+ };
32
+ const TabHeader = ({ config, onClick, leaves, }) => {
33
+ return (_jsxs("div", { children: [_jsxs("div", { className: "tab-header", children: [config.tabs
34
+ .map((tab, i) => [
35
+ _jsx("div", { className: "tab-placeholder", style: { width: "0px" }, "data-panel-name": tab }, `${i}-placeholder`),
36
+ _jsx(TabHandle, { name: tab, index: i, visible: config.tabIndex === i, onClick: onClick, children: leaves[tab].header || tab }, i),
37
+ ])
38
+ .flat(), _jsx("div", { className: "tab-placeholder" })] }), _jsx("div", { className: "tab-header-border" }), _jsx("div", { className: "tab-header-bottom" })] }));
39
+ };
40
+ const NestedPanel = React.memo(({ leaves, config, index, onResize, saveSizes, isLast, direction, style, panelElements, }) => {
41
+ const startEvent = useRef(null);
42
+ const savedSizes = useRef([]);
43
+ const forceUpdate = useForceUpdate();
44
+ useEffect(() => {
45
+ const handleMouseUp = (e) => {
46
+ document.removeEventListener("mousemove", startEvent.current?.handleMouseMove);
47
+ if (startEvent.current) {
48
+ e.preventDefault();
49
+ }
50
+ startEvent.current = null;
51
+ };
52
+ document.addEventListener("mouseup", handleMouseUp);
53
+ // Make sure to remove event listener on component unmount
54
+ return () => {
55
+ document.removeEventListener("mouseup", handleMouseUp);
56
+ document.removeEventListener("mousemove", startEvent.current?.handleMouseMove);
57
+ };
58
+ }, []);
59
+ useLayoutEffect(() => {
60
+ panelElements.set(config, panelRef.current);
61
+ return () => {
62
+ panelElements.delete(config);
63
+ };
64
+ }, [config]);
65
+ const handleMouseMove = useCallback((e) => {
66
+ if (!startEvent.current) {
67
+ return;
68
+ }
69
+ e.preventDefault();
70
+ const { clientX, clientY } = e;
71
+ // get Panel top left corner
72
+ const { top, left } = (startEvent.current?.target).parentElement.getBoundingClientRect();
73
+ let ratio;
74
+ if (startEvent.current.side === "bottom") {
75
+ ratio = (clientY - top) / startEvent.current.height;
76
+ }
77
+ else if (startEvent.current.side === "right") {
78
+ ratio = (clientX - left) / startEvent.current.width;
79
+ }
80
+ else {
81
+ return;
82
+ }
83
+ onResize && onResize(ratio, index, startEvent.current.target);
84
+ }, [onResize, index]);
85
+ const handleMouseDown = (e, side) => {
86
+ if (startEvent.current) {
87
+ return;
88
+ }
89
+ document.addEventListener("mousemove", handleMouseMove);
90
+ const { top, left } = e.currentTarget.parentElement.getBoundingClientRect();
91
+ e.preventDefault();
92
+ saveSizes && saveSizes();
93
+ startEvent.current = {
94
+ width: e.clientX - left,
95
+ height: e.clientY - top,
96
+ target: e.currentTarget,
97
+ side: side,
98
+ handleMouseMove,
99
+ size: config.size,
100
+ };
101
+ };
102
+ const makeStyle = () => {
103
+ if (config.kind === "row") {
104
+ // return {gridTemplateColumns: config.children.map(c => `calc((${100}% - var(--grid-gap) * ${config.children.length - 1}) * ${c.size / 100})`).join(" ")};
105
+ return {
106
+ gridTemplateColumns: config.children.map((c) => `${c.size}fr`).join(" "),
107
+ };
108
+ }
109
+ if (config.kind === "column") {
110
+ // return {gridTemplateRows: config.children.map(c => `calc((${100}% - var(--grid-gap) * ${config.children.length - 1}) * ${c.size / 100})`).join(" ")};
111
+ return {
112
+ gridTemplateRows: config.children.map((c) => `${c.size}fr`).join(" "),
113
+ };
114
+ }
115
+ };
116
+ const handleResize = useCallback((ratio, idx, target) => {
117
+ if (config.kind === "leaf")
118
+ return;
119
+ let size = savedSizes.current[idx] * ratio;
120
+ let nextSize = savedSizes.current[idx + 1] + (savedSizes.current[idx] - size);
121
+ const total = savedSizes.current.reduce((a, b) => a + b, 0);
122
+ const headerHeight = getPanelElementHeader(target.parentElement).offsetHeight;
123
+ if (config.kind === "column") {
124
+ const parentHeight = panelContentRef.current.offsetHeight;
125
+ if ((size * parentHeight) / total < headerHeight) {
126
+ size = (headerHeight / parentHeight) * total;
127
+ nextSize = savedSizes.current[idx + 1] + (savedSizes.current[idx] - size);
128
+ }
129
+ else if ((nextSize * parentHeight) / total < headerHeight) {
130
+ nextSize = (headerHeight / parentHeight) * total;
131
+ size = savedSizes.current[idx] + (savedSizes.current[idx + 1] - nextSize);
132
+ }
133
+ }
134
+ config.children[idx].size = size;
135
+ config.children[idx + 1].size = nextSize;
136
+ Object.assign(panelContentRef.current.style, makeStyle());
137
+ }, [config]);
138
+ const handleSaveSizes = useCallback(() => {
139
+ if (config.kind === "leaf")
140
+ return;
141
+ savedSizes.current = config.children.map((child) => child.size);
142
+ }, [config]);
143
+ const handleHeaderClick = (i) => {
144
+ if (config.kind === "leaf") {
145
+ forceUpdate();
146
+ config.tabIndex = i;
147
+ }
148
+ };
149
+ const panelContentRef = useRef(null);
150
+ const panelRef = useRef(null);
151
+ return (_jsxs("div", { className: `${config.kind} panel`, style: style, ref: panelRef, children: [config.kind === "leaf" ? (_jsx(TabHeader, { config: config, leaves: leaves, onClick: handleHeaderClick })) : null, _jsx("div", { className: "panel-content", ref: panelContentRef, style: makeStyle(), children: config.kind === "leaf" ? (config.tabIndex < config.tabs.length ? (_jsx("div", { children: leaves[config.tabs[config.tabIndex]].element })) : (_jsx("div", { style: { width: "100%", height: "100%" } }))) : (config.children.map((c, i) => (_jsx(NestedPanel, { config: c, leaves: leaves, saveSizes: handleSaveSizes, index: i, onResize: handleResize, isLast: i === config.children.length - 1, direction: config.kind, panelElements: panelElements }, i)))) }), !isLast && direction === "column" && (_jsx("div", { className: "resize-border bottom", onMouseDown: (e) => handleMouseDown(e, "bottom") })), !isLast && direction === "row" && (_jsx("div", { className: "resize-border right", onMouseDown: (e) => handleMouseDown(e, "right") }))] }));
152
+ });
153
+ const Overlay = ({ panelElements, onDrop, rootConfig, }) => {
154
+ const closestRef = useRef(null);
155
+ const lastItem = useRef(null);
156
+ let lastPlaceholder = useRef(null);
157
+ const clearDnDState = () => {
158
+ setTimeout(() => {
159
+ if (lastItem.current) {
160
+ lastItem.current.handleElement.style.display = "block";
161
+ lastItem.current = null;
162
+ }
163
+ }, 0);
164
+ if (lastPlaceholder.current) {
165
+ lastPlaceholder.current.style.width = "0px";
166
+ lastPlaceholder.current.style.transition = "0s linear";
167
+ setTimeout(() => {
168
+ lastPlaceholder.current.style.transition = "0.1s linear";
169
+ }, 0);
170
+ }
171
+ };
172
+ const dropRef = useDrop(() => ({
173
+ accept: "TabHeader",
174
+ drop: (item) => {
175
+ clearDnDState();
176
+ onDrop(closestRef.current, item.name);
177
+ },
178
+ }), [onDrop])[1];
179
+ const dragDropManager = useDragDropManager();
180
+ const monitor = dragDropManager.getMonitor();
181
+ const subscribeOffsetChangeRef = useRef(null);
182
+ const subscribeStateChangeRef = useRef(null);
183
+ useEffect(() => {
184
+ // print with uuid of rootConfig
185
+ if (subscribeStateChangeRef.current) {
186
+ subscribeStateChangeRef.current();
187
+ subscribeStateChangeRef.current = null;
188
+ }
189
+ subscribeStateChangeRef.current = monitor.subscribeToStateChange(() => {
190
+ const draggedItem = monitor.getItem();
191
+ if (!monitor.isDragging() && lastItem.current?.handleElement.previousSibling) {
192
+ lastItem.current.handleElement.previousSibling.style.height = "0px";
193
+ clearDnDState();
194
+ }
195
+ if (monitor.getItemType() === "TabHeader" && monitor.isDragging() && !subscribeOffsetChangeRef.current) {
196
+ const name = draggedItem.name;
197
+ const placeholder = draggedItem.handleElement.previousSibling;
198
+ if (placeholder) {
199
+ placeholder.style.height = draggedItem.handleElement.offsetHeight + "px";
200
+ }
201
+ const overlay = overlayRef.current;
202
+ let zones = [];
203
+ for (const [config, element] of panelElements.current.entries()) {
204
+ const rect = element.getBoundingClientRect();
205
+ const { left, top, width, height } = rect;
206
+ const pushZone = (index, left, top, width, height) => {
207
+ const rect = { left, top, width, height };
208
+ zones.push({ rect, config, index, element });
209
+ };
210
+ if (config.kind === "leaf") {
211
+ if (!config.tabs.includes(name)) {
212
+ pushZone("TOP", left, top, width, height / 2);
213
+ pushZone("BOTTOM", left, top + height / 2, width, height / 2);
214
+ pushZone("LEFT", left, top, width / 2, height);
215
+ pushZone("RIGHT", left + width / 2, top, width / 2, height);
216
+ }
217
+ pushZone("CENTER", left, top, width, height);
218
+ pushZone("TAB", left, top, width, getPanelElementHeader(element).offsetHeight);
219
+ }
220
+ else {
221
+ const firstTabs = config.children?.[0]?.tabs || [null];
222
+ const lastTabs = config.children?.[config.children.length - 1]?.tabs || [null];
223
+ if (config.kind === "row" || config === rootConfig) {
224
+ const zoneWidth = width / (config.kind === "row" ? config.children.length + 1 : 2);
225
+ // check that the dragged item is not the last item in the row and a single tab
226
+ if (lastTabs.length > 1 || lastTabs[0] !== name) {
227
+ pushZone("RIGHT", left + width - zoneWidth, top, zoneWidth, height);
228
+ }
229
+ if (firstTabs.length > 1 || firstTabs[0] !== name) {
230
+ pushZone("LEFT", left, top, zoneWidth, height);
231
+ }
232
+ }
233
+ if (config.kind === "column" || config === rootConfig) {
234
+ const zoneHeight = height / (config.kind === "column" ? config.children.length + 1 : 2);
235
+ if (lastTabs.length > 1 || lastTabs[0] !== name) {
236
+ pushZone("BOTTOM", left, top + height - zoneHeight, width, zoneHeight);
237
+ }
238
+ if (firstTabs.length > 1 || firstTabs[0] !== name) {
239
+ pushZone("TOP", left, top, width, zoneHeight);
240
+ }
241
+ }
242
+ }
243
+ }
244
+ if (!zones.length)
245
+ return;
246
+ overlay.style.display = "block";
247
+ overlay.style.transition = "0s linear";
248
+ lastItem.current = draggedItem;
249
+ draggedItem.handleElement.nextSibling.style.transition = "0.0s linear";
250
+ draggedItem.handleElement.nextSibling.style.width =
251
+ draggedItem.handleElement.getBoundingClientRect().offsetWidth + "px";
252
+ lastPlaceholder.current = draggedItem.handleElement.nextSibling;
253
+ subscribeOffsetChangeRef.current = monitor.subscribeToOffsetChange(() => {
254
+ let candidateZones = zones;
255
+ const offset = monitor.getClientOffset();
256
+ const draggedItem = monitor.getItem();
257
+ if (!offset || !draggedItem)
258
+ return;
259
+ const overlay = overlayRef.current;
260
+ if (overlay.style.transition !== "0.1s linear") {
261
+ setTimeout(() => {
262
+ overlay.style.transition = "0.1s linear";
263
+ }, 0);
264
+ }
265
+ draggedItem.handleElement.style.display = "none";
266
+ if (draggedItem.handleElement.nextSibling.style.transition !== "0.1s linear") {
267
+ setTimeout(() => {
268
+ draggedItem.handleElement.nextSibling.style.transition = "0.1s linear";
269
+ }, 0);
270
+ }
271
+ const { left: offsetX, top: offsetY } = overlay.parentElement.getBoundingClientRect();
272
+ const closest = candidateZones
273
+ .map((zone, i) => {
274
+ if (zone.index === "TAB") {
275
+ if (offset.x > zone.rect.left &&
276
+ offset.x < zone.rect.left + zone.rect.width &&
277
+ offset.y > zone.rect.top - zone.rect.height &&
278
+ offset.y < zone.rect.top + zone.rect.height * 2) {
279
+ return {
280
+ ...zone,
281
+ distance: -100000 + Math.abs(zone.rect.top - offset.y),
282
+ };
283
+ }
284
+ else {
285
+ return { ...zone, distance: 100000 };
286
+ }
287
+ }
288
+ const center = {
289
+ x: zone.rect.left + zone.rect.width / 2,
290
+ y: zone.rect.top + zone.rect.height / 2,
291
+ };
292
+ // const area = (zone.rect.width * zone.rect.height) / (containerRef.current!.offsetWidth * containerRef.current!.offsetHeight);
293
+ const distance = Math.sqrt(Math.pow(center.x - offset.x, 2) + Math.pow(center.y - offset.y, 2)); // / Math.sqrt(area);
294
+ return { ...zone, distance };
295
+ })
296
+ .sort((a, b) => a.distance - b.distance)[0];
297
+ closestRef.current = closest;
298
+ dropRef(closest.element);
299
+ overlay.style.left = `${closest.rect.left - offsetX}px`;
300
+ overlay.style.top = `${closest.rect.top - offsetY}px`;
301
+ overlay.style.width = `${closest.rect.width}px`;
302
+ overlay.style.height = `${closest.rect.height}px`;
303
+ if (closest.index === "TAB") {
304
+ // Lookup tab-placeholder nodes in the closest.element dom node
305
+ const tabPlaceholders = Array.from(closest.element.querySelectorAll(".tab-placeholder"));
306
+ const closestPlaceholder = tabPlaceholders
307
+ .filter((element) => element.getAttribute("data-panel-name") !== draggedItem.name)
308
+ .map((element, i) => {
309
+ const rect = element.getBoundingClientRect();
310
+ return {
311
+ before: element.getAttribute("data-panel-name"),
312
+ element: element,
313
+ distance: Math.abs(rect.left + rect.width / 2 - offset.x),
314
+ };
315
+ })
316
+ .sort((a, b) => a.distance - b.distance)[0];
317
+ if (lastPlaceholder.current && lastPlaceholder.current !== closestPlaceholder.element) {
318
+ lastPlaceholder.current.style.width = "0px";
319
+ }
320
+ closestPlaceholder.element.style.width = draggedItem.width + "px";
321
+ lastPlaceholder.current = closestPlaceholder.element;
322
+ closest.before = closestPlaceholder.before;
323
+ }
324
+ else if (lastPlaceholder.current) {
325
+ lastPlaceholder.current.style.width = "0px";
326
+ }
327
+ });
328
+ }
329
+ else if (subscribeOffsetChangeRef.current && !monitor.isDragging()) {
330
+ subscribeOffsetChangeRef.current();
331
+ subscribeOffsetChangeRef.current = null;
332
+ overlayRef.current.style.display = "none";
333
+ overlayRef.current.style.left = "0";
334
+ overlayRef.current.style.top = "0";
335
+ overlayRef.current.style.width = "0";
336
+ overlayRef.current.style.height = "0";
337
+ }
338
+ });
339
+ }, [monitor, onDrop, rootConfig]);
340
+ const overlayRef = useRef(null);
341
+ return _jsx("div", { className: "tab-handle-overlay", ref: overlayRef });
342
+ };
343
+ export function Layout(props) {
344
+ const children = React.Children.toArray(props.children);
345
+ const namedChildren = Object.fromEntries(children.map((c, i) => [
346
+ c.props.name || (c.key !== null ? c.key.toString().slice(2) : `unnamed-${i}`),
347
+ {
348
+ element: c.props.children,
349
+ header: c.props.header,
350
+ },
351
+ ]));
352
+ const panelElements = useRef(new Map());
353
+ const [rootConfig, setRootConfig] = useState(props.defaultConfig || {
354
+ kind: "row",
355
+ size: 1,
356
+ children: children.map((c, i) => ({
357
+ kind: "leaf",
358
+ tabs: [c.props.name || (c.key !== null ? c.key.toString().slice(2) : `unnamed-${i}`)],
359
+ tabIndex: 0,
360
+ size: 100 / children.length,
361
+ })),
362
+ });
363
+ let config = rootConfig;
364
+ if (rootConfig.kind !== "leaf" || rootConfig.tabs.length > 0) {
365
+ const newConfig = filterPanels(Object.keys(namedChildren), rootConfig);
366
+ if (newConfig !== rootConfig) {
367
+ config = newConfig || { kind: "leaf", tabs: [], tabIndex: 0, size: 100 };
368
+ setRootConfig(config);
369
+ }
370
+ }
371
+ const handleDrop = (zone, name) => {
372
+ const newConfig = movePanel(zone, name, rootConfig);
373
+ setRootConfig(newConfig);
374
+ };
375
+ const container = (_jsxs("div", { className: "container", children: [_jsx(NestedPanel, { leaves: namedChildren, config: config, panelElements: panelElements.current }), _jsx(Overlay, { panelElements: panelElements, onDrop: handleDrop, rootConfig: config })] }));
376
+ if (props.wrapDnd) {
377
+ return _jsx(DndProvider, { backend: HTML5Backend, children: container });
378
+ }
379
+ return container;
380
+ }
@@ -0,0 +1,67 @@
1
+ import React from "react";
2
+ /**
3
+ * Leaf layout configuration.
4
+ *
5
+ * Represents a panel that contains one or more tabs along with the current tab index and its size.
6
+ */
7
+ export type LeafLayoutConfig = {
8
+ kind: "leaf";
9
+ tabs: string[];
10
+ tabIndex: number;
11
+ size: number;
12
+ nesting?: number;
13
+ };
14
+ /**
15
+ * Container layout configuration.
16
+ *
17
+ * Represents a container panel that arranges its child panels in either a row or a column.
18
+ */
19
+ export type ContainerLayoutConfig = {
20
+ kind: "row" | "column";
21
+ children: LayoutConfig[];
22
+ size: number;
23
+ nesting?: number;
24
+ };
25
+ /**
26
+ * Layout configuration.
27
+ *
28
+ * A union type that represents either a leaf panel (with tabs) or a container panel (row/column with children).
29
+ */
30
+ export type LayoutConfig = LeafLayoutConfig | ContainerLayoutConfig;
31
+ /**
32
+ * Properties for a panel component.
33
+ *
34
+ * Defines the children to render within the panel, an optional name, and an optional header.
35
+ */
36
+ export type PanelProps = {
37
+ children: React.ReactNode;
38
+ name?: string;
39
+ header?: React.ReactNode;
40
+ };
41
+ /**
42
+ * Represents a drop zone within the layout.
43
+ *
44
+ * Includes the rectangular coordinates, the associated layout configuration,
45
+ * an a to indicate the drop position, and a reference to the related DOM element.
46
+ */
47
+ export type Zone = {
48
+ rect: {
49
+ left: number;
50
+ top: number;
51
+ width: number;
52
+ height: number;
53
+ };
54
+ config: LayoutConfig;
55
+ index: "LEFT" | "RIGHT" | "TOP" | "BOTTOM" | "CENTER" | "TAB";
56
+ element: HTMLElement;
57
+ before?: string;
58
+ };
59
+ /**
60
+ * Drag and drop item for tab header drag operations.
61
+ *
62
+ * Contains the panel name and a reference to the draggable element.
63
+ */
64
+ export type DnDItem = {
65
+ name: string;
66
+ handleElement: HTMLDivElement;
67
+ };
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ const LEFT = 0;
2
+ const RIGHT = 1;
3
+ const TOP = 2;
4
+ const BOTTOM = 3;
5
+ const TAB = 4;
6
+ export {};
@@ -0,0 +1,26 @@
1
+ import { Zone, LayoutConfig } from "./types";
2
+ /**
3
+ * Moves a panel within the layout based on a drop zone and panel name.
4
+ *
5
+ * This function traverses the layout config tree, removing the panel from its original position,
6
+ * and re-inserting it based on the provided drop zone. It handles both leaf and container nodes,
7
+ * ensuring proper size calculations and layout updates.
8
+ *
9
+ * @param zone - The drop zone where the panel is to be moved.
10
+ * @param name - The name of the panel being moved.
11
+ * @param inside - The layout config in which the move operation takes place.
12
+ * @returns The updated layout config after moving the panel.
13
+ */
14
+ export declare const movePanel: (zone: Zone | null, name: string, inside: LayoutConfig) => LayoutConfig;
15
+ /**
16
+ * Filters panels from a layout configuration based on a provided list of panel names.
17
+ *
18
+ * Traverses the layout configuration tree and removes any panels (or tabs within panels)
19
+ * whose names are not included in the specified list. It simplifies nodes by filtering
20
+ * out unwanted tabs and recursively updating container nodes.
21
+ *
22
+ * @param names - An array of panel names that should remain in the layout.
23
+ * @param inside - The layout configuration to filter.
24
+ * @returns The updated layout configuration with only the specified panels, or null if empty.
25
+ */
26
+ export declare const filterPanels: (names: string[], inside: LayoutConfig) => LayoutConfig;
package/dist/utils.js ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Simplifies a layout configuration by flattening nested layouts with the same kind.
3
+ *
4
+ * If the layout configuration is a row or column, this function will flatten any nested child configurations
5
+ * that have the same kind as the parent. It recalculates the size of nested items based on their parent's size.
6
+ *
7
+ * @param config - The layout configuration to simplify.
8
+ * @returns The simplified layout configuration.
9
+ */
10
+ const simplifyLayout = (config) => {
11
+ if (config.kind === "row" || config.kind === "column") {
12
+ let expandedChildren = [];
13
+ let changed = false;
14
+ config.children.forEach((child) => {
15
+ if (child.kind === config.kind) {
16
+ changed = true;
17
+ const totalChildContainerSize = child.children.reduce((a, b) => a + b.size, 0);
18
+ child.children.forEach((grandChild) => {
19
+ expandedChildren.push({
20
+ ...grandChild,
21
+ size: (child.size * grandChild.size) / totalChildContainerSize,
22
+ });
23
+ });
24
+ }
25
+ else {
26
+ expandedChildren.push(child);
27
+ }
28
+ });
29
+ if (changed) {
30
+ config = { ...config, children: expandedChildren };
31
+ }
32
+ }
33
+ return config;
34
+ };
35
+ /**
36
+ * Moves a panel within the layout based on a drop zone and panel name.
37
+ *
38
+ * This function traverses the layout config tree, removing the panel from its original position,
39
+ * and re-inserting it based on the provided drop zone. It handles both leaf and container nodes,
40
+ * ensuring proper size calculations and layout updates.
41
+ *
42
+ * @param zone - The drop zone where the panel is to be moved.
43
+ * @param name - The name of the panel being moved.
44
+ * @param inside - The layout config in which the move operation takes place.
45
+ * @returns The updated layout config after moving the panel.
46
+ */
47
+ export const movePanel = (zone, name, inside) => {
48
+ const editLayout = (visitedConfig) => {
49
+ let config = visitedConfig;
50
+ if (config.kind === "leaf" && config.tabs.includes(name)) {
51
+ /* If it's a simple leaf, try to remove the matching tab if it was
52
+ * the tab that was picked by the user (since we're moving it) */
53
+ const newTabs = config.tabs.filter((tabName) => tabName !== name);
54
+ config = {
55
+ ...config,
56
+ tabs: newTabs,
57
+ tabIndex: Math.min(newTabs.length - 1, config.tabIndex),
58
+ };
59
+ if (config.tabs.length === 0) {
60
+ config = null;
61
+ }
62
+ }
63
+ /* If this zone is the zone targeted as drop-zone by the user */
64
+ if (zone && visitedConfig === zone.config) {
65
+ if (config === null) {
66
+ return {
67
+ kind: "leaf",
68
+ tabs: [name],
69
+ tabIndex: 0,
70
+ size: visitedConfig.size,
71
+ };
72
+ }
73
+ // or it's a container zone
74
+ else if (config.kind === "row" || config.kind === "column") {
75
+ const totalSize = config.children.reduce((a, b) => a + b.size, 0);
76
+ const fraction = config.kind === "column"
77
+ ? zone.rect.height / zone.element.parentElement.offsetHeight
78
+ : zone.rect.width / zone.element.parentElement.offsetWidth;
79
+ // x / (y + x) = a
80
+ // x = a y + a x
81
+ // x = a y / ( 1 - a )
82
+ const newConfigKind = zone.index === "TOP" || zone.index === "BOTTOM" ? "column" : "row";
83
+ if (config.kind === newConfigKind) {
84
+ const newZone = {
85
+ kind: "leaf",
86
+ tabs: [name],
87
+ tabIndex: 0,
88
+ size: (totalSize * fraction) / (1 - fraction),
89
+ };
90
+ config = {
91
+ ...config,
92
+ children: zone.index === "LEFT" || zone.index === "TOP"
93
+ ? [newZone, ...config.children.map(editLayout).filter((c) => c !== null)]
94
+ : [...config.children.map(editLayout).filter((c) => c !== null), newZone],
95
+ };
96
+ }
97
+ else {
98
+ const newZone = {
99
+ kind: "leaf",
100
+ tabs: [name],
101
+ tabIndex: 0,
102
+ size: 50,
103
+ };
104
+ const oldConfig = {
105
+ ...config,
106
+ // Remove the panel that is being moved
107
+ children: config.children.map(editLayout).filter((c) => c !== null),
108
+ size: 50,
109
+ };
110
+ config = {
111
+ kind: newConfigKind,
112
+ children: zone.index === "TOP" || zone.index === "LEFT" ? [newZone, oldConfig] : [oldConfig, newZone],
113
+ size: config.size,
114
+ };
115
+ }
116
+ }
117
+ // Or it's a leaf zone
118
+ else if (config.kind === "leaf") {
119
+ if (zone.index === "CENTER") {
120
+ const newTabs = [...config.tabs.filter((tabName) => tabName !== name), name];
121
+ config = {
122
+ ...config,
123
+ tabs: newTabs,
124
+ tabIndex: newTabs.length - 1,
125
+ };
126
+ }
127
+ else if (zone.index === "TAB") {
128
+ const newTabs = [...config.tabs];
129
+ let insertIndex = newTabs.findIndex((tabName) => tabName === zone.before);
130
+ if (insertIndex === -1) {
131
+ insertIndex = newTabs.length;
132
+ }
133
+ newTabs.splice(insertIndex, 0, name);
134
+ config = {
135
+ ...config,
136
+ tabs: newTabs,
137
+ tabIndex: insertIndex,
138
+ };
139
+ }
140
+ else {
141
+ const newZone = {
142
+ kind: "leaf",
143
+ tabs: [name],
144
+ tabIndex: 0,
145
+ size: 50,
146
+ };
147
+ config = {
148
+ kind: zone.index === "TOP" || zone.index === "BOTTOM" ? "column" : "row",
149
+ children: zone.index === "TOP" || zone.index === "LEFT"
150
+ ? [newZone, { ...config, size: 50 }]
151
+ : [{ ...config, size: 50, }, newZone],
152
+ size: config.size,
153
+ };
154
+ }
155
+ }
156
+ }
157
+ // If there is nothing left after removing the dropped zone
158
+ else if (config === null) {
159
+ return null;
160
+ }
161
+ // Otherwise, recurse into the node
162
+ else {
163
+ let hasChanged = false;
164
+ if (config.kind !== "leaf") {
165
+ const children = config.children
166
+ .map((child) => {
167
+ const updated = editLayout(child);
168
+ if (updated !== child) {
169
+ hasChanged = true;
170
+ }
171
+ return updated;
172
+ })
173
+ .filter((child) => child !== null);
174
+ if (hasChanged) {
175
+ config = { ...config, children };
176
+ }
177
+ }
178
+ }
179
+ if ((config.kind === "leaf" && config.tabs.length === 0) ||
180
+ (config.kind !== "leaf" && config.children.length === 0)) {
181
+ return null;
182
+ }
183
+ /* Simplify a node of the layout by flattening row children of rows
184
+ * or column children of columns */
185
+ config = simplifyLayout(config);
186
+ return config;
187
+ };
188
+ return editLayout(inside);
189
+ };
190
+ /**
191
+ * Filters panels from a layout configuration based on a provided list of panel names.
192
+ *
193
+ * Traverses the layout configuration tree and removes any panels (or tabs within panels)
194
+ * whose names are not included in the specified list. It simplifies nodes by filtering
195
+ * out unwanted tabs and recursively updating container nodes.
196
+ *
197
+ * @param names - An array of panel names that should remain in the layout.
198
+ * @param inside - The layout configuration to filter.
199
+ * @returns The updated layout configuration with only the specified panels, or null if empty.
200
+ */
201
+ export const filterPanels = (names, inside) => {
202
+ const editLayout = (visitedConfig) => {
203
+ let config = visitedConfig;
204
+ if (config.kind === "leaf" && !config.tabs.every((name) => names.includes(name))) {
205
+ /* If it's a simple leaf, try to remove the matching tab if it was
206
+ * the tab that was picked by the user (since we're moving it) */
207
+ config = {
208
+ ...config,
209
+ tabs: config.tabs.filter((name) => names.includes(name)),
210
+ tabIndex: Math.min(config.tabs.length - 1, config.tabIndex),
211
+ };
212
+ if (config.tabs.length === 0) {
213
+ config = null;
214
+ }
215
+ }
216
+ // If there is nothing left after removing the dropped zone
217
+ if (config === null) {
218
+ return null;
219
+ }
220
+ // Otherwise, recurse into the node
221
+ else {
222
+ let hasChanged = false;
223
+ if (config.kind !== "leaf") {
224
+ const children = config.children
225
+ .map((child) => {
226
+ const updated = editLayout(child);
227
+ if (updated !== child) {
228
+ hasChanged = true;
229
+ }
230
+ return updated;
231
+ })
232
+ .filter((child) => child !== null);
233
+ if (hasChanged) {
234
+ config = { ...config, children };
235
+ }
236
+ }
237
+ }
238
+ if ((config.kind === "leaf" && config.tabs.length === 0) ||
239
+ (config.kind !== "leaf" && config.children.length === 0)) {
240
+ return null;
241
+ }
242
+ /* Simplify a node of the layout by flattening row children of rows
243
+ * or column children of columns */
244
+ config = simplifyLayout(config);
245
+ return config;
246
+ };
247
+ return editLayout(inside);
248
+ };
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "react-simple-dock",
3
+ "version": "0.1.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "type": "module",
7
+ "description": "Simple dock component for React",
8
+ "repository": "https://github.com/percevalw/react-simple-dock",
9
+ "author": "Perceval Wajsbürt <perceval.wajsburt@gmail.com>",
10
+ "scripts": {
11
+ "start": "react-scripts start",
12
+ "build": "react-scripts build",
13
+ "test": "react-scripts test",
14
+ "eject": "react-scripts eject",
15
+ "build:lib:babel": "rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__,*.md",
16
+ "build:lib": "rm -rf dist && tsc --build tsconfig.lib.json && cp src/lib/*.css dist && rm -rf lib/",
17
+ "prepublishOnly": "npm run build:lib",
18
+ "build:pret": "jlpm clean && jupyter labextension build .",
19
+ "build:pret:dev": "jlpm clean && jupyter labextension build --development True .",
20
+ "clean": "rm -rf pret/ui/simple_dock/js-extension lib",
21
+ "prepare": "husky install"
22
+ },
23
+ "dependencies": {
24
+ "react-dnd": ">=16.0.1",
25
+ "react-dnd-html5-backend": ">=16.0.1"
26
+ },
27
+ "peerDependencies": {
28
+ "@types/react": ">= 16",
29
+ "react": ">=16.0.0",
30
+ "react-dom": ">=16.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@testing-library/dom": "^10.4.0",
34
+ "@testing-library/jest-dom": "^6.6.3",
35
+ "@testing-library/react": "^16.2.0",
36
+ "@testing-library/user-event": "^13.5.0",
37
+ "@types/jest": "^27.5.2",
38
+ "@types/node": "^16.18.126",
39
+ "@types/react": "^19.0.10",
40
+ "@types/react-dom": "^19.0.4",
41
+ "babel-cli": "^6.26.0",
42
+ "husky": ">=6",
43
+ "lint-staged": ">=10",
44
+ "prettier": "^3.5.3",
45
+ "react": "^19.0.0",
46
+ "react-app-rewired": "^2.2.1",
47
+ "react-dom": "^19.0.0",
48
+ "react-scripts": "5.0.1",
49
+ "ts-loader": "^9.5.2",
50
+ "typescript": "^5.8.2",
51
+ "web-vitals": "^2.1.4"
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "LICENSE",
56
+ "README.md"
57
+ ],
58
+ "jupyterlab": {
59
+ "extension": "src/plugin.ts",
60
+ "schemaDir": "src/schema",
61
+ "outputDir": "pret/ui/simple_dock/js-extension",
62
+ "webpackConfig": "./webpack.jupyter.js"
63
+ },
64
+ "browserslist": {
65
+ "production": [
66
+ ">0.2%",
67
+ "not dead",
68
+ "not op_mini all"
69
+ ],
70
+ "development": [
71
+ "last 1 chrome version",
72
+ "last 1 firefox version",
73
+ "last 1 safari version"
74
+ ]
75
+ },
76
+ "prettier": {
77
+ "printWidth": 120,
78
+ "tabWidth": 4
79
+ },
80
+ "eslintConfig": {
81
+ "extends": [
82
+ "react-app",
83
+ "react-app/jest"
84
+ ]
85
+ },
86
+ "lint-staged": {
87
+ "*.{js,css,md}": "prettier --write"
88
+ }
89
+ }