Keep the color picker within the viewport (#2398)

Fixes #717.

The color picker opened at a fixed offset next to its input
(`calcPickerOffset`), so near the bottom or right edge of the window
part of it was cut off. It now measures the panel after it opens and
places it on the inline-end side of the input (the right in LTR, the
left in RTL), switching sides only when there's no room, then clamps it
inside the viewport with an 8px margin. It repositions on resize and
scroll while open, and on very short windows the panel scrolls instead
of overflowing. The panel stays hidden for the first render until it has
a position, so it doesn't flash at the old spot.

| Before | After |
|---|---|
|
![before](https://raw.githubusercontent.com/KhadeerBasha1232/maputnik/pr-assets/pr-2398/before.png)
|
![after](https://raw.githubusercontent.com/KhadeerBasha1232/maputnik/pr-assets/pr-2398/after.png)
|

Both open the `background-color` picker with the field at the bottom of
a 1280px-wide window, in Chromium.

In the issue, orangemug suggested opening the picker inside the editor
panel instead of over the map. I kept the existing popover here because
that's a much smaller change and fixes the clipping on its own; moving
the picker into the panel would change the layout of every color field.

**Performance:** the resize and scroll listeners are only attached while
a picker is open and are removed when it closes or unmounts. Each event
does two `getBoundingClientRect` calls and only sets state when the
position actually changes.

## Launch Checklist

 - [x] Briefly describe the changes in this PR.
 - [x] Link to related issues: fixes #717.
- [x] Include before/after visuals or gifs if this PR includes visual
changes.
- [x] Write tests for all new functionality: two e2e tests in
`layer-editor.spec.ts`. One opens the picker with its field at the
bottom of the window and checks the whole picker is in the viewport; it
fails on `main`. The other switches to Hebrew and checks the picker
opens to the left of its field; it fails when I force the LTR side.
`shouldBeInViewport` in the helper now takes an optional ratio for the
first one.
 - [x] Add an entry to `CHANGELOG.md` under the `## main` section.

Tested locally: `npm run lint` clean, `npx tsc --noEmit` clean, `npx
vitest run` (57 passed) and `npx playwright test
e2e/layer-editor.spec.ts e2e/sprite-picker.spec.ts` (75 passed;
`sprite-picker` also uses `shouldBeInViewport`). The new test fails when
I run it against `main`. I didn't run the full e2e suite locally (it
times out on Windows with several workers); it passes in CI on this PR.

Assisted-By: Claude Opus 5.5 (Claude Code). It helped write the change,
the test and this description. I've reviewed and tested the change and
can answer questions about it.
This commit is contained in:
SHAIK KHADEER BASHA authored and GitHub committed 2026-12-04 12:02:08 +02:00
1 parent 3e6e558d63
commit 87fe93bc03
5 files changed
+118 -26

No files matched your search

+1
View File
@@ -15,6 +15,7 @@
- _...Add new stuff here..._
### 🐞 Bug fixes
- Keep the color picker within the viewport when opening it near an edge, scrolling, or resizing.
- Apply layer renames when pressing Enter or leaving the ID field to avoid validating and saving the style on every keystroke.
- Add distinct screen reader labels for the anchor, X offset, and Y offset in each variable anchor offset row.
- Open `icon-padding` expressions in the expression editor so they can be viewed and edited.
+17
View File
@@ -178,6 +178,23 @@ describe("layer editor", () => {
});
});
test("keeps the whole color picker visible when opened near the bottom", async () => {
const bgId = await createBackground();
await when.click("layer-list-item:background:" + bgId);
await when.openColorPickerAtBottom("background-color");
await then(get.colorPicker()).shouldBeInViewport(1);
});
test("opens the color picker to the left of its field in a right-to-left language", async () => {
const bgId = await createBackground();
await when.select("maputnik-lang-select", "he");
await when.click("layer-list-item:background:" + bgId);
await when.openColorPicker("background-color");
await then(get.colorPickerSide("background-color")).shouldEqual("left");
});
describe("opacity", () => {
let bgId: string;
beforeEach(async () => {
+25
View File
@@ -373,6 +373,16 @@ export class MaputnikDriver {
await input.fill(value);
},
openColorPicker: async (fieldName: string) => {
await this.helper.get.elementByTestId("spec-field:" + fieldName).locator(".maputnik-color").click();
},
openColorPickerAtBottom: async (fieldName: string) => {
const input = this.helper.get.elementByTestId("spec-field:" + fieldName).locator(".maputnik-color");
await input.evaluate(element => element.scrollIntoView({ block: "end" }));
await input.click();
},
/** Sets a plain string spec field (e.g. a pattern), which has no dedicated input test id. */
setStringValue: async (fieldName: string, value: string) => {
const input = this.helper.get.elementByTestId("spec-field:" + fieldName).locator("input.maputnik-string");
@@ -404,6 +414,21 @@ export class MaputnikDriver {
spriteOptions: () => this.helper.get.element(".maputnik-sprite-option"),
colorPicker: () => this.helper.get.element(".chrome-picker"),
/** Which side of its input the open color picker sits next to: "left", "right", or "neither" when it isn't beside it. */
colorPickerSide: (fieldName: string) => this.helper.query(async () => {
const input = await this.helper.get.elementByTestId("spec-field:" + fieldName).locator(".maputnik-color").boundingBox();
const picker = await this.helper.get.element(".chrome-picker").boundingBox();
if (!input || !picker) throw new Error("The color picker is not open");
const maxGap = 16;
const gapOnLeft = input.x - (picker.x + picker.width);
const gapOnRight = picker.x - (input.x + input.width);
if (gapOnLeft >= 0 && gapOnLeft <= maxGap) return "left";
if (gapOnRight >= 0 && gapOnRight <= maxGap) return "right";
return "neither";
}),
spritePixel: (id: string, x: number, y: number) => this.helper.get.canvasPixel(`sprite-preview:${id}`, x, y),
canvas: () => this.helper.get.element("canvas"),
+2 -1
View File
@@ -105,7 +105,8 @@ export class Assertable<T> {
}
};
shouldNotExist = () => expect(this.locator()).toHaveCount(0);
shouldBeInViewport = () => expect(this.locator().first()).toBeInViewport();
/** `ratio` is the share of the element that must be visible; 1 means all of it. */
shouldBeInViewport = (ratio?: number) => expect(this.locator().first()).toBeInViewport({ ratio });
shouldBeFocused = () => expect(this.locator().first()).toBeFocused();
shouldNotBeFocused = () => expect(this.locator().first()).not.toBeFocused();
shouldHaveValue = (value: string) => expect(this.locator().first()).toHaveValue(value);
+73 -25
View File
@@ -3,6 +3,8 @@ import Color from "color";
import {ChromePicker, type ColorResult} from "react-color";
import lodash from "lodash";
const viewportMargin = 8;
function formatColor(color: ColorResult): string {
const rgb = color.rgb;
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${rgb.a})`;
@@ -19,11 +21,17 @@ export type InputColorProps = {
};
/*** Number fields with support for min, max and units and documentation*/
export class InputColor extends React.Component<InputColorProps> {
state = {
type InputColorState = {
pickerOpened: boolean
pickerPosition?: { end: number, top: number }
};
export class InputColor extends React.Component<InputColorProps, InputColorState> {
state: InputColorState = {
pickerOpened: false
};
colorInput: HTMLInputElement | null = null;
pickerPanel = React.createRef<HTMLDivElement>();
constructor (props: InputColorProps) {
super(props);
@@ -34,27 +42,54 @@ export class InputColor extends React.Component<InputColorProps> {
this.props.onChange(v);
}
//TODO: I much rather would do this with absolute positioning
//but I am too stupid to get it to work together with fixed position
//and scrollbars so I have to fallback to JavaScript
calcPickerOffset = () => {
const elem = this.colorInput;
if(elem) {
const pos = elem.getBoundingClientRect();
return {
top: pos.top,
left: pos.left + 196,
};
componentDidUpdate(_previousProps: InputColorProps, previousState: InputColorState) {
if (previousState.pickerOpened === this.state.pickerOpened) return;
if (this.state.pickerOpened) {
this.positionPicker();
window.addEventListener("resize", this.positionPicker);
window.addEventListener("scroll", this.positionPicker, true);
} else {
return {
top: 160,
left: 555,
};
this.removePositionListeners();
}
}
componentWillUnmount() {
this.removePositionListeners();
}
removePositionListeners() {
window.removeEventListener("resize", this.positionPicker);
window.removeEventListener("scroll", this.positionPicker, true);
}
positionPicker = () => {
const input = this.colorInput;
const panel = this.pickerPanel.current;
if (!input || !panel) return;
const anchor = input.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const viewport = document.documentElement;
const isRtl = getComputedStyle(panel).direction === "rtl";
// Inline offsets are measured from the viewport's inline-end edge (the right in LTR, the left in RTL),
// so the same placement works in both directions.
const anchorEnd = isRtl ? anchor.left : viewport.clientWidth - anchor.right;
const maxEnd = viewport.clientWidth - width - viewportMargin;
const maxTop = viewport.clientHeight - height - viewportMargin;
const preferredEnd = anchorEnd - width - viewportMargin;
const alternativeEnd = anchorEnd + anchor.width + viewportMargin;
const fitsBetterAtStart = preferredEnd < viewportMargin && alternativeEnd <= maxEnd;
const end = Math.max(viewportMargin, Math.min(maxEnd, fitsBetterAtStart ? alternativeEnd : preferredEnd));
const top = Math.max(viewportMargin, Math.min(maxTop, anchor.top));
if (this.state.pickerPosition?.end !== end || this.state.pickerPosition?.top !== top) {
this.setState({ pickerPosition: { end, top } });
}
};
togglePicker = () => {
this.setState({ pickerOpened: !this.state.pickerOpened });
this.setState(({ pickerOpened }) => ({ pickerOpened: !pickerOpened, pickerPosition: undefined }));
};
get color() {
@@ -73,7 +108,7 @@ export class InputColor extends React.Component<InputColorProps> {
}
render() {
const offset = this.calcPickerOffset();
const position = this.state.pickerPosition;
const currentColor = this.color.object();
const currentChromeColor = {
r: currentColor.r,
@@ -88,13 +123,26 @@ export class InputColor extends React.Component<InputColorProps> {
style={{
position: "fixed",
zIndex: 1,
left: offset.left,
top: offset.top,
insetInlineEnd: position?.end,
top: position?.top,
visibility: position ? "visible" : "hidden",
}}>
<ChromePicker
color={currentChromeColor}
onChange={c => this.onChangeNoCheck(formatColor(c))}
/>
<div
ref={this.pickerPanel}
className="maputnik-color-picker-panel"
style={{
width: "225px",
maxWidth: `calc(100vw - ${viewportMargin * 2}px)`,
maxHeight: `calc(100vh - ${viewportMargin * 2}px)`,
overflow: "auto",
}}
>
<ChromePicker
styles={{ default: { picker: { width: "100%" } } }}
color={currentChromeColor}
onChange={c => this.onChangeNoCheck(formatColor(c))}
/>
</div>
<div
className="maputnik-color-picker-offset"
onClick={this.togglePicker}