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[]>([]);
|
||||
Reference in new issue
Block a user