Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix: resize solver in the age of preview splits (#5317)
Peter Chinman4e9d4fb9ba6c
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsxindex 0f0a32ea03..ee6c519f45 100644--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx@@ -15,7 +15,6 @@ import {createMemo,createSelector,For,- on,onCleanup,type Setter,Show,@@ -26,7 +25,6 @@ import { SplitPanel } from './components/SplitPanel';import { SplitLayoutContext } from './context';import {createSplitLayout,- SplitEvent,type SplitId,type SplitManager,} from './layoutManager';@@ -76,16 +74,19 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {// Store a ref to each panel by idconst panelRefs = new Map<SplitId, HTMLDivElement>();- createEffect(- on(splitManager.events, (event) => {- if (event.type === SplitEvent.Remove) {- panelRefs.delete(event.splitId);- }- })- );const splits = createMemo(splitManager.splits);+ // Drop refs for departed splits by reconciling against the live list:+ // batched mutations can remove several splits in one flush (e.g. closing+ // a Preview Pair), and the events signal only surfaces the last event.+ createEffect(() => {+ const alive = new Set(splits().map(({ id }) => id));+ for (const id of panelRefs.keys()) {+ if (!alive.has(id)) panelRefs.delete(id);+ }+ });+const activeSplitSelector = createSelector(splitManager.activeSplitId);createEffect(() => props.setManager(splitManager));@@ -136,6 +137,14 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {<Resize.Panelid={id}minSize={splitMinWidthForContent(handle().content())}+ // A Preview Pair is one layout unit: its two splits+ // share the space a single split would get. Both+ // members key their group by the Controller's id.+ shareGroup={+ splitManager.viewerOf(id) !== undefined+ ? id+ : splitManager.controllerOf(id)+ }// Automatic redistribution targets an engaged// Controller at its configured preferred width.// This is not a hard max: the gutter can still bediff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex c187b6ae44..f4f135a2f9 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -1080,10 +1080,16 @@ export function createSplitLayout(// Closing a Preview Pair's Controller closes its Viewer too. Remove// the Viewer first so the Controller's final remove event determines- // which remaining split receives focus.- const viewerId = viewerOf(currentSplit.id);- if (viewerId) removeSplit(viewerId, false);- removeSplit(currentSplit.id);+ // which remaining split receives focus. One atomic mutation: a flush+ // between the removals would let a pending preview engagement (a+ // split waiting on room, see soup-view's initial-preview effect)+ // insert its Viewer into the still-crowded layout, min-crushing+ // every panel and scrambling the freed space's redistribution.+ batch(() => {+ const viewerId = viewerOf(currentSplit.id);+ if (viewerId) removeSplit(viewerId, false);+ removeSplit(currentSplit.id);+ });},getUrlSegments: () => contentUrlSegments(content()),getUrl: () => contentUrlSegments(content()).join('/'),@@ -1232,22 +1238,28 @@ export function createSplitLayout(contentChangeListeners.delete(id);entryStateCaptors.delete(id);- clearPreviewPairsFor(id);- setSplitNamesById(- produce((map) => {- delete map[id];- return map;- })- );- const nextSplits = state.splits.filter((s) => s.id !== id);- setState('splits', reconcile(nextSplits));+ // One atomic mutation: clearing the Preview Pair and removing the split+ // must reach reactive consumers together, so the departing split's panel+ // still carries its pair share-group when the resize solver drops it.+ batch(() => {+ clearPreviewPairsFor(id);+ setSplitNamesById(+ produce((map) => {+ delete map[id];+ return map;+ })+ );- dispatchEvent(SplitEvent.Remove, { splitId: id, splitIndex: idx });+ const nextSplits = state.splits.filter((s) => s.id !== id);+ setState('splits', reconcile(nextSplits));- if (nextSplits.length === 0 && createNewOnEmpty) {- createNewSplit({ content: DEFAULT_SPLIT_CONTENT, referredFrom: null });- }+ dispatchEvent(SplitEvent.Remove, { splitId: id, splitIndex: idx });++ if (nextSplits.length === 0 && createNewOnEmpty) {+ createNewSplit({ content: DEFAULT_SPLIT_CONTENT, referredFrom: null });+ }+ });}/**@@ -1376,21 +1388,28 @@ export function createSplitLayout(// replaces its content. Adopt an unclaimed placeholder already sitting// right of the controller instead of duplicating it. Without room for a// viewer, preview mode does not engage at all.- let viewerId = adoptableViewerFor(controllerId);- if (viewerId === undefined) {- if (!canAppendSplit()) return;- const controllerIndex = splitIndexById(controllerId);- const viewerHandle = createNewSplit({- content: PREVIEW_VIEWER_EMPTY_CONTENT,- activate: false,- referredFrom: null,- allowDuplicate: true,- insertIndex: controllerIndex >= 0 ? controllerIndex + 1 : undefined,- });- if (!viewerHandle) return;- viewerId = viewerHandle.id;- }- linkPreviewPair(controllerId, viewerId);+ //+ // Creating the viewer and linking the Preview Pair is one atomic+ // mutation: the viewer's resize panel must register with its pair+ // share-group already in place so it carves its width out of the+ // Controller instead of every split.+ batch(() => {+ let viewerId = adoptableViewerFor(controllerId);+ if (viewerId === undefined) {+ if (!canAppendSplit()) return;+ const controllerIndex = splitIndexById(controllerId);+ const viewerHandle = createNewSplit({+ content: PREVIEW_VIEWER_EMPTY_CONTENT,+ activate: false,+ referredFrom: null,+ allowDuplicate: true,+ insertIndex: controllerIndex >= 0 ? controllerIndex + 1 : undefined,+ });+ if (!viewerHandle) return;+ viewerId = viewerHandle.id;+ }+ linkPreviewPair(controllerId, viewerId);+ });// The Controller's configured width is enforced declaratively as an// automatic-redistribution preference and maximum (see@@ -1407,9 +1426,14 @@ export function createSplitLayout(}function disengagePreviewMode(controllerId: SplitId) {- const viewerId = viewerOf(controllerId);- unlinkPreviewPair(controllerId);- if (viewerId) removeSplit(viewerId);+ // Atomic for the same reason as removeSplit: the viewer's panel must+ // still carry its pair share-group when the resize solver drops it, so+ // its width returns to the Controller rather than every split.+ batch(() => {+ const viewerId = viewerOf(controllerId);+ unlinkPreviewPair(controllerId);+ if (viewerId) removeSplit(viewerId);+ });}function resetPreviewMode(controllerId: SplitId) {@@ -1615,24 +1639,26 @@ export function createSplitLayout(resultSplits.push(newSplit);}- // Clean up contentChangeListeners and splitNamesById for removed splits- for (const split of state.splits) {- if (!usedIds.has(split.id)) {- contentChangeListeners.delete(split.id);- entryStateCaptors.delete(split.id);- clearPreviewPairsFor(split.id);- setSplitNamesById(- produce((map) => {- delete map[split.id];- return map;- })- );- }- }-// Update order and unlink any Preview Pair that the rebuild separated- // before reactive consumers can observe the new split layout.+ // before reactive consumers can observe the new split layout. Removed+ // splits are cleaned up in the same atomic mutation so a removed+ // Preview Pair member's panel still carries its pair share-group when+ // the resize solver drops it.batch(() => {+ for (const split of state.splits) {+ if (!usedIds.has(split.id)) {+ contentChangeListeners.delete(split.id);+ entryStateCaptors.delete(split.id);+ clearPreviewPairsFor(split.id);+ setSplitNamesById(+ produce((map) => {+ delete map[split.id];+ return map;+ })+ );+ }+ }+setState('splits', resultSplits);pruneNonAdjacentPreviewPairs();});@@ -1887,11 +1913,15 @@ export function createSplitLayout(});}- for (const split of visibleSplits) {- if (split.id !== splitToKeep.id) {- removeSplit(split.id, false);+ // Atomic for the same reason as SplitHandle.close: no flush between+ // removals, so pending preview engagements only see the final layout.+ batch(() => {+ for (const split of visibleSplits) {+ if (split.id !== splitToKeep.id) {+ removeSplit(split.id, false);+ }}- }+ });const handle = getSplit(splitToKeep.id);if (handle) {diff --git a/apps/web/src/lib/core/component/Resize/Resize.tsx b/apps/web/src/lib/core/component/Resize/Resize.tsxindex cd31dd0e81..664c55e5ae 100644--- a/apps/web/src/lib/core/component/Resize/Resize.tsx+++ b/apps/web/src/lib/core/component/Resize/Resize.tsx@@ -109,6 +109,7 @@ function Zone(props: ParentProps<ZoneProps>) {minSize?: number;maxSize?: number;redistributionPreferredSize?: number;+ shareGroup?: string;}) {solver.updatePanel(id, config);@@ -213,6 +214,13 @@ type PanelProps = {minSize: number;maxSize?: number;redistributionPreferredSize?: number;+ /**+ * Panels sharing a `shareGroup` count as ONE unit for automatic share+ * allocation: an incoming member carves its share out of the group, a+ * departing member returns it, and redistribution-preference deltas settle+ * within the group before touching other panels.+ */+ shareGroup?: string;/*** Initial target size for the panel at registration time.* - number: interpreted as a percentage (e.g., 25 = 25%)@@ -280,6 +288,7 @@ function Panel(props: ParentProps<PanelProps>) {minSize: props.minSize,maxSize: props.maxSize ?? Infinity,redistributionPreferredSize: props.redistributionPreferredSize,+ shareGroup: props.shareGroup,target: getTarget(),},props.index@@ -292,6 +301,7 @@ function Panel(props: ParentProps<PanelProps>) {minSize: props.minSize,maxSize: props.maxSize ?? Infinity,redistributionPreferredSize: props.redistributionPreferredSize,+ shareGroup: props.shareGroup,});});@@ -307,6 +317,7 @@ function Panel(props: ParentProps<PanelProps>) {minSize: props.minSize,maxSize: props.maxSize ?? Infinity,redistributionPreferredSize: props.redistributionPreferredSize,+ shareGroup: props.shareGroup,target: getTarget(),},props.index@@ -334,6 +345,7 @@ function Panel(props: ParentProps<PanelProps>) {minSize: props.minSize,maxSize: props.maxSize ?? Infinity,redistributionPreferredSize: props.redistributionPreferredSize,+ shareGroup: props.shareGroup,target: getTarget(),},props.indexdiff --git a/apps/web/src/lib/core/component/Resize/solver.test.ts b/apps/web/src/lib/core/component/Resize/solver.test.tsindex 75046bc0c4..4687d3da51 100644--- a/apps/web/src/lib/core/component/Resize/solver.test.ts+++ b/apps/web/src/lib/core/component/Resize/solver.test.ts@@ -191,6 +191,475 @@ describe('createResizeSolver', () => {});});+ describe('shareGroup', () => {+ it('carves a joining member share from its group, leaving other units alone', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ expect(solver.solve().sizes.get('doc')).toBe(800);++ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(400);+ expect(solver.solve().sizes.get('viewer')).toBe(400);++ dispose();+ });++ it('returns a departing member share to its group', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });++ solver.dropPanel('viewer');+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(800);++ dispose();+ });++ it('counts a group as one unit when a standalone panel is added', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'doc', minSize: 100 });++ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(400);+ expect(solver.solve().sizes.get('viewer')).toBe(400);++ dispose();+ });++ it('settles a redistribution preference within the group', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });++ // The pin trades space with the viewer; the document keeps 50%.+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(440);+ expect(solver.solve().sizes.get('viewer')).toBe(360);++ dispose();+ });++ it('yields the pin to its unit budget when group-mates cannot fund it', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 400 });+ solver.addPanel({ id: 'controller', minSize: 400, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 400, shareGroup: 'pair' });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });++ // The viewer sits at its minimum, so the pair cannot fund the pin:+ // it shrinks back to the unit's budget instead of taking from the+ // document.+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(400);+ expect(solver.solve().sizes.get('viewer')).toBe(400);++ dispose();+ });++ it('keeps singles at equal unit shares when a split is added beside a pair', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'L', minSize: 400 });+ solver.addPanel({ id: 'controller', minSize: 340, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 400, shareGroup: 'pair' });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });++ // "New split right": three units intend a third each. The zone is too+ // tight to honor that (the pair's hard minimums are 340 + 400), but+ // the singles stay EQUAL and the pair only exceeds a third by its+ // minimums — the unfunded pin may not push the singles further down.+ solver.addPanel({ id: 'new', minSize: 400 });+ expect(solver.solve().sizes.get('L')).toBe(430);+ expect(solver.solve().sizes.get('new')).toBe(430);+ expect(solver.solve().sizes.get('controller')).toBe(340);+ expect(solver.solve().sizes.get('viewer')).toBe(400);++ dispose();+ });++ it('absorbs the group gutter so other panels never shift on join/leave', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size: () => 1608,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ expect(solver.solve().sizes.get('doc')).toBe(800);++ // The viewer's gutter comes out of the pair, not the other panels.+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(396);+ expect(solver.solve().sizes.get('viewer')).toBe(396);++ solver.updatePanel('controller', { redistributionPreferredSize: 440 });+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(440);+ expect(solver.solve().sizes.get('viewer')).toBe(352);++ // Disengage clears the preference alongside the drop (in the app both+ // land in one reactive flush); leaving then reclaims the gutter for+ // an exact round-trip.+ solver.updatePanel('controller', {+ redistributionPreferredSize: undefined,+ });+ expect(solver.solve().sizes.get('doc')).toBe(800);+ solver.dropPanel('viewer');+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(800);++ dispose();+ });++ it('keeps unit shares stable across zone resizes', async () => {+ const [size, setSize] = createSignal(1600);+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });++ expect(solver.solve().sizes.get('doc')).toBe(800);++ // Growing the zone keeps the document at half; the pinned controller+ // stays put and its group-mate absorbs the pair's growth.+ setSize(2000);+ expect(solver.solve().sizes.get('doc')).toBe(1000);+ expect(solver.solve().sizes.get('controller')).toBe(440);+ expect(solver.solve().sizes.get('viewer')).toBe(560);++ dispose();+ });++ it('routes gutter-drag growth past the controller preferred size to the viewer', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });+ expect(solver.solve().sizes.get('doc')).toBe(800);++ // Shrinking the document leaves the controller at its preferred+ // width; the freed space flows to the viewer.+ solver.moveHandle(0, -200);+ expect(solver.solve().sizes.get('doc')).toBe(600);+ expect(solver.solve().sizes.get('controller')).toBe(440);+ expect(solver.solve().sizes.get('viewer')).toBe(560);++ // Dragging the pair's own internal gutter still resizes the+ // controller directly.+ solver.moveHandle(1, 100);+ expect(solver.solve().sizes.get('controller')).toBe(540);+ expect(solver.solve().sizes.get('viewer')).toBe(460);++ dispose();+ });++ it('takes gutter-drag shrink from the viewer before the controller', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });++ // Growing the document squeezes the viewer while the controller+ // holds its preferred width...+ solver.moveHandle(0, 200);+ expect(solver.solve().sizes.get('doc')).toBe(1000);+ expect(solver.solve().sizes.get('controller')).toBe(440);+ expect(solver.solve().sizes.get('viewer')).toBe(160);++ // ...and only once the viewer bottoms out does the controller give.+ solver.moveHandle(0, 200);+ expect(solver.solve().sizes.get('doc')).toBe(1200);+ expect(solver.solve().sizes.get('controller')).toBe(300);+ expect(solver.solve().sizes.get('viewer')).toBe(100);++ dispose();+ });++ it('restores per-unit distribution when a split closes from a min-crushed layout', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size: () => 1704,+ panels: [],+ }),+ }));++ await Promise.resolve();++ // [L | pair(C+V) | R] in a zone where the pair's floor (440 + 400)+ // forces everything else onto its minimums.+ solver.addPanel({ id: 'L', minSize: 400 });+ solver.addPanel({ id: 'C', minSize: 340, shareGroup: 'pair' });+ solver.updatePanel('C', { redistributionPreferredSize: 440 });+ solver.addPanel({ id: 'V', minSize: 400, shareGroup: 'pair' });+ solver.addPanel({ id: 'R', minSize: 400 });++ // Rendering is constraint-dictated: L is crushed below its intent by+ // the pair's hard minimums (the unfunded pin has already yielded).+ expect(solver.solve().sizes.get('L')).toBe(471);+ expect(solver.solve().sizes.get('C')).toBe(340);+ expect(solver.solve().sizes.get('V')).toBe(400);+ expect(solver.solve().sizes.get('R')).toBe(469);++ // Closing R must distribute per UNIT: the crushed pixels carry no+ // intent, so L returns to half the zone and the pair takes the other+ // half — not two-thirds to the pair's two panels.+ solver.dropPanel('R');+ expect(solver.solve().sizes.get('L')).toBe(848);+ expect(solver.solve().sizes.get('C')).toBe(440);+ expect(solver.solve().sizes.get('V')).toBe(400);++ dispose();+ });++ it('resets to an equal share per unit', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'doc', minSize: 100 });+ solver.addPanel({ id: 'controller', minSize: 100, shareGroup: 'pair' });+ solver.addPanel({ id: 'viewer', minSize: 100, shareGroup: 'pair' });++ solver.moveHandle(0, -400);+ expect(solver.solve().sizes.get('doc')).toBe(400);++ solver.reset();+ expect(solver.solve().sizes.get('doc')).toBe(800);+ expect(solver.solve().sizes.get('controller')).toBe(400);+ expect(solver.solve().sizes.get('viewer')).toBe(400);++ dispose();+ });+ });++ describe('degenerate zone size', () => {+ it('shrinks panels together once free room is exhausted', async () => {+ const [size, setSize] = createSignal(2000);+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'A', minSize: 400 });+ solver.addPanel({ id: 'B', minSize: 400 });+ solver.addPanel({ id: 'C', minSize: 400 });++ // Drag the middle panel large: [400, 1200, 400].+ solver.moveHandle(0, -267);+ solver.moveHandle(1, 266);+ expect(solver.solve().sizes.get('B')).toBe(1200);++ // Shrinking the window below the summed minimums must crush all+ // panels together — not drain the large middle panel to zero while+ // its neighbors sit at their minimums.+ setSize(900);+ expect(solver.solve().sizes.get('A')).toBe(300);+ expect(solver.solve().sizes.get('B')).toBe(300);+ expect(solver.solve().sizes.get('C')).toBe(300);++ // Intent survives the crush: restoring the window restores the drag.+ setSize(2000);+ expect(solver.solve().sizes.get('A')).toBe(400);+ expect(solver.solve().sizes.get('B')).toBe(1200);+ expect(solver.solve().sizes.get('C')).toBe(400);++ dispose();+ });++ it('emits finite shares when the zone measures zero', async () => {+ const [size, setSize] = createSignal(1000);+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'A', minSize: 400 });+ solver.addPanel({ id: 'B', minSize: 400 });++ setSize(0);+ for (const share of solver.solve().shares.values()) {+ expect(Number.isFinite(share)).toBe(true);+ }++ setSize(1000);+ expect(solver.solve().sizes.get('A')).toBe(500);+ expect(solver.solve().sizes.get('B')).toBe(500);++ dispose();+ });++ it('keeps the share model through a transient too-small solve', async () => {+ const [size, setSize] = createSignal(1000);+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 0,+ size,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'A', minSize: 400 });+ solver.addPanel({ id: 'B', minSize: 400 });+ solver.moveHandle(0, 100);+ expect(solver.solve().sizes.get('A')).toBe(600);++ // The zone transiently measures smaller than the summed minimums+ // (e.g. mid-boot); restoring it must restore the prior proportions.+ setSize(300);+ setSize(1000);+ expect(solver.solve().sizes.get('A')).toBe(600);+ expect(solver.solve().sizes.get('B')).toBe(400);++ dispose();+ });+ });+describe('canFitPanel', () => {it('accounts for the gutter added by the candidate panel', () => {createRoot((dispose) => {diff --git a/apps/web/src/lib/core/component/Resize/solver.ts b/apps/web/src/lib/core/component/Resize/solver.tsindex ece53eee7c..4bab72ef34 100644--- a/apps/web/src/lib/core/component/Resize/solver.ts+++ b/apps/web/src/lib/core/component/Resize/solver.ts@@ -18,6 +18,7 @@ type ResizeSolver = {minSize?: number;maxSize?: number;redistributionPreferredSize?: number;+ shareGroup?: string;}) => void;solve: () => LayoutResult;@@ -77,7 +78,16 @@ function computeFractionalShares(if (totalFree > 0) {for (let i = 0; i < n; i++) {const room = Math.max(0, free[i]);- const take = Math.round((room / totalFree) * Math.abs(diff));+ // Cap each take at the panel's own room: when the total diff+ // exceeds the total free room, an uncapped take would push the+ // panel past its min/max (a large panel could hit zero width while+ // its neighbors sit at their minimums). The capped remainder falls+ // through to the too-small handling below, which shrinks every+ // panel together.+ const take = Math.min(+ room,+ Math.round((room / totalFree) * Math.abs(diff))+ );if (Number.isFinite(take)) {clamped[i] += diff > 0 ? take : -take;}@@ -113,16 +123,15 @@ function computeFractionalShares(const containerTooSmall = usable < totalMinSizes;if (containerTooSmall) {- let totalCurrentSize = sumArray(clamped);+ // Below the summed minimums nothing has room left to give, so+ // every panel shrinks together by the same factor — sizes stay+ // proportional to the minimums and always sum to the usable+ // space.+ const totalCurrentSize = sumArray(clamped);if (totalCurrentSize > 0) {+ const scale = usable / totalCurrentSize;for (let i = 0; i < n; i++) {- const proportion = clamped[i] / totalCurrentSize;- const shrinkAmount = Math.min(- remaining * proportion,- clamped[i]- );- clamped[i] -= shrinkAmount;- remaining -= shrinkAmount;+ clamped[i] *= scale;}}}@@ -137,7 +146,9 @@ function computeFractionalShares(if (i >= 1) {offsets[i] = offsets[i - 1] + clamped[i - 1] + gutter;}- shares[i] = clamped[i] / usable;+ // A zero-measure zone (e.g. mid-boot) must not emit NaN shares into+ // the layout result consumers read.+ shares[i] = usable > 0 ? clamped[i] / usable : 0;}return {@@ -158,6 +169,25 @@ function initPanel(panel: PanelConfig): Panel {};}+/**+ * Panels with the same `shareGroup` form one layout unit; every ungrouped+ * panel is a unit of its own. Automatic share allocation is per unit, so a+ * group collectively receives the space a single panel would.+ */+function countUnits(panels: readonly Pick<Panel, 'shareGroup'>[]): number {+ const groups = new Set<string>();+ let units = 0;+ for (const panel of panels) {+ if (panel.shareGroup === undefined) {+ units += 1;+ } else if (!groups.has(panel.shareGroup)) {+ groups.add(panel.shareGroup);+ units += 1;+ }+ }+ return units;+}+/*** Pin automatic-layout preferences when the remaining panels can absorb the* leftover space. Preferences yield to every panel's minimum size, while@@ -207,19 +237,83 @@ function applyRedistributionPreferences(// Avoid leaving a gap when no other panel can absorb the remaining space.if (resolvedPreferredTotal + remainingMax + EPSILON < usable) return panels;+ // Settle a pinned panel's size delta within its share group first: the+ // group is one layout unit, so pinning one member trades space with its+ // group-mates and leaves the other units' sizes alone. Whatever the+ // group-mates cannot fund shrinks the pin itself (down to the panel's+ // hard minimum) instead of taking space from other units. Hard minimums+ // always still leak to the global solve.+ const shareAdjustments = new Map<PanelId, number>();+ const adjustedShare = (panel: Panel) =>+ panel.share + (shareAdjustments.get(panel.id) ?? 0);+ for (const entry of preferredPanels) {+ const { panel, size } = entry;+ if (panel.shareGroup === undefined) continue;+ const groupMates = panels.filter(+ (candidate) =>+ candidate.shareGroup === panel.shareGroup &&+ candidate.id !== panel.id &&+ !preferredIds.has(candidate.id)+ );+ if (groupMates.length === 0) continue;++ const delta = size / usable - panel.share;+ if (delta > EPSILON) {+ // The pin grows the panel: group-mates give up share, weighted by+ // their room above minimum.+ const capacities = groupMates.map((mate) =>+ Math.max(0, adjustedShare(mate) - mate.minSize / usable)+ );+ const totalCapacity = sumArray(capacities);+ const applied = Math.min(delta, totalCapacity);+ if (totalCapacity > 0 && applied > 0) {+ groupMates.forEach((mate, i) => {+ const give = applied * (capacities[i] / totalCapacity);+ shareAdjustments.set(+ mate.id,+ (shareAdjustments.get(mate.id) ?? 0) - give+ );+ });+ }+ const unfunded = delta - applied;+ if (unfunded > EPSILON) {+ entry.size = Math.max(panel.minSize, (panel.share + applied) * usable);+ }+ } else if (delta < -EPSILON) {+ // The pin shrinks the panel: group-mates receive the freed share,+ // weighted by their current shares.+ const weights = groupMates.map((mate) =>+ Math.max(0, adjustedShare(mate))+ );+ const totalWeight = sumArray(weights);+ groupMates.forEach((mate, i) => {+ const weight =+ totalWeight > 0 ? weights[i] / totalWeight : 1 / groupMates.length;+ shareAdjustments.set(+ mate.id,+ (shareAdjustments.get(mate.id) ?? 0) + -delta * weight+ );+ });+ }+ }+const preferredSizeById = new Map(preferredPanels.map(({ panel, size }) => [panel.id, size]));return panels.map((panel) => {const preferred = preferredSizeById.get(panel.id);- return preferred === undefined+ if (preferred !== undefined) {+ return {+ ...panel,+ minSize: preferred,+ maxSize: preferred,+ share: preferred / usable,+ };+ }+ const adjustment = shareAdjustments.get(panel.id);+ return adjustment === undefined? panel- : {- ...panel,- minSize: preferred,- maxSize: preferred,- share: preferred / usable,- };+ : { ...panel, share: Math.max(0, panel.share + adjustment) };});}@@ -276,7 +370,15 @@ export function createResizeSolver(params: {offsets: new Map(),});- // the solve on dependencies effect+ // The solve on dependencies effect.+ //+ // Shares are INTENT: they record how the user wants space divided between+ // layout units, and only unit arithmetic (panels joining/leaving) and+ // manual gutter drags write them. A solve renders intent under the current+ // constraints (minimums, pins) but NEVER writes the result back — solved+ // pixels in a tight zone are constraint-dictated and carry no intent, and+ // baking them in would permanently distort the model (e.g. a min-crushed+ // Preview Pair would keep its crushed proportions after space frees up).createEffect(() => {const ps = panelsInOrder();const solveKind = nextSolveKind;@@ -288,54 +390,9 @@ export function createResizeSolver(params: {? applyRedistributionPreferences(ps, usable): ps;- // run the solve to get pixel values- const solve = computeFractionalShares(- solvePanels,- params.size(),- params.gutter()+ setLayout(+ computeFractionalShares(solvePanels, params.size(), params.gutter()));-- // basically update the float share values to match the actual pixel sizes returned by the solve.- const ids = order();- const n = ids.length;- if (usable > 0 && n > 0) {- const clampedPx = ids.map((id) => solve.sizes.get(id) ?? 0);- const mins = solvePanels.map((p) => p.minSize ?? 0);- const maxs = solvePanels.map((p) => p.maxSize ?? Infinity);-- const free: number[] = [];- const clamped: number[] = [];- for (let i = 0; i < n; i++) {- const x = clampedPx[i];- if (x > mins[i] + EPSILON && x < maxs[i] - EPSILON) free.push(i);- else clamped.push(i);- }-- for (const i of clamped) {- panelData[ids[i]].share = clampedPx[i] / usable;- }-- const sumModelFree = sumArray(free.map((i) => panelData[ids[i]].share));- const sumPxFree = sumArray(free.map((i) => clampedPx[i])) / usable;-- if (free.length > 0) {- if (sumModelFree > 0) {- const k = sumPxFree / sumModelFree;- for (const i of free) panelData[ids[i]].share *= k;- } else {- const eq = sumPxFree / free.length;- for (const i of free) panelData[ids[i]].share = eq;- }- }-- // account for floating point drift- const sum = sumArray(ids.map((id) => panelData[id].share));- if (sum > 0 && Math.abs(sum - 1) > EPSILON) {- for (const id of ids) panelData[id].share /= sum;- }- }-- setLayout(solve);});function addPanel(panel: PanelConfig, ndx?: number) {@@ -350,8 +407,63 @@ export function createResizeSolver(params: {const usableSize = getUsable(nextLength, params.size(), params.gutter());- // Calculate incoming share based on target spec, defaulting to equal share- let incomingShare = 1 / nextLength;+ // A panel joining a live share group carves its share out of the+ // group's members: the group is one layout unit, so the other units+ // keep their sizes. The group also absorbs the gutter the new panel+ // introduces — usable space shrinks by one gutter, so without the+ // correction every other panel would shift by its slice of it.+ const groupMemberIds =+ panel.shareGroup === undefined+ ? []+ : ids.filter((id) => panelData[id].shareGroup === panel.shareGroup);+ if (groupMemberIds.length > 0) {+ const memberIdSet = new Set(groupMemberIds);+ const groupShare = sumArray(+ groupMemberIds.map((id) => panelData[id].share)+ );+ const usableBefore = getUsable(length, params.size(), params.gutter());+ const memberScale = groupMemberIds.length / (groupMemberIds.length + 1);+ let incomingGroupShare = groupShare;+ if (usableBefore > 0 && usableSize > 0) {+ const nextGroupShare = Math.max(+ 0,+ (groupShare * usableBefore - params.gutter()) / usableSize+ );+ const rescale = usableBefore / usableSize;+ const groupRescale = groupShare > 0 ? nextGroupShare / groupShare : 0;+ for (const id of ids) {+ panelData[id].share *= memberIdSet.has(id)+ ? groupRescale * memberScale+ : rescale;+ }+ incomingGroupShare = nextGroupShare;+ } else {+ // Zone size unknown: fall back to a plain within-group carve.+ for (const id of groupMemberIds) {+ panelData[id].share *= memberScale;+ }+ }+ panelData[panel.id] = {+ ...initPanel(panel),+ share: incomingGroupShare / (groupMemberIds.length + 1),+ };++ if (index >= order().length) {+ setOrder((prev) => [...prev, panel.id]);+ } else {+ setOrder((prev) => [+ ...prev.slice(0, index),+ panel.id,+ ...prev.slice(index),+ ]);+ }+ setDirty();+ return;+ }++ // Calculate incoming share based on target spec, defaulting to an+ // equal share per layout unit (a share group counts as one unit).+ let incomingShare = 1 / (countUnits(ids.map((id) => panelData[id])) + 1);if (panel.target && usableSize > 0) {switch (panel.target.kind) {@@ -409,6 +521,7 @@ export function createResizeSolver(params: {minSize?: number;maxSize?: number;redistributionPreferredSize?: number;+ shareGroup?: string;}) {const panel = panelData[id];@@ -435,6 +548,11 @@ export function createResizeSolver(params: {changed = true;}}+ if ('shareGroup' in config) {+ // Membership alone moves no pixels, so it does not dirty the layout;+ // it only informs future share allocation.+ panel.shareGroup = config.shareGroup;+ }if (changed) setDirty();}@@ -446,6 +564,57 @@ export function createResizeSolver(params: {const nextLength = nextIds.length;if (length === nextLength) return;+ // A departing group member leaves its share to the rest of its group,+ // so the group keeps its overall size and other units are unaffected.+ // The group also reclaims the gutter the departing panel frees —+ // mirroring the join-time absorption — so other panels' pixel widths+ // survive an engage/disengage round-trip exactly. The proportional+ // renormalization below then only fixes drift.+ const dropped = panelData[id];+ const groupMemberIds =+ dropped?.shareGroup === undefined+ ? []+ : nextIds.filter(+ (x) => panelData[x]?.shareGroup === dropped.shareGroup+ );+ if (groupMemberIds.length > 0 && dropped.share > 0) {+ const memberSum = sumArray(+ groupMemberIds.map((x) => panelData[x].share)+ );+ const usableBefore = getUsable(length, params.size(), params.gutter());+ const usableAfter = getUsable(+ nextLength,+ params.size(),+ params.gutter()+ );+ if (usableBefore > 0 && usableAfter > 0) {+ const groupShare = memberSum + dropped.share;+ const nextGroupShare =+ (groupShare * usableBefore + params.gutter()) / usableAfter;+ const rescale = usableBefore / usableAfter;+ const memberIdSet = new Set(groupMemberIds);+ for (const x of nextIds) {+ if (!memberIdSet.has(x)) panelData[x].share *= rescale;+ }+ for (const x of groupMemberIds) {+ const weight =+ memberSum > 0+ ? panelData[x].share / memberSum+ : 1 / groupMemberIds.length;+ panelData[x].share = nextGroupShare * weight;+ }+ } else {+ // Zone size unknown: fall back to a plain within-group hand-off.+ for (const x of groupMemberIds) {+ const weight =+ memberSum > 0+ ? panelData[x].share / memberSum+ : 1 / groupMemberIds.length;+ panelData[x].share += dropped.share * weight;+ }+ }+ }+const sum = sumArray(nextIds.map((id) => untrack(() => panelData[id]?.share ?? 0)));@@ -489,7 +658,13 @@ export function createResizeSolver(params: {const L = ndx;const R = ndx + 1;- const shares = ids.map((id) => panelData[id]!.share);+ // Drags anchor to the RENDERED layout (what the user sees), which can+ // differ from the intent shares when constraints or pins are active.+ // The dragged result is then written back as the new intent below —+ // manual resizing is the one interaction that redefines intent from+ // rendered reality.+ const rendered = untrack(layout).shares;+ const shares = ids.map((id) => rendered.get(id) ?? panelData[id]!.share);const bounds = (i: number) => {if (i < 0 || i >= panels.length) return [0, 0];@@ -505,6 +680,115 @@ export function createResizeSolver(params: {return Math.max(0, maxS - shares[i]);};+ /**+ * The preferred share a grouped panel soft-pins to during gutter drags,+ * or undefined for panels without one.+ */+ const preferredShare = (i: number): number | undefined => {+ const panel = panels[i];+ const preferred = panel.redistributionPreferredSize;+ if (+ panel.shareGroup === undefined ||+ preferred === undefined ||+ !Number.isFinite(preferred)+ ) {+ return undefined;+ }+ const px = Math.min(Math.max(preferred, panel.minSize), panel.maxSize);+ return px / usable;+ };++ /** Contiguous group-mates of panel `i`, walking in direction `dir`. */+ const matesBeyond = (i: number, dir: 1 | -1): number[] => {+ const group = panels[i].shareGroup;+ if (group === undefined) return [];+ const mates: number[] = [];+ for (+ let j = i + dir;+ j >= 0 && j < n && panels[j].shareGroup === group;+ j += dir+ ) {+ mates.push(j);+ }+ return mates;+ };++ /**+ * Grow capacity of the handle's neighbor, including group-mates behind+ * it when growth cascades past a preferred size (see growFrom).+ */+ const growCapFrom = (i: number, dir: 1 | -1) => {+ const mates = preferredShare(i) === undefined ? [] : matesBeyond(i, dir);+ return growCap(i) + sumArray(mates.map(growCap));+ };++ /**+ * Grow the handle's neighbor `i` by `amount`. A grouped panel with a+ * preferred size (a preview Controller) soft-caps at that preferred size: overflow flows+ * to its group-mates beyond it (its Viewer) rather than growing it past+ * its configured width. Dragging the group's own internal gutter is+ * unaffected — there the mates sit on the handle side, so the neighbor+ * grows directly.+ */+ const growFrom = (+ newShares: number[],+ i: number,+ dir: 1 | -1,+ amount: number+ ) => {+ const preferred = preferredShare(i);+ const mates = preferred === undefined ? [] : matesBeyond(i, dir);+ if (preferred === undefined || mates.length === 0) {+ newShares[i] += amount;+ return;+ }+ const softCap = Math.max(preferred, newShares[i]);+ const direct = Math.min(amount, Math.max(0, softCap - newShares[i]));+ newShares[i] += direct;+ let remain = amount - direct;+ for (const j of mates) {+ if (remain <= EPSILON) break;+ const [, maxS] = bounds(j);+ const take = Math.min(remain, Math.max(0, maxS - newShares[j]));+ newShares[j] += take;+ remain -= take;+ }+ // Group-mates saturated: the rest lands on the neighbor after all.+ newShares[i] += remain;+ };++ /**+ * Shrink the stack starting at `from`, walking away from the handle.+ * Grouped panels with a preferred size hold it while their elastic+ * group-mates give space (pass 1); only when the whole stack is+ * otherwise exhausted do they shrink below it to their minimum (pass 2).+ */+ const shrinkStack = (+ newShares: number[],+ from: number,+ dir: 1 | -1,+ amount: number+ ) => {+ let remain = amount;+ for (let i = from; i >= 0 && i < n && remain > EPSILON; i += dir) {+ const [minS] = bounds(i);+ const preferred = preferredShare(i);+ const floor =+ preferred === undefined+ ? minS+ : Math.max(minS, Math.min(preferred, newShares[i]));+ const take = Math.min(Math.max(0, newShares[i] - floor), remain);+ newShares[i] -= take;+ remain -= take;+ }+ for (let i = from; i >= 0 && i < n && remain > EPSILON; i += dir) {+ const [minS] = bounds(i);+ const take = Math.min(Math.max(0, newShares[i] - minS), remain);+ newShares[i] -= take;+ remain -= take;+ }+ };+const shrinkCapLeftStack = () => {let cap = 0;for (let i = L; i >= 0; i--) {@@ -524,49 +808,32 @@ export function createResizeSolver(params: {};if (dShare < 0) {- // Move LEFT: shrink LEFT stack, grow RIGHT (R only)+ // Move LEFT: shrink LEFT stack, grow RIGHTconst req = -dShare;const capShrinkLeft = shrinkCapLeftStack();- const capGrowR = growCap(R);+ const capGrowR = growCapFrom(R, 1);const applied = Math.min(req, capShrinkLeft, capGrowR);if (applied <= 0) return;const newShares = shares.slice();// shrink from the handle outward: L, L-1, L-2, ...- let remain = applied;- for (let i = L; i >= 0 && remain > EPSILON; i--) {- const [minS] = bounds(i);- const take = Math.min(newShares[i] - minS, remain);- if (take > 0) {- newShares[i] -= take;- remain -= take;- }- }- // grow immediate right neighbor only- newShares[R] += applied;+ shrinkStack(newShares, L, -1, applied);+ growFrom(newShares, R, 1, applied);for (let i = 0; i < n; i++) {panelData[ids[i]].share = newShares[i];}} else {- // dShare > 0: Move RIGHT: shrink RIGHT stack, grow LEFT (L only)+ // dShare > 0: Move RIGHT: shrink RIGHT stack, grow LEFTconst req = dShare;const capShrinkRight = shrinkCapRightStack();- const capGrowL = growCap(L);+ const capGrowL = growCapFrom(L, -1);const applied = Math.min(req, capShrinkRight, capGrowL);if (applied <= 0) return;const newShares = shares.slice();- let remain = applied;- for (let i = R; i < n && remain > EPSILON; i++) {- const [minS] = bounds(i);- const take = Math.min(newShares[i] - minS, remain);- if (take > 0) {- newShares[i] -= take;- remain -= take;- }- }- newShares[L] += applied;+ shrinkStack(newShares, R, 1, applied);+ growFrom(newShares, L, -1, applied);for (let i = 0; i < n; i++) {panelData[ids[i]].share = newShares[i];@@ -591,9 +858,23 @@ export function createResizeSolver(params: {solve: layout,reset: () => {const panels = panelsInOrder();- const n = panels.length;+ const units = countUnits(panels);+ if (units === 0) return;+ const groupSizes = new Map<string, number>();+ for (const panel of panels) {+ if (panel.shareGroup !== undefined) {+ groupSizes.set(+ panel.shareGroup,+ (groupSizes.get(panel.shareGroup) ?? 0) + 1+ );+ }+ }+ // Equal share per unit; group members split their unit's share.for (const panel of panels) {- panelData[panel.id].share = 1 / n;+ panelData[panel.id].share =+ panel.shareGroup === undefined+ ? 1 / units+ : 1 / units / groupSizes.get(panel.shareGroup)!;}setDirty();},diff --git a/apps/web/src/lib/core/component/Resize/types.ts b/apps/web/src/lib/core/component/Resize/types.tsindex f2d3303ce2..1d18fac5a8 100644--- a/apps/web/src/lib/core/component/Resize/types.ts+++ b/apps/web/src/lib/core/component/Resize/types.ts@@ -18,6 +18,8 @@ export type Panel = {minSize: number;maxSize: number;redistributionPreferredSize?: number;+ /** Panels with the same key form one layout unit for automatic sizing. */+ shareGroup?: string;share: number;target: PanelSizeSpec;};@@ -27,6 +29,7 @@ export type PanelConfig = {minSize?: number;maxSize?: number;redistributionPreferredSize?: number;+ shareGroup?: string;target?: PanelSizeSpec;};@@ -46,6 +49,7 @@ export type ResizeZoneCtx = {minSize?: number;maxSize?: number;redistributionPreferredSize?: number;+ shareGroup?: string;}) => void;gutterSize: () => number;