@basementuniverse/layout 1.0.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,7 @@
1
+ Copyright 2025 Gordon Larrigan
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # Layout
2
+
3
+ A component for managing flexible layouts in HTML5 Canvas games. It supports nested layouts with dock, stack, and leaf node types.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @basementuniverse/layout
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { Layout } from '@basementuniverse/layout';
15
+
16
+ const layout = new Layout({
17
+ root: {
18
+ id: 'root',
19
+ type: 'stack',
20
+ direction: 'vertical',
21
+ padding: { x: '10px', y: '10px' },
22
+ children: [
23
+ {
24
+ id: 'header',
25
+ type: 'leaf',
26
+ size: { y: '60px' }, // Full width, 60px height
27
+ },
28
+ {
29
+ id: 'content',
30
+ type: 'stack',
31
+ direction: 'horizontal',
32
+ gap: '10px',
33
+ children: [
34
+ {
35
+ id: 'sidebar',
36
+ type: 'leaf',
37
+ size: { x: '200px' },
38
+ },
39
+ {
40
+ id: 'main',
41
+ type: 'leaf',
42
+ },
43
+ ],
44
+ },
45
+ ],
46
+ },
47
+ });
48
+
49
+ // Update layout with canvas size
50
+ layout.update({ x: 1024, y: 768 });
51
+
52
+ // Get calculated node positions and sizes
53
+ const headerNode = layout.get('header');
54
+ console.log(`Header: ${headerNode.width}x${headerNode.height} at (${headerNode.left}, ${headerNode.top})`);
55
+
56
+ // Control visibility
57
+ layout.setVisibility('sidebar', false);
58
+
59
+ // Control layout participation
60
+ layout.setActivated('header', false); // Header won't affect layout calculations
61
+ ```
62
+
63
+ ## Layout node types
64
+
65
+ ```typescript
66
+ type LayoutNodeOptions = {
67
+ id: string;
68
+ type: 'dock' | 'stack' | 'leaf';
69
+ offset?: LayoutVec2;
70
+ padding?: LayoutVec2;
71
+ size?: Partial<LayoutVec2>;
72
+ minSize?: Partial<LayoutVec2>;
73
+ maxSize?: Partial<LayoutVec2>;
74
+ aspectRatio?: number;
75
+ visible?: boolean;
76
+ };
77
+ ```
78
+
79
+ ### Dock Layout
80
+
81
+ Positions children at specific dock positions.
82
+
83
+ ```typescript
84
+ type DockLayoutNodeOptions = {
85
+ type: 'dock';
86
+ topLeft?: LayoutNodeOptions;
87
+ topCenter?: LayoutNodeOptions;
88
+ topRight?: LayoutNodeOptions;
89
+ leftCenter?: LayoutNodeOptions;
90
+ center?: LayoutNodeOptions;
91
+ rightCenter?: LayoutNodeOptions;
92
+ bottomLeft?: LayoutNodeOptions;
93
+ bottomCenter?: LayoutNodeOptions;
94
+ bottomRight?: LayoutNodeOptions;
95
+ };
96
+ ```
97
+
98
+ ### Stack Layout
99
+
100
+ Arranges children in a vertical or horizontal stack with optional alignment and spacing.
101
+
102
+ ```typescript
103
+ type StackLayoutNodeOptions = {
104
+ type: 'stack';
105
+ direction: 'vertical' | 'horizontal';
106
+ align?: 'start' | 'center' | 'end' | 'stretch';
107
+ gap?: Measurement;
108
+ children: LayoutNodeOptions[];
109
+ };
110
+ ```
111
+
112
+ ### Leaf Layout
113
+
114
+ Terminal nodes that don't contain children.
115
+
116
+ ```typescript
117
+ type LeafLayoutNodeOptions = {
118
+ type: 'leaf';
119
+ };
120
+ ```
121
+
122
+ ## Measurements
123
+
124
+ All measurements support:
125
+ - **Pixels**: `'100px'`
126
+ - **Percentages**: `'50%'` (relative to parent)
127
+ - **Auto**: `'auto'` (fills available space)
128
+
129
+ ## API
130
+
131
+ ### Layout Class
132
+
133
+ - `update(size, offset?)` - Recalculate layout with new canvas size
134
+ - `get(id)` - Get calculated node data by ID
135
+ - `setVisibility(id, visible)` - Set visibility (affects children). If `visible` is undefined, toggles current state.
136
+ - `setActivated(id, activated)` - Set activation (affects layout and children). If `activated` is undefined, toggles current state.
137
+ - `hasNode(id)` - Check if node exists
138
+ - `getNodeIds()` - Get all node IDs
139
+
140
+ ### CalculatedNode Properties
141
+
142
+ ```typescript
143
+ type CalculatedNode = {
144
+ // Center
145
+ center: vec2;
146
+
147
+ // Corners
148
+ topLeft: vec2;
149
+ topRight: vec2;
150
+ bottomLeft: vec2;
151
+ bottomRight: vec2;
152
+
153
+ // Edge centers
154
+ topCenter: vec2;
155
+ bottomCenter: vec2;
156
+ leftCenter: vec2;
157
+ rightCenter: vec2;
158
+
159
+ // Edges
160
+ top: number;
161
+ bottom: number;
162
+ left: number;
163
+ right: number;
164
+
165
+ // Size
166
+ width: number;
167
+ height: number;
168
+
169
+ // Other
170
+ aspectRatio: number;
171
+ activated: boolean;
172
+ visible: boolean;
173
+ };
174
+ ```
@@ -0,0 +1,125 @@
1
+ import { vec2 } from '@basementuniverse/vec';
2
+ type MeasurementUnit = 'px' | '%';
3
+ export type Measurement = 'auto' | `${number}${MeasurementUnit}`;
4
+ export type LayoutVec2 = {
5
+ x: Measurement;
6
+ y: Measurement;
7
+ };
8
+ export type LayoutOptions = {
9
+ root: LayoutNodeOptions;
10
+ };
11
+ export type LayoutNodeOptions = {
12
+ id: string;
13
+ type: 'dock' | 'stack' | 'leaf';
14
+ offset?: LayoutVec2;
15
+ padding?: LayoutVec2;
16
+ size?: Partial<LayoutVec2>;
17
+ minSize?: Partial<LayoutVec2>;
18
+ maxSize?: Partial<LayoutVec2>;
19
+ aspectRatio?: number;
20
+ visible?: boolean;
21
+ } & (DockLayoutNodeOptions | StackLayoutNodeOptions | LeafLayoutNodeOptions);
22
+ type DockLayoutNodeOptions = {
23
+ type: 'dock';
24
+ topLeft?: LayoutNodeOptions;
25
+ topCenter?: LayoutNodeOptions;
26
+ topRight?: LayoutNodeOptions;
27
+ leftCenter?: LayoutNodeOptions;
28
+ center?: LayoutNodeOptions;
29
+ rightCenter?: LayoutNodeOptions;
30
+ bottomLeft?: LayoutNodeOptions;
31
+ bottomCenter?: LayoutNodeOptions;
32
+ bottomRight?: LayoutNodeOptions;
33
+ };
34
+ type StackLayoutNodeOptions = {
35
+ type: 'stack';
36
+ direction: 'vertical' | 'horizontal';
37
+ align?: 'start' | 'center' | 'end' | 'stretch';
38
+ gap?: Measurement;
39
+ children: LayoutNodeOptions[];
40
+ };
41
+ type LeafLayoutNodeOptions = {
42
+ type: 'leaf';
43
+ };
44
+ export type CalculatedNode = {
45
+ center: vec2;
46
+ topLeft: vec2;
47
+ topRight: vec2;
48
+ bottomLeft: vec2;
49
+ bottomRight: vec2;
50
+ topCenter: vec2;
51
+ bottomCenter: vec2;
52
+ leftCenter: vec2;
53
+ rightCenter: vec2;
54
+ top: number;
55
+ bottom: number;
56
+ left: number;
57
+ right: number;
58
+ width: number;
59
+ height: number;
60
+ aspectRatio: number;
61
+ activated: boolean;
62
+ visible: boolean;
63
+ };
64
+ export declare class Layout {
65
+ private static readonly DEFAULT_OPTIONS;
66
+ private root;
67
+ private nodes;
68
+ private calculatedNodes;
69
+ private dirty;
70
+ private cache;
71
+ constructor(options?: Partial<LayoutOptions>);
72
+ registerNode(node: LayoutNode): void;
73
+ private generateCacheKey;
74
+ private parseMeasurement;
75
+ private calculateNodeSize;
76
+ private calculateNodeOffset;
77
+ private calculateNodePadding;
78
+ update(size: vec2, offset?: vec2): void;
79
+ private calculateNode;
80
+ private calculateNodeWithSize;
81
+ private calculateChildren;
82
+ private calculateDockChildren;
83
+ private calculateStackChildren;
84
+ private calculateStackChildSizes;
85
+ get(id: string): CalculatedNode | null;
86
+ setVisibility(id: string, visible?: boolean): void;
87
+ private setNodeVisibility;
88
+ setActivated(id: string, activated?: boolean): void;
89
+ private setNodeActivated;
90
+ /**
91
+ * Get all node IDs in the layout
92
+ */
93
+ getNodeIds(): string[];
94
+ /**
95
+ * Check if a node exists in the layout
96
+ */
97
+ hasNode(id: string): boolean;
98
+ /**
99
+ * Clear the layout cache and mark as dirty
100
+ * Useful for debugging or when memory usage becomes a concern
101
+ */
102
+ clearCache(): void;
103
+ /**
104
+ * Get cache statistics for debugging/monitoring
105
+ */
106
+ getCacheStats(): {
107
+ size: number;
108
+ dirty: boolean;
109
+ };
110
+ }
111
+ declare abstract class LayoutNode {
112
+ options: LayoutNodeOptions;
113
+ protected layout: Layout;
114
+ protected children: LayoutNode[];
115
+ protected visible: boolean;
116
+ protected activated: boolean;
117
+ constructor(options: LayoutNodeOptions, layout: Layout);
118
+ protected abstract initializeChildren(): void;
119
+ setVisibility(visible: boolean): void;
120
+ setActivated(activated: boolean): void;
121
+ getChildren(): LayoutNode[];
122
+ isVisible(): boolean;
123
+ isActivated(): boolean;
124
+ }
125
+ export {};
package/build/index.js ADDED
@@ -0,0 +1,79 @@
1
+ /*
2
+ * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
3
+ * This devtool is neither made for production nor for readable output files.
4
+ * It uses "eval()" calls to create a separate source file in the browser devtools.
5
+ * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
6
+ * or disable the default devtool with "devtool: false".
7
+ * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
8
+ */
9
+ (function webpackUniversalModuleDefinition(root, factory) {
10
+ if(typeof exports === 'object' && typeof module === 'object')
11
+ module.exports = factory();
12
+ else if(typeof define === 'function' && define.amd)
13
+ define([], factory);
14
+ else {
15
+ var a = factory();
16
+ for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
17
+ }
18
+ })(self, () => {
19
+ return /******/ (() => { // webpackBootstrap
20
+ /******/ var __webpack_modules__ = ({
21
+
22
+ /***/ "./index.ts":
23
+ /*!******************!*\
24
+ !*** ./index.ts ***!
25
+ \******************/
26
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
27
+
28
+ "use strict";
29
+ eval("{\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Layout = void 0;\nconst vec_1 = __webpack_require__(/*! @basementuniverse/vec */ \"./node_modules/@basementuniverse/vec/vec.js\");\n// -----------------------------------------------------------------------------\n// Classes\n// -----------------------------------------------------------------------------\nclass Layout {\n constructor(options = {}) {\n this.nodes = new Map();\n this.calculatedNodes = new Map();\n this.dirty = true;\n this.cache = new Map();\n const actualOptions = Object.assign({}, Layout.DEFAULT_OPTIONS, options);\n this.root = nodeFactory(actualOptions.root, this);\n this.registerNode(this.root);\n }\n registerNode(node) {\n this.nodes.set(node.options.id, node);\n }\n generateCacheKey(size, offset) {\n // Create a compact representation of size and offset\n const sizeOffset = `${size.x},${size.y},${offset.x},${offset.y}`;\n // Create a compact representation of node activation states\n const nodeStates = [];\n for (const [id, node] of this.nodes) {\n if (!node.isActivated()) {\n nodeStates.push(id);\n }\n }\n // Sort to ensure consistent cache keys regardless of iteration order\n nodeStates.sort();\n const activationState = nodeStates.join('|');\n return `${sizeOffset}:${activationState}`;\n }\n parseMeasurement(measurement, parentSize) {\n if (measurement === 'auto') {\n return parentSize;\n }\n if (measurement.endsWith('%')) {\n const percentage = parseFloat(measurement.slice(0, -1));\n return (percentage / 100) * parentSize;\n }\n if (measurement.endsWith('px')) {\n return parseFloat(measurement.slice(0, -2));\n }\n throw new Error(`Invalid measurement: ${measurement}`);\n }\n calculateNodeSize(node, parentSize, availableSize) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n const options = node.options;\n let width;\n let height;\n const targetSize = availableSize || parentSize;\n // Handle size specification\n if (((_a = options.size) === null || _a === void 0 ? void 0 : _a.x) !== undefined) {\n width = this.parseMeasurement(options.size.x, targetSize.x);\n }\n else {\n width = targetSize.x; // Default to 100%\n }\n if (((_b = options.size) === null || _b === void 0 ? void 0 : _b.y) !== undefined) {\n height = this.parseMeasurement(options.size.y, targetSize.y);\n }\n else {\n height = targetSize.y; // Default to 100%\n }\n // Handle aspect ratio\n if (options.aspectRatio !== undefined) {\n if (((_c = options.size) === null || _c === void 0 ? void 0 : _c.x) !== undefined && ((_d = options.size) === null || _d === void 0 ? void 0 : _d.y) === undefined) {\n height = width / options.aspectRatio;\n }\n else if (((_e = options.size) === null || _e === void 0 ? void 0 : _e.y) !== undefined &&\n ((_f = options.size) === null || _f === void 0 ? void 0 : _f.x) === undefined) {\n width = height * options.aspectRatio;\n }\n else if (((_g = options.size) === null || _g === void 0 ? void 0 : _g.x) === undefined &&\n ((_h = options.size) === null || _h === void 0 ? void 0 : _h.y) === undefined) {\n // Default to width = 100%, calculate height from aspect ratio\n width = targetSize.x;\n height = width / options.aspectRatio;\n }\n }\n // Apply min/max constraints\n if (((_j = options.minSize) === null || _j === void 0 ? void 0 : _j.x) !== undefined) {\n const minWidth = this.parseMeasurement(options.minSize.x, targetSize.x);\n width = Math.max(width, minWidth);\n }\n if (((_k = options.minSize) === null || _k === void 0 ? void 0 : _k.y) !== undefined) {\n const minHeight = this.parseMeasurement(options.minSize.y, targetSize.y);\n height = Math.max(height, minHeight);\n }\n if (((_l = options.maxSize) === null || _l === void 0 ? void 0 : _l.x) !== undefined) {\n const maxWidth = this.parseMeasurement(options.maxSize.x, targetSize.x);\n width = Math.min(width, maxWidth);\n }\n if (((_m = options.maxSize) === null || _m === void 0 ? void 0 : _m.y) !== undefined) {\n const maxHeight = this.parseMeasurement(options.maxSize.y, targetSize.y);\n height = Math.min(height, maxHeight);\n }\n return (0, vec_1.vec2)(width, height);\n }\n calculateNodeOffset(node, parentSize) {\n if (!node.options.offset) {\n return (0, vec_1.vec2)();\n }\n return (0, vec_1.vec2)(this.parseMeasurement(node.options.offset.x, parentSize.x), this.parseMeasurement(node.options.offset.y, parentSize.y));\n }\n calculateNodePadding(node, nodeSize) {\n if (!node.options.padding) {\n return (0, vec_1.vec2)();\n }\n return (0, vec_1.vec2)(this.parseMeasurement(node.options.padding.x, nodeSize.x), this.parseMeasurement(node.options.padding.y, nodeSize.y));\n }\n update(size, offset = (0, vec_1.vec2)()) {\n const cacheKey = this.generateCacheKey(size, offset);\n // Check if we have a cached result for these parameters\n if (!this.dirty && this.cache.has(cacheKey)) {\n this.calculatedNodes = new Map(this.cache.get(cacheKey));\n return;\n }\n // Calculate the layout\n this.calculatedNodes.clear();\n this.calculateNode(this.root, size, offset, size);\n // Store the result in cache\n this.cache.set(cacheKey, new Map(this.calculatedNodes));\n this.dirty = false;\n }\n calculateNode(node, parentSize, position, rootSize) {\n if (!node.isActivated()) {\n return; // Skip deactivated nodes\n }\n const nodeSize = this.calculateNodeSize(node, parentSize);\n const nodeOffset = this.calculateNodeOffset(node, parentSize);\n const actualPosition = vec_1.vec2.add(position, nodeOffset);\n const padding = this.calculateNodePadding(node, nodeSize);\n // Calculate all the CalculatedNode properties\n const calculated = {\n center: vec_1.vec2.add(actualPosition, vec_1.vec2.scale(nodeSize, 0.5)),\n topLeft: actualPosition,\n topRight: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(nodeSize.x, 0)),\n bottomLeft: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(0, nodeSize.y)),\n bottomRight: vec_1.vec2.add(actualPosition, nodeSize),\n topCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(nodeSize.x * 0.5, 0)),\n bottomCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(nodeSize.x * 0.5, nodeSize.y)),\n leftCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(0, nodeSize.y * 0.5)),\n rightCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(nodeSize.x, nodeSize.y * 0.5)),\n top: actualPosition.y,\n bottom: actualPosition.y + nodeSize.y,\n left: actualPosition.x,\n right: actualPosition.x + nodeSize.x,\n width: nodeSize.x,\n height: nodeSize.y,\n aspectRatio: nodeSize.x / nodeSize.y,\n activated: node.isActivated(),\n visible: node.isVisible(),\n };\n this.calculatedNodes.set(node.options.id, calculated);\n // Calculate children based on node type\n this.calculateChildren(node, nodeSize, actualPosition, padding, rootSize);\n }\n calculateNodeWithSize(node, parentSize, position, rootSize, preCalculatedSize) {\n if (!node.isActivated()) {\n return; // Skip deactivated nodes\n }\n const nodeOffset = this.calculateNodeOffset(node, parentSize);\n const actualPosition = vec_1.vec2.add(position, nodeOffset);\n const padding = this.calculateNodePadding(node, preCalculatedSize);\n // Calculate all the CalculatedNode properties using the pre-calculated size\n const calculated = {\n center: vec_1.vec2.add(actualPosition, vec_1.vec2.scale(preCalculatedSize, 0.5)),\n topLeft: actualPosition,\n topRight: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(preCalculatedSize.x, 0)),\n bottomLeft: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(0, preCalculatedSize.y)),\n bottomRight: vec_1.vec2.add(actualPosition, preCalculatedSize),\n topCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(preCalculatedSize.x * 0.5, 0)),\n bottomCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(preCalculatedSize.x * 0.5, preCalculatedSize.y)),\n leftCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(0, preCalculatedSize.y * 0.5)),\n rightCenter: vec_1.vec2.add(actualPosition, (0, vec_1.vec2)(preCalculatedSize.x, preCalculatedSize.y * 0.5)),\n top: actualPosition.y,\n bottom: actualPosition.y + preCalculatedSize.y,\n left: actualPosition.x,\n right: actualPosition.x + preCalculatedSize.x,\n width: preCalculatedSize.x,\n height: preCalculatedSize.y,\n aspectRatio: preCalculatedSize.x / preCalculatedSize.y,\n activated: node.isActivated(),\n visible: node.isVisible(),\n };\n this.calculatedNodes.set(node.options.id, calculated);\n // Calculate children based on node type\n this.calculateChildren(node, preCalculatedSize, actualPosition, padding, rootSize);\n }\n calculateChildren(node, nodeSize, position, padding, rootSize) {\n const contentSize = vec_1.vec2.sub(nodeSize, vec_1.vec2.scale(padding, 2));\n const contentPosition = vec_1.vec2.add(position, padding);\n switch (node.options.type) {\n case 'dock':\n this.calculateDockChildren(node, contentSize, contentPosition, rootSize);\n break;\n case 'stack':\n this.calculateStackChildren(node, contentSize, contentPosition, rootSize);\n break;\n case 'leaf':\n // Leaf nodes have no children\n break;\n }\n }\n calculateDockChildren(node, size, position, rootSize) {\n const dockOptions = node.options;\n const children = node.getChildren();\n // Map positions to their corresponding child nodes\n const positionMap = new Map();\n const positions = [\n 'topLeft',\n 'topCenter',\n 'topRight',\n 'leftCenter',\n 'center',\n 'rightCenter',\n 'bottomLeft',\n 'bottomCenter',\n 'bottomRight',\n ];\n let childIndex = 0;\n for (const pos of positions) {\n if (dockOptions[pos] && childIndex < children.length) {\n positionMap.set(pos, children[childIndex]);\n childIndex++;\n }\n }\n // Calculate positions for each dock position\n const dockPositions = {\n topLeft: position,\n topCenter: vec_1.vec2.add(position, (0, vec_1.vec2)(size.x * 0.5, 0)),\n topRight: vec_1.vec2.add(position, (0, vec_1.vec2)(size.x, 0)),\n leftCenter: vec_1.vec2.add(position, (0, vec_1.vec2)(0, size.y * 0.5)),\n center: vec_1.vec2.add(position, vec_1.vec2.scale(size, 0.5)),\n rightCenter: vec_1.vec2.add(position, (0, vec_1.vec2)(size.x, size.y * 0.5)),\n bottomLeft: vec_1.vec2.add(position, (0, vec_1.vec2)(0, size.y)),\n bottomCenter: vec_1.vec2.add(position, (0, vec_1.vec2)(size.x * 0.5, size.y)),\n bottomRight: vec_1.vec2.add(position, size),\n };\n // Calculate each positioned child\n for (const [pos, child] of positionMap) {\n const anchorPoint = dockPositions[pos];\n const childSize = this.calculateNodeSize(child, size);\n // Calculate the top-left position based on the anchor point and position\n let childPosition;\n switch (pos) {\n case 'topLeft':\n // Anchor at top-left, so position is already correct\n childPosition = anchorPoint;\n break;\n case 'topCenter':\n // Anchor at top-center, so offset by half width to the left\n childPosition = vec_1.vec2.sub(anchorPoint, (0, vec_1.vec2)(childSize.x * 0.5, 0));\n break;\n case 'topRight':\n // Anchor at top-right, so offset by full width to the left\n childPosition = vec_1.vec2.sub(anchorPoint, (0, vec_1.vec2)(childSize.x, 0));\n break;\n case 'leftCenter':\n // Anchor at left-center, so offset by half height upward\n childPosition = vec_1.vec2.sub(anchorPoint, (0, vec_1.vec2)(0, childSize.y * 0.5));\n break;\n case 'center':\n // Anchor at center, so offset by half width and half height\n childPosition = vec_1.vec2.sub(anchorPoint, vec_1.vec2.scale(childSize, 0.5));\n break;\n case 'rightCenter':\n // Anchor at right-center, so offset by full width to the left and\n // half height upward\n childPosition = vec_1.vec2.sub(anchorPoint, (0, vec_1.vec2)(childSize.x, childSize.y * 0.5));\n break;\n case 'bottomLeft':\n // Anchor at bottom-left, so offset by full height upward\n childPosition = vec_1.vec2.sub(anchorPoint, (0, vec_1.vec2)(0, childSize.y));\n break;\n case 'bottomCenter':\n // Anchor at bottom-center, so offset by half width to the left and\n // full height upward\n childPosition = vec_1.vec2.sub(anchorPoint, (0, vec_1.vec2)(childSize.x * 0.5, childSize.y));\n break;\n case 'bottomRight':\n // Anchor at bottom-right, so offset by full width and height\n childPosition = vec_1.vec2.sub(anchorPoint, childSize);\n break;\n default:\n childPosition = anchorPoint;\n break;\n }\n this.calculateNode(child, size, childPosition, rootSize);\n }\n }\n calculateStackChildren(node, size, position, rootSize) {\n const stackOptions = node.options;\n const children = node.getChildren().filter(child => child.isActivated());\n if (children.length === 0)\n return;\n const isVertical = stackOptions.direction === 'vertical';\n const gap = stackOptions.gap\n ? this.parseMeasurement(stackOptions.gap, isVertical ? size.y : size.x)\n : 0;\n const totalGap = gap * (children.length - 1);\n const availableSize = isVertical\n ? (0, vec_1.vec2)(size.x, size.y - totalGap)\n : (0, vec_1.vec2)(size.x - totalGap, size.y);\n // Calculate sizes for all children, handling 'auto' correctly for stack\n // layouts\n const childSizes = this.calculateStackChildSizes(children, size, availableSize, isVertical);\n let currentOffset = 0;\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n const childSize = childSizes[i];\n // Position child based on stack direction and alignment\n let childPosition;\n if (isVertical) {\n let x = position.x;\n // Apply horizontal alignment\n switch (stackOptions.align) {\n case 'center':\n x = position.x + (size.x - childSize.x) * 0.5;\n break;\n case 'end':\n x = position.x + size.x - childSize.x;\n break;\n case 'stretch':\n // For stretch, we override the child size\n childSize.x = size.x;\n break;\n // 'start' is default (x = position.x)\n }\n childPosition = (0, vec_1.vec2)(x, position.y + currentOffset);\n currentOffset += childSize.y + gap;\n }\n else {\n let y = position.y;\n // Apply vertical alignment\n switch (stackOptions.align) {\n case 'center':\n y = position.y + (size.y - childSize.y) * 0.5;\n break;\n case 'end':\n y = position.y + size.y - childSize.y;\n break;\n case 'stretch':\n // For stretch, we override the child size\n childSize.y = size.y;\n break;\n // 'start' is default (y = position.y)\n }\n childPosition = (0, vec_1.vec2)(position.x + currentOffset, y);\n currentOffset += childSize.x + gap;\n }\n this.calculateNodeWithSize(child, size, childPosition, rootSize, childSize);\n }\n }\n calculateStackChildSizes(children, size, availableSize, isVertical) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const childSizes = [];\n const autoChildren = [];\n let usedSpace = 0;\n // First pass: calculate sizes for non-auto children and track auto children\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n const options = child.options;\n const relevantSizeProperty = isVertical\n ? (_a = options.size) === null || _a === void 0 ? void 0 : _a.y\n : (_b = options.size) === null || _b === void 0 ? void 0 : _b.x;\n const isAutoSized = relevantSizeProperty === undefined || relevantSizeProperty === 'auto';\n if (isAutoSized) {\n // Mark as auto-sized for second pass\n autoChildren.push(i);\n // Placeholder size, will be calculated in second pass\n childSizes.push((0, vec_1.vec2)(0, 0));\n }\n else {\n // Calculate size normally for non-auto children\n const childSize = this.calculateNodeSize(child, size, availableSize);\n childSizes.push(childSize);\n // Track used space in the stack direction\n usedSpace += isVertical ? childSize.y : childSize.x;\n }\n }\n // Second pass: distribute remaining space among auto children\n if (autoChildren.length > 0) {\n const remainingSpace = (isVertical ? availableSize.y : availableSize.x) - usedSpace;\n const autoSize = Math.max(0, remainingSpace / autoChildren.length);\n for (const childIndex of autoChildren) {\n const child = children[childIndex];\n if (isVertical) {\n // For vertical stacks, auto applies to height, width uses normal\n // calculation\n const width = ((_c = child.options.size) === null || _c === void 0 ? void 0 : _c.x) !== undefined\n ? this.parseMeasurement(child.options.size.x, size.x)\n : size.x;\n childSizes[childIndex] = (0, vec_1.vec2)(width, autoSize);\n }\n else {\n // For horizontal stacks, auto applies to width, height uses normal\n // calculation\n const height = ((_d = child.options.size) === null || _d === void 0 ? void 0 : _d.y) !== undefined\n ? this.parseMeasurement(child.options.size.y, size.y)\n : size.y;\n childSizes[childIndex] = (0, vec_1.vec2)(autoSize, height);\n }\n // Apply min/max constraints to the auto-sized dimension\n const finalSize = childSizes[childIndex];\n const options = child.options;\n if (isVertical) {\n if (((_e = options.minSize) === null || _e === void 0 ? void 0 : _e.y) !== undefined) {\n const minHeight = this.parseMeasurement(options.minSize.y, size.y);\n finalSize.y = Math.max(finalSize.y, minHeight);\n }\n if (((_f = options.maxSize) === null || _f === void 0 ? void 0 : _f.y) !== undefined) {\n const maxHeight = this.parseMeasurement(options.maxSize.y, size.y);\n finalSize.y = Math.min(finalSize.y, maxHeight);\n }\n }\n else {\n if (((_g = options.minSize) === null || _g === void 0 ? void 0 : _g.x) !== undefined) {\n const minWidth = this.parseMeasurement(options.minSize.x, size.x);\n finalSize.x = Math.max(finalSize.x, minWidth);\n }\n if (((_h = options.maxSize) === null || _h === void 0 ? void 0 : _h.x) !== undefined) {\n const maxWidth = this.parseMeasurement(options.maxSize.x, size.x);\n finalSize.x = Math.min(finalSize.x, maxWidth);\n }\n }\n }\n }\n return childSizes;\n }\n get(id) {\n return this.calculatedNodes.get(id) || null;\n }\n setVisibility(id, visible) {\n const node = this.nodes.get(id);\n if (!node)\n return;\n this.setNodeVisibility(node, visible === undefined ? !node.isVisible() : visible);\n }\n setNodeVisibility(node, visible) {\n node.setVisibility(visible);\n // Apply to all children recursively\n for (const child of node.getChildren()) {\n this.setNodeVisibility(child, visible);\n }\n }\n setActivated(id, activated) {\n const node = this.nodes.get(id);\n if (!node)\n return;\n this.setNodeActivated(node, activated === undefined ? !node.isActivated() : activated);\n this.dirty = true;\n }\n setNodeActivated(node, activated) {\n node.setActivated(activated);\n // Apply to all children recursively\n for (const child of node.getChildren()) {\n this.setNodeActivated(child, activated);\n }\n }\n /**\n * Get all node IDs in the layout\n */\n getNodeIds() {\n return Array.from(this.nodes.keys());\n }\n /**\n * Check if a node exists in the layout\n */\n hasNode(id) {\n return this.nodes.has(id);\n }\n /**\n * Clear the layout cache and mark as dirty\n * Useful for debugging or when memory usage becomes a concern\n */\n clearCache() {\n this.cache.clear();\n this.dirty = true;\n }\n /**\n * Get cache statistics for debugging/monitoring\n */\n getCacheStats() {\n return {\n size: this.cache.size,\n dirty: this.dirty,\n };\n }\n}\nexports.Layout = Layout;\nLayout.DEFAULT_OPTIONS = {\n root: {\n id: 'default',\n type: 'leaf',\n },\n};\nclass LayoutNode {\n constructor(options, layout) {\n var _a;\n this.options = options;\n this.children = [];\n this.visible = true;\n this.activated = true;\n this.layout = layout;\n this.visible = (_a = options.visible) !== null && _a !== void 0 ? _a : true;\n this.initializeChildren();\n }\n setVisibility(visible) {\n this.visible = visible;\n }\n setActivated(activated) {\n this.activated = activated;\n }\n getChildren() {\n return this.children;\n }\n isVisible() {\n return this.visible;\n }\n isActivated() {\n return this.activated;\n }\n}\nclass DockLayoutNode extends LayoutNode {\n constructor(options, layout) {\n super(options, layout);\n }\n initializeChildren() {\n const dockOptions = this.options;\n const positions = [\n 'topLeft',\n 'topCenter',\n 'topRight',\n 'leftCenter',\n 'center',\n 'rightCenter',\n 'bottomLeft',\n 'bottomCenter',\n 'bottomRight',\n ];\n for (const position of positions) {\n const childOptions = dockOptions[position];\n if (childOptions) {\n const child = nodeFactory(childOptions, this.layout);\n this.children.push(child);\n this.layout.registerNode(child);\n }\n }\n }\n}\nclass StackLayoutNode extends LayoutNode {\n constructor(options, layout) {\n super(options, layout);\n }\n initializeChildren() {\n const stackOptions = this.options;\n for (const childOptions of stackOptions.children) {\n const child = nodeFactory(childOptions, this.layout);\n this.children.push(child);\n this.layout.registerNode(child);\n }\n }\n}\nclass LeafLayoutNode extends LayoutNode {\n constructor(options, layout) {\n super(options, layout);\n }\n initializeChildren() {\n // Leaf nodes have no children\n }\n}\n// -----------------------------------------------------------------------------\n// Utility functions\n// -----------------------------------------------------------------------------\nfunction nodeFactory(options, layout) {\n switch (options.type) {\n case 'dock':\n return new DockLayoutNode(options, layout);\n case 'stack':\n return new StackLayoutNode(options, layout);\n case 'leaf':\n return new LeafLayoutNode(options, layout);\n default:\n throw new Error(`Unknown node type: ${options.type}`);\n }\n}\n\n\n//# sourceURL=webpack://@basementuniverse/layout/./index.ts?\n}");
30
+
31
+ /***/ }),
32
+
33
+ /***/ "./node_modules/@basementuniverse/vec/vec.js":
34
+ /*!***************************************************!*\
35
+ !*** ./node_modules/@basementuniverse/vec/vec.js ***!
36
+ \***************************************************/
37
+ /***/ ((module) => {
38
+
39
+ eval("{/**\n * @overview A small vector and matrix library\n * @author Gordon Larrigan\n */\n\nconst _vec_times = (f, n) => Array(n).fill(0).map((_, i) => f(i));\nconst _vec_chunk = (a, n) => _vec_times(i => a.slice(i * n, i * n + n), Math.ceil(a.length / n));\nconst _vec_dot = (a, b) => a.reduce((n, v, i) => n + v * b[i], 0);\nconst _vec_is_vec2 = a => typeof a === 'object' && 'x' in a && 'y' in a;\nconst _vec_is_vec3 = a => typeof a === 'object' && 'x' in a && 'y' in a && 'z' in a;\n\n/**\n * A 2d vector\n * @typedef {Object} vec2\n * @property {number} x The x component of the vector\n * @property {number} y The y component of the vector\n */\n\n/**\n * Create a new 2d vector\n * @param {number|vec2} [x] The x component of the vector, or a vector to copy\n * @param {number} [y] The y component of the vector\n * @return {vec2} A new 2d vector\n * @example <caption>various ways to initialise a vector</caption>\n * let a = vec2(3, 2); // (3, 2)\n * let b = vec2(4); // (4, 4)\n * let c = vec2(a); // (3, 2)\n * let d = vec2(); // (0, 0)\n */\nconst vec2 = (x, y) => {\n if (!x && !y) {\n return { x: 0, y: 0 };\n }\n if (_vec_is_vec2(x)) {\n return { x: x.x || 0, y: x.y || 0 };\n }\n return { x: x, y: y ?? x };\n};\n\n/**\n * Get the components of a vector as an array\n * @param {vec2} a The vector to get components from\n * @return {Array<number>} The vector components as an array\n */\nvec2.components = a => [a.x, a.y];\n\n/**\n * Create a vector from an array of components\n * @param {Array<number>} components The components of the vector\n * @return {vec2} A new vector\n */\nvec2.fromComponents = components => vec2(...components.slice(0, 2));\n\n/**\n * Return a unit vector (1, 0)\n * @return {vec2} A unit vector (1, 0)\n */\nvec2.ux = () => vec2(1, 0);\n\n/**\n * Return a unit vector (0, 1)\n * @return {vec2} A unit vector (0, 1)\n */\nvec2.uy = () => vec2(0, 1);\n\n/**\n * Add vectors\n * @param {vec2} a Vector a\n * @param {vec2|number} b Vector or scalar b\n * @return {vec2} a + b\n */\nvec2.add = (a, b) => ({ x: a.x + (b.x ?? b), y: a.y + (b.y ?? b) });\n\n/**\n * Add multiple vectors\n * @param {...any} v Vectors to add\n * @returns {vec2} The sum of the vectors\n */\nvec2.addm = (...v) => v.reduce((a, b) => vec2.add(a, b), vec2());\n\n/**\n * Subtract vectors\n * @param {vec2} a Vector a\n * @param {vec2|number} b Vector or scalar b\n * @return {vec2} a - b\n */\nvec2.sub = (a, b) => ({ x: a.x - (b.x ?? b), y: a.y - (b.y ?? b) });\n\n/**\n * Subtract multiple vectors\n * @param {...any} v Vectors to subtract\n * @returns {vec2} The result of subtracting the vectors\n */\nvec2.subm = (...v) => v.reduce((a, b) => vec2.sub(a, b));\n\n/**\n * Scale a vector\n * @param {vec2} a Vector a\n * @param {vec2|number} b Vector or scalar b\n * @return {vec2} a * b\n */\nvec2.mul = (a, b) => ({ x: a.x * (b.x ?? b), y: a.y * (b.y ?? b) });\n\n/**\n * Scale a vector by a scalar, alias for vec2.mul\n * @param {vec2} a Vector a\n * @param {number} b Scalar b\n * @return {vec2} a * b\n */\nvec2.scale = (a, b) => vec2.mul(a, b);\n\n/**\n * Divide a vector\n * @param {vec2} a Vector a\n * @param {vec2|number} b Vector or scalar b\n * @return {vec2} a / b\n */\nvec2.div = (a, b) => ({ x: a.x / (b.x ?? b), y: a.y / (b.y ?? b) });\n\n/**\n * Get the length of a vector\n * @param {vec2} a Vector a\n * @return {number} |a|\n */\nvec2.len = a => Math.sqrt(a.x * a.x + a.y * a.y);\n\n/**\n * Get the length of a vector using taxicab geometry\n * @param {vec2} a Vector a\n * @return {number} |a|\n */\nvec2.manhattan = a => Math.abs(a.x) + Math.abs(a.y);\n\n/**\n * Normalise a vector\n * @param {vec2} a The vector to normalise\n * @return {vec2} ^a\n */\nvec2.nor = a => {\n let len = vec2.len(a);\n return len ? { x: a.x / len, y: a.y / len } : vec2();\n};\n\n/**\n * Get a dot product of vectors\n * @param {vec2} a Vector a\n * @param {vec2} b Vector b\n * @return {number} a ∙ b\n */\nvec2.dot = (a, b) => a.x * b.x + a.y * b.y;\n\n/**\n * Rotate a vector by r radians\n * @param {vec2} a The vector to rotate\n * @param {number} r The angle to rotate by, measured in radians\n * @return {vec2} A rotated vector\n */\nvec2.rot = (a, r) => {\n let s = Math.sin(r),\n c = Math.cos(r);\n return { x: c * a.x - s * a.y, y: s * a.x + c * a.y };\n};\n\n/**\n * Fast method to rotate a vector by -90, 90 or 180 degrees\n * @param {vec2} a The vector to rotate\n * @param {number} r 1 for 90 degrees (cw), -1 for -90 degrees (ccw), 2 or -2 for 180 degrees\n * @return {vec2} A rotated vector\n */\nvec2.rotf = (a, r) => {\n switch (r) {\n case 1: return vec2(a.y, -a.x);\n case -1: return vec2(-a.y, a.x);\n case 2: case -2: return vec2(-a.x, -a.y);\n default: return a;\n }\n};\n\n/**\n * Scalar cross product of two vectors\n * @param {vec2} a Vector a\n * @param {vec2} b Vector b\n * @return {number} a × b\n */\nvec2.cross = (a, b) => {\n return a.x * b.y - a.y * b.x;\n};\n\n/**\n * Check if two vectors are equal\n * @param {vec2} a Vector a\n * @param {vec2} b Vector b\n * @return {boolean} True if vectors a and b are equal, false otherwise\n */\nvec2.eq = (a, b) => a.x === b.x && a.y === b.y;\n\n/**\n * Get the angle of a vector\n * @param {vec2} a Vector a\n * @return {number} The angle of vector a in radians\n */\nvec2.rad = a => Math.atan2(a.y, a.x);\n\n/**\n * Copy a vector\n * @param {vec2} a The vector to copy\n * @return {vec2} A copy of vector a\n */\nvec2.cpy = a => vec2(a);\n\n/**\n * A function to call on each component of a 2d vector\n * @callback vec2MapCallback\n * @param {number} value The component value\n * @param {'x' | 'y'} label The component label (x or y)\n * @return {number} The mapped component\n */\n\n/**\n * Call a function on each component of a vector and build a new vector from the results\n * @param {vec2} a Vector a\n * @param {vec2MapCallback} f The function to call on each component of the vector\n * @return {vec2} Vector a mapped through f\n */\nvec2.map = (a, f) => ({ x: f(a.x, 'x'), y: f(a.y, 'y') });\n\n/**\n * Convert a vector into a string\n * @param {vec2} a The vector to convert\n * @param {string} [s=', '] The separator string\n * @return {string} A string representation of the vector\n */\nvec2.str = (a, s = ', ') => `${a.x}${s}${a.y}`;\n\n/**\n * Swizzle a vector with a string of component labels\n *\n * The string can contain:\n * - `x` or `y`\n * - `u` or `v` (aliases for `x` and `y`, respectively)\n * - `X`, `Y`, `U`, `V` (negated versions of the above)\n * - `0` or `1` (these will be passed through unchanged)\n * - `.` to return the component that would normally be at this position (or 0)\n *\n * Any other characters will default to 0\n * @param {vec2} a The vector to swizzle\n * @param {string} [s='..'] The swizzle string\n * @return {Array<number>} The swizzled components\n * @example <caption>swizzling a vector</caption>\n * let a = vec2(3, -2);\n * vec2.swiz(a, 'x'); // [3]\n * vec2.swiz(a, 'yx'); // [-2, 3]\n * vec2.swiz(a, 'xY'); // [3, 2]\n * vec2.swiz(a, 'Yy'); // [2, -2]\n * vec2.swiz(a, 'x.x'); // [3, -2, 3]\n * vec2.swiz(a, 'y01x'); // [-2, 0, 1, 3]\n */\nvec2.swiz = (a, s = '..') => {\n const result = [];\n s.split('').forEach((c, i) => {\n switch (c) {\n case 'x': case 'u': result.push(a.x); break;\n case 'y': case 'v': result.push(a.y); break;\n case 'X': case 'U': result.push(-a.x); break;\n case 'Y': case 'V': result.push(-a.y); break;\n case '0': result.push(0); break;\n case '1': result.push(1); break;\n case '.': result.push([a.x, a.y][i] ?? 0); break;\n default: result.push(0);\n }\n });\n return result;\n};\n\n/**\n * Polar coordinates for a 2d vector\n * @typedef {Object} polarCoordinates2d\n * @property {number} r The magnitude (radius) of the vector\n * @property {number} theta The angle of the vector\n */\n\n/**\n * Convert a vector into polar coordinates\n * @param {vec2} a The vector to convert\n * @return {polarCoordinates2d} The magnitude and angle of the vector\n */\nvec2.polar = a => ({ r: vec2.len(a), theta: Math.atan2(a.y, a.x) });\n\n/**\n * Convert polar coordinates into a vector\n * @param {number} r The magnitude (radius) of the vector\n * @param {number} theta The angle of the vector\n * @return {vec2} A vector with the given angle and magnitude\n */\nvec2.fromPolar = (r, theta) => vec2(r * Math.cos(theta), r * Math.sin(theta));\n\n/**\n * A 3d vector\n * @typedef {Object} vec3\n * @property {number} x The x component of the vector\n * @property {number} y The y component of the vector\n * @property {number} z The z component of the vector\n */\n\n/**\n * Create a new 3d vector\n * @param {number|vec3|vec2} [x] The x component of the vector, or a vector to copy\n * @param {number} [y] The y component of the vector, or the z component if x is a vec2\n * @param {number} [z] The z component of the vector\n * @return {vec3} A new 3d vector\n * @example <caption>various ways to initialise a vector</caption>\n * let a = vec3(3, 2, 1); // (3, 2, 1)\n * let b = vec3(4, 5); // (4, 5, 0)\n * let c = vec3(6); // (6, 6, 6)\n * let d = vec3(a); // (3, 2, 1)\n * let e = vec3(); // (0, 0, 0)\n * let f = vec3(vec2(1, 2), 3); // (1, 2, 3)\n * let g = vec3(vec2(4, 5)); // (4, 5, 0)\n */\nconst vec3 = (x, y, z) => {\n if (!x && !y && !z) {\n return { x: 0, y: 0, z: 0 };\n }\n if (_vec_is_vec3(x)) {\n return { x: x.x || 0, y: x.y || 0, z: x.z || 0 };\n }\n if (_vec_is_vec2(x)) {\n return { x: x.x || 0, y: x.y || 0, z: y || 0 };\n }\n return { x: x, y: y ?? x, z: z ?? x };\n};\n\n/**\n * Get the components of a vector as an array\n * @param {vec3} a The vector to get components from\n * @return {Array<number>} The vector components as an array\n */\nvec3.components = a => [a.x, a.y, a.z];\n\n/**\n * Create a vector from an array of components\n * @param {Array<number>} components The components of the vector\n * @return {vec3} A new vector\n */\nvec3.fromComponents = components => vec3(...components.slice(0, 3));\n\n/**\n * Return a unit vector (1, 0, 0)\n * @return {vec3} A unit vector (1, 0, 0)\n */\nvec3.ux = () => vec3(1, 0, 0);\n\n/**\n * Return a unit vector (0, 1, 0)\n * @return {vec3} A unit vector (0, 1, 0)\n */\nvec3.uy = () => vec3(0, 1, 0);\n\n/**\n * Return a unit vector (0, 0, 1)\n * @return {vec3} A unit vector (0, 0, 1)\n */\nvec3.uz = () => vec3(0, 0, 1);\n\n/**\n * Add vectors\n * @param {vec3} a Vector a\n * @param {vec3|number} b Vector or scalar b\n * @return {vec3} a + b\n */\nvec3.add = (a, b) => ({ x: a.x + (b.x ?? b), y: a.y + (b.y ?? b), z: a.z + (b.z ?? b) });\n\n/**\n * Add multiple vectors\n * @param {...any} v Vectors to add\n * @returns {vec3} The sum of the vectors\n */\nvec3.addm = (...v) => v.reduce((a, b) => vec3.add(a, b), vec3());\n\n/**\n * Subtract vectors\n * @param {vec3} a Vector a\n * @param {vec3|number} b Vector or scalar b\n * @return {vec3} a - b\n */\nvec3.sub = (a, b) => ({ x: a.x - (b.x ?? b), y: a.y - (b.y ?? b), z: a.z - (b.z ?? b) });\n\n/**\n * Subtract multiple vectors\n * @param {...any} v Vectors to subtract\n * @returns {vec3} The result of subtracting the vectors\n */\nvec3.subm = (...v) => v.reduce((a, b) => vec3.sub(a, b));\n\n/**\n * Scale a vector\n * @param {vec3} a Vector a\n * @param {vec3|number} b Vector or scalar b\n * @return {vec3} a * b\n */\nvec3.mul = (a, b) => ({ x: a.x * (b.x ?? b), y: a.y * (b.y ?? b), z: a.z * (b.z ?? b) });\n\n/**\n * Scale a vector by a scalar, alias for vec3.mul\n * @param {vec3} a Vector a\n * @param {number} b Scalar b\n * @return {vec3} a * b\n */\nvec3.scale = (a, b) => vec3.mul(a, b);\n\n/**\n * Divide a vector\n * @param {vec3} a Vector a\n * @param {vec3|number} b Vector or scalar b\n * @return {vec3} a / b\n */\nvec3.div = (a, b) => ({ x: a.x / (b.x ?? b), y: a.y / (b.y ?? b), z: a.z / (b.z ?? b) });\n\n/**\n * Get the length of a vector\n * @param {vec3} a Vector a\n * @return {number} |a|\n */\nvec3.len = a => Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z);\n\n/**\n * Get the length of a vector using taxicab geometry\n * @param {vec3} a Vector a\n * @return {number} |a|\n */\nvec3.manhattan = a => Math.abs(a.x) + Math.abs(a.y) + Math.abs(a.z);\n\n/**\n * Normalise a vector\n * @param {vec3} a The vector to normalise\n * @return {vec3} ^a\n */\nvec3.nor = a => {\n let len = vec3.len(a);\n return len ? { x: a.x / len, y: a.y / len, z: a.z / len } : vec3();\n};\n\n/**\n * Get a dot product of vectors\n * @param {vec3} a Vector a\n * @param {vec3} b Vector b\n * @return {number} a ∙ b\n */\nvec3.dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;\n\n/**\n * Rotate a vector using a rotation matrix\n * @param {vec3} a The vector to rotate\n * @param {mat} m The rotation matrix\n * @return {vec3} A rotated vector\n */\nvec3.rot = (a, m) => vec3(\n vec3.dot(vec3.fromComponents(mat.row(m, 1)), a),\n vec3.dot(vec3.fromComponents(mat.row(m, 2)), a),\n vec3.dot(vec3.fromComponents(mat.row(m, 3)), a)\n);\n\n/**\n * Rotate a vector by r radians around the x axis\n * @param {vec3} a The vector to rotate\n * @param {number} r The angle to rotate by, measured in radians\n * @return {vec3} A rotated vector\n */\nvec3.rotx = (a, r) => vec3(\n a.x,\n a.y * Math.cos(r) - a.z * Math.sin(r),\n a.y * Math.sin(r) + a.z * Math.cos(r)\n);\n\n/**\n * Rotate a vector by r radians around the y axis\n * @param {vec3} a The vector to rotate\n * @param {number} r The angle to rotate by, measured in radians\n * @return {vec3} A rotated vector\n */\nvec3.roty = (a, r) => vec3(\n a.x * Math.cos(r) + a.z * Math.sin(r),\n a.y,\n -a.x * Math.sin(r) + a.z * Math.cos(r)\n);\n\n/**\n * Rotate a vector by r radians around the z axis\n * @param {vec3} a The vector to rotate\n * @param {number} r The angle to rotate by, measured in radians\n * @return {vec3} A rotated vector\n */\nvec3.rotz = (a, r) => vec3(\n a.x * Math.cos(r) - a.y * Math.sin(r),\n a.x * Math.sin(r) + a.y * Math.cos(r),\n a.z\n);\n\n/**\n * Rotate a vector using a quaternion\n * @param {vec3} a The vector to rotate\n * @param {Array<number>} q The quaternion to rotate by\n * @return {vec3} A rotated vector\n */\nvec3.rotq = (v, q) => {\n if (q.length !== 4) {\n return vec3();\n }\n\n const d = Math.sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);\n if (d === 0) {\n return vec3();\n }\n\n const uq = [q[0] / d, q[1] / d, q[2] / d, q[3] / d];\n const u = vec3(...uq.slice(0, 3));\n const s = uq[3];\n return vec3.add(\n vec3.add(\n vec3.mul(u, 2 * vec3.dot(u, v)),\n vec3.mul(v, s * s - vec3.dot(u, u))\n ),\n vec3.mul(vec3.cross(u, v), 2 * s)\n );\n};\n\n/**\n * Rotate a vector using Euler angles\n * @param {vec3} a The vector to rotate\n * @param {vec3} e The Euler angles to rotate by\n * @return {vec3} A rotated vector\n */\nvec3.rota = (a, e) => vec3.rotz(vec3.roty(vec3.rotx(a, e.x), e.y), e.z);\n\n/**\n * Get the cross product of vectors\n * @param {vec3} a Vector a\n * @param {vec3} b Vector b\n * @return {vec3} a × b\n */\nvec3.cross = (a, b) => vec3(\n a.y * b.z - a.z * b.y,\n a.z * b.x - a.x * b.z,\n a.x * b.y - a.y * b.x\n);\n\n/**\n * Check if two vectors are equal\n * @param {vec3} a Vector a\n * @param {vec3} b Vector b\n * @return {boolean} True if vectors a and b are equal, false otherwise\n */\nvec3.eq = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;\n\n/**\n * Get the angle of a vector from the x axis\n * @param {vec3} a Vector a\n * @return {number} The angle of vector a in radians\n */\nvec3.radx = a => Math.atan2(a.z, a.y);\n\n/**\n * Get the angle of a vector from the y axis\n * @param {vec3} a Vector a\n * @return {number} The angle of vector a in radians\n */\nvec3.rady = a => Math.atan2(a.x, a.y);\n\n/**\n * Get the angle of a vector from the z axis\n * @param {vec3} a Vector a\n * @return {number} The angle of vector a in radians\n */\nvec3.radz = a => Math.atan2(a.y, a.z);\n\n/**\n * Copy a vector\n * @param {vec3} a The vector to copy\n * @return {vec3} A copy of vector a\n */\nvec3.cpy = a => vec3(a);\n\n/**\n * A function to call on each component of a 3d vector\n * @callback vec3MapCallback\n * @param {number} value The component value\n * @param {'x' | 'y' | 'z'} label The component label (x, y or z)\n * @return {number} The mapped component\n */\n\n/**\n * Call a function on each component of a vector and build a new vector from the results\n * @param {vec3} a Vector a\n * @param {vec3MapCallback} f The function to call on each component of the vector\n * @return {vec3} Vector a mapped through f\n */\nvec3.map = (a, f) => ({ x: f(a.x, 'x'), y: f(a.y, 'y'), z: f(a.z, 'z') });\n\n/**\n * Convert a vector into a string\n * @param {vec3} a The vector to convert\n * @param {string} [s=', '] The separator string\n * @return {string} A string representation of the vector\n */\nvec3.str = (a, s = ', ') => `${a.x}${s}${a.y}${s}${a.z}`;\n\n/**\n * Swizzle a vector with a string of component labels\n *\n * The string can contain:\n * - `x`, `y` or `z`\n * - `u`, `v` or `w` (aliases for `x`, `y` and `z`, respectively)\n * - `r`, `g` or `b` (aliases for `x`, `y` and `z`, respectively)\n * - `X`, `Y`, `Z`, `U`, `V`, `W`, `R`, `G`, `B` (negated versions of the above)\n * - `0` or `1` (these will be passed through unchanged)\n * - `.` to return the component that would normally be at this position (or 0)\n *\n * Any other characters will default to 0\n * @param {vec3} a The vector to swizzle\n * @param {string} [s='...'] The swizzle string\n * @return {Array<number>} The swizzled components\n * @example <caption>swizzling a vector</caption>\n * let a = vec3(3, -2, 1);\n * vec3.swiz(a, 'x'); // [3]\n * vec3.swiz(a, 'zyx'); // [1, -2, 3]\n * vec3.swiz(a, 'xYZ'); // [3, 2, -1]\n * vec3.swiz(a, 'Zzx'); // [-1, 1, 3]\n * vec3.swiz(a, 'x.x'); // [3, -2, 3]\n * vec3.swiz(a, 'y01zx'); // [-2, 0, 1, 1, 3]\n */\nvec3.swiz = (a, s = '...') => {\n const result = [];\n s.split('').forEach((c, i) => {\n switch (c) {\n case 'x': case 'u': case 'r': result.push(a.x); break;\n case 'y': case 'v': case 'g': result.push(a.y); break;\n case 'z': case 'w': case 'b': result.push(a.z); break;\n case 'X': case 'U': case 'R': result.push(-a.x); break;\n case 'Y': case 'V': case 'G': result.push(-a.y); break;\n case 'Z': case 'W': case 'B': result.push(-a.z); break;\n case '0': result.push(0); break;\n case '1': result.push(1); break;\n case '.': result.push([a.x, a.y, a.z][i] ?? 0); break;\n default: result.push(0);\n }\n });\n return result;\n};\n\n/**\n * Polar coordinates for a 3d vector\n * @typedef {Object} polarCoordinates3d\n * @property {number} r The magnitude (radius) of the vector\n * @property {number} theta The tilt angle of the vector\n * @property {number} phi The pan angle of the vector\n */\n\n/**\n * Convert a vector into polar coordinates\n * @param {vec3} a The vector to convert\n * @return {polarCoordinates3d} The magnitude, tilt and pan of the vector\n */\nvec3.polar = a => {\n let r = vec3.len(a),\n theta = Math.acos(a.y / r),\n phi = Math.atan2(a.z, a.x);\n return { r, theta, phi };\n};\n\n/**\n * Convert polar coordinates into a vector\n * @param {number} r The magnitude (radius) of the vector\n * @param {number} theta The tilt of the vector\n * @param {number} phi The pan of the vector\n * @return {vec3} A vector with the given angle and magnitude\n */\nvec3.fromPolar = (r, theta, phi) => {\n const sinTheta = Math.sin(theta);\n return vec3(\n r * sinTheta * Math.cos(phi),\n r * Math.cos(theta),\n r * sinTheta * Math.sin(phi)\n );\n};\n\n/**\n * A matrix\n * @typedef {Object} mat\n * @property {number} m The number of rows in the matrix\n * @property {number} n The number of columns in the matrix\n * @property {Array<number>} entries The matrix values\n */\n\n/**\n * Create a new matrix\n * @param {number} [m=4] The number of rows\n * @param {number} [n=4] The number of columns\n * @param {Array<number>} [entries=[]] Matrix values in reading order\n * @return {mat} A new matrix\n */\nconst mat = (m = 4, n = 4, entries = []) => ({\n m, n,\n entries: entries.concat(Array(m * n).fill(0)).slice(0, m * n)\n});\n\n/**\n * Get an identity matrix of size n\n * @param {number} n The size of the matrix\n * @return {mat} An identity matrix\n */\nmat.identity = n => mat(n, n, Array(n * n).fill(0).map((v, i) => +(Math.floor(i / n) === i % n)));\n\n/**\n * Get an entry from a matrix\n * @param {mat} a Matrix a\n * @param {number} i The row offset\n * @param {number} j The column offset\n * @return {number} The value at position (i, j) in matrix a\n */\nmat.get = (a, i, j) => a.entries[(j - 1) + (i - 1) * a.n];\n\n/**\n * Set an entry of a matrix\n * @param {mat} a Matrix a\n * @param {number} i The row offset\n * @param {number} j The column offset\n * @param {number} v The value to set in matrix a\n */\nmat.set = (a, i, j, v) => { a.entries[(j - 1) + (i - 1) * a.n] = v; };\n\n/**\n * Get a row from a matrix as an array\n * @param {mat} a Matrix a\n * @param {number} m The row offset\n * @return {Array<number>} Row m from matrix a\n */\nmat.row = (a, m) => {\n const s = (m - 1) * a.n;\n return a.entries.slice(s, s + a.n);\n};\n\n/**\n * Get a column from a matrix as an array\n * @param {mat} a Matrix a\n * @param {number} n The column offset\n * @return {Array<number>} Column n from matrix a\n */\nmat.col = (a, n) => _vec_times(i => mat.get(a, (i + 1), n), a.m);\n\n/**\n * Add matrices\n * @param {mat} a Matrix a\n * @param {mat} b Matrix b\n * @return {mat} a + b\n */\nmat.add = (a, b) => a.m === b.m && a.n === b.n && mat.map(a, (v, i) => v + b.entries[i]);\n\n/**\n * Subtract matrices\n * @param {mat} a Matrix a\n * @param {mat} b Matrix b\n * @return {mat} a - b\n */\nmat.sub = (a, b) => a.m === b.m && a.n === b.n && mat.map(a, (v, i) => v - b.entries[i]);\n\n/**\n * Multiply matrices\n * @param {mat} a Matrix a\n * @param {mat} b Matrix b\n * @return {mat|false} ab or false if the matrices cannot be multiplied\n */\nmat.mul = (a, b) => {\n if (a.n !== b.m) { return false; }\n const result = mat(a.m, b.n);\n for (let i = 1; i <= a.m; i++) {\n for (let j = 1; j <= b.n; j++) {\n mat.set(result, i, j, _vec_dot(mat.row(a, i), mat.col(b, j)));\n }\n }\n return result;\n};\n\n/**\n * Multiply a matrix by a vector\n * @param {mat} a Matrix a\n * @param {vec2|vec3|number[]} b Vector b\n * @return {vec2|vec3|number[]|false} ab or false if the matrix and vector cannot be multiplied\n */\nmat.mulv = (a, b) => {\n let n, bb, rt;\n if (_vec_is_vec3(b)) {\n bb = vec3.components(b);\n n = 3;\n rt = vec3.fromComponents;\n } else if (_vec_is_vec2(b)) {\n bb = vec2.components(b);\n n = 2;\n rt = vec2.fromComponents;\n } else {\n bb = b;\n n = b.length ?? 0;\n rt = v => v;\n }\n if (a.n !== n) { return false; }\n const result = [];\n for (let i = 1; i <= a.m; i++) {\n result.push(_vec_dot(mat.row(a, i), bb));\n }\n return rt(result);\n}\n\n/**\n * Scale a matrix\n * @param {mat} a Matrix a\n * @param {number} b Scalar b\n * @return {mat} a * b\n */\nmat.scale = (a, b) => mat.map(a, v => v * b);\n\n/**\n * Transpose a matrix\n * @param {mat} a The matrix to transpose\n * @return {mat} A transposed matrix\n */\nmat.trans = a => mat(a.n, a.m, _vec_times(i => mat.col(a, (i + 1)), a.n).flat());\n\n/**\n * Get the minor of a matrix\n * @param {mat} a Matrix a\n * @param {number} i The row offset\n * @param {number} j The column offset\n * @return {mat|false} The (i, j) minor of matrix a or false if the matrix is not square\n */\nmat.minor = (a, i, j) => {\n if (a.m !== a.n) { return false; }\n const entries = [];\n for (let ii = 1; ii <= a.m; ii++) {\n if (ii === i) { continue; }\n for (let jj = 1; jj <= a.n; jj++) {\n if (jj === j) { continue; }\n entries.push(mat.get(a, ii, jj));\n }\n }\n return mat(a.m - 1, a.n - 1, entries);\n};\n\n/**\n * Get the determinant of a matrix\n * @param {mat} a Matrix a\n * @return {number|false} |a| or false if the matrix is not square\n */\nmat.det = a => {\n if (a.m !== a.n) { return false; }\n if (a.m === 1) {\n return a.entries[0];\n }\n if (a.m === 2) {\n return a.entries[0] * a.entries[3] - a.entries[1] * a.entries[2];\n }\n let total = 0, sign = 1;\n for (let j = 1; j <= a.n; j++) {\n total += sign * a.entries[j - 1] * mat.det(mat.minor(a, 1, j));\n sign *= -1;\n }\n return total;\n};\n\n/**\n * Normalise a matrix\n * @param {mat} a The matrix to normalise\n * @return {mat|false} ^a or false if the matrix is not square\n */\nmat.nor = a => {\n if (a.m !== a.n) { return false; }\n const d = mat.det(a);\n return mat.map(a, i => i * d);\n};\n\n/**\n * Get the adjugate of a matrix\n * @param {mat} a The matrix from which to get the adjugate\n * @return {mat} The adjugate of a\n */\nmat.adj = a => {\n const minors = mat(a.m, a.n);\n for (let i = 1; i <= a.m; i++) {\n for (let j = 1; j <= a.n; j++) {\n mat.set(minors, i, j, mat.det(mat.minor(a, i, j)));\n }\n }\n const cofactors = mat.map(minors, (v, i) => v * (i % 2 ? -1 : 1));\n return mat.trans(cofactors);\n};\n\n/**\n * Get the inverse of a matrix\n * @param {mat} a The matrix to invert\n * @return {mat|false} a^-1 or false if the matrix has no inverse\n */\nmat.inv = a => {\n if (a.m !== a.n) { return false; }\n const d = mat.det(a);\n if (d === 0) { return false; }\n return mat.scale(mat.adj(a), 1 / d);\n};\n\n/**\n * Check if two matrices are equal\n * @param {mat} a Matrix a\n * @param {mat} b Matrix b\n * @return {boolean} True if matrices a and b are identical, false otherwise\n */\nmat.eq = (a, b) => a.m === b.m && a.n === b.n && mat.str(a) === mat.str(b);\n\n/**\n * Copy a matrix\n * @param {mat} a The matrix to copy\n * @return {mat} A copy of matrix a\n */\nmat.cpy = a => mat(a.m, a.n, [...a.entries]);\n\n/**\n * A function to call on each entry of a matrix\n * @callback matrixMapCallback\n * @param {number} value The entry value\n * @param {number} index The entry index\n * @param {Array<number>} entries The array of matrix entries\n * @return {number} The mapped entry\n */\n\n/**\n * Call a function on each entry of a matrix and build a new matrix from the results\n * @param {mat} a Matrix a\n * @param {matrixMapCallback} f The function to call on each entry of the matrix\n * @return {mat} Matrix a mapped through f\n */\nmat.map = (a, f) => mat(a.m, a.n, a.entries.map(f));\n\n/**\n * Convert a matrix into a string\n * @param {mat} a The matrix to convert\n * @param {string} [ms=', '] The separator string for columns\n * @param {string} [ns='\\n'] The separator string for rows\n * @return {string} A string representation of the matrix\n */\nmat.str = (a, ms = ', ', ns = '\\n') => _vec_chunk(a.entries, a.n).map(r => r.join(ms)).join(ns);\n\nif (true) {\n module.exports = { vec2, vec3, mat };\n}\n\n\n//# sourceURL=webpack://@basementuniverse/layout/./node_modules/@basementuniverse/vec/vec.js?\n}");
40
+
41
+ /***/ })
42
+
43
+ /******/ });
44
+ /************************************************************************/
45
+ /******/ // The module cache
46
+ /******/ var __webpack_module_cache__ = {};
47
+ /******/
48
+ /******/ // The require function
49
+ /******/ function __webpack_require__(moduleId) {
50
+ /******/ // Check if module is in cache
51
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
52
+ /******/ if (cachedModule !== undefined) {
53
+ /******/ return cachedModule.exports;
54
+ /******/ }
55
+ /******/ // Create a new module (and put it into the cache)
56
+ /******/ var module = __webpack_module_cache__[moduleId] = {
57
+ /******/ // no module.id needed
58
+ /******/ // no module.loaded needed
59
+ /******/ exports: {}
60
+ /******/ };
61
+ /******/
62
+ /******/ // Execute the module function
63
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
64
+ /******/
65
+ /******/ // Return the exports of the module
66
+ /******/ return module.exports;
67
+ /******/ }
68
+ /******/
69
+ /************************************************************************/
70
+ /******/
71
+ /******/ // startup
72
+ /******/ // Load entry module and return exports
73
+ /******/ // This entry module can't be inlined because the eval devtool is used.
74
+ /******/ var __webpack_exports__ = __webpack_require__("./index.ts");
75
+ /******/
76
+ /******/ return __webpack_exports__;
77
+ /******/ })()
78
+ ;
79
+ });
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@basementuniverse/layout",
3
+ "version": "1.0.0",
4
+ "description": "Create responsive layouts for HTML5 Canvas.",
5
+ "author": "Gordon Larrigan <gordonlarrigan@gmail.com> (https://gordonlarrigan.com)",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/basementuniverse/layout.git"
10
+ },
11
+ "main": "build/index.js",
12
+ "types": "build/index.d.ts",
13
+ "files": [
14
+ "build"
15
+ ],
16
+ "scripts": {
17
+ "build": "webpack",
18
+ "watch": "webpack --watch"
19
+ },
20
+ "dependencies": {
21
+ "@basementuniverse/utils": "^1.7.1",
22
+ "@basementuniverse/vec": "^2.4.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^18.11.12",
26
+ "clean-webpack-plugin": "^4.0.0-alpha.0",
27
+ "ts-loader": "^8.0.7",
28
+ "typescript": "^4.9.4",
29
+ "webpack": "^5.3.2",
30
+ "webpack-cli": "^4.1.0"
31
+ }
32
+ }