Skip to content

Commit

Permalink
Normalize layouts not totalling to 100%
Browse files Browse the repository at this point in the history
Resolves bvaughn#227
  • Loading branch information
Timur Sufiev committed Dec 7, 2023
1 parent 1133472 commit b7e05d2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,25 @@ describe("validatePanelGroupLayout", () => {
).toEqual([10, 60, 30]);
});

it("should reject layouts that do not total 100%", () => {
verifyExpectedWarnings(
() =>
validatePanelGroupLayout({
groupSizePixels: NaN,
layout: [10, 20, 30],
panelConstraints: [{}, {}, {}],
}),
"Invalid layout total size"
);
it("should normalize layouts that do not total 100%", () => {
let layout;
verifyExpectedWarnings(() => {
layout = validatePanelGroupLayout({
groupSizePixels: NaN,
layout: [10, 20, 20],
panelConstraints: [{}, {}, {}],
});
}, "Invalid layout total size");
expect(layout).toEqual([20, 40, 40]);

verifyExpectedWarnings(
() =>
validatePanelGroupLayout({
groupSizePixels: NaN,
layout: [50, 100, 150],
panelConstraints: [{}, {}, {}],
}),
"Invalid layout total size"
);
verifyExpectedWarnings(() => {
layout = validatePanelGroupLayout({
groupSizePixels: NaN,
layout: [50, 100, 50],
panelConstraints: [{}, {}, {}],
});
}, "Invalid layout total size");
expect(layout).toEqual([25, 50, 25]);
});

it("should reject layouts that do not match the number of panels", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export function validatePanelGroupLayout({
panelConstraints: PanelConstraints[];
}): number[] {
const nextLayout = [...prevLayout];
const nextLayoutTotalSize = nextLayout.reduce(
(accumulated, current) => accumulated + current,
0
);

// Validate layout expectations
if (nextLayout.length !== panelConstraints.length) {
Expand All @@ -22,21 +26,21 @@ export function validatePanelGroupLayout({
.map((size) => `${size}%`)
.join(", ")}`
);
} else if (
!fuzzyNumbersEqual(
nextLayout.reduce((accumulated, current) => accumulated + current, 0),
100
)
) {
} else if (!fuzzyNumbersEqual(nextLayoutTotalSize, 100)) {
// This is not ideal so we should warn about it, but it may be recoverable in some cases
// (especially if the amount is small)
if (isDevelopment) {
console.warn(
`WARNING: Invalid layout total size: ${nextLayout
.map((size) => `${size}%`)
.join(", ")}`
.join(", ")}. Layout normalization will be applied.`
);
}
for (let index = 0; index < panelConstraints.length; index++) {
const unsafeSize = nextLayout[index]!;
const safeSize = (100 / nextLayoutTotalSize) * unsafeSize;
nextLayout[index] = safeSize;
}
}

let remainingSize = 0;
Expand Down

0 comments on commit b7e05d2

Please sign in to comment.