fix: improve previews for small sprites (#2370)

# fix: improve previews for small sprites

## Description

Small sprites appeared at their original display size in the sprite
picker, making them difficult to recognize when choosing an icon or
pattern.

- Render previews in a fixed 36 × 36 CSS pixel canvas. Scale and center
each sprite while preserving its aspect ratio.
- Prefer matching `@2x.json` metadata and `@2x.png` atlas for previews.
Use the base atlas when `@2x` metadata is unavailable.
- Size the canvas backing store for the display's device pixel ratio.
Preserve query strings and fragments when building sprite URLs.

Follow-up to [#2364](https://github.com/maplibre/maputnik/pull/2364),
which extended sprite previews to all sprite-backed fields as part of
[#1294](https://github.com/maplibre/maputnik/issues/1294).

## Visuals

### Before

Small sprites appear at their original display size in the picker.

![Small oneway sprite before the
change](https://github.com/user-attachments/assets/91c353fc-2ea0-4550-9554-94dcf83ad4fa)

### After

The same sprites are scaled to fit the fixed-size preview using the
`@2x` atlas.

![Larger oneway sprite after the
change](https://github.com/user-attachments/assets/aab062a8-13b4-4e2a-8d59-8652be7d731f)

## Verification

All checks for this change passed.

- Playwright covers the `@2x` atlas, the centered 36 × 36 preview for a
small rectangular sprite, the 72 × 72 canvas at device pixel ratio 2,
and the base atlas fallback. Existing coverage exercises SDF, sprite
selection, image failures, and catalog updates.
- `npm run lint`
- `npm run lint-css`
- `npm run build`
- `npm run test-unit -- --run` (55 passed)
- `npm run test -- e2e/sprite-picker.spec.ts --workers=2` (21 passed)
- Confirmed that deliberately changing the expected CSS width, backing
canvas width, and fallback pixel color fails the corresponding tests.
Restored the correct assertions.

## 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: FantasticSPM <asd507172@gmail.com>
This commit is contained in:
FantasticSPM
2026-11-26 23:09:35 +02:00
committed by GitHub
co-authored by FantasticSPM
parent 2b2b433189
commit 648831ac67
11 changed files with 111 additions and 30 deletions
+1
View File
@@ -12,6 +12,7 @@
- _...Add new stuff here..._
### 🐞 Bug fixes
- Make small sprites easier to recognize in the sprite picker with fixed-size previews and high-resolution sprite assets
- Prevent a crash when converting a function to an expression
- Prevent a crash when deleting either stop from a function with two stops
- Preserve expanded layer groups when deleting layers, including the first layer of a group
+2 -2
View File
@@ -2,8 +2,8 @@
"red": {
"x": 0,
"y": 0,
"width": 16,
"height": 16,
"width": 4,
"height": 2,
"pixelRatio": 1
},
"green": {
+31
View File
@@ -0,0 +1,31 @@
{
"red": {
"x": 0,
"y": 0,
"width": 8,
"height": 4,
"pixelRatio": 2
},
"green": {
"x": 32,
"y": 0,
"width": 32,
"height": 32,
"pixelRatio": 2
},
"sdf-circle": {
"x": 64,
"y": 0,
"width": 64,
"height": 64,
"pixelRatio": 2,
"sdf": true
},
"retina-square": {
"x": 128,
"y": 0,
"width": 32,
"height": 32,
"pixelRatio": 2
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1005 B

+1 -1
View File
@@ -1 +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.
Sprite fixtures authored for this test suite and distributed under the repository MIT license. The 96×32 base atlas contains a small red rectangle, a green square, an analytic circle distance field (alpha=0.75+signedDistance/8), and a blue 2× square. The 192×64 `@2x` atlas uses doubled positions and dimensions for the base sprites and keeps the blue square at its original 2× resolution. The alternate catalog serves the blue square through the base atlas.
+3
View File
@@ -59,6 +59,9 @@ export class MaputnikDriver {
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({ url: /\/sprite-atlas@2x\.json\?key=test$/, response: { fixture: "sprite-atlas@2x.json" } });
await this.helper.given.interceptAndMockResponse({ url: /\/sprite-atlas@2x\.png\?key=test$/, response: { fixture: "sprite-atlas@2x.png" } });
await this.helper.given.interceptAndMockResponse({ url: /\/sprite-alternate@2x\.json$/, response: null });
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({
+33 -9
View File
@@ -1,4 +1,4 @@
import { describe, beforeEach, test } from "./utils/fixtures";
import { describe, beforeEach, test, expect } from "./utils/fixtures";
import { MaputnikDriver } from "./maputnik-driver";
describe("sprite picker", () => {
@@ -9,9 +9,9 @@ describe("sprite picker", () => {
await when.openSpritePicker();
});
test("shows the catalog names and atlas crops in the option rows", async () => {
test("shows the catalog names and @2x 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("red", 8, 18)).shouldDeepNestedInclude([255, 0, 0, 255]);
await then(get.spritePixel("green", 8, 8)).shouldDeepNestedInclude([0, 128, 0, 255]);
});
@@ -44,9 +44,25 @@ describe("sprite picker", () => {
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("enlarges and centers a small sprite without stretching it", async () => {
await then(get.elementByTestId("sprite-preview:red")).shouldHaveCss("width", "36px");
await then(get.elementByTestId("sprite-preview:red")).shouldHaveCss("height", "36px");
await then(get.spritePixel("red", 30, 18)).shouldDeepNestedInclude([255, 0, 0, 255]);
await then(get.spritePixel("red", 18, 5)).shouldDeepNestedInclude([0, 0, 0, 0]);
await then(get.spritePixel("red", 18, 30)).shouldDeepNestedInclude([0, 0, 0, 0]);
});
describe("on a high-density display", () => {
test.use({ deviceScaleFactor: 2 });
test("draws a high-resolution thumbnail at the same display size", async () => {
const preview = get.elementByTestId("sprite-preview:retina-square");
await then(preview).shouldHaveCss("width", "36px");
await then(preview).shouldHaveCss("height", "36px");
await expect(preview).toHaveAttribute("width", "72");
await expect(preview).toHaveAttribute("height", "72");
await then(get.spritePixel("retina-square", 60, 60)).shouldDeepNestedInclude([0, 0, 255, 255]);
});
});
test("keeps free-form sprite names", async () => {
@@ -76,6 +92,12 @@ describe("sprite picker", () => {
await then(get.spriteOptions()).shouldHaveText("blue");
});
test("renders the base atlas when @2x metadata is unavailable", async () => {
await when.openSpriteStyle("sprite-alternate-style");
await when.openSpritePicker();
await then(get.spritePixel("blue", 18, 18)).shouldDeepNestedInclude([0, 0, 255, 255]);
});
test("clears the catalog when the next style has no sprite", async () => {
await when.openSpriteStyle("sprite-empty-style");
await when.openSpritePicker();
@@ -104,7 +126,7 @@ describe("sprite-backed properties", () => {
await when.openSpritePicker(layerId, property);
await then(get.spriteOptions()).shouldHaveLength(4);
await then(get.spritePixel("red", 8, 8)).shouldDeepNestedInclude([255, 0, 0, 255]);
await then(get.spritePixel("red", 8, 18)).shouldDeepNestedInclude([255, 0, 0, 255]);
await when.chooseSprite("green");
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
@@ -135,12 +157,14 @@ 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 given.interceptAndMockResponse({ url: /sprite-atlas@2x\.png/, response: {} });
await when.setStyle("sprite");
await when.openSpritePicker();
});
test("can still select a name when the atlas fails to load", async () => {
await then(get.spriteOptions()).shouldHaveLength(4);
await then(get.elementByTestId("sprite-preview:green")).shouldNotExist();
await when.chooseSprite("green");
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "green" } }] });
});
@@ -150,7 +174,7 @@ 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 given.holdResponse(/sprite-atlas@2x\.json/, "sprite-atlas@2x.json", "old-sprite");
await when.setStyle("sprite");
await when.waitForResponse("old-sprite");
await when.openSpriteStyle("sprite-alternate-style");
+2 -3
View File
@@ -2,7 +2,7 @@ import React from "react";
import classnames from "classnames";
import { useCombobox } from "downshift";
import { SpriteCatalogContext } from "./SpriteCatalogContext";
import { drawSprite, type Sprite } from "../libs/sprites";
import { drawSprite, SPRITE_PREVIEW_SIZE, type Sprite } from "../libs/sprites";
function SpritePreview({ sprite, atlas }: { sprite: Sprite; atlas?: HTMLImageElement }) {
const canvas = React.useRef<HTMLCanvasElement>(null);
@@ -15,10 +15,9 @@ function SpritePreview({ sprite, atlas }: { sprite: Sprite; atlas?: HTMLImageEle
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 }} />}
style={{ width: SPRITE_PREVIEW_SIZE, height: SPRITE_PREVIEW_SIZE }} />}
</span>;
}
+14 -5
View File
@@ -38,14 +38,23 @@ export async function downloadSpriteMetadata(sprite: SpriteSpecification | undef
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") }));
for (const [metadataExtension, imageExtension] of [["@2x.json", "@2x.png"], [".json", ".png"]] as const) {
const metadata = await loadJSON<Record<string, Omit<Sprite, "id" | "imageUrl">> | null>(
spriteURL(url, metadataExtension), null,
);
const entries = 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
);
if (entries.length) {
const imageUrl = spriteURL(url, imageExtension);
return entries.map(([name, item]) => ({ ...item, id: id === "default" ? name : `${id}:${name}`, imageUrl }));
}
}
} catch {
return [];
}
return [];
}));
return catalogs.flat();
}
+4 -4
View File
@@ -7,8 +7,8 @@ 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");
expect(spriteURL("https://sprites.test/icons?key=secret#section", "@2x.json")).toBe("https://sprites.test/icons@2x.json?key=secret#section");
expect(spriteURL("/icons?key=secret", "@2x.png")).toBe("https://editor.test/icons@2x.png?key=secret");
});
it("keeps atlas bounds and SDF/pixel ratio metadata with MapLibre namespace IDs", async () => {
@@ -20,8 +20,8 @@ describe("sprite metadata", () => {
{ 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 },
{ id: "circle", imageUrl: "https://sprites.test/a@2x.png", x: 5, y: 7, width: 32, height: 24, pixelRatio: 2, sdf: true },
{ id: "extra:circle", imageUrl: "https://sprites.test/b@2x.png", x: 5, y: 7, width: 32, height: 24, pixelRatio: 2, sdf: true },
]);
});
+20 -6
View File
@@ -15,7 +15,7 @@ export function spriteSources(sprite: SpriteSpecification | undefined) {
return typeof sprite === "string" ? [{ id: "default", url: sprite }] : sprite || [];
}
export function spriteURL(baseUrl: string, extension: ".json" | ".png"): string {
export function spriteURL(baseUrl: string, extension: ".json" | ".png" | "@2x.json" | "@2x.png"): string {
const url = new URL(baseUrl, globalThis.document?.baseURI);
url.pathname += extension;
return url.toString();
@@ -31,14 +31,28 @@ export function decodeSdf(data: Uint8ClampedArray): void {
}
}
export function drawSprite(canvas: HTMLCanvasElement, atlas: HTMLImageElement, sprite: Sprite): void {
canvas.width = sprite.width;
canvas.height = sprite.height;
export const SPRITE_PREVIEW_SIZE = 36;
export function drawSprite(canvas: HTMLCanvasElement, atlas: HTMLImageElement, sprite: Sprite, size = SPRITE_PREVIEW_SIZE): void {
const pixelRatio = window.devicePixelRatio || 1;
canvas.width = Math.max(1, Math.round(size * pixelRatio));
canvas.height = Math.max(1, Math.round(size * pixelRatio));
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);
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
context.clearRect(0, 0, size, size);
const scale = Math.min(size / sprite.width, size / sprite.height);
const width = sprite.width * scale;
const height = sprite.height * scale;
const x = (size - width) / 2;
const y = (size - height) / 2;
context.imageSmoothingEnabled = true;
context.imageSmoothingQuality = "high";
context.drawImage(atlas, sprite.x, sprite.y, sprite.width, sprite.height, x, y, width, height);
if (sprite.sdf) {
const image = context.getImageData(0, 0, sprite.width, sprite.height);
const image = context.getImageData(0, 0, canvas.width, canvas.height);
decodeSdf(image.data);
context.putImageData(image, 0, 0);
}