From 648831ac679fe752627a6710f87d2d904b5cd8ba Mon Sep 17 00:00:00 2001 From: FantasticSPM <128824672+FantasticSPM@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:09:35 +0800 Subject: [PATCH] fix: improve previews for small sprites (#2370) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # 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 --- CHANGELOG.md | 1 + e2e/fixtures/sprite-atlas.json | 4 +-- e2e/fixtures/sprite-atlas@2x.json | 31 ++++++++++++++++++++++ e2e/fixtures/sprite-atlas@2x.png | Bin 0 -> 1005 bytes e2e/fixtures/sprite-fixtures.md | 2 +- e2e/maputnik-driver.ts | 3 +++ e2e/sprite-picker.spec.ts | 42 +++++++++++++++++++++++------- src/components/InputSprite.tsx | 5 ++-- src/libs/metadata.ts | 19 ++++++++++---- src/libs/sprites.test.ts | 8 +++--- src/libs/sprites.ts | 26 +++++++++++++----- 11 files changed, 111 insertions(+), 30 deletions(-) create mode 100644 e2e/fixtures/sprite-atlas@2x.json create mode 100644 e2e/fixtures/sprite-atlas@2x.png diff --git a/CHANGELOG.md b/CHANGELOG.md index f3ffa9d2..59fb8b85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/e2e/fixtures/sprite-atlas.json b/e2e/fixtures/sprite-atlas.json index 999234e5..c0197a2a 100644 --- a/e2e/fixtures/sprite-atlas.json +++ b/e2e/fixtures/sprite-atlas.json @@ -2,8 +2,8 @@ "red": { "x": 0, "y": 0, - "width": 16, - "height": 16, + "width": 4, + "height": 2, "pixelRatio": 1 }, "green": { diff --git a/e2e/fixtures/sprite-atlas@2x.json b/e2e/fixtures/sprite-atlas@2x.json new file mode 100644 index 00000000..8a807d83 --- /dev/null +++ b/e2e/fixtures/sprite-atlas@2x.json @@ -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 + } +} diff --git a/e2e/fixtures/sprite-atlas@2x.png b/e2e/fixtures/sprite-atlas@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..fdf6ff71ec382c828195f2e38970bbbe42ab07f1 GIT binary patch literal 1005 zcmeAS@N?(olHy`uVBq!ia0vp^2Y}dtgAGXfEaktaqI2e==@s_0&dqE z6xk*V1Z}l9|G77mdq(sQmOInGI@_f_IeKG<;PX8_QLY;d6VJt^FTS($&Q^~v&!SZ8 z&nlN6cM04*zy5ZK3`0Bv!#)Ova`%4sg3T(%6VmTZop1f~$HT|>jvMz2Ff$}HL>oJpE@H!iA_RM`_Q=v#(N!% z#~PD6jgy&p7#bL3_J01OKk4OZp9RT{S0V(_A9I8|I{a!pHAxXl~cS78ceG~WO<@AWIxw~jry2eokP+-K&5D}WWRnjv} zRyw&k^XQrQv_*>xopLhQSnxmn{-WTR1Smj-*o@x)Q@}FmPxRk`y8%nbWS3>ddptJ`KD~Z^w3zMYFYB+|L!); zDqYD{>08cc*#mXWw_Wt?*P6sVTmP`c{Zs}9d=KM++Iy*$(<+MM!wcV9y- zZ$^+4F7Q+r#LwSxOM17_=eBFiMV0gCUX;syzm~TZ7##<`yBhDl_VW7V@a&uY`zPF8 zSh{h-_lv)ow$xf576HXq!_i2im)9(^SDRXYb(^tcSutbw%Ac0gzhC{9)3Zuo4l_8` zFP&MPp1XOHbV8Ne(e0~36}!&-zg@eJKS9rax~FyN8gOv6Y%(;ed(o>ee~CRlYz>e3 z^fU1@9`q-+_$Xaf0LMxAx&8dTlf%Q-`mOy`lUw>?XG+~^7UOs9AR88_-BUe$tTA-f z_DkRQe`}l3x@GYhmXLa|)Vqxi>KnX1uUZ(b^juYK!TWx2Dm#;sfA->w-TKnIH0>sr z6$IO`F%*P{O7D*TWK(W>SIN>aujBe&r&{HobB;2E{r&G_^e=R?ZQzrlcA#!x0@->` zcbe4IS&xO7WqK!PyjJ`6Eddx=4UBmcQrO&d{nM{V-@5-uMI01G5)bnJ1NA^N*Y{)g X%xn^dpS_=iFaUw4tDnm{r-UW|gi*Qm literal 0 HcmV?d00001 diff --git a/e2e/fixtures/sprite-fixtures.md b/e2e/fixtures/sprite-fixtures.md index ce18d1f7..14900d89 100644 --- a/e2e/fixtures/sprite-fixtures.md +++ b/e2e/fixtures/sprite-fixtures.md @@ -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. diff --git a/e2e/maputnik-driver.ts b/e2e/maputnik-driver.ts index 968f76d7..2deca7e0 100644 --- a/e2e/maputnik-driver.ts +++ b/e2e/maputnik-driver.ts @@ -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({ diff --git a/e2e/sprite-picker.spec.ts b/e2e/sprite-picker.spec.ts index 059f7d72..50a3e50f 100644 --- a/e2e/sprite-picker.spec.ts +++ b/e2e/sprite-picker.spec.ts @@ -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"); diff --git a/src/components/InputSprite.tsx b/src/components/InputSprite.tsx index 339a0be9..7dc5fda3 100644 --- a/src/components/InputSprite.tsx +++ b/src/components/InputSprite.tsx @@ -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(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 ; } diff --git a/src/libs/metadata.ts b/src/libs/metadata.ts index 6b449417..e8c5cd91 100644 --- a/src/libs/metadata.ts +++ b/src/libs/metadata.ts @@ -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>>(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> | 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(); } diff --git a/src/libs/sprites.test.ts b/src/libs/sprites.test.ts index ff002841..f0af5a29 100644 --- a/src/libs/sprites.test.ts +++ b/src/libs/sprites.test.ts @@ -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 }, ]); }); diff --git a/src/libs/sprites.ts b/src/libs/sprites.ts index 2076c33e..ebed9be4 100644 --- a/src/libs/sprites.ts +++ b/src/libs/sprites.ts @@ -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); }