diff --git a/CHANGELOG.md b/CHANGELOG.md index ccd38bef..cce86011 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## main ### ✨ Features and improvements +- Preview sprites in the icon-image dropdown, with searchable names and keyboard selection - Replace Cypress with Playwright for end-to-end tests and Vitest browser mode (Playwright provider) for component tests; drop the `@shellygo/cypress-test-utils` helper in favour of a `MaputnikDriver` page object - Upgrade to MapLibre GL JS 6 and Vite 8, and update the remaining dependencies - Remove the RTL text plugin, since MapLibre GL JS now renders right-to-left text natively diff --git a/e2e/fixtures/sprite-alternate-style.json b/e2e/fixtures/sprite-alternate-style.json new file mode 100644 index 00000000..f5019012 --- /dev/null +++ b/e2e/fixtures/sprite-alternate-style.json @@ -0,0 +1,41 @@ +{ + "version": 8, + "name": "Sprite preview test", + "center": [ + 0, + 0 + ], + "zoom": 0, + "sources": { + "points": { + "type": "geojson", + "data": { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [ + 0, + 0 + ] + } + } + ] + } + } + }, + "sprite": "http://localhost:8888/sprite-alternate", + "layers": [ + { + "id": "symbols", + "type": "symbol", + "source": "points", + "layout": { + "icon-image": "red" + } + } + ] +} diff --git a/e2e/fixtures/sprite-alternate.json b/e2e/fixtures/sprite-alternate.json new file mode 100644 index 00000000..6c309d74 --- /dev/null +++ b/e2e/fixtures/sprite-alternate.json @@ -0,0 +1,9 @@ +{ + "blue": { + "x": 64, + "y": 0, + "width": 32, + "height": 32, + "pixelRatio": 2 + } +} diff --git a/e2e/fixtures/sprite-atlas.json b/e2e/fixtures/sprite-atlas.json new file mode 100644 index 00000000..999234e5 --- /dev/null +++ b/e2e/fixtures/sprite-atlas.json @@ -0,0 +1,31 @@ +{ + "red": { + "x": 0, + "y": 0, + "width": 16, + "height": 16, + "pixelRatio": 1 + }, + "green": { + "x": 16, + "y": 0, + "width": 16, + "height": 16, + "pixelRatio": 1 + }, + "sdf-circle": { + "x": 32, + "y": 0, + "width": 32, + "height": 32, + "pixelRatio": 1, + "sdf": true + }, + "retina-square": { + "x": 64, + "y": 0, + "width": 32, + "height": 32, + "pixelRatio": 2 + } +} diff --git a/e2e/fixtures/sprite-atlas.png b/e2e/fixtures/sprite-atlas.png new file mode 100644 index 00000000..c0ea1cc0 Binary files /dev/null and b/e2e/fixtures/sprite-atlas.png differ diff --git a/e2e/fixtures/sprite-empty-style.json b/e2e/fixtures/sprite-empty-style.json new file mode 100644 index 00000000..cac06ba8 --- /dev/null +++ b/e2e/fixtures/sprite-empty-style.json @@ -0,0 +1,40 @@ +{ + "version": 8, + "name": "Sprite preview test", + "center": [ + 0, + 0 + ], + "zoom": 0, + "sources": { + "points": { + "type": "geojson", + "data": { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [ + 0, + 0 + ] + } + } + ] + } + } + }, + "layers": [ + { + "id": "symbols", + "type": "symbol", + "source": "points", + "layout": { + "icon-image": "red" + } + } + ] +} diff --git a/e2e/fixtures/sprite-fixtures.md b/e2e/fixtures/sprite-fixtures.md new file mode 100644 index 00000000..ce18d1f7 --- /dev/null +++ b/e2e/fixtures/sprite-fixtures.md @@ -0,0 +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. diff --git a/e2e/fixtures/sprite-namespaced-style.json b/e2e/fixtures/sprite-namespaced-style.json new file mode 100644 index 00000000..1ea74e9f --- /dev/null +++ b/e2e/fixtures/sprite-namespaced-style.json @@ -0,0 +1,50 @@ +{ + "version": 8, + "name": "Sprite preview test", + "center": [ + 0, + 0 + ], + "zoom": 0, + "sources": { + "points": { + "type": "geojson", + "data": { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [ + 0, + 0 + ] + } + } + ] + } + } + }, + "sprite": [ + { + "id": "default", + "url": "http://localhost:8888/sprite-atlas?key=test" + }, + { + "id": "extra", + "url": "http://localhost:8888/sprite-alternate" + } + ], + "layers": [ + { + "id": "symbols", + "type": "symbol", + "source": "points", + "layout": { + "icon-image": "red" + } + } + ] +} diff --git a/e2e/fixtures/sprite-style.json b/e2e/fixtures/sprite-style.json new file mode 100644 index 00000000..e193edae --- /dev/null +++ b/e2e/fixtures/sprite-style.json @@ -0,0 +1,41 @@ +{ + "version": 8, + "name": "Sprite preview test", + "center": [ + 0, + 0 + ], + "zoom": 0, + "sources": { + "points": { + "type": "geojson", + "data": { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [ + 0, + 0 + ] + } + } + ] + } + } + }, + "sprite": "http://localhost:8888/sprite-atlas?key=test", + "layers": [ + { + "id": "symbols", + "type": "symbol", + "source": "points", + "layout": { + "icon-image": "red" + } + } + ] +} diff --git a/e2e/maputnik-driver.ts b/e2e/maputnik-driver.ts index cd0f2d7c..31fb1248 100644 --- a/e2e/maputnik-driver.ts +++ b/e2e/maputnik-driver.ts @@ -30,6 +30,10 @@ export class MaputnikDriver { setupMockBackedResponses: async () => { const styleFixtures = [ + "sprite-style.json", + "sprite-alternate-style.json", + "sprite-namespaced-style.json", + "sprite-empty-style.json", "example-style.json", "example-layer-style.json", "geojson-style.json", @@ -51,6 +55,10 @@ export class MaputnikDriver { alias: fixture === "example-style.json" ? "example-style.json" : undefined, }); } + for (const atlas of ["sprite-atlas", "sprite-alternate"]) { + 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({ method: "GET", url: /example\.local\//, response: [] }); await this.helper.given.interceptAndMockResponse({ method: "GET", url: /example\.com\//, response: [] }); await this.helper.given.interceptAndMockResponse({ @@ -71,6 +79,33 @@ export class MaputnikDriver { modal: this.modalDriver.when, + openSpritePicker: async () => { + await this.helper.when.click("layer-list-item:symbols"); + await this.helper.when.scrollIntoView("spec-field:icon-image"); + await this.helper.get.elementByTestId("spec-field:icon-image").locator("input").fill(""); + }, + + scrollSpritePickerToBottom: () => this.helper.when.scrollIntoView("spec-field:icon-image", "end"), + + searchSprites: (text: string) => this.helper.get.elementByTestId("spec-field-input:icon-image").fill(text), + + chooseSprite: (id: string) => this.helper.when.click(`sprite-option:${id}`), + + chooseSpriteWithKeyboard: async () => { + const input = this.helper.get.elementByTestId("spec-field-input:icon-image"); + await input.press("ArrowDown"); + await input.press("Enter"); + }, + + closeSpritePicker: () => this.helper.get.elementByTestId("spec-field-input:icon-image").press("Escape"), + + openSpriteStyle: async (name: "sprite-alternate-style" | "sprite-empty-style") => { + await this.helper.when.click("nav:open"); + const input = this.helper.get.elementByTestId("modal:open.url.input"); + await input.fill(baseUrl + name + ".json"); + await input.press("Enter"); + }, + deleteLayer: async (id: string, control: "menu" | "trash" = "menu") => { if (control === "trash") { await this.helper.when.hover("layer-list-item:" + id); @@ -85,6 +120,8 @@ export class MaputnikDriver { setStyle: async ( styleProperties: + | "sprite" + | "sprite_namespaced" | "geojson" | "raster" | "both" @@ -99,6 +136,8 @@ export class MaputnikDriver { zoom?: number ) => { const styleFileByKey: Record = { + sprite: "sprite-style.json", + sprite_namespaced: "sprite-namespaced-style.json", geojson: "geojson-style.json", raster: "raster-style.json", both: "geojson-raster-style.json", @@ -360,6 +399,10 @@ export class MaputnikDriver { isMac: () => isMac, + spriteOptions: () => this.helper.get.element(".maputnik-sprite-option"), + + spritePixel: (id: string, x: number, y: number) => this.helper.get.canvasPixel(`sprite-preview:${id}`, x, y), + canvas: () => this.helper.get.element("canvas"), searchControl: () => this.helper.get.element(".maplibregl-ctrl-geocoder"), diff --git a/e2e/playwright-helper.ts b/e2e/playwright-helper.ts index 8de97774..22c7766d 100644 --- a/e2e/playwright-helper.ts +++ b/e2e/playwright-helper.ts @@ -105,6 +105,7 @@ export class Assertable { } }; shouldNotExist = () => expect(this.locator()).toHaveCount(0); + shouldBeInViewport = () => expect(this.locator().first()).toBeInViewport(); shouldBeFocused = () => expect(this.locator().first()).toBeFocused(); shouldNotBeFocused = () => expect(this.locator().first()).not.toBeFocused(); shouldHaveValue = (value: string) => expect(this.locator().first()).toHaveValue(value); @@ -191,6 +192,7 @@ async function centerOf(locator: Locator): Promise<{ x: number; y: number }> { * It is used by the MaputnikDriver to implement the Maputnik-specific test helpers. */ export class PlaywrightHelper { + private readonly heldResponses = new Map }>(); private readonly recordedRequests = new Map(); private get page(): Page { @@ -236,6 +238,21 @@ export class PlaywrightHelper { }); }, + holdResponse: async (url: RegExp, fixture: string, alias: string) => { + let release!: () => void; + let finish!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const done = new Promise(resolve => { finish = resolve; }); + this.heldResponses.set(alias, { release, done }); + this.recordedRequests.set(alias, []); + await this.page.route(url, async route => { + this.recordedRequests.get(alias)!.push(route.request()); + await gate; + await route.fulfill({ path: path.join(FIXTURES_DIR, fixture) }); + finish(); + }); + }, + intercept: async (pattern: RegExp, alias: string, _method = "GET") => { this.recordedRequests.set(alias, []); await this.page.route(pattern, (route) => { @@ -254,11 +271,10 @@ export class PlaywrightHelper { if (alias) this.recordedRequests.set(alias, []); await this.page.route(url, (route) => { if (alias) this.recordedRequests.get(alias)!.push(route.request()); - const body = - response && typeof response === "object" && "fixture" in (response as any) - ? this.readFixture((response as { fixture: string }).fixture) - : response; - route.fulfill({ json: body }); + if (response && typeof response === "object" && "fixture" in response) { + return route.fulfill({ path: path.join(FIXTURES_DIR, (response as { fixture: string }).fixture) }); + } + route.fulfill({ json: response }); }); }, }; @@ -270,6 +286,21 @@ export class PlaywrightHelper { await this.page.goto(url); }, + releaseResponse: async (alias: string) => { + const response = this.heldResponses.get(alias)!; + response.release(); + await response.done; + // Give fetch consumers a rendering turn after the response has been delivered. + await this.page.evaluate(() => new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + })); + }, + + scrollIntoView: (testId: string, block: "center" | "end" = "center") => + this.testId(testId).evaluate((element, block) => element.scrollIntoView({ block }), block), + + screenshot: (filename: string) => this.page.screenshot({ path: filename }), + wait: (ms: number) => this.page.waitForTimeout(ms), tab: () => this.page.keyboard.press("Tab"), @@ -452,6 +483,12 @@ export class PlaywrightHelper { }; public get = { + canvasPixel: (testId: string, x: number, y: number) => this.query(async () => + this.testId(testId).evaluate((element, point) => Array.from( + (element as HTMLCanvasElement).getContext("2d")!.getImageData(point.x, point.y, 1, 1).data + ), { x, y }) + ), + element: (selector: string) => this.page.locator(selector), localStorageItem: (key: string) => diff --git a/e2e/sprite-picker.spec.ts b/e2e/sprite-picker.spec.ts new file mode 100644 index 00000000..653ecbbf --- /dev/null +++ b/e2e/sprite-picker.spec.ts @@ -0,0 +1,132 @@ +import { describe, beforeEach, test } from "./utils/fixtures"; +import { MaputnikDriver } from "./maputnik-driver"; + +describe("sprite picker", () => { + const { given, when, get, then } = new MaputnikDriver(); + beforeEach(async () => { + await given.setupMockBackedResponses(); + await when.setStyle("sprite"); + await when.openSpritePicker(); + }); + + test("shows the catalog names and 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("green", 8, 8)).shouldDeepNestedInclude([0, 128, 0, 255]); + }); + + test("keeps the menu in the viewport when the field is near the bottom", async () => { + await when.scrollSpritePickerToBottom(); + await then(get.elementByTestId("sprite-preview:red")).shouldBeInViewport(); + await then(get.elementByTestId("sprite-preview:retina-square")).shouldBeInViewport(); + }); + + test("filters names without case sensitivity", async () => { + await when.searchSprites("GrEeN"); + await then(get.spriteOptions()).shouldHaveLength(1); + await then(get.spriteOptions()).shouldHaveText("green"); + }); + + test("stores the selected sprite ID", async () => { + await when.chooseSprite("green"); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "green" } }] }); + }); + + test("selects a filtered sprite with the keyboard", async () => { + await when.searchSprites("sdf"); + await when.chooseSpriteWithKeyboard(); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "sdf-circle" } }] }); + await then(get.spriteOptions()).shouldNotExist(); + }); + + test("renders an SDF silhouette with transparent outside pixels", async () => { + await then(get.spritePixel("sdf-circle", 16, 16)).shouldDeepNestedInclude([0, 0, 0, 255]); + 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("keeps free-form sprite names", async () => { + await when.searchSprites("custom-{type}"); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "custom-{type}" } }] }); + }); + + test("Escape closes the menu without selecting an option", async () => { + await when.searchSprites("gr"); + await when.closeSpritePicker(); + await then(get.spriteOptions()).shouldNotExist(); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "gr" } }] }); + }); + + test("keeps expressions in the existing expression editor", async () => { + await when.chooseSprite("green"); + await when.makeExpression("icon-image"); + await then(get.element("[data-wd-key='spec-field-container:icon-image'] .maputnik-expression-editor")).shouldBeVisible(); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": ["literal", "green"] } }] }); + await then(get.elementByTestId("spec-field-input:icon-image")).shouldNotExist(); + }); + + test("replaces the catalog when a different sprite source is opened", async () => { + await when.openSpriteStyle("sprite-alternate-style"); + await when.openSpritePicker(); + await then(get.spriteOptions()).shouldHaveLength(1); + await then(get.spriteOptions()).shouldHaveText("blue"); + }); + + test("clears the catalog when the next style has no sprite", async () => { + await when.openSpriteStyle("sprite-empty-style"); + await when.openSpritePicker(); + await then(get.spriteOptions()).shouldHaveLength(0); + }); +}); + +describe("namespaced sprite picker", () => { + const { given, when, get, then } = new MaputnikDriver(); + beforeEach(async () => { + await given.setupMockBackedResponses(); + await when.setStyle("sprite_namespaced"); + await when.openSpritePicker(); + }); + + test("retains MapLibre sprite namespaces when selecting an ID", async () => { + await when.chooseSprite("extra:blue"); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "extra:blue" } }] }); + }); +}); + +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 when.setStyle("sprite"); + await when.openSpritePicker(); + }); + + test("can still select a name when the atlas fails to load", async () => { + await when.chooseSprite("green"); + await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": "green" } }] }); + }); +}); + +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 when.setStyle("sprite"); + await when.waitForResponse("old-sprite"); + await when.openSpriteStyle("sprite-alternate-style"); + await when.openSpritePicker(); + await then(get.spriteOptions()).shouldHaveText("blue"); + }); + + test("does not restore an old catalog after the source changes", async () => { + await when.releaseResponse("old-sprite"); + await then(get.spriteOptions()).shouldHaveLength(1); + await then(get.spriteOptions()).shouldHaveText("blue"); + }); +}); diff --git a/src/components/App.tsx b/src/components/App.tsx index aad9d6cd..7cc25c04 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -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 { 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 { vectorLayers: {}, mapState: "map", spec: latest, + sprites: [], mapView: { zoom: 0, center: { @@ -301,6 +307,7 @@ export class App extends React.Component { } componentWillUnmount() { + this.spriteRequest++; window.removeEventListener("keydown", this.handleKeyPress); } @@ -318,10 +325,12 @@ export class App extends React.Component { }); } - 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 { 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 { errors={this.state.errors} />; - const layerEditor = selectedLayer ? { onLayerVisibilityToggle={this.onLayerVisibilityToggle} onLayerIdChange={this.onLayerIdChange} errors={this.state.errors} - /> : undefined; + /> : undefined; const bottomPanel = (this.state.errors.length + this.state.infos.length) > 0 ? { case "resolvedImage": case "formatted": case "string": + if (this.props.fieldName === "icon-image") { + return } />; + } if (iconProperties.indexOf(this.props.fieldName!) >= 0) { const options = this.props.fieldSpec.values || []; return (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 ; +} + +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>(new Map()); + const wrapperRef = React.useRef(null); + const [menuStyle, setMenuStyle] = React.useState({ 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
+ +
+ {isOpen && items.map((sprite, index) =>
+ + {sprite.id} +
)} +
+
; +} diff --git a/src/components/SpriteCatalogContext.ts b/src/components/SpriteCatalogContext.ts new file mode 100644 index 00000000..5c65ff1e --- /dev/null +++ b/src/components/SpriteCatalogContext.ts @@ -0,0 +1,4 @@ +import { createContext } from "react"; +import type { Sprite } from "../libs/sprites"; + +export const SpriteCatalogContext = createContext([]); diff --git a/src/libs/metadata.ts b/src/libs/metadata.ts index 8eba10fc..6b449417 100644 --- a/src/libs/metadata.ts +++ b/src/libs/metadata.ts @@ -1,3 +1,6 @@ +import type { SpriteSpecification } from "@maplibre/maplibre-gl-style-spec"; +import { spriteSources, spriteURL, type Sprite } from "./sprites"; + async function loadJSON(url: string, defaultValue: T): Promise { try { const response = await fetch(url, { @@ -31,9 +34,18 @@ export async function downloadGlyphsMetadata(urlTemplate: string): Promise { - if(!baseUrl) return []; - const url = baseUrl + ".json"; - const glyphs = await loadJSON(url, {} as Record); - return Object.keys(glyphs); +export async function downloadSpriteMetadata(sprite: SpriteSpecification | undefined): Promise { + 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") })); + } catch { + return []; + } + })); + return catalogs.flat(); } diff --git a/src/libs/sprites.test.ts b/src/libs/sprites.test.ts new file mode 100644 index 00000000..ff002841 --- /dev/null +++ b/src/libs/sprites.test.ts @@ -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]); + }); +}); diff --git a/src/libs/sprites.ts b/src/libs/sprites.ts new file mode 100644 index 00000000..2076c33e --- /dev/null +++ b/src/libs/sprites.ts @@ -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); + } +} diff --git a/src/styles/_input.scss b/src/styles/_input.scss index 3660cebb..df644a34 100644 --- a/src/styles/_input.scss +++ b/src/styles/_input.scss @@ -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) {