mirror of
https://github.com/maputnik/editor.git
synced 2026-11-30 13:54:20 +00:00
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.  ### After The same sprites are scaled to fit the fixed-size preview using the `@2x` atlas.  ## 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:
1 parent
2b2b433189
commit
648831ac67
11 files changed
+111
-30
No files matched your search
@@ -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
@@ -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();
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user