mirror of
https://github.com/maputnik/editor.git
synced 2026-11-27 04:23:45 +00:00
feat: preview sprites in the icon-image picker (#2359)
## Description Add a dedicated sprite autocomplete for literal `icon-image` values. Each searchable option shows its thumbnail and name, and selection keeps the original sprite ID in the style. Keyboard selection and free-form text remain available; expressions continue to use the existing expression editor. Pattern fields keep their existing inputs. The preview uses atlas bounds and pixel ratios. SDF sprites are decoded into neutral black silhouettes using MapLibre's distance-field contour, rather than displaying the distance bitmap. This is a catalog preview, not a rendering of the layer's data/zoom-dependent paint or halos. Sprite arrays retain MapLibre namespaces, and URL query parameters remain after the JSON/PNG extension. Metadata responses from a previous style are ignored after the sprite source changes. Missing atlas images leave the names usable. The menu opens above the field when there is not enough space below it. Fixes #1294. Implements the scope proposed in the issue and welcomed by CommanderStorm; follows #1792's request for a separate sprite input with images in the option rows. No new dependencies or changes to the generic `InputAutocomplete` component. ## Visuals | Before | After | | --- | --- | |  |  | SDF preview beside the actual MapLibre render of the selected fixture:  [Isolated screenshots and provenance](https://github.com/jjohnnystwsss/maputnik/tree/d368f3509fbb7c308ecdce6c97701af982bff14c) (not part of the feature diff). ## Verification - Five new pure-logic tests cover URL handling, metadata namespaces/bounds, empty sources and SDF alpha conversion; all 55 unit tests pass. - Fifteen new driver-based browser cases cover actual option pixels, search, mouse/keyboard selection, viewport placement, persisted style values, expression editing, sprite replacement/removal, namespaces, broken images and delayed old responses. - On the untouched base, the thumbnail assertion fails while all four text options are present. - Deliberately changing the expected thumbnail color fails; disabling the stale-response guard also fails. Both mutations were reverted. - Full official `npm test -- --workers 2`: all 199 cases pass (184 existing + 15 new). Lint, SCSS lint and type-checked production build: passed. Small sprite fixtures were authored for this change and carry the repository's MIT license. No external tile, sprite or paid service is required by the new cases. Codex assisted with the design, implementation and tests; the preview and actual map output were inspected locally. ## Launch Checklist - [x] Briefly describe the changes in this PR. - [x] Link to related issues. - [x] Include before/after visuals or gifs if this PR includes visual changes. - [x] Write tests for all new functionality. - [x] Add an entry to `CHANGELOG.md` under the `## main` section. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
## main
|
||||
|
||||
### ✨ Features and improvements
|
||||
- Preview sprites in the icon-image dropdown, with searchable names and keyboard selection
|
||||
- Replace Cypress with Playwright for end-to-end tests and Vitest browser mode (Playwright provider) for component tests; drop the `@shellygo/cypress-test-utils` helper in favour of a `MaputnikDriver` page object
|
||||
- Upgrade to MapLibre GL JS 6 and Vite 8, and update the remaining dependencies
|
||||
- Remove the RTL text plugin, since MapLibre GL JS now renders right-to-left text natively
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": 8,
|
||||
"name": "Sprite preview test",
|
||||
"center": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"zoom": 0,
|
||||
"sources": {
|
||||
"points": {
|
||||
"type": "geojson",
|
||||
"data": {
|
||||
"type": "FeatureCollection",
|
||||
"features": [
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": {},
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": [
|
||||
0,
|
||||
0
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"sprite": "http://localhost:8888/sprite-alternate",
|
||||
"layers": [
|
||||
{
|
||||
"id": "symbols",
|
||||
"type": "symbol",
|
||||
"source": "points",
|
||||
"layout": {
|
||||
"icon-image": "red"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"blue": {
|
||||
"x": 64,
|
||||
"y": 0,
|
||||
"width": 32,
|
||||
"height": 32,
|
||||
"pixelRatio": 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"red": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 16,
|
||||
"height": 16,
|
||||
"pixelRatio": 1
|
||||
},
|
||||
"green": {
|
||||
"x": 16,
|
||||
"y": 0,
|
||||
"width": 16,
|
||||
"height": 16,
|
||||
"pixelRatio": 1
|
||||
},
|
||||
"sdf-circle": {
|
||||
"x": 32,
|
||||
"y": 0,
|
||||
"width": 32,
|
||||
"height": 32,
|
||||
"pixelRatio": 1,
|
||||
"sdf": true
|
||||
},
|
||||
"retina-square": {
|
||||
"x": 64,
|
||||
"y": 0,
|
||||
"width": 32,
|
||||
"height": 32,
|
||||
"pixelRatio": 2
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 712 B |
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"version": 8,
|
||||
"name": "Sprite preview test",
|
||||
"center": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"zoom": 0,
|
||||
"sources": {
|
||||
"points": {
|
||||
"type": "geojson",
|
||||
"data": {
|
||||
"type": "FeatureCollection",
|
||||
"features": [
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": {},
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": [
|
||||
0,
|
||||
0
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"layers": [
|
||||
{
|
||||
"id": "symbols",
|
||||
"type": "symbol",
|
||||
"source": "points",
|
||||
"layout": {
|
||||
"icon-image": "red"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Sprite fixtures authored for this test suite and distributed under the repository MIT license. The 96×32 atlas has red/green squares, an analytic circle distance field (alpha=0.75+signedDistance/8), and a blue 2× square. No third-party assets.
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"version": 8,
|
||||
"name": "Sprite preview test",
|
||||
"center": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"zoom": 0,
|
||||
"sources": {
|
||||
"points": {
|
||||
"type": "geojson",
|
||||
"data": {
|
||||
"type": "FeatureCollection",
|
||||
"features": [
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": {},
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": [
|
||||
0,
|
||||
0
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"sprite": [
|
||||
{
|
||||
"id": "default",
|
||||
"url": "http://localhost:8888/sprite-atlas?key=test"
|
||||
},
|
||||
{
|
||||
"id": "extra",
|
||||
"url": "http://localhost:8888/sprite-alternate"
|
||||
}
|
||||
],
|
||||
"layers": [
|
||||
{
|
||||
"id": "symbols",
|
||||
"type": "symbol",
|
||||
"source": "points",
|
||||
"layout": {
|
||||
"icon-image": "red"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": 8,
|
||||
"name": "Sprite preview test",
|
||||
"center": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"zoom": 0,
|
||||
"sources": {
|
||||
"points": {
|
||||
"type": "geojson",
|
||||
"data": {
|
||||
"type": "FeatureCollection",
|
||||
"features": [
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": {},
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": [
|
||||
0,
|
||||
0
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"sprite": "http://localhost:8888/sprite-atlas?key=test",
|
||||
"layers": [
|
||||
{
|
||||
"id": "symbols",
|
||||
"type": "symbol",
|
||||
"source": "points",
|
||||
"layout": {
|
||||
"icon-image": "red"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -30,6 +30,10 @@ export class MaputnikDriver {
|
||||
|
||||
setupMockBackedResponses: async () => {
|
||||
const styleFixtures = [
|
||||
"sprite-style.json",
|
||||
"sprite-alternate-style.json",
|
||||
"sprite-namespaced-style.json",
|
||||
"sprite-empty-style.json",
|
||||
"example-style.json",
|
||||
"example-layer-style.json",
|
||||
"geojson-style.json",
|
||||
@@ -51,6 +55,10 @@ export class MaputnikDriver {
|
||||
alias: fixture === "example-style.json" ? "example-style.json" : undefined,
|
||||
});
|
||||
}
|
||||
for (const atlas of ["sprite-atlas", "sprite-alternate"]) {
|
||||
await this.helper.given.interceptAndMockResponse({ method: "GET", url: new RegExp(`/${atlas}\\.json(?:\\?|$)`), response: { fixture: `${atlas}.json` } });
|
||||
await this.helper.given.interceptAndMockResponse({ method: "GET", url: new RegExp(`/${atlas}\\.png(?:\\?|$)`), response: { fixture: "sprite-atlas.png" } });
|
||||
}
|
||||
await this.helper.given.interceptAndMockResponse({ method: "GET", url: /example\.local\//, response: [] });
|
||||
await this.helper.given.interceptAndMockResponse({ method: "GET", url: /example\.com\//, response: [] });
|
||||
await this.helper.given.interceptAndMockResponse({
|
||||
@@ -71,6 +79,33 @@ export class MaputnikDriver {
|
||||
|
||||
modal: this.modalDriver.when,
|
||||
|
||||
openSpritePicker: async () => {
|
||||
await this.helper.when.click("layer-list-item:symbols");
|
||||
await this.helper.when.scrollIntoView("spec-field:icon-image");
|
||||
await this.helper.get.elementByTestId("spec-field:icon-image").locator("input").fill("");
|
||||
},
|
||||
|
||||
scrollSpritePickerToBottom: () => this.helper.when.scrollIntoView("spec-field:icon-image", "end"),
|
||||
|
||||
searchSprites: (text: string) => this.helper.get.elementByTestId("spec-field-input:icon-image").fill(text),
|
||||
|
||||
chooseSprite: (id: string) => this.helper.when.click(`sprite-option:${id}`),
|
||||
|
||||
chooseSpriteWithKeyboard: async () => {
|
||||
const input = this.helper.get.elementByTestId("spec-field-input:icon-image");
|
||||
await input.press("ArrowDown");
|
||||
await input.press("Enter");
|
||||
},
|
||||
|
||||
closeSpritePicker: () => this.helper.get.elementByTestId("spec-field-input:icon-image").press("Escape"),
|
||||
|
||||
openSpriteStyle: async (name: "sprite-alternate-style" | "sprite-empty-style") => {
|
||||
await this.helper.when.click("nav:open");
|
||||
const input = this.helper.get.elementByTestId("modal:open.url.input");
|
||||
await input.fill(baseUrl + name + ".json");
|
||||
await input.press("Enter");
|
||||
},
|
||||
|
||||
deleteLayer: async (id: string, control: "menu" | "trash" = "menu") => {
|
||||
if (control === "trash") {
|
||||
await this.helper.when.hover("layer-list-item:" + id);
|
||||
@@ -85,6 +120,8 @@ export class MaputnikDriver {
|
||||
|
||||
setStyle: async (
|
||||
styleProperties:
|
||||
| "sprite"
|
||||
| "sprite_namespaced"
|
||||
| "geojson"
|
||||
| "raster"
|
||||
| "both"
|
||||
@@ -99,6 +136,8 @@ export class MaputnikDriver {
|
||||
zoom?: number
|
||||
) => {
|
||||
const styleFileByKey: Record<string, string> = {
|
||||
sprite: "sprite-style.json",
|
||||
sprite_namespaced: "sprite-namespaced-style.json",
|
||||
geojson: "geojson-style.json",
|
||||
raster: "raster-style.json",
|
||||
both: "geojson-raster-style.json",
|
||||
@@ -360,6 +399,10 @@ export class MaputnikDriver {
|
||||
|
||||
isMac: () => isMac,
|
||||
|
||||
spriteOptions: () => this.helper.get.element(".maputnik-sprite-option"),
|
||||
|
||||
spritePixel: (id: string, x: number, y: number) => this.helper.get.canvasPixel(`sprite-preview:${id}`, x, y),
|
||||
|
||||
canvas: () => this.helper.get.element("canvas"),
|
||||
|
||||
searchControl: () => this.helper.get.element(".maplibregl-ctrl-geocoder"),
|
||||
|
||||
@@ -105,6 +105,7 @@ export class Assertable<T> {
|
||||
}
|
||||
};
|
||||
shouldNotExist = () => expect(this.locator()).toHaveCount(0);
|
||||
shouldBeInViewport = () => expect(this.locator().first()).toBeInViewport();
|
||||
shouldBeFocused = () => expect(this.locator().first()).toBeFocused();
|
||||
shouldNotBeFocused = () => expect(this.locator().first()).not.toBeFocused();
|
||||
shouldHaveValue = (value: string) => expect(this.locator().first()).toHaveValue(value);
|
||||
@@ -191,6 +192,7 @@ async function centerOf(locator: Locator): Promise<{ x: number; y: number }> {
|
||||
* It is used by the MaputnikDriver to implement the Maputnik-specific test helpers.
|
||||
*/
|
||||
export class PlaywrightHelper {
|
||||
private readonly heldResponses = new Map<string, { release(): void; done: Promise<void> }>();
|
||||
private readonly recordedRequests = new Map<string, Request[]>();
|
||||
|
||||
private get page(): Page {
|
||||
@@ -236,6 +238,21 @@ export class PlaywrightHelper {
|
||||
});
|
||||
},
|
||||
|
||||
holdResponse: async (url: RegExp, fixture: string, alias: string) => {
|
||||
let release!: () => void;
|
||||
let finish!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const done = new Promise<void>(resolve => { finish = resolve; });
|
||||
this.heldResponses.set(alias, { release, done });
|
||||
this.recordedRequests.set(alias, []);
|
||||
await this.page.route(url, async route => {
|
||||
this.recordedRequests.get(alias)!.push(route.request());
|
||||
await gate;
|
||||
await route.fulfill({ path: path.join(FIXTURES_DIR, fixture) });
|
||||
finish();
|
||||
});
|
||||
},
|
||||
|
||||
intercept: async (pattern: RegExp, alias: string, _method = "GET") => {
|
||||
this.recordedRequests.set(alias, []);
|
||||
await this.page.route(pattern, (route) => {
|
||||
@@ -254,11 +271,10 @@ export class PlaywrightHelper {
|
||||
if (alias) this.recordedRequests.set(alias, []);
|
||||
await this.page.route(url, (route) => {
|
||||
if (alias) this.recordedRequests.get(alias)!.push(route.request());
|
||||
const body =
|
||||
response && typeof response === "object" && "fixture" in (response as any)
|
||||
? this.readFixture((response as { fixture: string }).fixture)
|
||||
: response;
|
||||
route.fulfill({ json: body });
|
||||
if (response && typeof response === "object" && "fixture" in response) {
|
||||
return route.fulfill({ path: path.join(FIXTURES_DIR, (response as { fixture: string }).fixture) });
|
||||
}
|
||||
route.fulfill({ json: response });
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -270,6 +286,21 @@ export class PlaywrightHelper {
|
||||
await this.page.goto(url);
|
||||
},
|
||||
|
||||
releaseResponse: async (alias: string) => {
|
||||
const response = this.heldResponses.get(alias)!;
|
||||
response.release();
|
||||
await response.done;
|
||||
// Give fetch consumers a rendering turn after the response has been delivered.
|
||||
await this.page.evaluate(() => new Promise<void>(resolve => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
}));
|
||||
},
|
||||
|
||||
scrollIntoView: (testId: string, block: "center" | "end" = "center") =>
|
||||
this.testId(testId).evaluate((element, block) => element.scrollIntoView({ block }), block),
|
||||
|
||||
screenshot: (filename: string) => this.page.screenshot({ path: filename }),
|
||||
|
||||
wait: (ms: number) => this.page.waitForTimeout(ms),
|
||||
|
||||
tab: () => this.page.keyboard.press("Tab"),
|
||||
@@ -452,6 +483,12 @@ export class PlaywrightHelper {
|
||||
};
|
||||
|
||||
public get = {
|
||||
canvasPixel: (testId: string, x: number, y: number) => this.query(async () =>
|
||||
this.testId(testId).evaluate((element, point) => Array.from(
|
||||
(element as HTMLCanvasElement).getContext("2d")!.getImageData(point.x, point.y, 1, 1).data
|
||||
), { x, y })
|
||||
),
|
||||
|
||||
element: (selector: string) => this.page.locator(selector),
|
||||
|
||||
localStorageItem: (key: string) =>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, beforeEach, test } from "./utils/fixtures";
|
||||
import { MaputnikDriver } from "./maputnik-driver";
|
||||
|
||||
describe("sprite picker", () => {
|
||||
const { given, when, get, then } = new MaputnikDriver();
|
||||
beforeEach(async () => {
|
||||
await given.setupMockBackedResponses();
|
||||
await when.setStyle("sprite");
|
||||
await when.openSpritePicker();
|
||||
});
|
||||
|
||||
test("shows the catalog names and atlas crops in the option rows", async () => {
|
||||
await then(get.spriteOptions()).shouldHaveLength(4);
|
||||
await then(get.spritePixel("red", 8, 8)).shouldDeepNestedInclude([255, 0, 0, 255]);
|
||||
await then(get.spritePixel("green", 8, 8)).shouldDeepNestedInclude([0, 128, 0, 255]);
|
||||
});
|
||||
|
||||
test("keeps the menu in the viewport when the field is near the bottom", async () => {
|
||||
await when.scrollSpritePickerToBottom();
|
||||
await then(get.elementByTestId("sprite-preview:red")).shouldBeInViewport();
|
||||
await then(get.elementByTestId("sprite-preview:retina-square")).shouldBeInViewport();
|
||||
});
|
||||
|
||||
test("filters names without case sensitivity", async () => {
|
||||
await when.searchSprites("GrEeN");
|
||||
await then(get.spriteOptions()).shouldHaveLength(1);
|
||||
await then(get.spriteOptions()).shouldHaveText("green");
|
||||
});
|
||||
|
||||
test("stores the selected sprite ID", async () => {
|
||||
await when.chooseSprite("green");
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "green" } }] });
|
||||
});
|
||||
|
||||
test("selects a filtered sprite with the keyboard", async () => {
|
||||
await when.searchSprites("sdf");
|
||||
await when.chooseSpriteWithKeyboard();
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "sdf-circle" } }] });
|
||||
await then(get.spriteOptions()).shouldNotExist();
|
||||
});
|
||||
|
||||
test("renders an SDF silhouette with transparent outside pixels", async () => {
|
||||
await then(get.spritePixel("sdf-circle", 16, 16)).shouldDeepNestedInclude([0, 0, 0, 255]);
|
||||
await then(get.spritePixel("sdf-circle", 0, 0)).shouldDeepNestedInclude([0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test("respects the sprite pixel ratio", async () => {
|
||||
await then(get.elementByTestId("sprite-preview:retina-square")).shouldHaveCss("width", "16px");
|
||||
await then(get.spritePixel("retina-square", 16, 16)).shouldDeepNestedInclude([0, 0, 255, 255]);
|
||||
});
|
||||
|
||||
test("keeps free-form sprite names", async () => {
|
||||
await when.searchSprites("custom-{type}");
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "custom-{type}" } }] });
|
||||
});
|
||||
|
||||
test("Escape closes the menu without selecting an option", async () => {
|
||||
await when.searchSprites("gr");
|
||||
await when.closeSpritePicker();
|
||||
await then(get.spriteOptions()).shouldNotExist();
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "gr" } }] });
|
||||
});
|
||||
|
||||
test("keeps expressions in the existing expression editor", async () => {
|
||||
await when.chooseSprite("green");
|
||||
await when.makeExpression("icon-image");
|
||||
await then(get.element("[data-wd-key='spec-field-container:icon-image'] .maputnik-expression-editor")).shouldBeVisible();
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": ["literal", "green"] } }] });
|
||||
await then(get.elementByTestId("spec-field-input:icon-image")).shouldNotExist();
|
||||
});
|
||||
|
||||
test("replaces the catalog when a different sprite source is opened", async () => {
|
||||
await when.openSpriteStyle("sprite-alternate-style");
|
||||
await when.openSpritePicker();
|
||||
await then(get.spriteOptions()).shouldHaveLength(1);
|
||||
await then(get.spriteOptions()).shouldHaveText("blue");
|
||||
});
|
||||
|
||||
test("clears the catalog when the next style has no sprite", async () => {
|
||||
await when.openSpriteStyle("sprite-empty-style");
|
||||
await when.openSpritePicker();
|
||||
await then(get.spriteOptions()).shouldHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("namespaced sprite picker", () => {
|
||||
const { given, when, get, then } = new MaputnikDriver();
|
||||
beforeEach(async () => {
|
||||
await given.setupMockBackedResponses();
|
||||
await when.setStyle("sprite_namespaced");
|
||||
await when.openSpritePicker();
|
||||
});
|
||||
|
||||
test("retains MapLibre sprite namespaces when selecting an ID", async () => {
|
||||
await when.chooseSprite("extra:blue");
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "extra:blue" } }] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("sprite image failures", () => {
|
||||
const { given, when, get, then } = new MaputnikDriver();
|
||||
beforeEach(async () => {
|
||||
await given.setupMockBackedResponses();
|
||||
await given.interceptAndMockResponse({ url: /sprite-atlas\.png/, response: {} });
|
||||
await when.setStyle("sprite");
|
||||
await when.openSpritePicker();
|
||||
});
|
||||
|
||||
test("can still select a name when the atlas fails to load", async () => {
|
||||
await when.chooseSprite("green");
|
||||
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "green" } }] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("late sprite metadata", () => {
|
||||
const { given, when, get, then } = new MaputnikDriver();
|
||||
beforeEach(async () => {
|
||||
await given.setupMockBackedResponses();
|
||||
await given.holdResponse(/sprite-atlas\.json/, "sprite-atlas.json", "old-sprite");
|
||||
await when.setStyle("sprite");
|
||||
await when.waitForResponse("old-sprite");
|
||||
await when.openSpriteStyle("sprite-alternate-style");
|
||||
await when.openSpritePicker();
|
||||
await then(get.spriteOptions()).shouldHaveText("blue");
|
||||
});
|
||||
|
||||
test("does not restore an old catalog after the source changes", async () => {
|
||||
await when.releaseResponse("old-sprite");
|
||||
await then(get.spriteOptions()).shouldHaveLength(1);
|
||||
await then(get.spriteOptions()).shouldHaveText("blue");
|
||||
});
|
||||
});
|
||||
+17
-8
@@ -28,6 +28,9 @@ import { ModalShortcuts } from "./modals/ModalShortcuts";
|
||||
import { ModalDebug } from "./modals/ModalDebug";
|
||||
import { ModalGlobalState } from "./modals/ModalGlobalState";
|
||||
|
||||
import { SpriteCatalogContext } from "./SpriteCatalogContext";
|
||||
import type { Sprite } from "../libs/sprites";
|
||||
|
||||
import {downloadGlyphsMetadata, downloadSpriteMetadata} from "../libs/metadata";
|
||||
import { emptyStyle, getAccessToken, replaceAccessTokens } from "../libs/style";
|
||||
import { undoMessages, redoMessages } from "../libs/diffmessage";
|
||||
@@ -109,6 +112,7 @@ type AppState = {
|
||||
sources: {[key: string]: SourceSpecification & {layers: string[]} },
|
||||
vectorLayers: {},
|
||||
spec: any,
|
||||
sprites: Sprite[],
|
||||
mapView: {
|
||||
zoom: number,
|
||||
center: {
|
||||
@@ -143,6 +147,7 @@ export class App extends React.Component<any, AppState> {
|
||||
revisionStore: RevisionStore;
|
||||
styleStore: IStyleStore | null = null;
|
||||
layerWatcher: LayerWatcher;
|
||||
private spriteRequest = 0;
|
||||
|
||||
constructor(props: any) {
|
||||
super(props);
|
||||
@@ -159,6 +164,7 @@ export class App extends React.Component<any, AppState> {
|
||||
vectorLayers: {},
|
||||
mapState: "map",
|
||||
spec: latest,
|
||||
sprites: [],
|
||||
mapView: {
|
||||
zoom: 0,
|
||||
center: {
|
||||
@@ -301,6 +307,7 @@ export class App extends React.Component<any, AppState> {
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.spriteRequest++;
|
||||
window.removeEventListener("keydown", this.handleKeyPress);
|
||||
}
|
||||
|
||||
@@ -318,10 +325,12 @@ export class App extends React.Component<any, AppState> {
|
||||
});
|
||||
}
|
||||
|
||||
updateIcons(baseUrl: string) {
|
||||
downloadSpriteMetadata(baseUrl).then(icons => {
|
||||
this.setState({ spec: updateRootSpec(this.state.spec, "sprite", icons)});
|
||||
});
|
||||
async updateIcons(sprite: StyleSpecification["sprite"]) {
|
||||
const request = ++this.spriteRequest;
|
||||
this.setState(state => ({ sprites: [], spec: updateRootSpec(state.spec, "sprite", []) }));
|
||||
const sprites = await downloadSpriteMetadata(sprite);
|
||||
if (request !== this.spriteRequest) return;
|
||||
this.setState(state => ({ sprites, spec: updateRootSpec(state.spec, "sprite", sprites.map(sprite => sprite.id)) }));
|
||||
}
|
||||
|
||||
onChangeMetadataProperty = (property: string, value: any) => {
|
||||
@@ -481,8 +490,8 @@ export class App extends React.Component<any, AppState> {
|
||||
if(newStyle.glyphs !== this.state.mapStyle.glyphs) {
|
||||
this.updateFonts(newStyle.glyphs as string);
|
||||
}
|
||||
if(newStyle.sprite !== this.state.mapStyle.sprite) {
|
||||
this.updateIcons(newStyle.sprite as string);
|
||||
if(!isEqual(newStyle.sprite, this.state.mapStyle.sprite)) {
|
||||
this.updateIcons(newStyle.sprite);
|
||||
}
|
||||
|
||||
if (opts.addRevision) {
|
||||
@@ -919,7 +928,7 @@ export class App extends React.Component<any, AppState> {
|
||||
errors={this.state.errors}
|
||||
/>;
|
||||
|
||||
const layerEditor = selectedLayer ? <LayerEditor
|
||||
const layerEditor = selectedLayer ? <SpriteCatalogContext.Provider value={this.state.sprites}><LayerEditor
|
||||
key={this.state.selectedLayerOriginalId}
|
||||
layer={selectedLayer}
|
||||
layerIndex={this.state.selectedLayerIndex}
|
||||
@@ -935,7 +944,7 @@ export class App extends React.Component<any, AppState> {
|
||||
onLayerVisibilityToggle={this.onLayerVisibilityToggle}
|
||||
onLayerIdChange={this.onLayerIdChange}
|
||||
errors={this.state.errors}
|
||||
/> : undefined;
|
||||
/></SpriteCatalogContext.Provider> : undefined;
|
||||
|
||||
const bottomPanel = (this.state.errors.length + this.state.infos.length) > 0 ? <MessagePanel
|
||||
currentLayer={selectedLayer}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { InputDynamicArray, type InputDynamicArrayProps } from "./InputDynamicAr
|
||||
import { InputFont, type InputFontProps } from "./InputFont";
|
||||
import { InputAutocomplete, type InputAutocompleteProps } from "./InputAutocomplete";
|
||||
import { InputEnum, type InputEnumProps } from "./InputEnum";
|
||||
import { InputSprite } from "./InputSprite";
|
||||
import capitalize from "lodash.capitalize";
|
||||
|
||||
const iconProperties = ["background-pattern", "fill-pattern", "line-pattern", "fill-extrusion-pattern", "icon-image"];
|
||||
@@ -72,6 +73,9 @@ export class InputSpec extends React.Component<InputSpecProps> {
|
||||
case "resolvedImage":
|
||||
case "formatted":
|
||||
case "string":
|
||||
if (this.props.fieldName === "icon-image") {
|
||||
return <InputSprite {...commonProps as React.ComponentProps<typeof InputSprite>} />;
|
||||
}
|
||||
if (iconProperties.indexOf(this.props.fieldName!) >= 0) {
|
||||
const options = this.props.fieldSpec.values || [];
|
||||
return <InputAutocomplete
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import React from "react";
|
||||
import classnames from "classnames";
|
||||
import { useCombobox } from "downshift";
|
||||
import { SpriteCatalogContext } from "./SpriteCatalogContext";
|
||||
import { drawSprite, type Sprite } from "../libs/sprites";
|
||||
|
||||
function SpritePreview({ sprite, atlas }: { sprite: Sprite; atlas?: HTMLImageElement }) {
|
||||
const canvas = React.useRef<HTMLCanvasElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (!canvas.current || !atlas) return;
|
||||
try {
|
||||
drawSprite(canvas.current, atlas, sprite);
|
||||
} catch {
|
||||
// A failed/tainted image must not prevent choosing the sprite by name.
|
||||
canvas.current.width = 0;
|
||||
}
|
||||
}, [atlas, sprite]);
|
||||
const scale = Math.min(1 / sprite.pixelRatio, 32 / Math.max(sprite.width, sprite.height));
|
||||
return <span className="maputnik-sprite-preview" aria-hidden="true">
|
||||
{atlas && <canvas ref={canvas} data-wd-key={`sprite-preview:${sprite.id}`}
|
||||
style={{ width: sprite.width * scale, height: sprite.height * scale }} />}
|
||||
</span>;
|
||||
}
|
||||
|
||||
type InputSpriteProps = {
|
||||
value?: string;
|
||||
onChange?(value: string | undefined): unknown;
|
||||
"aria-label"?: string;
|
||||
"data-wd-key"?: string;
|
||||
};
|
||||
|
||||
export function InputSprite({ value, onChange = () => {}, "aria-label": ariaLabel, "data-wd-key": testId }: InputSpriteProps) {
|
||||
const sprites = React.useContext(SpriteCatalogContext);
|
||||
const [input, setInput] = React.useState(value || "");
|
||||
const [atlases, setAtlases] = React.useState<Map<string, HTMLImageElement>>(new Map());
|
||||
const wrapperRef = React.useRef<HTMLDivElement>(null);
|
||||
const [menuStyle, setMenuStyle] = React.useState<React.CSSProperties>({ maxHeight: 240 });
|
||||
const items = React.useMemo(() => sprites.filter(sprite => sprite.id.toLowerCase().includes(input.toLowerCase())), [sprites, input]);
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
setAtlases(new Map());
|
||||
const images = [...new Set(sprites.map(sprite => sprite.imageUrl))].map(url => {
|
||||
const image = new Image();
|
||||
image.crossOrigin = "anonymous";
|
||||
image.onload = () => {
|
||||
if (!cancelled) setAtlases(previous => new Map(previous).set(url, image));
|
||||
};
|
||||
image.src = url;
|
||||
return image;
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
images.forEach(image => { image.onload = null; });
|
||||
};
|
||||
}, [sprites]);
|
||||
|
||||
React.useEffect(() => { setInput(value || ""); }, [value]);
|
||||
|
||||
const { isOpen, getInputProps, getMenuProps, getItemProps, highlightedIndex, openMenu } = useCombobox({
|
||||
items,
|
||||
inputValue: input,
|
||||
itemToString: item => item?.id || "",
|
||||
stateReducer: (_state, action) => action.type === useCombobox.stateChangeTypes.InputClick
|
||||
? { ...action.changes, isOpen: true } : action.changes,
|
||||
onSelectedItemChange: ({ selectedItem }) => onChange(selectedItem?.id),
|
||||
onInputValueChange: ({ inputValue, type }) => {
|
||||
setInput(inputValue || "");
|
||||
if (type === useCombobox.stateChangeTypes.InputChange) onChange(inputValue || undefined);
|
||||
},
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const resize = () => {
|
||||
const bounds = wrapperRef.current?.getBoundingClientRect();
|
||||
if (!bounds) return;
|
||||
const below = window.innerHeight - bounds.bottom - 10;
|
||||
const above = bounds.top - 40; // keep the toolbar clear
|
||||
const upwards = below < Math.min(240, items.length * 42 + 4) && above > below;
|
||||
setMenuStyle({ maxHeight: Math.max(36, Math.min(240, upwards ? above : below)),
|
||||
top: upwards ? undefined : "100%", bottom: upwards ? "100%" : undefined });
|
||||
};
|
||||
resize();
|
||||
window.addEventListener("resize", resize);
|
||||
window.addEventListener("scroll", resize, true);
|
||||
return () => {
|
||||
window.removeEventListener("resize", resize);
|
||||
window.removeEventListener("scroll", resize, true);
|
||||
};
|
||||
}, [isOpen, items.length]);
|
||||
|
||||
return <div ref={wrapperRef} className="maputnik-autocomplete maputnik-sprite-autocomplete">
|
||||
<input {...getInputProps({
|
||||
"aria-label": ariaLabel, "data-wd-key": testId,
|
||||
className: "maputnik-string", spellCheck: false, onFocus: openMenu,
|
||||
})} />
|
||||
<div {...getMenuProps()} className="maputnik-autocomplete-menu" style={menuStyle}>
|
||||
{isOpen && items.map((sprite, index) => <div key={sprite.id} {...getItemProps({
|
||||
item: sprite, index,
|
||||
"data-wd-key": `sprite-option:${sprite.id}`,
|
||||
className: classnames("maputnik-autocomplete-menu-item maputnik-sprite-option", {
|
||||
"maputnik-autocomplete-menu-item-selected": highlightedIndex === index,
|
||||
}),
|
||||
})}>
|
||||
<SpritePreview sprite={sprite} atlas={atlases.get(sprite.imageUrl)} />
|
||||
<span className="maputnik-sprite-name">{sprite.id}</span>
|
||||
</div>)}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createContext } from "react";
|
||||
import type { Sprite } from "../libs/sprites";
|
||||
|
||||
export const SpriteCatalogContext = createContext<Sprite[]>([]);
|
||||
+17
-5
@@ -1,3 +1,6 @@
|
||||
import type { SpriteSpecification } from "@maplibre/maplibre-gl-style-spec";
|
||||
import { spriteSources, spriteURL, type Sprite } from "./sprites";
|
||||
|
||||
async function loadJSON<T>(url: string, defaultValue: T): Promise<T> {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
@@ -31,9 +34,18 @@ export async function downloadGlyphsMetadata(urlTemplate: string): Promise<strin
|
||||
return [...new Set(fonts)];
|
||||
}
|
||||
|
||||
export async function downloadSpriteMetadata(baseUrl: string): Promise<string[]> {
|
||||
if(!baseUrl) return [];
|
||||
const url = baseUrl + ".json";
|
||||
const glyphs = await loadJSON(url, {} as Record<string, string>);
|
||||
return Object.keys(glyphs);
|
||||
export async function downloadSpriteMetadata(sprite: SpriteSpecification | undefined): Promise<Sprite[]> {
|
||||
const catalogs = await Promise.all(spriteSources(sprite).map(async ({ id, url }) => {
|
||||
if (!url) return [];
|
||||
try {
|
||||
const metadata = await loadJSON<Record<string, Omit<Sprite, "id" | "imageUrl">>>(spriteURL(url, ".json"), {});
|
||||
return Object.entries(metadata).filter(([, item]) => item &&
|
||||
[item.x, item.y, item.width, item.height, item.pixelRatio].every(Number.isFinite) &&
|
||||
item.x >= 0 && item.y >= 0 && item.width > 0 && item.height > 0 && item.pixelRatio > 0
|
||||
).map(([name, item]) => ({ ...item, id: id === "default" ? name : `${id}:${name}`, imageUrl: spriteURL(url, ".png") }));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}));
|
||||
return catalogs.flat();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { decodeSdf, spriteURL } from "./sprites";
|
||||
import { downloadSpriteMetadata } from "./metadata";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("sprite metadata", () => {
|
||||
it("keeps tokens after the extension and resolves root-relative URLs", () => {
|
||||
vi.stubGlobal("document", { baseURI: "https://editor.test/maputnik/" });
|
||||
expect(spriteURL("https://sprites.test/icons?key=secret#section", ".json")).toBe("https://sprites.test/icons.json?key=secret#section");
|
||||
expect(spriteURL("/icons?key=secret", ".png")).toBe("https://editor.test/icons.png?key=secret");
|
||||
});
|
||||
|
||||
it("keeps atlas bounds and SDF/pixel ratio metadata with MapLibre namespace IDs", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => ({
|
||||
circle: { x: 5, y: 7, width: 32, height: 24, pixelRatio: 2, sdf: true },
|
||||
}) }));
|
||||
const sprites = await downloadSpriteMetadata([
|
||||
{ id: "default", url: "https://sprites.test/a" },
|
||||
{ id: "extra", url: "https://sprites.test/b" },
|
||||
]);
|
||||
expect(sprites).toEqual([
|
||||
{ id: "circle", imageUrl: "https://sprites.test/a.png", x: 5, y: 7, width: 32, height: 24, pixelRatio: 2, sdf: true },
|
||||
{ id: "extra:circle", imageUrl: "https://sprites.test/b.png", x: 5, y: 7, width: 32, height: 24, pixelRatio: 2, sdf: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores invalid rectangles without losing valid names", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => ({
|
||||
valid: { x: 0, y: 0, width: 16, height: 16, pixelRatio: 1 },
|
||||
zero: { x: 0, y: 0, width: 0, height: 16, pixelRatio: 1 },
|
||||
invalid: null,
|
||||
}) }));
|
||||
expect((await downloadSpriteMetadata("https://sprites.test/a")).map(sprite => sprite.id)).toEqual(["valid"]);
|
||||
});
|
||||
|
||||
it("has no catalog when the style has no sprite", async () => {
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
expect(await downloadSpriteMetadata(undefined)).toEqual([]);
|
||||
expect(await downloadSpriteMetadata("")).toEqual([]);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SDF previews", () => {
|
||||
it("turns distances into a black silhouette rather than displaying the distance bitmap", () => {
|
||||
const data = new Uint8ClampedArray([255, 50, 20, 0, 255, 50, 20, 128, 255, 50, 20, 191, 255, 50, 20, 255]);
|
||||
decodeSdf(data);
|
||||
expect(Array.from(data)).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 0, 0, 0, 255]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { SpriteSpecification } from "@maplibre/maplibre-gl-style-spec";
|
||||
|
||||
export type Sprite = {
|
||||
id: string;
|
||||
imageUrl: string;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
pixelRatio: number;
|
||||
sdf?: boolean;
|
||||
};
|
||||
|
||||
export function spriteSources(sprite: SpriteSpecification | undefined) {
|
||||
return typeof sprite === "string" ? [{ id: "default", url: sprite }] : sprite || [];
|
||||
}
|
||||
|
||||
export function spriteURL(baseUrl: string, extension: ".json" | ".png"): string {
|
||||
const url = new URL(baseUrl, globalThis.document?.baseURI);
|
||||
url.pathname += extension;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** Decode the alpha distance field using MapLibre's 0.75 contour and edge smoothing.
|
||||
* Previews use a neutral black fill rather than the layer's zoom/data-dependent paint. */
|
||||
export function decodeSdf(data: Uint8ClampedArray): void {
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const t = Math.max(0, Math.min(1, (data[i + 3] / 255 - (0.75 - 0.105)) / (2 * 0.105)));
|
||||
data[i] = data[i + 1] = data[i + 2] = 0;
|
||||
data[i + 3] = Math.round(t * t * (3 - 2 * t) * 255);
|
||||
}
|
||||
}
|
||||
|
||||
export function drawSprite(canvas: HTMLCanvasElement, atlas: HTMLImageElement, sprite: Sprite): void {
|
||||
canvas.width = sprite.width;
|
||||
canvas.height = sprite.height;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return;
|
||||
context.drawImage(atlas, sprite.x, sprite.y, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
|
||||
if (sprite.sdf) {
|
||||
const image = context.getImageData(0, 0, sprite.width, sprite.height);
|
||||
decodeSdf(image.data);
|
||||
context.putImageData(image, 0, 0);
|
||||
}
|
||||
}
|
||||
@@ -219,6 +219,36 @@
|
||||
}
|
||||
}
|
||||
|
||||
.maputnik-sprite-autocomplete {
|
||||
position: relative;
|
||||
|
||||
.maputnik-autocomplete-menu {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.maputnik-sprite-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: vars.$margin-2;
|
||||
}
|
||||
|
||||
.maputnik-sprite-preview {
|
||||
flex: 0 0 36px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: repeating-conic-gradient(vars.$color-white 0% 25%, vars.$color-lowgray 0% 50%) 0 0 / 8px 8px;
|
||||
}
|
||||
|
||||
.maputnik-sprite-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// FONT
|
||||
.maputnik-font {
|
||||
.maputnik-autocomplete:not(:last-child) {
|
||||
|
||||
Reference in New Issue
Block a user