mirror of
https://github.com/maputnik/editor.git
synced 2026-11-30 13:54:20 +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 parent
2296b77c37
commit
54f0ba140a
20 files changed
+711
-18
No files matched your search
+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