Edit text-variable-anchor-offset as a list of anchors with offsets (#2393)

`text-variable-anchor-offset` is the only layer property whose spec
type, `variableAnchorOffsetCollection`, had no input. `InputSpec` fell
through to its `default` case, so the layer editor showed the label with
nothing next to it, even when the layer had a value. It also logged `No
proper field input for text-variable-anchor-offset` on every render
(mentioned in #1524). HarelM suggested looking for spec properties that
maputnik doesn't support yet in #2391, and this is the one I found for
layers.

The value is a flat list of anchors, each followed by its `[x, y]`
offset, e.g. `["top", [0, 4], "left", [3, 0]]`. The new
`InputVariableAnchorOffsetCollection` shows one row per anchor: an
anchor dropdown (the same nine values as `text-variable-anchor`), then
the x and y offsets. It reuses the add/remove row layout and the delete
button from `InputDynamicArray`. "Add value" appends `center` with `[0,
0]`, and removing the last row unsets the property.

`FieldFunction` used to route every value of this type to the plain
input, including expressions. It now does that only for a literal list
(`isVariableAnchorOffsetCollection` in `spec-helper.ts`). An expression,
including the `["literal", ...]` that "Convert to expression" produces,
opens the expression editor as it does for other properties.

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

Both show a symbol layer with `"text-variable-anchor-offset": ["top",
[0, 1], "left", [2, 0]]` in Chromium.

**Performance:** none. The input only renders for this one property, and
the type check is a single pass over a short array.

## Launch Checklist

 - [x] Briefly describe the changes in this PR.
- [x] Link to related issues: #1524 (the console warning), follow-up to
#2391.
- [x] Include before/after visuals or gifs if this PR includes visual
changes.
- [x] Write tests for all new functionality: three e2e tests in
`layers-list.spec.ts` (save an anchor with its offset, change the
anchor, remove a row) and a unit test for
`isVariableAnchorOffsetCollection`. All three e2e tests fail on `main`,
and the anchor and remove tests fail when I change the expected anchor
or skip the delete.
 - [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 the full `npx playwright test` (213
passed). I also checked it in the dev server: editing an offset,
changing an anchor, adding and removing rows all save to the style, and
a layer whose value is a `case` expression opens in the expression
editor.

Assisted-By: Claude Opus 5.5 (Claude Code). It helped write the change,
the tests 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 07:51:16 +02:00
1 parent 3a5d9aee9e
commit c9f44b0cd6
9 files changed
+183 -4

No files matched your search

+1
View File
@@ -10,6 +10,7 @@
- Add `font-faces`, `sky`, `roll` and `centerAltitude` to the style settings modal
- The sidebar can now be resized, both as a whole and in the split between the layer list and the layer editor
- Allow viewing and changing the map's max zoom in the debug modal
- Edit `text-variable-anchor-offset` as a list of anchors, each with an x and y offset; it previously showed no input
- _...Add new stuff here..._
### 🐞 Bug fixes
+31
View File
@@ -228,6 +228,37 @@ describe("layers list", () => {
await then(get.propertyArrayAddButton("spec-field:icon-padding")).shouldNotExist();
});
describe("text-variable-anchor-offset", () => {
let id: string;
beforeEach(async () => {
id = await when.modal.fillLayers({ type: "symbol", layer: "example" });
// the new pair's last input is its y offset
await when.addValueToPropertyArray("spec-field:text-variable-anchor-offset", "4");
});
test("should save an anchor with its offset", async () => {
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
layers: [{ id, layout: { "text-variable-anchor-offset": ["center", [0, 4]] } }],
});
});
test("should save a changed anchor", async () => {
await when.selectWithin("spec-field:text-variable-anchor-offset", "top");
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
layers: [{ id, layout: { "text-variable-anchor-offset": ["top", [0, 4]] } }],
});
});
test("should remove an anchor row", async () => {
// the row's delete button shares the function stop's class
await when.deleteFunctionStop("text-variable-anchor-offset");
await then(get.element("[data-wd-key='spec-field:text-variable-anchor-offset'] select")).shouldNotExist();
});
});
});
describe("raster", () => {
+2 -2
View File
@@ -5,7 +5,7 @@ import { DataProperty, type Stop } from "./DataProperty";
import { ZoomProperty } from "./ZoomProperty";
import { ExpressionProperty } from "./ExpressionProperty";
import {function as styleFunction} from "@maplibre/maplibre-gl-style-spec";
import {findDefaultFromSpec} from "../libs/spec-helper";
import {findDefaultFromSpec, isVariableAnchorOffsetCollection} from "../libs/spec-helper";
import { type MappedLayerErrors } from "../libs/definitions";
@@ -100,7 +100,7 @@ function getDataType(value: any, fieldSpec={} as any) {
else if (fieldSpec.type === "padding") {
return "value";
}
else if (fieldSpec.type === "variableAnchorOffsetCollection") {
else if (fieldSpec.type === "variableAnchorOffsetCollection" && isVariableAnchorOffsetCollection(value)) {
return "value";
}
else if (isZoomField(value)) {
+1 -1
View File
@@ -150,7 +150,7 @@ type DeleteValueInputButtonProps = {
onClick?(...args: unknown[]): unknown
} & WithTranslation;
class DeleteValueInputButton extends React.Component<DeleteValueInputButtonProps> {
export class DeleteValueInputButton extends React.Component<DeleteValueInputButtonProps> {
render() {
const t = this.props.t;
return <InputButton
+6
View File
@@ -9,6 +9,7 @@ import { InputDynamicArray, type InputDynamicArrayProps } from "./InputDynamicAr
import { InputFont, type InputFontProps } from "./InputFont";
import { InputEnum, type InputEnumProps } from "./InputEnum";
import { InputSprite } from "./InputSprite";
import { InputVariableAnchorOffsetCollection, type InputVariableAnchorOffsetCollectionProps } from "./InputVariableAnchorOffsetCollection";
import capitalize from "lodash.capitalize";
const iconProperties = ["background-pattern", "fill-pattern", "line-pattern", "fill-extrusion-pattern", "icon-image"];
@@ -129,6 +130,11 @@ export class InputSpec extends React.Component<InputSpecProps> {
value={(Array.isArray(this.props.value) ? this.props.value : [this.props.value]) as (string | number | undefined)[]}
/>
);
case "variableAnchorOffsetCollection": return (
<InputVariableAnchorOffsetCollection
{...commonProps as InputVariableAnchorOffsetCollectionProps}
/>
);
default:
console.warn(`No proper field input for ${this.props.fieldName} type: ${this.props.fieldSpec?.type}`);
return null;
@@ -0,0 +1,102 @@
import React from "react";
import capitalize from "lodash.capitalize";
import { type WithTranslation, withTranslation } from "react-i18next";
import latest from "@maplibre/maplibre-gl-style-spec/dist/latest.json";
import { InputNumber } from "./InputNumber";
import { InputEnum } from "./InputEnum";
import { InputButton } from "./InputButton";
import { DeleteValueInputButton } from "./InputDynamicArray";
import { type VariableAnchorOffsetCollection } from "../libs/spec-helper";
const anchorOptions = Object.keys(latest.layout_symbol["text-variable-anchor"].values).map(v => [v, capitalize(v)]);
export type InputVariableAnchorOffsetCollectionProps = {
value?: VariableAnchorOffsetCollection
onChange?(value: VariableAnchorOffsetCollection | undefined): unknown
"aria-label"?: string
label?: string
};
type InputVariableAnchorOffsetCollectionInternalProps = InputVariableAnchorOffsetCollectionProps & WithTranslation;
/** Edits the anchor and offset pairs of a `text-variable-anchor-offset` value, one row per anchor */
class InputVariableAnchorOffsetCollectionInternal extends React.Component<InputVariableAnchorOffsetCollectionInternalProps> {
get values(): VariableAnchorOffsetCollection {
return this.props.value || [];
}
changeAnchor(pairIdx: number, anchor: string) {
const values = this.values.slice(0);
values[pairIdx * 2] = anchor;
this.props.onChange?.(values);
}
changeOffset(pairIdx: number, axis: 0 | 1, newValue: number | undefined) {
const values = this.values.slice(0);
const offset = (values[pairIdx * 2 + 1] as [number, number]).slice(0) as [number, number];
offset[axis] = newValue ?? 0;
values[pairIdx * 2 + 1] = offset;
this.props.onChange?.(values);
}
addValue = () => {
this.props.onChange?.([...this.values, anchorOptions[0][0], [0, 0]]);
};
deleteValue(pairIdx: number) {
const values = this.values.slice(0);
values.splice(pairIdx * 2, 2);
this.props.onChange?.(values.length > 0 ? values : undefined);
}
render() {
const t = this.props.t;
const i18nProps = { t, i18n: this.props.i18n, tReady: this.props.tReady };
const label = this.props["aria-label"] || this.props.label;
const rows = [];
for (let i = 0; i < this.values.length / 2; i++) {
const anchor = this.values[i * 2] as string;
const [x, y] = this.values[i * 2 + 1] as [number, number];
rows.push(<div key={i} className="maputnik-array-block">
<div className="maputnik-array-block-action">
<DeleteValueInputButton onClick={() => this.deleteValue(i)} {...i18nProps} />
</div>
<div className="maputnik-array-block-content">
<div className="maputnik-variable-anchor-offset">
<InputEnum
options={anchorOptions}
value={anchor}
onChange={(v) => this.changeAnchor(i, v as string)}
aria-label={label}
/>
<InputNumber
value={x}
onChange={(v) => this.changeOffset(i, 0, v)}
aria-label={label}
/>
<InputNumber
value={y}
onChange={(v) => this.changeOffset(i, 1, v)}
aria-label={label}
/>
</div>
</div>
</div>);
}
return (
<div className="maputnik-array">
{rows}
<InputButton
className="maputnik-array-add-value"
onClick={this.addValue}
>
{t("Add value")}
</InputButton>
</div>
);
}
}
export const InputVariableAnchorOffsetCollection = withTranslation()(InputVariableAnchorOffsetCollectionInternal);
+14 -1
View File
@@ -1,5 +1,18 @@
import { describe, it, expect } from "vitest";
import { findDefaultFromSpec } from "./spec-helper";
import { findDefaultFromSpec, isVariableAnchorOffsetCollection } from "./spec-helper";
describe("isVariableAnchorOffsetCollection", () => {
it("accepts anchors alternating with [x, y] offsets", () => {
expect(isVariableAnchorOffsetCollection(["top", [0, 4], "left", [3, 0]])).toBe(true);
});
it("rejects expressions and malformed lists", () => {
expect(isVariableAnchorOffsetCollection(["literal", ["top", [0, 4]]])).toBe(false);
expect(isVariableAnchorOffsetCollection(["case", ["has", "name"], ["literal", ["top", [0, 4]]], ["literal", ["left", [3, 0]]]])).toBe(false);
expect(isVariableAnchorOffsetCollection(["top", [0, 4], "left"])).toBe(false);
expect(isVariableAnchorOffsetCollection(["top", [0]])).toBe(false);
});
});
describe("findDefaultFromSpec", () => {
it("returns the spec default when present (even if falsy)", () => {
+11
View File
@@ -1,3 +1,14 @@
/** A `text-variable-anchor-offset` value: anchors alternating with their `[x, y]` offsets */
export type VariableAnchorOffsetCollection = (string | [number, number])[];
/** Whether `value` is a literal anchor and offset list rather than an expression */
export function isVariableAnchorOffsetCollection(value: unknown): value is VariableAnchorOffsetCollection {
return Array.isArray(value) && value.length % 2 === 0 && value.every((item, i) => i % 2 === 0
? typeof item === "string"
: Array.isArray(item) && item.length === 2 && item.every(n => typeof n === "number")
);
}
/**
* If we don't have a default value just make one up
*/
+15
View File
@@ -95,6 +95,21 @@
display: inline-block;
float: right;
}
// an anchor dropdown followed by its x and y offsets
.maputnik-variable-anchor-offset {
display: flex;
gap: vars.$margin-2;
> * {
flex: 1;
min-width: 0;
}
> :first-child {
flex: 2;
}
}
}
// SELECT