Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] 1bf365df02 chore(deps): Bump react-dom and @types/react-dom
Bumps [react-dom](https://github.com/facebook/react/tree/HEAD/packages/react-dom) and [@types/react-dom](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react-dom). These dependencies needed to be updated together.

Updates `react-dom` from 18.3.1 to 19.1.1
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.1.1/packages/react-dom)

Updates `@types/react-dom` from 18.2.22 to 19.1.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react-dom)

---
updated-dependencies:
- dependency-name: react-dom
  dependency-version: 19.1.1
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: "@types/react-dom"
  dependency-version: 19.1.6
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-28 16:35:46 +00:00
55 changed files with 1478 additions and 1476 deletions
+23 -29
View File
@@ -7,7 +7,17 @@ on:
branches: [ main ] branches: [ main ]
jobs: jobs:
build-docker:
name: build docker
runs-on: ubuntu-latest
if: ${{ github.event_name == 'push' || github.event_name == 'pull_request' }}
steps:
- uses: actions/checkout@v4
- run: docker build -t test-docker-image-build .
# build the editor
build-node: build-node:
name: "build on ${{ matrix.os }}" name: "build on ${{ matrix.os }}"
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
@@ -20,8 +30,8 @@ jobs:
os: [ ubuntu-latest, windows-latest, macos-latest ] os: [ ubuntu-latest, windows-latest, macos-latest ]
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
- uses: actions/setup-node@v5 - uses: actions/setup-node@v4
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- run: npm ci - run: npm ci
@@ -37,8 +47,8 @@ jobs:
if: ${{ github.event_name == 'push' || github.event_name == 'pull_request' }} if: ${{ github.event_name == 'push' || github.event_name == 'pull_request' }}
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
- uses: actions/setup-node@v5 - uses: actions/setup-node@v4
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- run: npm ci - run: npm ci
@@ -51,7 +61,7 @@ jobs:
# Build and upload desktop CLI artifacts # Build and upload desktop CLI artifacts
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v6 uses: actions/setup-go@v5
with: with:
go-version: ^1.23.x go-version: ^1.23.x
cache-dependency-path: desktop/go.sum cache-dependency-path: desktop/go.sum
@@ -79,39 +89,23 @@ jobs:
path: ./desktop/bin/windows/ path: ./desktop/bin/windows/
e2e-tests: e2e-tests:
name: "E2E tests using chrome" name: "E2E tests using ${{ matrix.browser }}"
strategy:
fail-fast: false
matrix:
browser: [ chrome ]
runs-on: ubuntu-latest runs-on: ubuntu-22.04
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v4
- run: npm ci - run: npm ci
- name: Cypress run - name: Cypress run
uses: cypress-io/github-action@v6 uses: cypress-io/github-action@v6
with: with:
build: npm run build build: npm run build
start: npm run start start: npm run start
browser: chrome browser: ${{ matrix.browser }}
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
with:
files: ${{ github.workspace }}/.nyc_output/out.json
verbose: true
e2e-tests-docker:
name: "E2E tests using chrome and docker"
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- run: npm ci
- name: Cypress run
uses: cypress-io/github-action@v6
with:
build: docker build -t maputnik .
start: docker run --rm --network host maputnik --port=8888
browser: chrome
- name: Upload coverage reports to Codecov - name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5 uses: codecov/codecov-action@v5
with: with:
+1 -1
View File
@@ -38,7 +38,7 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v5 uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
+2 -2
View File
@@ -16,13 +16,13 @@ jobs:
run: run:
shell: bash shell: bash
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
ref: main ref: main
- name: Use Node.js from nvmrc - name: Use Node.js from nvmrc
uses: actions/setup-node@v5 uses: actions/setup-node@v4
with: with:
node-version-file: ".nvmrc" node-version-file: ".nvmrc"
+3 -3
View File
@@ -10,10 +10,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ github.event_name == 'push' }} if: ${{ github.event_name == 'push' }}
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
- name: Use Node.js from nvmrc - name: Use Node.js from nvmrc
uses: actions/setup-node@v5 uses: actions/setup-node@v4
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
@@ -46,6 +46,6 @@ jobs:
registry: ghcr.io registry: ghcr.io
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/checkout@v5 - uses: actions/checkout@v4
- run: docker build -t ghcr.io/maplibre/maputnik:main . - run: docker build -t ghcr.io/maplibre/maputnik:main .
- run: docker push ghcr.io/maplibre/maputnik:main - run: docker push ghcr.io/maplibre/maputnik:main
+5 -5
View File
@@ -13,13 +13,13 @@ jobs:
run: run:
shell: bash shell: bash
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
ref: main ref: main
- name: Use Node.js from nvmrc - name: Use Node.js from nvmrc
uses: actions/setup-node@v5 uses: actions/setup-node@v4
with: with:
node-version-file: ".nvmrc" node-version-file: ".nvmrc"
@@ -39,19 +39,19 @@ jobs:
run: run:
shell: bash shell: bash
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
ref: main ref: main
- name: Use Node.js from nvmrc - name: Use Node.js from nvmrc
uses: actions/setup-node@v5 uses: actions/setup-node@v4
with: with:
node-version-file: ".nvmrc" node-version-file: ".nvmrc"
registry-url: "https://registry.npmjs.org" registry-url: "https://registry.npmjs.org"
- name: Set up Go for desktop build - name: Set up Go for desktop build
uses: actions/setup-go@v6 uses: actions/setup-go@v5
with: with:
go-version: ^1.23.x go-version: ^1.23.x
cache-dependency-path: desktop/go.sum cache-dependency-path: desktop/go.sum
+1 -1
View File
@@ -6,7 +6,7 @@ ci:
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0 rev: v5.0.0
hooks: hooks:
- id: check-added-large-files - id: check-added-large-files
- id: check-executables-have-shebangs - id: check-executables-have-shebangs
+2 -15
View File
@@ -1,14 +1,5 @@
## main ## main
### ✨ Features and improvements
- _...Add new stuff here..._
### 🐞 Bug fixes
- _...Add new stuff here..._
## 3.0.0
### ✨ Features and improvements ### ✨ Features and improvements
- Fix radio/delete filter buttons styling regression - Fix radio/delete filter buttons styling regression
- Add german translation - Add german translation
@@ -25,17 +16,13 @@
- Remove usage of legacy `childContextTypes` API - Remove usage of legacy `childContextTypes` API
- Refactor Field components to use arrow function syntax - Refactor Field components to use arrow function syntax
- Replace react-autocomplete with Downshift in the autocomplete component - Replace react-autocomplete with Downshift in the autocomplete component
- Add LocationIQ as supported map provider with access token field and gallery style - _...Add new stuff here..._
- Use maputnik go binary for the docker image to allow file watching
- Revmove support for `debug` and `localport` url parameters
- Replace react-sortable-hoc with dnd-kit to avoid react console warnings and also use a maintained library
### 🐞 Bug fixes ### 🐞 Bug fixes
- Fix incorrect handing of network error response (#944) - Fix incorrect handing of network error response (#944)
- Show an error when adding a layer with a duplicate ID - Show an error when adding a layer with a duplicate ID
- Replace deprecated `ReactDOM.render` usage with `createRoot` and drop the - _...Add new stuff here..._
`DOMNodeRemoved` cleanup hack
## 2.1.1 ## 2.1.1
+10 -8
View File
@@ -1,14 +1,16 @@
FROM golang:1.23-alpine AS builder FROM node:18 as builder
WORKDIR /maputnik WORKDIR /maputnik
RUN apk add --no-cache nodejs npm make git gcc g++ libc-dev # Only copy package.json to prevent npm install from running on every build
COPY package.json package-lock.json .npmrc ./
RUN npm ci
# Build maputnik # Build maputnik
COPY . . COPY . .
RUN npm ci RUN npx vite build
RUN CGO_ENABLED=1 GOOS=linux npm run build-linux
FROM alpine:latest #---------------------------------------------------------------------------
WORKDIR /app # Create a clean nginx-alpine slim image with just the build results
COPY --from=builder /maputnik/desktop/bin/linux ./ FROM nginx:alpine-slim
ENTRYPOINT ["/app/maputnik"]
COPY --from=builder /maputnik/dist /usr/share/nginx/html/
+1 -7
View File
@@ -18,15 +18,9 @@ targeted at developers and map designers.
- In a Docker, run this command and browse to http://localhost:8888, Ctrl+C to stop the server. - In a Docker, run this command and browse to http://localhost:8888, Ctrl+C to stop the server.
```bash ```bash
docker run -it --rm -p 8888:8000 ghcr.io/maplibre/maputnik:main docker run -it --rm -p 8888:80 ghcr.io/maplibre/maputnik:main
``` ```
To see the CLI options (for example file watching or style serving) run:
```bash
docker run -it --rm -p 8888:8000 ghcr.io/maplibre/maputnik:main --help
```
You might need to mount a volume (`-v`) to be able to use these options.
## Documentation ## Documentation
The documentation can be found in the [Wiki](https://github.com/maplibre/maputnik/wiki). You are welcome to collaborate! The documentation can be found in the [Wiki](https://github.com/maplibre/maputnik/wiki). You are welcome to collaborate!
+1
View File
@@ -16,6 +16,7 @@ describe("history", () => {
it("undo/redo", () => { it("undo/redo", () => {
when.setStyle("geojson"); when.setStyle("geojson");
when.modal.open(); when.modal.open();
then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [] });
when.modal.fillLayers({ when.modal.fillLayers({
id: "step 1", id: "step 1",
+4 -89
View File
@@ -378,57 +378,8 @@ describe("layers", () => {
}); });
it("groups", () => { it("groups", () => {
when.modal.open(); // TODO
const id1 = when.modal.fillLayers({ // Click each of the layer groups.
id: "aa",
type: "line",
layer: "example",
});
when.modal.open();
const id2 = when.modal.fillLayers({
id: "aa-2",
type: "line",
layer: "example",
});
when.modal.open();
const id3 = when.modal.fillLayers({
id: "b",
type: "line",
layer: "example",
});
then(get.elementByTestId("layer-list-item:" + id1)).shouldBeVisible();
then(get.elementByTestId("layer-list-item:" + id2)).shouldNotBeVisible();
then(get.elementByTestId("layer-list-item:" + id3)).shouldBeVisible();
when.click("layer-list-group:aa-0");
then(get.elementByTestId("layer-list-item:" + id1)).shouldBeVisible();
then(get.elementByTestId("layer-list-item:" + id2)).shouldBeVisible();
then(get.elementByTestId("layer-list-item:" + id3)).shouldBeVisible();
when.click("layer-list-item:" + id2);
when.click("skip-target-layer-editor");
when.click("menu-move-layer-down");
then(get.elementByTestId("layer-list-group:aa-0")).shouldNotExist();
then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
layers: [
{
id: "aa",
type: "line",
source: "example",
},
{
id: "b",
type: "line",
source: "example",
},
{
id: "aa-2",
type: "line",
source: "example",
},
],
});
}); });
}); });
@@ -544,7 +495,9 @@ describe("layers", () => {
}); });
}); });
describe("layereditor jsonlint should error", ()=>{ describe("layereditor jsonlint should error", ()=>{
it("add", () => { it("add", () => {
const id = when.modal.fillLayers({ const id = when.modal.fillLayers({
type: "circle", type: "circle",
@@ -570,42 +523,4 @@ describe("layers", () => {
error.should('exist'); error.should('exist');
}); });
}); });
describe("drag and drop", () => {
it("move layer should update local storage", () => {
when.modal.open();
const firstId = when.modal.fillLayers({
id: "a",
type: "background",
});
when.modal.open();
const secondId = when.modal.fillLayers({
id: "b",
type: "background",
});
when.modal.open();
const thirdId = when.modal.fillLayers({
id: "c",
type: "background",
});
when.dragAndDrop(get.elementByTestId("layer-list-item:" + firstId), get.elementByTestId("layer-list-item:" + thirdId));
then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
layers: [
{
id: secondId,
type: "background",
},
{
id: thirdId,
type: "background",
},
{
id: firstId,
type: "background",
},
],
});
});
});
}); });
+10 -10
View File
@@ -94,8 +94,8 @@ export class MaputnikDriver {
public when = { public when = {
...this.helper.when, ...this.helper.when,
modal: this.modalDriver.when, modal: this.modalDriver.when,
doWithin: (selector: string, fn: () => void) => { within: (selector: string, fn: () => void) => {
this.helper.when.doWithin(fn, selector); this.helper.when.within(fn, selector);
}, },
tab: () => this.helper.get.element("body").tab(), tab: () => this.helper.get.element("body").tab(),
waitForExampleFileResponse: () => { waitForExampleFileResponse: () => {
@@ -110,25 +110,25 @@ export class MaputnikDriver {
styleProperties: "geojson" | "raster" | "both" | "layer" | "", styleProperties: "geojson" | "raster" | "both" | "layer" | "",
zoom?: number zoom?: number
) => { ) => {
const url = new URL(baseUrl); let url = "?debug";
switch (styleProperties) { switch (styleProperties) {
case "geojson": case "geojson":
url.searchParams.set("style", baseUrl + "geojson-style.json"); url += `&style=${baseUrl}geojson-style.json`;
break; break;
case "raster": case "raster":
url.searchParams.set("style", baseUrl + "raster-style.json"); url += `&style=${baseUrl}raster-style.json`;
break; break;
case "both": case "both":
url.searchParams.set("style", baseUrl + "geojson-raster-style.json"); url += `&style=${baseUrl}geojson-raster-style.json`;
break; break;
case "layer": case "layer":
url.searchParams.set("style", baseUrl + "example-layer-style.json"); url += `&style=${baseUrl}/example-layer-style.json`;
break; break;
} }
if (zoom) { if (zoom) {
url.hash = `${zoom}/41.3805/2.1635`; url += `#${zoom}/41.3805/2.1635`;
} }
this.helper.when.visit(url.toString()); this.helper.when.visit(baseUrl + url);
if (styleProperties) { if (styleProperties) {
this.helper.when.acceptConfirm(); this.helper.when.acceptConfirm();
} }
@@ -145,7 +145,7 @@ export class MaputnikDriver {
}, },
selectWithin: (selector: string, value: string) => { selectWithin: (selector: string, value: string) => {
this.when.doWithin(selector, () => { this.when.within(selector, () => {
this.helper.get.element("select").select(value); this.helper.get.element("select").select(value);
}); });
}, },
+2 -2
View File
@@ -20,8 +20,8 @@ export default class ModalDriver {
this.helper.when.type("add-layer.layer-id.input", id); this.helper.when.type("add-layer.layer-id.input", id);
if (layer) { if (layer) {
this.helper.when.doWithin(() => { this.helper.when.within(() => {
this.helper.get.element("input").clear().type(layer!); this.helper.get.element("input").type(layer!);
}, "add-layer.layer-source-block"); }, "add-layer.layer-source-block");
} }
this.helper.when.click("add-layer"); this.helper.when.click("add-layer");
-12
View File
@@ -224,18 +224,6 @@ describe("modals", () => {
).shouldInclude({ "maputnik:stadia_access_token": apiKey }); ).shouldInclude({ "maputnik:stadia_access_token": apiKey });
}); });
it("locationiq access token", () => {
const apiKey = "testing123";
when.setValue(
"modal:settings.maputnik:locationiq_access_token",
apiKey
);
when.click("modal:settings.name");
then(
get.styleFromLocalStorage().then((style) => style.metadata)
).shouldInclude({ "maputnik:locationiq_access_token": apiKey });
});
it("style renderer", () => { it("style renderer", () => {
cy.on("uncaught:exception", () => false); // this is due to the fact that this is an invalid style for openlayers cy.on("uncaught:exception", () => false); // this is due to the fact that this is an invalid style for openlayers
when.select("modal:settings.maputnik:renderer", "ol"); when.select("modal:settings.maputnik:renderer", "ol");
+2 -5
View File
@@ -2,7 +2,8 @@ SOURCEDIR=.
SOURCES := $(shell find $(SOURCEDIR) -name '*.go') SOURCES := $(shell find $(SOURCEDIR) -name '*.go')
BINARY=maputnik BINARY=maputnik
VERSION := $(shell node -p "require('../package.json').version") VERSION := $(shell node -p "require('../package.json').version")
GOBIN := $(or $(shell if [ -d /go/bin ]; then echo "/go/bin"; fi),$(HOME)/go/bin) GOPATH := $(if $(GOPATH),$(GOPATH),$(HOME)/go)
GOBIN := $(if $(GOBIN),$(GOBIN),$(HOME)/go/bin)
all: $(BINARY) all: $(BINARY)
@@ -10,10 +11,6 @@ $(BINARY): $(GOBIN)/gox $(GOBIN)/go-winres $(SOURCES) version.go rice-box.go win
$(GOBIN)/go-winres make --product-version=$(VERSION) $(GOBIN)/go-winres make --product-version=$(VERSION)
$(GOBIN)/gox -osarch "windows/amd64 linux/amd64 darwin/amd64" -output "bin/{{.OS}}/${BINARY}" $(GOBIN)/gox -osarch "windows/amd64 linux/amd64 darwin/amd64" -output "bin/{{.OS}}/${BINARY}"
bin/linux/$(BINARY): $(GOBIN)/gox $(GOBIN)/go-winres $(SOURCES) version.go rice-box.go winres/winres.json
$(GOBIN)/go-winres make --product-version=$(VERSION)
$(GOBIN)/gox -osarch "linux/amd64" -output "bin/{{.OS}}/${BINARY}"
winres/winres.json: winres/winres_template.json winres/winres.json: winres/winres_template.json
sed 's/{{.Version}}/$(VERSION)/g' winres/winres_template.json > $@ sed 's/{{.Version}}/$(VERSION)/g' winres/winres_template.json > $@
+2 -1
View File
@@ -5,7 +5,8 @@ import (
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"github.com/GeertJohan/go.rice"
"github.com/GeertJohan/go.rice"
"github.com/gorilla/handlers" "github.com/gorilla/handlers"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/maputnik/desktop/filewatch" "github.com/maputnik/desktop/filewatch"
+611 -605
View File
File diff suppressed because it is too large Load Diff
+26 -29
View File
@@ -1,14 +1,13 @@
{ {
"name": "maputnik", "name": "maputnik",
"version": "3.0.0", "version": "2.1.1",
"description": "A MapLibre GL visual style editor", "description": "A MapLibre GL visual style editor",
"type": "module", "type": "module",
"main": "''", "main": "''",
"scripts": { "scripts": {
"start": "vite", "start": "vite",
"build": "tsc && vite build --mode=production", "build": "tsc && vite build --base=/maputnik/",
"build-desktop": "tsc && vite build --mode=desktop && cd desktop && make", "build-desktop": "tsc && vite build --base=/ && cd desktop && make",
"build-linux": "tsc && vite build --mode=desktop && cd desktop && make bin/linux/maputnik",
"i18n:refresh": "i18next 'src/**/*.{ts,tsx,js,jsx}'", "i18n:refresh": "i18next 'src/**/*.{ts,tsx,js,jsx}'",
"lint": "eslint", "lint": "eslint",
"test": "cypress run", "test": "cypress run",
@@ -24,26 +23,22 @@
"license": "MIT", "license": "MIT",
"homepage": "https://github.com/maplibre/maputnik#readme", "homepage": "https://github.com/maplibre/maputnik#readme",
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@mapbox/mapbox-gl-rtl-text": "^0.3.0", "@mapbox/mapbox-gl-rtl-text": "^0.3.0",
"@maplibre/maplibre-gl-geocoder": "^1.9.0", "@maplibre/maplibre-gl-geocoder": "^1.9.0",
"@maplibre/maplibre-gl-inspect": "^1.7.1", "@maplibre/maplibre-gl-inspect": "^1.7.1",
"@maplibre/maplibre-gl-style-spec": "^23.3.0", "@maplibre/maplibre-gl-style-spec": "^23.2.3",
"@mdi/js": "^7.4.47", "@mdi/js": "^7.4.47",
"@mdi/react": "^1.6.1", "@mdi/react": "^1.6.1",
"@prantlf/jsonlint": "^16.0.0", "@prantlf/jsonlint": "^16.0.0",
"array-move": "^4.0.0", "array-move": "^4.0.0",
"buffer": "^6.0.3", "buffer": "^6.0.3",
"classnames": "^2.5.1", "classnames": "^2.5.1",
"codemirror": "^5.65.20", "codemirror": "^5.65.19",
"color": "^5.0.0", "color": "^5.0.0",
"detect-browser": "^5.3.0", "detect-browser": "^5.3.0",
"downshift": "^9.0.10",
"events": "^3.3.0", "events": "^3.3.0",
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"i18next": "^25.5.2", "i18next": "^25.3.2",
"i18next-browser-languagedetector": "^8.2.0", "i18next-browser-languagedetector": "^8.2.0",
"i18next-resources-to-backend": "^1.2.1", "i18next-resources-to-backend": "^1.2.1",
"json-stringify-pretty-compact": "^4.0.0", "json-stringify-pretty-compact": "^4.0.0",
@@ -55,23 +50,25 @@
"lodash.get": "^4.4.2", "lodash.get": "^4.4.2",
"lodash.isequal": "^4.5.0", "lodash.isequal": "^4.5.0",
"lodash.throttle": "^4.1.1", "lodash.throttle": "^4.1.1",
"maplibre-gl": "^5.7.1", "maplibre-gl": "^5.5.0",
"maputnik-design": "github:maputnik/design#172b06c", "maputnik-design": "github:maputnik/design#172b06c",
"ol": "^10.6.1", "ol": "^10.6.1",
"ol-mapbox-style": "^13.1.0", "ol-mapbox-style": "^13.0.1",
"pmtiles": "^4.3.0", "pmtiles": "^4.3.0",
"prop-types": "^15.8.1", "prop-types": "^15.8.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-accessible-accordion": "^5.0.1", "react-accessible-accordion": "^5.0.1",
"react-aria-menubutton": "^7.0.3", "react-aria-menubutton": "^7.0.3",
"react-aria-modal": "^5.0.2", "react-aria-modal": "^5.0.2",
"downshift": "^9.0.10",
"react-collapse": "^5.1.1", "react-collapse": "^5.1.1",
"react-color": "^2.19.3", "react-color": "^2.19.3",
"react-dom": "^18.2.0", "react-dom": "^19.1.1",
"react-file-reader-input": "^2.0.0", "react-file-reader-input": "^2.0.0",
"react-i18next": "^15.7.3", "react-i18next": "^15.6.1",
"react-icon-base": "^2.1.2", "react-icon-base": "^2.1.2",
"react-icons": "^5.5.0", "react-icons": "^5.5.0",
"react-sortable-hoc": "^2.0.0",
"reconnecting-websocket": "^4.4.0", "reconnecting-websocket": "^4.4.0",
"slugify": "^1.6.6", "slugify": "^1.6.6",
"string-hash": "^1.1.3", "string-hash": "^1.1.3",
@@ -95,12 +92,12 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@cypress/code-coverage": "^3.14.6", "@cypress/code-coverage": "^3.14.5",
"@eslint/js": "^9.35.0", "@eslint/js": "^9.31.0",
"@istanbuljs/nyc-config-typescript": "^1.0.2", "@istanbuljs/nyc-config-typescript": "^1.0.2",
"@rollup/plugin-replace": "^6.0.2", "@rollup/plugin-replace": "^6.0.2",
"@shellygo/cypress-test-utils": "^6.0.1", "@shellygo/cypress-test-utils": "^5.0.2",
"@types/codemirror": "^5.60.16", "@types/codemirror": "^5.60.15",
"@types/color": "^4.2.0", "@types/color": "^4.2.0",
"@types/cors": "^2.8.19", "@types/cors": "^2.8.19",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
@@ -118,17 +115,17 @@
"@types/react-aria-modal": "^5.0.0", "@types/react-aria-modal": "^5.0.0",
"@types/react-collapse": "^5.0.4", "@types/react-collapse": "^5.0.4",
"@types/react-color": "^3.0.13", "@types/react-color": "^3.0.13",
"@types/react-dom": "^18.2.22", "@types/react-dom": "^19.1.6",
"@types/react-file-reader-input": "^2.0.4", "@types/react-file-reader-input": "^2.0.4",
"@types/react-icon-base": "^2.1.6", "@types/react-icon-base": "^2.1.6",
"@types/string-hash": "^1.1.3", "@types/string-hash": "^1.1.3",
"@types/uuid": "^10.0.0", "@types/uuid": "^10.0.0",
"@types/wicg-file-system-access": "^2023.10.6", "@types/wicg-file-system-access": "^2023.10.6",
"@vitejs/plugin-react": "^5.0.2", "@vitejs/plugin-react": "^4.7.0",
"cors": "^2.8.5", "cors": "^2.8.5",
"cypress": "^15.1.0", "cypress": "^14.5.2",
"cypress-plugin-tab": "^1.0.5", "cypress-plugin-tab": "^1.0.5",
"eslint": "^9.35.0", "eslint": "^9.31.0",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20", "eslint-plugin-react-refresh": "^0.4.20",
@@ -137,14 +134,14 @@
"istanbul-lib-coverage": "^3.2.2", "istanbul-lib-coverage": "^3.2.2",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"react-hot-loader": "^4.13.1", "react-hot-loader": "^4.13.1",
"sass": "^1.92.1", "sass": "^1.89.2",
"stylelint": "^16.24.0", "stylelint": "^16.22.0",
"stylelint-config-recommended-scss": "^16.0.0", "stylelint-config-recommended-scss": "^15.0.1",
"stylelint-scss": "^6.12.1", "stylelint-scss": "^6.12.1",
"typescript": "^5.8.3", "typescript": "^5.8.3",
"typescript-eslint": "^8.43.0", "typescript-eslint": "^8.38.0",
"uuid": "^13.0.0", "uuid": "^11.1.0",
"vite": "^7.1.5", "vite": "^6.3.5",
"vite-plugin-istanbul": "^7.1.0" "vite-plugin-istanbul": "^7.1.0"
} }
} }
+144 -90
View File
@@ -27,14 +27,17 @@ import ModalDebug from './ModalDebug'
import {downloadGlyphsMetadata, downloadSpriteMetadata} from '../libs/metadata' import {downloadGlyphsMetadata, downloadSpriteMetadata} from '../libs/metadata'
import style from '../libs/style' import style from '../libs/style'
import { initialStyleUrl, loadStyleUrl, removeStyleQuerystring } from '../libs/urlopen'
import { undoMessages, redoMessages } from '../libs/diffmessage' import { undoMessages, redoMessages } from '../libs/diffmessage'
import { createStyleStore, type IStyleStore } from '../libs/store/style-store-factory' import { StyleStore } from '../libs/stylestore'
import { ApiStyleStore } from '../libs/apistore'
import { RevisionStore } from '../libs/revisions' import { RevisionStore } from '../libs/revisions'
import LayerWatcher from '../libs/layerwatcher' import LayerWatcher from '../libs/layerwatcher'
import tokens from '../config/tokens.json' import tokens from '../config/tokens.json'
import isEqual from 'lodash.isequal' import isEqual from 'lodash.isequal'
import Debug from '../libs/debug'
import { SortEnd } from 'react-sortable-hoc';
import { MapOptions } from 'maplibre-gl'; import { MapOptions } from 'maplibre-gl';
import { OnStyleChangedOpts, StyleSpecificationWithId } from '../libs/definitions'
// Buffer must be defined globally for @maplibre/maplibre-gl-style-spec validate() function to succeed. // Buffer must be defined globally for @maplibre/maplibre-gl-style-spec validate() function to succeed.
window.Buffer = buffer.Buffer; window.Buffer = buffer.Buffer;
@@ -43,7 +46,6 @@ function setFetchAccessToken(url: string, mapStyle: StyleSpecification) {
const matchesTilehosting = url.match(/\.tilehosting\.com/); const matchesTilehosting = url.match(/\.tilehosting\.com/);
const matchesMaptiler = url.match(/\.maptiler\.com/); const matchesMaptiler = url.match(/\.maptiler\.com/);
const matchesThunderforest = url.match(/\.thunderforest\.com/); const matchesThunderforest = url.match(/\.thunderforest\.com/);
const matchesLocationIQ = url.match(/\.locationiq\.com/);
if (matchesTilehosting || matchesMaptiler) { if (matchesTilehosting || matchesMaptiler) {
const accessToken = style.getAccessToken("openmaptiles", mapStyle, {allowFallback: true}) const accessToken = style.getAccessToken("openmaptiles", mapStyle, {allowFallback: true})
if (accessToken) { if (accessToken) {
@@ -56,12 +58,6 @@ function setFetchAccessToken(url: string, mapStyle: StyleSpecification) {
return url.replace('{key}', accessToken) return url.replace('{key}', accessToken)
} }
} }
else if (matchesLocationIQ) {
const accessToken = style.getAccessToken("locationiq", mapStyle, {allowFallback: true})
if (accessToken) {
return url.replace('{key}', accessToken)
}
}
else { else {
return url; return url;
} }
@@ -80,6 +76,12 @@ function updateRootSpec(spec: any, fieldName: string, newValues: any) {
} }
} }
type OnStyleChangedOpts = {
save?: boolean
addRevision?: boolean
initialLoad?: boolean
}
type MappedErrors = { type MappedErrors = {
message: string message: string
parsed?: { parsed?: {
@@ -95,11 +97,11 @@ type MappedErrors = {
type AppState = { type AppState = {
errors: MappedErrors[], errors: MappedErrors[],
infos: string[], infos: string[],
mapStyle: StyleSpecificationWithId, mapStyle: StyleSpecification & {id: string},
dirtyMapStyle?: StyleSpecification, dirtyMapStyle?: StyleSpecification,
selectedLayerIndex: number, selectedLayerIndex: number,
selectedLayerOriginalId?: string, selectedLayerOriginalId?: string,
sources: {[key: string]: SourceSpecification & {layers: string[]} }, sources: {[key: string]: SourceSpecification},
vectorLayers: {}, vectorLayers: {},
spec: any, spec: any,
mapView: { mapView: {
@@ -131,56 +133,25 @@ type AppState = {
export default class App extends React.Component<any, AppState> { export default class App extends React.Component<any, AppState> {
revisionStore: RevisionStore; revisionStore: RevisionStore;
styleStore: IStyleStore | null = null; styleStore: StyleStore | ApiStyleStore;
layerWatcher: LayerWatcher; layerWatcher: LayerWatcher;
constructor(props: any) { constructor(props: any) {
super(props) super(props)
this.revisionStore = new RevisionStore(); this.revisionStore = new RevisionStore()
this.configureKeyboardShortcuts(); const params = new URLSearchParams(window.location.search.substring(1))
let port = params.get("localport")
this.state = { if (port == null && (window.location.port !== "80" && window.location.port !== "443")) {
errors: [], port = window.location.port
infos: [],
mapStyle: style.emptyStyle,
selectedLayerIndex: 0,
sources: {},
vectorLayers: {},
mapState: "map",
spec: latest,
mapView: {
zoom: 0,
center: {
lng: 0,
lat: 0,
},
},
isOpen: {
settings: false,
sources: false,
open: false,
shortcuts: false,
export: false,
debug: false,
},
maplibreGlDebugOptions: {
showTileBoundaries: false,
showCollisionBoxes: false,
showOverdrawInspector: false,
},
openlayersDebugOptions: {
debugToolbox: false,
},
fileHandle: null,
} }
this.styleStore = new ApiStyleStore({
this.layerWatcher = new LayerWatcher({ onLocalStyleChange: mapStyle => this.onStyleChanged(mapStyle, {save: false}),
onVectorLayersChange: v => this.setState({ vectorLayers: v }) port: port,
host: params.get("localhost")
}) })
}
configureKeyboardShortcuts = () => {
const shortcuts = [ const shortcuts = [
{ {
key: "?", key: "?",
@@ -250,6 +221,74 @@ export default class App extends React.Component<any, AppState> {
} }
} }
}) })
const styleUrl = initialStyleUrl()
if(styleUrl && window.confirm("Load style from URL: " + styleUrl + " and discard current changes?")) {
this.styleStore = new StyleStore()
loadStyleUrl(styleUrl, mapStyle => this.onStyleChanged(mapStyle))
removeStyleQuerystring()
} else {
if(styleUrl) {
removeStyleQuerystring()
}
this.styleStore.init(err => {
if(err) {
console.log('Falling back to local storage for storing styles')
this.styleStore = new StyleStore()
}
this.styleStore.latestStyle(mapStyle => this.onStyleChanged(mapStyle, {initialLoad: true}))
if(Debug.enabled()) {
Debug.set("maputnik", "styleStore", this.styleStore);
Debug.set("maputnik", "revisionStore", this.revisionStore);
}
})
}
if(Debug.enabled()) {
Debug.set("maputnik", "revisionStore", this.revisionStore);
Debug.set("maputnik", "styleStore", this.styleStore);
}
this.state = {
errors: [],
infos: [],
mapStyle: style.emptyStyle,
selectedLayerIndex: 0,
sources: {},
vectorLayers: {},
mapState: "map",
spec: latest,
mapView: {
zoom: 0,
center: {
lng: 0,
lat: 0,
},
},
isOpen: {
settings: false,
sources: false,
open: false,
shortcuts: false,
export: false,
// TODO: Disabled for now, this should be opened on the Nth visit to the editor
debug: false,
},
maplibreGlDebugOptions: {
showTileBoundaries: false,
showCollisionBoxes: false,
showOverdrawInspector: false,
},
openlayersDebugOptions: {
debugToolbox: false,
},
fileHandle: null,
}
this.layerWatcher = new LayerWatcher({
onVectorLayersChange: v => this.setState({ vectorLayers: v })
})
} }
handleKeyPress = (e: KeyboardEvent) => { handleKeyPress = (e: KeyboardEvent) => {
@@ -275,8 +314,7 @@ export default class App extends React.Component<any, AppState> {
} }
} }
async componentDidMount() { componentDidMount() {
this.styleStore = await createStyleStore((mapStyle, opts) => this.onStyleChanged(mapStyle, opts));
window.addEventListener("keydown", this.handleKeyPress); window.addEventListener("keydown", this.handleKeyPress);
} }
@@ -284,8 +322,8 @@ export default class App extends React.Component<any, AppState> {
window.removeEventListener("keydown", this.handleKeyPress); window.removeEventListener("keydown", this.handleKeyPress);
} }
saveStyle(snapshotStyle: StyleSpecificationWithId) { saveStyle(snapshotStyle: StyleSpecification & {id: string}) {
this.styleStore?.save(snapshotStyle) this.styleStore.save(snapshotStyle)
} }
updateFonts(urlTemplate: string) { updateFonts(urlTemplate: string) {
@@ -326,7 +364,7 @@ export default class App extends React.Component<any, AppState> {
this.onStyleChanged(changedStyle) this.onStyleChanged(changedStyle)
} }
onStyleChanged = (newStyle: StyleSpecificationWithId, opts: OnStyleChangedOpts={}): void => { onStyleChanged = (newStyle: StyleSpecification & {id: string}, opts: OnStyleChangedOpts={}) => {
opts = { opts = {
save: true, save: true,
addRevision: true, addRevision: true,
@@ -357,6 +395,7 @@ export default class App extends React.Component<any, AppState> {
} }
const errors: ValidationError[] = validateStyleMin(newStyle) || []; const errors: ValidationError[] = validateStyleMin(newStyle) || [];
// The validate function doesn't give us errors for duplicate error with // The validate function doesn't give us errors for duplicate error with
// empty string for layer.id, manually deal with that here. // empty string for layer.id, manually deal with that here.
const layerErrors: (Error | ValidationError)[] = []; const layerErrors: (Error | ValidationError)[] = [];
@@ -435,7 +474,7 @@ export default class App extends React.Component<any, AppState> {
if (errors.length > 0) { if (errors.length > 0) {
dirtyMapStyle = cloneDeep(newStyle); dirtyMapStyle = cloneDeep(newStyle);
for (const error of errors) { errors.forEach(error => {
const {message} = error; const {message} = error;
if (message) { if (message) {
try { try {
@@ -445,10 +484,10 @@ export default class App extends React.Component<any, AppState> {
unset(dirtyMapStyle, unsetPath); unset(dirtyMapStyle, unsetPath);
} }
catch (err) { catch (err) {
console.warn(message + " " + err); console.warn(err);
} }
} }
} });
} }
if(newStyle.glyphs !== this.state.mapStyle.glyphs) { if(newStyle.glyphs !== this.state.mapStyle.glyphs) {
@@ -462,7 +501,7 @@ export default class App extends React.Component<any, AppState> {
this.revisionStore.addRevision(newStyle); this.revisionStore.addRevision(newStyle);
} }
if (opts.save) { if (opts.save) {
this.saveStyle(newStyle); this.saveStyle(newStyle as StyleSpecification & {id: string});
} }
this.setState({ this.setState({
@@ -495,7 +534,7 @@ export default class App extends React.Component<any, AppState> {
}) })
} }
onMoveLayer = (move: {oldIndex: number; newIndex: number}) => { onMoveLayer = (move: SortEnd) => {
let { oldIndex, newIndex } = move; let { oldIndex, newIndex } = move;
let layers = this.state.mapStyle.layers; let layers = this.state.mapStyle.layers;
oldIndex = clamp(oldIndex, 0, layers.length-1); oldIndex = clamp(oldIndex, 0, layers.length-1);
@@ -575,7 +614,7 @@ export default class App extends React.Component<any, AppState> {
}, this.setStateInUrl); }, this.setStateInUrl);
} }
setDefaultValues = (styleObj: StyleSpecificationWithId) => { setDefaultValues = (styleObj: StyleSpecification & {id: string}) => {
const metadata: {[key: string]: string} = styleObj.metadata || {} as any const metadata: {[key: string]: string} = styleObj.metadata || {} as any
if(metadata['maputnik:renderer'] === undefined) { if(metadata['maputnik:renderer'] === undefined) {
const changedStyle = { const changedStyle = {
@@ -591,28 +630,27 @@ export default class App extends React.Component<any, AppState> {
} }
} }
openStyle = (styleObj: StyleSpecificationWithId, fileHandle: FileSystemFileHandle | null) => { openStyle = (styleObj: StyleSpecification & {id: string}, fileHandle: FileSystemFileHandle | null) => {
this.setState({fileHandle: fileHandle}); this.setState({fileHandle: fileHandle});
styleObj = this.setDefaultValues(styleObj) styleObj = this.setDefaultValues(styleObj)
this.onStyleChanged(styleObj) this.onStyleChanged(styleObj)
} }
async fetchSources() { fetchSources() {
const sourceList: {[key: string]: SourceSpecification & {layers: string[]}} = {}; const sourceList: {[key: string]: any} = {};
for(const key of Object.keys(this.state.mapStyle.sources)) {
const source = this.state.mapStyle.sources[key]; for(const [key, val] of Object.entries(this.state.mapStyle.sources)) {
if(source.type !== "vector" || !('url' in source)) { if(
sourceList[key] = this.state.sources[key] || {...this.state.mapStyle.sources[key]}; !Object.prototype.hasOwnProperty.call(this.state.sources, key) &&
if (sourceList[key].layers === undefined) { val.type === "vector" &&
sourceList[key].layers = []; Object.prototype.hasOwnProperty.call(val, "url")
} ) {
} else {
sourceList[key] = { sourceList[key] = {
type: source.type, type: val.type,
layers: [] layers: []
}; };
let url = source.url; let url = val.url;
try { try {
url = setFetchAccessToken(url!, this.state.mapStyle) url = setFetchAccessToken(url!, this.state.mapStyle)
@@ -625,28 +663,44 @@ export default class App extends React.Component<any, AppState> {
return; return;
} }
// Create new objects before setState
const sources = Object.assign({}, {
[key]: this.state.sources[key],
});
for(const layer of json.vector_layers) { for(const layer of json.vector_layers) {
sourceList[key].layers.push(layer.id) (sources[key] as any).layers.push(layer.id)
} }
this.setState({
sources: sources
});
}; };
try { if (url!.startsWith("pmtiles://")) {
if (url!.startsWith("pmtiles://")) { (new PMTiles(url!.substr(10))).getTileJson("")
const json = await (new PMTiles(url!.substring(10))).getTileJson(""); .then(json => setVectorLayers(json))
setVectorLayers(json); .catch(err => {
} else { console.error("Failed to process sources for '%s'", url, err);
const response = await fetch(url!, { mode: 'cors' }); });
const json = await response.json(); } else {
setVectorLayers(json); fetch(url!, {
} mode: 'cors',
} catch(err) { })
console.error(`Failed to process source for url: '${url}', ${err}`); .then(response => response.json())
.then(json => setVectorLayers(json))
.catch(err => {
console.error("Failed to process sources for '%s'", url, err);
});
} }
} }
else {
sourceList[key] = this.state.sources[key] || this.state.mapStyle.sources[key];
}
} }
if(!isEqual(this.state.sources, sourceList)) { if(!isEqual(this.state.sources, sourceList)) {
console.debug("Setting sources", sourceList); console.debug("Setting sources");
this.setState({ this.setState({
sources: sourceList sources: sourceList
}) })
+2 -3
View File
@@ -16,7 +16,6 @@ import pkgJson from '../../package.json'
import maputnikLogo from 'maputnik-design/logos/logo-color.svg?inline' import maputnikLogo from 'maputnik-design/logos/logo-color.svg?inline'
import { withTranslation, WithTranslation } from 'react-i18next'; import { withTranslation, WithTranslation } from 'react-i18next';
import { supportedLanguages } from '../i18n'; import { supportedLanguages } from '../i18n';
import type { OnStyleChangedCallback } from '../libs/definitions';
// This is required because of <https://stackoverflow.com/a/49846426>, there isn't another way to detect support that I'm aware of. // This is required because of <https://stackoverflow.com/a/49846426>, there isn't another way to detect support that I'm aware of.
const browser = detect(); const browser = detect();
@@ -94,9 +93,9 @@ export type MapState = "map" | "inspect" | "filter-achromatopsia" | "filter-deut
type AppToolbarInternalProps = { type AppToolbarInternalProps = {
mapStyle: object mapStyle: object
inspectModeEnabled: boolean inspectModeEnabled: boolean
onStyleChanged: OnStyleChangedCallback onStyleChanged(...args: unknown[]): unknown
// A new style has been uploaded // A new style has been uploaded
onStyleOpen: OnStyleChangedCallback onStyleOpen(...args: unknown[]): unknown
// A dict of source id's and the available source layers // A dict of source id's and the available source layers
sources: object sources: object
children?: React.ReactNode children?: React.ReactNode
+11 -13
View File
@@ -13,30 +13,28 @@ type FieldSourceInternalProps = {
error?: {message: string} error?: {message: string}
} & WithTranslation; } & WithTranslation;
const FieldSourceInternal: React.FC<FieldSourceInternalProps> = ({ const FieldSourceInternal: React.FC<FieldSourceInternalProps> = (props) => {
onChange = () => {}, const t = props.t;
sourceIds = [],
wdKey,
value,
error,
t
}) => {
return ( return (
<Block <Block
label={t('Source')} label={t('Source')}
fieldSpec={latest.layer.source} fieldSpec={latest.layer.source}
error={error} error={props.error}
data-wd-key={wdKey} data-wd-key={props.wdKey}
> >
<InputAutocomplete <InputAutocomplete
value={value} value={props.value}
onChange={onChange} onChange={props.onChange}
options={sourceIds?.map((src) => [src, src])} options={props.sourceIds?.map((src) => [src, src])}
/> />
</Block> </Block>
); );
}; };
FieldSourceInternal.defaultProps = {
onChange: () => {},
sourceIds: [],
};
const FieldSource = withTranslation()(FieldSourceInternal); const FieldSource = withTranslation()(FieldSourceInternal);
export default FieldSource; export default FieldSource;
+13 -11
View File
@@ -9,31 +9,33 @@ type FieldSourceLayerInternalProps = {
value?: string value?: string
onChange?(...args: unknown[]): unknown onChange?(...args: unknown[]): unknown
sourceLayerIds?: unknown[] sourceLayerIds?: unknown[]
isFixed?: boolean
error?: {message: string} error?: {message: string}
} & WithTranslation; } & WithTranslation;
const FieldSourceLayerInternal: React.FC<FieldSourceLayerInternalProps> = ({ const FieldSourceLayerInternal: React.FC<FieldSourceLayerInternalProps> = (props) => {
onChange = () => {}, const t = props.t;
sourceLayerIds = [],
value,
error,
t
}) => {
return ( return (
<Block <Block
label={t('Source Layer')} label={t('Source Layer')}
fieldSpec={latest.layer['source-layer']} fieldSpec={latest.layer['source-layer']}
data-wd-key="layer-source-layer" data-wd-key="layer-source-layer"
error={error} error={props.error}
> >
<InputAutocomplete <InputAutocomplete
value={value} value={props.value}
onChange={onChange} onChange={props.onChange}
options={sourceLayerIds?.map((l) => [l, l])} options={props.sourceLayerIds?.map((l) => [l, l])}
/> />
</Block> </Block>
); );
}; };
FieldSourceLayerInternal.defaultProps = {
onChange: () => {},
sourceLayerIds: [],
isFixed: false,
};
const FieldSourceLayer = withTranslation()(FieldSourceLayerInternal); const FieldSourceLayer = withTranslation()(FieldSourceLayerInternal);
export default FieldSourceLayer; export default FieldSourceLayer;
+28 -21
View File
@@ -1,10 +1,10 @@
import React from 'react' import React from 'react'
import {v8} from '@maplibre/maplibre-gl-style-spec'
import latest from '@maplibre/maplibre-gl-style-spec/dist/latest.json'
import Block from './Block' import Block from './Block'
import InputSelect from './InputSelect' import InputSelect from './InputSelect'
import InputString from './InputString' import InputString from './InputString'
import { WithTranslation, withTranslation } from 'react-i18next'; import { WithTranslation, withTranslation } from 'react-i18next';
import { startCase } from 'lodash'
type FieldTypeInternalProps = { type FieldTypeInternalProps = {
value: string value: string
@@ -14,34 +14,41 @@ type FieldTypeInternalProps = {
disabled?: boolean disabled?: boolean
} & WithTranslation; } & WithTranslation;
const FieldTypeInternal: React.FC<FieldTypeInternalProps> = ({ const FieldTypeInternal: React.FC<FieldTypeInternalProps> = (props) => {
t, const t = props.t;
value,
wdKey,
onChange,
error,
disabled = false
}) => {
const layerstypes: [string, string][] = Object.keys(v8.layer.type.values || {}).map(v => [v, startCase(v.replace(/-/g, ' '))]);
return ( return (
<Block label={t('Type')} fieldSpec={v8.layer.type} <Block label={t('Type')} fieldSpec={latest.layer.type}
data-wd-key={wdKey} data-wd-key={props.wdKey}
error={error} error={props.error}
> >
{disabled && ( {props.disabled && (
<InputString value={value} disabled={true} /> <InputString value={props.value} disabled={true} />
)} )}
{!disabled && ( {!props.disabled && (
<InputSelect <InputSelect
options={layerstypes} options={[
onChange={onChange} ['background', 'Background'],
value={value} ['fill', 'Fill'],
data-wd-key={wdKey + '.select'} ['line', 'Line'],
['symbol', 'Symbol'],
['raster', 'Raster'],
['circle', 'Circle'],
['fill-extrusion', 'Fill Extrusion'],
['hillshade', 'Hillshade'],
['heatmap', 'Heatmap'],
]}
onChange={props.onChange}
value={props.value}
data-wd-key={props.wdKey + '.select'}
/> />
)} )}
</Block> </Block>
); );
}; };
FieldTypeInternal.defaultProps = {
disabled: false,
};
const FieldType = withTranslation()(FieldTypeInternal); const FieldType = withTranslation()(FieldTypeInternal);
export default FieldType; export default FieldType;
+2 -3
View File
@@ -1,7 +1,7 @@
import React from 'react' import React from 'react'
import {mdiTableRowPlusAfter} from '@mdi/js'; import {mdiTableRowPlusAfter} from '@mdi/js';
import {isEqual} from 'lodash'; import {isEqual} from 'lodash';
import {ExpressionSpecification, LegacyFilterSpecification} from 'maplibre-gl' import {ExpressionSpecification, LegacyFilterSpecification, StyleSpecification} from 'maplibre-gl'
import {latest, migrate, convertFilter} from '@maplibre/maplibre-gl-style-spec' import {latest, migrate, convertFilter} from '@maplibre/maplibre-gl-style-spec'
import {mdiFunctionVariant} from '@mdi/js'; import {mdiFunctionVariant} from '@mdi/js';
@@ -14,7 +14,6 @@ import InputButton from './InputButton'
import Doc from './Doc' import Doc from './Doc'
import ExpressionProperty from './_ExpressionProperty'; import ExpressionProperty from './_ExpressionProperty';
import { WithTranslation, withTranslation } from 'react-i18next'; import { WithTranslation, withTranslation } from 'react-i18next';
import type { StyleSpecificationWithId } from '../libs/definitions';
function combiningFilter(props: FilterEditorInternalProps): LegacyFilterSpecification | ExpressionSpecification { function combiningFilter(props: FilterEditorInternalProps): LegacyFilterSpecification | ExpressionSpecification {
@@ -40,7 +39,7 @@ function migrateFilter(filter: LegacyFilterSpecification | ExpressionSpecificati
return (migrate(createStyleFromFilter(filter) as any).layers[0] as any).filter; return (migrate(createStyleFromFilter(filter) as any).layers[0] as any).filter;
} }
function createStyleFromFilter(filter: LegacyFilterSpecification | ExpressionSpecification): StyleSpecificationWithId { function createStyleFromFilter(filter: LegacyFilterSpecification | ExpressionSpecification): StyleSpecification & {id: string} {
return { return {
"id": "tmp", "id": "tmp",
"version": 8, "version": 8,
+31 -95
View File
@@ -4,7 +4,6 @@ import {Accordion} from 'react-accessible-accordion';
import {MdMoreVert} from 'react-icons/md' import {MdMoreVert} from 'react-icons/md'
import { IconContext } from 'react-icons' import { IconContext } from 'react-icons'
import {BackgroundLayerSpecification, LayerSpecification, SourceSpecification} from 'maplibre-gl'; import {BackgroundLayerSpecification, LayerSpecification, SourceSpecification} from 'maplibre-gl';
import {v8} from '@maplibre/maplibre-gl-style-spec';
import FieldJson from './FieldJson' import FieldJson from './FieldJson'
import FilterEditor from './FilterEditor' import FilterEditor from './FilterEditor'
@@ -18,79 +17,23 @@ import FieldComment from './FieldComment'
import FieldSource from './FieldSource' import FieldSource from './FieldSource'
import FieldSourceLayer from './FieldSourceLayer' import FieldSourceLayer from './FieldSourceLayer'
import { changeType, changeProperty } from '../libs/layer' import { changeType, changeProperty } from '../libs/layer'
import layout from '../config/layout.json'
import {formatLayerId} from '../libs/format'; import {formatLayerId} from '../libs/format';
import { WithTranslation, withTranslation } from 'react-i18next'; import { WithTranslation, withTranslation } from 'react-i18next';
import { TFunction } from 'i18next'; import { TFunction } from 'i18next';
import { NON_SOURCE_LAYERS } from '../libs/non-source-layers';
import { OnMoveLayerCallback } from '../libs/definitions';
type MaputnikLayoutGroup = {
id: string;
title: string;
type: string;
fields: string[];
}
function getLayoutForSymbolType(t: TFunction): MaputnikLayoutGroup[] { function getLayoutForType(type: LayerSpecification["type"], t: TFunction) {
const groups: MaputnikLayoutGroup[] = []; return layout[type] ? {
groups.push({ ...layout[type],
title: t("General layout properties"), groups: layout[type].groups.map(group => {
id: "General_layout_properties", return {
type: "properties", ...group,
fields: Object.keys(v8["layout_symbol"]).filter(f => f.startsWith("symbol-")) id: group.title.replace(/ /g, "_"),
}); title: t(group.title)
groups.push({ };
title: t("Text layout properties"), }),
id: "Text_layout_properties", } : layout.invalid;
type: "properties",
fields: Object.keys(v8["layout_symbol"]).filter(f => f.startsWith("text-"))
});
groups.push({
title: t("Icon layout properties"),
id: "Icon_layout_properties",
type: "properties",
fields: Object.keys(v8["layout_symbol"]).filter(f => f.startsWith("icon-"))
});
groups.push({
title: t("Text paint properties"),
id: "Text_paint_properties",
type: "properties",
fields: Object.keys(v8["paint_symbol"]).filter(f => f.startsWith("text-"))
});
groups.push({
title: t("Icon paint properties"),
id: "Icon_paint_properties",
type: "properties",
fields: Object.keys(v8["paint_symbol"]).filter(f => f.startsWith("icon-"))
});
return groups;
}
function getLayoutForType(type: LayerSpecification["type"], t: TFunction): MaputnikLayoutGroup[] {
if (Object.keys(v8.layer.type.values).indexOf(type) < 0) {
return []
}
if (type === "symbol") {
return getLayoutForSymbolType(t);
}
const groups: MaputnikLayoutGroup[] = [];
if (Object.keys(v8["paint_" + type]).length > 0) {
groups.push({
title: t("Paint properties"),
id: "Paint_properties",
type: "properties",
fields: Object.keys(v8["paint_" + type]),
});
}
if (Object.keys(v8["layout_" + type]).length > 0) {
groups.push({
title: t("Layout properties"),
id: "Layout_properties",
type: "properties",
fields: Object.keys(v8["layout_" + type])
});
}
return groups;
} }
function layoutGroups(layerType: LayerSpecification["type"], t: TFunction): {id: string, title: string, type: string, fields?: string[]}[] { function layoutGroups(layerType: LayerSpecification["type"], t: TFunction): {id: string, title: string, type: string, fields?: string[]}[] {
@@ -110,18 +53,18 @@ function layoutGroups(layerType: LayerSpecification["type"], t: TFunction): {id:
type: 'jsoneditor' type: 'jsoneditor'
} }
return [layerGroup, filterGroup] return [layerGroup, filterGroup]
.concat(getLayoutForType(layerType, t)) .concat(getLayoutForType(layerType, t).groups)
.concat([editorGroup]) .concat([editorGroup])
} }
type LayerEditorInternalProps = { type LayerEditorInternalProps = {
layer: LayerSpecification layer: LayerSpecification
sources: {[key: string]: SourceSpecification & {layers: string[]}} sources: {[key: string]: SourceSpecification}
vectorLayers: {[key: string]: any} vectorLayers: {[key: string]: any}
spec: object spec: object
onLayerChanged(...args: unknown[]): unknown onLayerChanged(...args: unknown[]): unknown
onLayerIdChange(...args: unknown[]): unknown onLayerIdChange(...args: unknown[]): unknown
onMoveLayer: OnMoveLayerCallback onMoveLayer(...args: unknown[]): unknown
onLayerDestroy(...args: unknown[]): unknown onLayerDestroy(...args: unknown[]): unknown
onLayerCopy(...args: unknown[]): unknown onLayerCopy(...args: unknown[]): unknown
onLayerVisibilityToggle(...args: unknown[]): unknown onLayerVisibilityToggle(...args: unknown[]): unknown
@@ -146,10 +89,11 @@ class LayerEditorInternal extends React.Component<LayerEditorInternalProps, Laye
constructor(props: LayerEditorInternalProps) { constructor(props: LayerEditorInternalProps) {
super(props) super(props)
//TODO: Clean this up and refactor into function
const editorGroups: {[keys:string]: boolean} = {} const editorGroups: {[keys:string]: boolean} = {}
for (const group of layoutGroups(this.props.layer.type, props.t)) { layoutGroups(this.props.layer.type, props.t).forEach(group => {
editorGroups[group.title] = true editorGroups[group.title] = true
} })
this.state = { editorGroups } this.state = { editorGroups }
} }
@@ -157,11 +101,11 @@ class LayerEditorInternal extends React.Component<LayerEditorInternalProps, Laye
static getDerivedStateFromProps(props: Readonly<LayerEditorInternalProps>, state: LayerEditorState) { static getDerivedStateFromProps(props: Readonly<LayerEditorInternalProps>, state: LayerEditorState) {
const additionalGroups = { ...state.editorGroups } const additionalGroups = { ...state.editorGroups }
for (const group of getLayoutForType(props.layer.type, props.t)) { getLayoutForType(props.layer.type, props.t).groups.forEach(group => {
if(!(group.title in additionalGroups)) { if(!(group.title in additionalGroups)) {
additionalGroups[group.title] = true additionalGroups[group.title] = true
} }
} })
return { return {
editorGroups: additionalGroups editorGroups: additionalGroups
@@ -209,7 +153,7 @@ class LayerEditorInternal extends React.Component<LayerEditorInternalProps, Laye
let sourceLayerIds; let sourceLayerIds;
const layer = this.props.layer as Exclude<LayerSpecification, BackgroundLayerSpecification>; const layer = this.props.layer as Exclude<LayerSpecification, BackgroundLayerSpecification>;
if(Object.prototype.hasOwnProperty.call(this.props.sources, layer.source)) { if(Object.prototype.hasOwnProperty.call(this.props.sources, layer.source)) {
sourceLayerIds = this.props.sources[layer.source].layers; sourceLayerIds = (this.props.sources[layer.source] as any).layers;
} }
switch(type) { switch(type) {
@@ -236,7 +180,7 @@ class LayerEditorInternal extends React.Component<LayerEditorInternalProps, Laye
onChange={v => this.changeProperty(null, 'source', v)} onChange={v => this.changeProperty(null, 'source', v)}
/> />
} }
{!NON_SOURCE_LAYERS.includes(this.props.layer.type) && {['background', 'raster', 'hillshade', 'heatmap'].indexOf(this.props.layer.type) < 0 &&
<FieldSourceLayer <FieldSourceLayer
error={errorData['source-layer']} error={errorData['source-layer']}
sourceLayerIds={sourceLayerIds} sourceLayerIds={sourceLayerIds}
@@ -323,38 +267,30 @@ class LayerEditorInternal extends React.Component<LayerEditorInternalProps, Laye
const layout = this.props.layer.layout || {} const layout = this.props.layer.layout || {}
const items: {[key: string]: { const items: {[key: string]: {text: string, handler: () => void, disabled?: boolean}} = {
text: string,
handler: () => void,
disabled?: boolean,
wdKey?: string
}} = {
delete: { delete: {
text: t("Delete"), text: t("Delete"),
handler: () => this.props.onLayerDestroy(this.props.layerIndex), handler: () => this.props.onLayerDestroy(this.props.layerIndex)
wdKey: "menu-delete-layer"
}, },
duplicate: { duplicate: {
text: t("Duplicate"), text: t("Duplicate"),
handler: () => this.props.onLayerCopy(this.props.layerIndex), handler: () => this.props.onLayerCopy(this.props.layerIndex)
wdKey: "menu-duplicate-layer"
}, },
hide: { hide: {
text: (layout.visibility === "none") ? t("Show") : t("Hide"), text: (layout.visibility === "none") ? t("Show") : t("Hide"),
handler: () => this.props.onLayerVisibilityToggle(this.props.layerIndex), handler: () => this.props.onLayerVisibilityToggle(this.props.layerIndex)
wdKey: "menu-hide-layer"
}, },
moveLayerUp: { moveLayerUp: {
text: t("Move layer up"), text: t("Move layer up"),
// Not actually used...
disabled: this.props.isFirstLayer, disabled: this.props.isFirstLayer,
handler: () => this.moveLayer(-1), handler: () => this.moveLayer(-1)
wdKey: "menu-move-layer-up"
}, },
moveLayerDown: { moveLayerDown: {
text: t("Move layer down"), text: t("Move layer down"),
// Not actually used...
disabled: this.props.isLastLayer, disabled: this.props.isLastLayer,
handler: () => this.moveLayer(+1), handler: () => this.moveLayer(+1)
wdKey: "menu-move-layer-down"
} }
} }
@@ -391,7 +327,7 @@ class LayerEditorInternal extends React.Component<LayerEditorInternalProps, Laye
{Object.keys(items).map((id) => { {Object.keys(items).map((id) => {
const item = items[id]; const item = items[id];
return <li key={id}> return <li key={id}>
<MenuItem value={id} className='more-menu__menu__item' data-wd-key={item.wdKey}> <MenuItem value={id} className='more-menu__menu__item'>
{item.text} {item.text}
</MenuItem> </MenuItem>
</li> </li>
+16 -42
View File
@@ -1,28 +1,16 @@
import React, {type JSX} from 'react' import React, {type JSX} from 'react'
import classnames from 'classnames' import classnames from 'classnames'
import lodash from 'lodash'; import lodash from 'lodash';
import {
DndContext,
PointerSensor,
useSensor,
useSensors,
closestCenter,
DragEndEvent,
} from '@dnd-kit/core';
import {
SortableContext,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import LayerListGroup from './LayerListGroup' import LayerListGroup from './LayerListGroup'
import LayerListItem from './LayerListItem' import LayerListItem from './LayerListItem'
import ModalAdd from './ModalAdd' import ModalAdd from './ModalAdd'
import type {LayerSpecification, SourceSpecification} from 'maplibre-gl'; import {SortEndHandler, SortableContainer} from 'react-sortable-hoc';
import type {LayerSpecification} from 'maplibre-gl';
import generateUniqueId from '../libs/document-uid'; import generateUniqueId from '../libs/document-uid';
import { findClosestCommonPrefix, layerPrefix } from '../libs/layer'; import { findClosestCommonPrefix, layerPrefix } from '../libs/layer';
import { WithTranslation, withTranslation } from 'react-i18next'; import { WithTranslation, withTranslation } from 'react-i18next';
import { OnMoveLayerCallback } from '../libs/definitions';
type LayerListContainerProps = { type LayerListContainerProps = {
layers: LayerSpecification[] layers: LayerSpecification[]
@@ -32,7 +20,7 @@ type LayerListContainerProps = {
onLayerDestroy?(...args: unknown[]): unknown onLayerDestroy?(...args: unknown[]): unknown
onLayerCopy(...args: unknown[]): unknown onLayerCopy(...args: unknown[]): unknown
onLayerVisibilityToggle(...args: unknown[]): unknown onLayerVisibilityToggle(...args: unknown[]): unknown
sources: Record<string, SourceSpecification & {layers: string[]}>; sources: object
errors: any[] errors: any[]
}; };
type LayerListContainerInternalProps = LayerListContainerProps & WithTranslation; type LayerListContainerInternalProps = LayerListContainerProps & WithTranslation;
@@ -254,6 +242,7 @@ class LayerListContainerInternal extends React.Component<LayerListContainerInter
'maputnik-layer-list-item-group-last': idxInGroup == layers.length - 1 && layers.length > 1, 'maputnik-layer-list-item-group-last': idxInGroup == layers.length - 1 && layers.length > 1,
'maputnik-layer-list-item--error': !!layerError 'maputnik-layer-list-item--error': !!layerError
})} })}
index={idx}
key={layer.key} key={layer.key}
id={layer.key} id={layer.key}
layerId={layer.id} layerId={layer.id}
@@ -330,35 +319,20 @@ class LayerListContainerInternal extends React.Component<LayerListContainerInter
} }
const LayerListContainer = withTranslation()(LayerListContainerInternal); const LayerListContainer = withTranslation()(LayerListContainerInternal);
const LayerListContainerSortable = SortableContainer((props: LayerListContainerProps) => <LayerListContainer {...props} />)
type LayerListProps = LayerListContainerProps & { type LayerListProps = LayerListContainerProps & {
onMoveLayer: OnMoveLayerCallback onMoveLayer: SortEndHandler
}; };
const LayerList: React.FC<LayerListProps> = (props) => { export default class LayerList extends React.Component<LayerListProps> {
const sensors = useSensors(useSensor(PointerSensor)); render() {
return <LayerListContainerSortable
const handleDragEnd = (event: DragEndEvent) => { {...this.props}
const {active, over} = event; helperClass='sortableHelper'
if (!over) return; onSortEnd={this.props.onMoveLayer.bind(this)}
useDragHandle={true}
const oldIndex = props.layers.findIndex(layer => layer.id === active.id); shouldCancelStart={() => false}
const newIndex = props.layers.findIndex(layer => layer.id === over.id); />
}
if (oldIndex !== -1 && newIndex !== -1 && oldIndex !== newIndex) {
props.onMoveLayer({oldIndex, newIndex});
}
};
const layerIds = props.layers.map(layer => layer.id);
return (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={layerIds} strategy={verticalListSortingStrategy}>
<LayerListContainer {...props} />
</SortableContext>
</DndContext>
);
} }
export default LayerList;
+53 -81
View File
@@ -1,23 +1,20 @@
import React from 'react' import React from 'react'
import classnames from 'classnames' import classnames from 'classnames'
import {MdContentCopy, MdVisibility, MdVisibilityOff, MdDelete} from 'react-icons/md' import {MdContentCopy, MdVisibility, MdVisibilityOff, MdDelete} from 'react-icons/md'
import { IconContext } from 'react-icons' import { IconContext } from 'react-icons'
import {useSortable} from '@dnd-kit/sortable'
import {CSS} from '@dnd-kit/utilities'
import IconLayer from './IconLayer' import IconLayer from './IconLayer'
import {SortableElement, SortableHandle} from 'react-sortable-hoc'
type DraggableLabelProps = { type DraggableLabelProps = {
layerId: string layerId: string
layerType: string layerType: string
dragAttributes?: React.HTMLAttributes<HTMLElement>
dragListeners?: React.HTMLAttributes<HTMLElement>
}; };
const DraggableLabel: React.FC<DraggableLabelProps> = (props) => { const DraggableLabel = SortableHandle((props: DraggableLabelProps) => {
const {dragAttributes, dragListeners} = props; return <div className="maputnik-layer-list-item-handle">
return <div className="maputnik-layer-list-item-handle" {...dragAttributes} {...dragListeners}>
<IconLayer <IconLayer
className="layer-handle__icon" className="layer-handle__icon"
type={props.layerType} type={props.layerType}
@@ -26,7 +23,7 @@ const DraggableLabel: React.FC<DraggableLabelProps> = (props) => {
{props.layerId} {props.layerId}
</button> </button>
</div> </div>
}; });
type IconActionProps = { type IconActionProps = {
action: string action: string
@@ -85,80 +82,55 @@ type LayerListItemProps = {
onLayerVisibilityToggle?(...args: unknown[]): unknown onLayerVisibilityToggle?(...args: unknown[]): unknown
}; };
const LayerListItem = React.forwardRef<HTMLLIElement, LayerListItemProps>((props, ref) => { class LayerListItem extends React.Component<LayerListItemProps> {
const { static defaultProps = {
isSelected = false, isSelected: false,
visibility = 'visible', visibility: 'visible',
onLayerCopy = () => {}, onLayerCopy: () => {},
onLayerDestroy = () => {}, onLayerDestroy: () => {},
onLayerVisibilityToggle = () => {}, onLayerVisibilityToggle: () => {},
} = props; }
const { render() {
attributes, const visibilityAction = this.props.visibility === 'visible' ? 'show' : 'hide';
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({id: props.layerId});
const style = { return <IconContext.Provider value={{size: '14px'}}>
transform: CSS.Transform.toString(transform), <li
transition, id={this.props.id}
opacity: isDragging ? 0.5 : 1, key={this.props.layerId}
}; onClick={_e => this.props.onLayerSelect(this.props.layerIndex)}
data-wd-key={"layer-list-item:"+this.props.layerId}
className={classnames({
"maputnik-layer-list-item": true,
"maputnik-layer-list-item-selected": this.props.isSelected,
[this.props.className!]: true,
})}>
<DraggableLabel {...this.props} />
<span style={{flexGrow: 1}} />
<IconAction
wdKey={"layer-list-item:"+this.props.layerId+":delete"}
action={'delete'}
classBlockName="delete"
onClick={_e => this.props.onLayerDestroy!(this.props.layerIndex)}
/>
<IconAction
wdKey={"layer-list-item:"+this.props.layerId+":copy"}
action={'duplicate'}
classBlockName="duplicate"
onClick={_e => this.props.onLayerCopy!(this.props.layerIndex)}
/>
<IconAction
wdKey={"layer-list-item:"+this.props.layerId+":toggle-visibility"}
action={visibilityAction}
classBlockName="visibility"
classBlockModifier={visibilityAction}
onClick={_e => this.props.onLayerVisibilityToggle!(this.props.layerIndex)}
/>
</li>
</IconContext.Provider>
}
}
const visibilityAction = visibility === 'visible' ? 'show' : 'hide'; const LayerListItemSortable = SortableElement<LayerListItemProps>((props: LayerListItemProps) => <LayerListItem {...props} />);
// Cast ref to MutableRefObject since we know from the codebase that's what's always passed export default LayerListItemSortable;
const refObject = ref as React.MutableRefObject<HTMLLIElement | null> | null;
return <IconContext.Provider value={{size: '14px'}}>
<li
ref={(node) => {
setNodeRef(node);
if (refObject) {
refObject.current = node;
}
}}
style={style}
id={props.id}
onClick={_e => props.onLayerSelect(props.layerIndex)}
data-wd-key={"layer-list-item:" + props.layerId}
className={classnames({
"maputnik-layer-list-item": true,
"maputnik-layer-list-item-selected": isSelected,
[props.className!]: true,
})}>
<DraggableLabel
layerId={props.layerId}
layerType={props.layerType}
dragAttributes={attributes}
dragListeners={listeners}
/>
<span style={{flexGrow: 1}} />
<IconAction
wdKey={"layer-list-item:" + props.layerId+":delete"}
action={'delete'}
classBlockName="delete"
onClick={_e => onLayerDestroy!(props.layerIndex)}
/>
<IconAction
wdKey={"layer-list-item:" + props.layerId+":copy"}
action={'duplicate'}
classBlockName="duplicate"
onClick={_e => onLayerCopy!(props.layerIndex)}
/>
<IconAction
wdKey={"layer-list-item:"+props.layerId+":toggle-visibility"}
action={visibilityAction}
classBlockName="visibility"
classBlockModifier={visibilityAction}
onClick={_e => onLayerVisibilityToggle!(props.layerIndex)}
/>
</li>
</IconContext.Provider>
});
export default LayerListItem;
+8 -28
View File
@@ -1,5 +1,5 @@
import React, {type JSX} from 'react' import React, {type JSX} from 'react'
import {createRoot} from 'react-dom/client' import ReactDOM from 'react-dom'
import MapLibreGl, {LayerSpecification, LngLat, Map, MapOptions, SourceSpecification, StyleSpecification} from 'maplibre-gl' import MapLibreGl, {LayerSpecification, LngLat, Map, MapOptions, SourceSpecification, StyleSpecification} from 'maplibre-gl'
import MaplibreInspect from '@maplibre/maplibre-gl-inspect' import MaplibreInspect from '@maplibre/maplibre-gl-inspect'
import colors from '@maplibre/maplibre-gl-inspect/lib/colors' import colors from '@maplibre/maplibre-gl-inspect/lib/colors'
@@ -17,14 +17,8 @@ import { withTranslation, WithTranslation } from 'react-i18next'
import i18next from 'i18next' import i18next from 'i18next'
import { Protocol } from "pmtiles"; import { Protocol } from "pmtiles";
function renderPopup( function renderPopup(popup: JSX.Element, mountNode: ReactDOM.Container): HTMLElement {
popupElement: JSX.Element, ReactDOM.render(popup, mountNode);
mountNode: HTMLElement,
popup: MapLibreGl.Popup
): HTMLElement {
const root = createRoot(mountNode);
popup.once('close', () => root.unmount());
root.render(popupElement);
return mountNode as HTMLElement; return mountNode as HTMLElement;
} }
@@ -180,12 +174,10 @@ class MapMaplibreGlInternal extends React.Component<MapMaplibreGlInternalProps,
const tmpNode = document.createElement('div'); const tmpNode = document.createElement('div');
const inspectPopup = new MapLibreGl.Popup({
closeOnClick: false
});
const inspect = new MaplibreInspect({ const inspect = new MaplibreInspect({
popup: inspectPopup, popup: new MapLibreGl.Popup({
closeOnClick: false
}),
showMapPopup: true, showMapPopup: true,
showMapPopupOnHover: false, showMapPopupOnHover: false,
showInspectMapPopupOnHover: true, showInspectMapPopupOnHover: true,
@@ -197,21 +189,9 @@ class MapMaplibreGlInternal extends React.Component<MapMaplibreGlInternalProps,
buildInspectStyle: (originalMapStyle: StyleSpecification, coloredLayers: HighlightedLayer[]) => buildInspectStyle(originalMapStyle, coloredLayers, this.props.highlightedLayer), buildInspectStyle: (originalMapStyle: StyleSpecification, coloredLayers: HighlightedLayer[]) => buildInspectStyle(originalMapStyle, coloredLayers, this.props.highlightedLayer),
renderPopup: (features: InspectFeature[]) => { renderPopup: (features: InspectFeature[]) => {
if(this.props.inspectModeEnabled) { if(this.props.inspectModeEnabled) {
return renderPopup( return renderPopup(<MapMaplibreGlFeaturePropertyPopup features={features} />, tmpNode);
<MapMaplibreGlFeaturePropertyPopup features={features} />,
tmpNode,
inspectPopup
);
} else { } else {
return renderPopup( return renderPopup(<MapMaplibreGlLayerPopup features={features} onLayerSelect={this.onLayerSelectById} zoom={this.state.zoom} />, tmpNode);
<MapMaplibreGlLayerPopup
features={features}
onLayerSelect={this.onLayerSelectById}
zoom={this.state.zoom}
/>,
tmpNode,
inspectPopup
);
} }
} }
}) })
+38 -28
View File
@@ -6,9 +6,8 @@ import FieldType from './FieldType'
import FieldId from './FieldId' import FieldId from './FieldId'
import FieldSource from './FieldSource' import FieldSource from './FieldSource'
import FieldSourceLayer from './FieldSourceLayer' import FieldSourceLayer from './FieldSourceLayer'
import type {LayerSpecification, SourceSpecification} from 'maplibre-gl' import type {LayerSpecification} from 'maplibre-gl'
import { WithTranslation, withTranslation } from 'react-i18next'; import { WithTranslation, withTranslation } from 'react-i18next';
import { NON_SOURCE_LAYERS } from '../libs/non-source-layers'
type ModalAddInternalProps = { type ModalAddInternalProps = {
layers: LayerSpecification[] layers: LayerSpecification[]
@@ -16,7 +15,7 @@ type ModalAddInternalProps = {
isOpen: boolean isOpen: boolean
onOpenToggle(open: boolean): unknown onOpenToggle(open: boolean): unknown
// A dict of source id's and the available source layers // A dict of source id's and the available source layers
sources: Record<string, SourceSpecification & {layers: string[]}>; sources: any
} & WithTranslation; } & WithTranslation;
type ModalAddState = { type ModalAddState = {
@@ -42,7 +41,7 @@ class ModalAddInternal extends React.Component<ModalAddInternalProps, ModalAddSt
if(this.state.type !== 'background') { if(this.state.type !== 'background') {
layer.source = this.state.source layer.source = this.state.source
if(!NON_SOURCE_LAYERS.includes(this.state.type) && this.state['source-layer']) { if(this.state.type !== 'raster' && this.state['source-layer']) {
layer['source-layer'] = this.state['source-layer'] layer['source-layer'] = this.state['source-layer']
} }
} }
@@ -62,12 +61,9 @@ class ModalAddInternal extends React.Component<ModalAddInternalProps, ModalAddSt
error: null, error: null,
} }
if(Object.keys(props.sources).length > 0) { if(props.sources.length > 0) {
state.source = Object.keys(this.props.sources)[0]; state.source = Object.keys(this.props.sources)[0];
const sourceLayers = this.props.sources[state.source].layers || [] state['source-layer'] = this.props.sources[state.source as keyof ModalAddInternalProps["sources"]][0]
if (sourceLayers.length > 0) {
state['source-layer'] = sourceLayers[0];
}
} }
this.state = state; this.state = state;
} }
@@ -101,26 +97,39 @@ class ModalAddInternal extends React.Component<ModalAddInternalProps, ModalAddSt
return sourceObj.layers || []; return sourceObj.layers || [];
} }
getSources(type: LayerSpecification["type"]) { getSources(type: string) {
const sources = [];
switch(type) { const types = {
case 'background': vector: [
return []; "fill",
case 'hillshade': "line",
case 'color-relief': "symbol",
return Object.entries(this.props.sources).filter(([_, v]) => v.type === 'raster-dem').map(([k, _]) => k); "circle",
case 'raster': "fill-extrusion",
return Object.entries(this.props.sources).filter(([_, v]) => v.type === 'raster').map(([k, _]) => k); "heatmap"
case 'heatmap': ],
case 'circle': raster: [
case 'fill': "raster"
case 'fill-extrusion': ],
case 'line': geojson: [
case 'symbol': "fill",
return Object.entries(this.props.sources).filter(([_, v]) => v.type === 'vector' || v.type === 'geojson').map(([k, _]) => k); "line",
default: "symbol",
return []; "circle",
"fill-extrusion",
"heatmap"
]
} }
for(const [key, val] of Object.entries(this.props.sources) as any) {
const valType = val.type as keyof typeof types;
if(types[valType] && types[valType].indexOf(type) > -1) {
sources.push(key);
}
}
return sources;
} }
@@ -173,8 +182,9 @@ class ModalAddInternal extends React.Component<ModalAddInternalProps, ModalAddSt
onChange={(v: string) => this.setState({ source: v })} onChange={(v: string) => this.setState({ source: v })}
/> />
} }
{!NON_SOURCE_LAYERS.includes(this.state.type) && {['background', 'raster', 'hillshade', 'heatmap'].indexOf(this.state.type) < 0 &&
<FieldSourceLayer <FieldSourceLayer
isFixed={true}
sourceLayerIds={layers} sourceLayerIds={layers}
value={this.state['source-layer']} value={this.state['source-layer']}
onChange={(v: string) => this.setState({ 'source-layer': v })} onChange={(v: string) => this.setState({ 'source-layer': v })}
+3 -9
View File
@@ -3,6 +3,7 @@ import Slugify from 'slugify'
import {saveAs} from 'file-saver' import {saveAs} from 'file-saver'
import {version} from 'maplibre-gl/package.json' import {version} from 'maplibre-gl/package.json'
import {format} from '@maplibre/maplibre-gl-style-spec' import {format} from '@maplibre/maplibre-gl-style-spec'
import type {StyleSpecification} from 'maplibre-gl'
import {MdMap, MdSave} from 'react-icons/md' import {MdMap, MdSave} from 'react-icons/md'
import {WithTranslation, withTranslation} from 'react-i18next'; import {WithTranslation, withTranslation} from 'react-i18next';
@@ -11,7 +12,6 @@ import InputButton from './InputButton'
import Modal from './Modal' import Modal from './Modal'
import style from '../libs/style' import style from '../libs/style'
import fieldSpecAdditional from '../libs/field-spec-additional' import fieldSpecAdditional from '../libs/field-spec-additional'
import type {OnStyleChangedCallback, StyleSpecificationWithId} from '../libs/definitions'
const MAPLIBRE_GL_VERSION = version; const MAPLIBRE_GL_VERSION = version;
@@ -19,8 +19,8 @@ const showSaveFilePickerAvailable = typeof window.showSaveFilePicker === "functi
type ModalExportInternalProps = { type ModalExportInternalProps = {
mapStyle: StyleSpecificationWithId mapStyle: StyleSpecification & { id: string }
onStyleChanged: OnStyleChangedCallback onStyleChanged(...args: unknown[]): unknown
isOpen: boolean isOpen: boolean
onOpenToggle(...args: unknown[]): unknown onOpenToggle(...args: unknown[]): unknown
onSetFileHandle(fileHandle: FileSystemFileHandle | null): unknown onSetFileHandle(fileHandle: FileSystemFileHandle | null): unknown
@@ -186,12 +186,6 @@ class ModalExportInternal extends React.Component<ModalExportInternalProps> {
value={(this.props.mapStyle.metadata || {} as any)['maputnik:stadia_access_token']} value={(this.props.mapStyle.metadata || {} as any)['maputnik:stadia_access_token']}
onChange={this.changeMetadataProperty.bind(this, "maputnik:stadia_access_token")} onChange={this.changeMetadataProperty.bind(this, "maputnik:stadia_access_token")}
/> />
<FieldString
label={fsa.maputnik.locationiq_access_token.label}
fieldSpec={fsa.maputnik.locationiq_access_token}
value={(this.props.mapStyle.metadata || {} as any)['maputnik:locationiq_access_token']}
onChange={this.changeMetadataProperty.bind(this, "maputnik:locationiq_access_token")}
/>
</div> </div>
<div className="maputnik-modal-export-buttons"> <div className="maputnik-modal-export-buttons">
+3 -12
View File
@@ -12,11 +12,10 @@ import FieldEnum from './FieldEnum'
import FieldColor from './FieldColor' import FieldColor from './FieldColor'
import Modal from './Modal' import Modal from './Modal'
import fieldSpecAdditional from '../libs/field-spec-additional' import fieldSpecAdditional from '../libs/field-spec-additional'
import type {OnStyleChangedCallback, StyleSpecificationWithId} from '../libs/definitions';
type ModalSettingsInternalProps = { type ModalSettingsInternalProps = {
mapStyle: StyleSpecificationWithId mapStyle: StyleSpecification
onStyleChanged: OnStyleChangedCallback onStyleChanged(...args: unknown[]): unknown
onChangeMetadataProperty(...args: unknown[]): unknown onChangeMetadataProperty(...args: unknown[]): unknown
isOpen: boolean isOpen: boolean
onOpenToggle(...args: unknown[]): unknown onOpenToggle(...args: unknown[]): unknown
@@ -63,7 +62,7 @@ class ModalSettingsInternal extends React.Component<ModalSettingsInternalProps>
changeTerrainProperty(property: keyof TerrainSpecification, value: any) { changeTerrainProperty(property: keyof TerrainSpecification, value: any) {
const terrain = { const terrain = {
...this.props.mapStyle.terrain, ...this.props.mapStyle.terrain,
} as TerrainSpecification; }
if (value === undefined) { if (value === undefined) {
delete terrain[property]; delete terrain[property];
@@ -165,14 +164,6 @@ class ModalSettingsInternal extends React.Component<ModalSettingsInternalProps>
onChange={onChangeMetadataProperty.bind(this, "maputnik:stadia_access_token")} onChange={onChangeMetadataProperty.bind(this, "maputnik:stadia_access_token")}
/> />
<FieldString
label={fsa.maputnik.locationiq_access_token.label}
fieldSpec={fsa.maputnik.locationiq_access_token}
data-wd-key="modal:settings.maputnik:locationiq_access_token"
value={metadata['maputnik:locationiq_access_token']}
onChange={onChangeMetadataProperty.bind(this, "maputnik:locationiq_access_token")}
/>
<FieldArray <FieldArray
label={t("Center")} label={t("Center")}
fieldSpec={latest.$root.center} fieldSpec={latest.$root.center}
+3 -4
View File
@@ -1,7 +1,7 @@
import React from 'react' import React from 'react'
import {MdAddCircleOutline, MdDelete} from 'react-icons/md' import {MdAddCircleOutline, MdDelete} from 'react-icons/md'
import latest from '@maplibre/maplibre-gl-style-spec/dist/latest.json' import latest from '@maplibre/maplibre-gl-style-spec/dist/latest.json'
import type {GeoJSONSourceSpecification, RasterDEMSourceSpecification, RasterSourceSpecification, SourceSpecification, VectorSourceSpecification} from 'maplibre-gl' import type {GeoJSONSourceSpecification, RasterDEMSourceSpecification, RasterSourceSpecification, SourceSpecification, StyleSpecification, VectorSourceSpecification} from 'maplibre-gl'
import { WithTranslation, withTranslation } from 'react-i18next'; import { WithTranslation, withTranslation } from 'react-i18next';
import Modal from './Modal' import Modal from './Modal'
@@ -13,7 +13,6 @@ import ModalSourcesTypeEditor, { EditorMode } from './ModalSourcesTypeEditor'
import style from '../libs/style' import style from '../libs/style'
import { deleteSource, addSource, changeSource } from '../libs/source' import { deleteSource, addSource, changeSource } from '../libs/source'
import publicSources from '../config/tilesets.json' import publicSources from '../config/tilesets.json'
import { OnStyleChangedCallback, StyleSpecificationWithId } from '../libs/definitions';
type PublicSourceProps = { type PublicSourceProps = {
@@ -271,10 +270,10 @@ class AddSource extends React.Component<AddSourceProps, AddSourceState> {
} }
type ModalSourcesInternalProps = { type ModalSourcesInternalProps = {
mapStyle: StyleSpecificationWithId mapStyle: StyleSpecification
isOpen: boolean isOpen: boolean
onOpenToggle(...args: unknown[]): unknown onOpenToggle(...args: unknown[]): unknown
onStyleChanged: OnStyleChangedCallback onStyleChanged(...args: unknown[]): unknown
} & WithTranslation; } & WithTranslation;
class ModalSourcesInternal extends React.Component<ModalSourcesInternalProps> { class ModalSourcesInternal extends React.Component<ModalSourcesInternalProps> {
+1 -1
View File
@@ -17,7 +17,7 @@ class FunctionInputButtonsInternal extends React.Component<FunctionInputButtonsI
const t = this.props.t; const t = this.props.t;
let makeZoomInputButton, makeDataInputButton, expressionInputButton; let makeZoomInputButton, makeDataInputButton, expressionInputButton;
if (this.props.fieldSpec.expression?.parameters.includes('zoom')) { if (this.props.fieldSpec.expression.parameters.includes('zoom')) {
expressionInputButton = ( expressionInputButton = (
<InputButton <InputButton
className="maputnik-make-zoom-function" className="maputnik-make-zoom-function"
+240
View File
@@ -0,0 +1,240 @@
{
"line": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"line-opacity",
"line-color",
"line-width",
"line-offset",
"line-blur",
"line-dasharray",
"line-pattern",
"line-translate",
"line-translate-anchor",
"line-gap-width"
]
},
{
"title": "Layout properties",
"type": "properties",
"fields": [
"line-cap",
"line-join",
"line-miter-limit",
"line-round-limit"
]
}
]
},
"background": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"background-color",
"background-pattern",
"background-opacity"
]
}
]
},
"fill": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"fill-opacity",
"fill-color",
"fill-antialias",
"fill-outline-color",
"fill-pattern",
"fill-translate",
"fill-translate-anchor"
]
}
]
},
"fill-extrusion": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"fill-extrusion-opacity",
"fill-extrusion-color",
"fill-extrusion-translate",
"fill-extrusion-translate-anchor",
"fill-extrusion-pattern",
"fill-extrusion-height",
"fill-extrusion-base",
"fill-extrusion-vertical-gradient"
]
}
]
},
"circle": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"circle-color",
"circle-opacity",
"circle-stroke-color",
"circle-stroke-opacity",
"circle-blur",
"circle-radius",
"circle-stroke-width",
"circle-pitch-scale",
"circle-translate",
"circle-translate-anchor",
"circle-pitch-alignment"
]
}
]
},
"symbol": {
"groups": [
{
"title": "General layout properties",
"type": "properties",
"fields": [
"symbol-placement",
"symbol-spacing",
"symbol-avoid-edges",
"symbol-z-order"
]
},
{
"title": "Text layout properties",
"type": "properties",
"fields": [
"text-field",
"text-font",
"text-size",
"text-line-height",
"text-padding",
"text-allow-overlap",
"text-ignore-placement",
"text-pitch-alignment",
"text-rotation-alignment",
"text-max-width",
"text-letter-spacing",
"text-justify",
"text-anchor",
"text-max-angle",
"text-writing-mode",
"text-rotate",
"text-keep-upright",
"text-transform",
"text-offset",
"text-optional",
"text-variable-anchor",
"text-radial-offset"
]
},
{
"title": "Icon layout properties",
"type": "properties",
"fields": [
"icon-image",
"icon-allow-overlap",
"icon-ignore-placement",
"icon-optional",
"icon-rotation-alignment",
"icon-size",
"icon-text-fit",
"icon-text-fit-padding",
"icon-rotate",
"icon-padding",
"icon-keep-upright",
"icon-offset",
"icon-anchor",
"icon-pitch-alignment"
]
},
{
"title": "Text paint properties",
"type": "properties",
"fields": [
"text-color",
"text-opacity",
"text-halo-color",
"text-halo-width",
"text-halo-blur",
"text-translate",
"text-translate-anchor"
]
},
{
"title": "Icon paint properties",
"type": "properties",
"fields": [
"icon-color",
"icon-opacity",
"icon-halo-color",
"icon-halo-width",
"icon-halo-blur",
"icon-translate",
"icon-translate-anchor"
]
}
]
},
"raster": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"raster-opacity",
"raster-hue-rotate",
"raster-brightness-min",
"raster-brightness-max",
"raster-saturation",
"raster-contrast",
"raster-fade-duration",
"raster-resampling"
]
}
]
},
"hillshade": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"hillshade-illumination-direction",
"hillshade-illumination-anchor",
"hillshade-exaggeration",
"hillshade-shadow-color",
"hillshade-highlight-color",
"hillshade-accent-color"
]
}
]
},
"heatmap": {
"groups": [
{
"title": "Paint properties",
"type": "properties",
"fields": [
"heatmap-radius",
"heatmap-weight",
"heatmap-intensity",
"heatmap-opacity"
]
}
]
},
"invalid": {
"groups": []
}
}
-6
View File
@@ -29,12 +29,6 @@
"url": "https://cdn.jsdelivr.net/gh/openmaptiles/dark-matter-gl-style@v1.9/style.json", "url": "https://cdn.jsdelivr.net/gh/openmaptiles/dark-matter-gl-style@v1.9/style.json",
"thumbnail": "https://maputnik.github.io/thumbnails/dark-matter.png" "thumbnail": "https://maputnik.github.io/thumbnails/dark-matter.png"
}, },
{
"id": "locationiq-streets",
"title": "LocationIQ Streets",
"url": "https://tiles.locationiq.com/v3/streets/vector.json?key={key}",
"thumbnail": "https://static-assets.locationiq.com/maputnik/locationiq-streets.png"
},
{ {
"id": "maptiler-basic-gl-style", "id": "maptiler-basic-gl-style",
"title": "MapTiler Basic", "title": "MapTiler Basic",
-5
View File
@@ -18,10 +18,5 @@
"type": "vector", "type": "vector",
"url": "https://s3-eu-west-1.amazonaws.com/tiles.os.uk/v2/data/vector/open-zoomstack/config.json", "url": "https://s3-eu-west-1.amazonaws.com/tiles.os.uk/v2/data/vector/open-zoomstack/config.json",
"title": "OS Open Zoomstack v2" "title": "OS Open Zoomstack v2"
},
"locationiq": {
"type": "vector",
"url": "https://tiles.locationiq.com/v3/pbf/tiles.json?key={key}",
"title": "LocationIQ"
} }
} }
+1 -2
View File
@@ -1,5 +1,4 @@
{ {
"openmaptiles": "get_your_own_OpIi9ZULNHzrESv6T2vL", "openmaptiles": "get_your_own_OpIi9ZULNHzrESv6T2vL",
"thunderforest": "b71f7f0ba4064f5eb9e903859a9cf5c6", "thunderforest": "b71f7f0ba4064f5eb9e903859a9cf5c6"
"locationiq": "pk.put_your_api_key_here7bb23dffeb4"
} }
@@ -1,38 +1,46 @@
import style from '../style' import style from './style.js'
import {format} from '@maplibre/maplibre-gl-style-spec' import {format} from '@maplibre/maplibre-gl-style-spec'
import type {StyleSpecification} from 'maplibre-gl'
import ReconnectingWebSocket from 'reconnecting-websocket' import ReconnectingWebSocket from 'reconnecting-websocket'
import type {IStyleStore, OnStyleChangedCallback, StyleSpecificationWithId} from '../definitions'
export type ApiStyleStoreOptions = { export type ApiStyleStoreOptions = {
onLocalStyleChange?: OnStyleChangedCallback port: string | null
host: string | null
onLocalStyleChange?: (style: any) => void
} }
export class ApiStyleStore implements IStyleStore { export class ApiStyleStore {
localUrl: string; localUrl: string;
websocketUrl: string; websocketUrl: string;
latestStyleId: string | undefined = undefined; latestStyleId: string | undefined = undefined;
onLocalStyleChange: OnStyleChangedCallback; onLocalStyleChange: (style: any) => void;
constructor(opts: ApiStyleStoreOptions) { constructor(opts: ApiStyleStoreOptions) {
this.onLocalStyleChange = opts.onLocalStyleChange || (() => {}) this.onLocalStyleChange = opts.onLocalStyleChange || (() => {})
const port = window.location.port const port = opts.port || '8000'
const host = 'localhost' const host = opts.host || 'localhost'
this.localUrl = `http://${host}:${port}` this.localUrl = `http://${host}:${port}`
this.websocketUrl = `ws://${host}:${port}/ws` this.websocketUrl = `ws://${host}:${port}/ws`
this.init = this.init.bind(this) this.init = this.init.bind(this)
} }
async init(): Promise<void> { init(cb: (...args: any[]) => void) {
try { fetch(this.localUrl + '/styles', {
const response = await fetch(this.localUrl + '/styles', {mode: 'cors'}); mode: 'cors',
const body = await response.json(); })
const styleIds = body; .then((response) => {
this.latestStyleId = styleIds[0] return response.json();
this.notifyLocalChanges(); })
} catch { .then((body) => {
throw new Error('Can not connect to style API'); const styleIds = body;
} this.latestStyleId = styleIds[0]
this.notifyLocalChanges()
cb(null)
})
.catch(() => {
cb(new Error('Can not connect to style API'))
})
} }
notifyLocalChanges() { notifyLocalChanges() {
@@ -51,20 +59,24 @@ export class ApiStyleStore implements IStyleStore {
} }
} }
async getLatestStyle(): Promise<StyleSpecificationWithId> { latestStyle(cb: (...args: any[]) => void) {
if(this.latestStyleId) { if(this.latestStyleId) {
const response = await fetch(this.localUrl + '/styles/' + this.latestStyleId, { fetch(this.localUrl + '/styles/' + this.latestStyleId, {
mode: 'cors', mode: 'cors',
}); })
const body = await response.json(); .then(function(response) {
return style.ensureStyleValidity(body); return response.json();
})
.then(function(body) {
cb(style.ensureStyleValidity(body))
})
} else { } else {
throw new Error('No latest style available. You need to init the api backend first.') throw new Error('No latest style available. You need to init the api backend first.')
} }
} }
// Save current style replacing previous version // Save current style replacing previous version
save(mapStyle: StyleSpecificationWithId) { save(mapStyle: StyleSpecification & { id: string }) {
const styleJSON = format( const styleJSON = format(
style.stripAccessTokens( style.stripAccessTokens(
style.replaceAccessTokens(mapStyle) style.replaceAccessTokens(mapStyle)
+48
View File
@@ -0,0 +1,48 @@
interface DebugStore {
[namespace: string]: {
[key: string]: any
}
}
const debugStore: DebugStore = {};
function enabled() {
const qs = new URL(window.location.href).searchParams;
const debugQs = qs.get("debug");
if(debugQs) {
return !!debugQs.match(/^(|1|true)$/);
}
else {
return false;
}
}
function genErr() {
return new Error("Debug not enabled, enable by appending '?debug' to your query string");
}
function set(namespace: keyof DebugStore, key: string, value: any) {
if(!enabled()) {
throw genErr();
}
debugStore[namespace] = debugStore[namespace] || {};
debugStore[namespace][key] = value;
}
function get(namespace: keyof DebugStore, key: string) {
if(!enabled()) {
throw genErr();
}
if(Object.prototype.hasOwnProperty.call(debugStore, namespace)) {
return debugStore[namespace][key];
}
}
const mod = {
enabled,
get,
set
};
(window as any).debug = mod;
export default mod;
-18
View File
@@ -1,18 +0,0 @@
import type { StyleSpecification } from "maplibre-gl";
export type StyleSpecificationWithId = StyleSpecification & {id: string};
export type OnStyleChangedOpts = {
save?: boolean;
addRevision?: boolean;
initialLoad?: boolean;
}
export type OnStyleChangedCallback = (newStyle: StyleSpecificationWithId, opts: OnStyleChangedOpts={}) => void;
export type OnMoveLayerCallback = (move: {oldIndex: number; newIndex: number}) => void;
export interface IStyleStore {
getLatestStyle(): Promise<StyleSpecificationWithId>;
save(mapStyle: StyleSpecificationWithId): StyleSpecificationWithId;
}
-6
View File
@@ -20,12 +20,6 @@ const spec = (t: TFunction) => ({
docUrl: "https://docs.stadiamaps.com/authentication/", docUrl: "https://docs.stadiamaps.com/authentication/",
docUrlLinkText: t("Learn More") docUrlLinkText: t("Learn More")
}, },
locationiq_access_token: {
label: t("LocationIQ Access Token"),
doc: t("Public access token for LocationIQ services."),
docUrl: "https://docs.locationiq.com/docs/maps",
docUrlLinkText: t("Learn More")
},
style_renderer: { style_renderer: {
label: t("Style Renderer"), label: t("Style Renderer"),
doc: t("Choose the default Maputnik renderer for this style.") doc: t("Choose the default Maputnik renderer for this style.")
-1
View File
@@ -1 +0,0 @@
export const NON_SOURCE_LAYERS = ['background', 'raster', 'hillshade', 'heatmap', 'color-relief']
+3 -3
View File
@@ -1,7 +1,7 @@
import { StyleSpecificationWithId } from "./definitions"; import type {StyleSpecification} from "maplibre-gl";
export class RevisionStore { export class RevisionStore {
revisions: StyleSpecificationWithId[]; revisions: (StyleSpecification & {id: string})[];
currentIdx: number; currentIdx: number;
@@ -18,7 +18,7 @@ export class RevisionStore {
return this.revisions[this.currentIdx] return this.revisions[this.currentIdx]
} }
addRevision(revision: StyleSpecificationWithId) { addRevision(revision: StyleSpecification & {id: string}) {
// clear any "redo" revisions once a change is made // clear any "redo" revisions once a change is made
// and ensure current index is at end of list // and ensure current index is at end of list
this.revisions = this.revisions.slice(0, this.currentIdx + 1); this.revisions = this.revisions.slice(0, this.currentIdx + 1);
+4 -5
View File
@@ -1,7 +1,6 @@
import type {SourceSpecification} from "maplibre-gl"; import type {StyleSpecification, SourceSpecification} from "maplibre-gl";
import type {StyleSpecificationWithId} from "./definitions";
export function deleteSource(mapStyle: StyleSpecificationWithId, sourceId: string) { export function deleteSource(mapStyle: StyleSpecification, sourceId: string) {
const remainingSources = { ...mapStyle.sources} const remainingSources = { ...mapStyle.sources}
delete remainingSources[sourceId] delete remainingSources[sourceId]
return { return {
@@ -11,11 +10,11 @@ export function deleteSource(mapStyle: StyleSpecificationWithId, sourceId: strin
} }
export function addSource(mapStyle: StyleSpecificationWithId, sourceId: string, source: SourceSpecification) { export function addSource(mapStyle: StyleSpecification, sourceId: string, source: SourceSpecification) {
return changeSource(mapStyle, sourceId, source) return changeSource(mapStyle, sourceId, source)
} }
export function changeSource(mapStyle: StyleSpecificationWithId, sourceId: string, source: SourceSpecification) { export function changeSource(mapStyle: StyleSpecification, sourceId: string, source: SourceSpecification) {
const changedSources = { const changedSources = {
...mapStyle.sources, ...mapStyle.sources,
[sourceId]: source [sourceId]: source
-29
View File
@@ -1,29 +0,0 @@
/// <reference types="vite/client" />
import { IStyleStore, OnStyleChangedCallback } from "../definitions";
import { getStyleUrlFromAddressbarAndRemoveItIfNeeded, loadStyleUrl } from "../urlopen";
import { ApiStyleStore } from "./apistore";
import { StyleStore } from "./stylestore";
export async function createStyleStore(onStyleChanged: OnStyleChangedCallback): Promise<IStyleStore> {
const styleUrl = getStyleUrlFromAddressbarAndRemoveItIfNeeded();
const useStyleUrl = styleUrl && window.confirm("Load style from URL: " + styleUrl + " and discard current changes?");
let styleStore: IStyleStore;
if (import.meta.env.MODE === 'desktop' && !useStyleUrl) {
const apiStyleStore = new ApiStyleStore({
onLocalStyleChange: mapStyle => onStyleChanged(mapStyle, {save: false}),
});
try {
await apiStyleStore.init();
styleStore = apiStyleStore;
} catch {
styleStore = new StyleStore();
}
} else {
styleStore = new StyleStore();
}
const styleToLoad = useStyleUrl ? await loadStyleUrl(styleUrl) : await styleStore.getLatestStyle();
onStyleChanged(styleToLoad, {initialLoad: true, save: false});
return styleStore;
}
export type { IStyleStore };
+6 -10
View File
@@ -1,7 +1,6 @@
import {derefLayers} from '@maplibre/maplibre-gl-style-spec' import {derefLayers} from '@maplibre/maplibre-gl-style-spec'
import type {StyleSpecification, LayerSpecification} from 'maplibre-gl' import type {StyleSpecification, LayerSpecification} from 'maplibre-gl'
import tokens from '../config/tokens.json' import tokens from '../config/tokens.json'
import type {StyleSpecificationWithId} from './definitions'
// Empty style is always used if no style could be restored or fetched // Empty style is always used if no style could be restored or fetched
const emptyStyle = ensureStyleValidity({ const emptyStyle = ensureStyleValidity({
@@ -14,14 +13,15 @@ function generateId() {
return Math.random().toString(36).substring(2, 9) return Math.random().toString(36).substring(2, 9)
} }
function ensureHasId(style: StyleSpecification & { id?: string }): StyleSpecificationWithId { function ensureHasId(style: StyleSpecification & { id?: string }): StyleSpecification & { id: string } {
if(!('id' in style) || !style.id) { if(!('id' in style) || !style.id) {
style.id = generateId(); style.id = generateId();
return style as StyleSpecification & { id: string };
} }
return style as StyleSpecificationWithId; return style as StyleSpecification & { id: string };
} }
function ensureHasNoInteractive(style: StyleSpecificationWithId) { function ensureHasNoInteractive(style: StyleSpecification & {id: string}) {
const changedLayers = style.layers.map(layer => { const changedLayers = style.layers.map(layer => {
const changedLayer: LayerSpecification & { interactive?: any } = { ...layer } const changedLayer: LayerSpecification & { interactive?: any } = { ...layer }
delete changedLayer.interactive delete changedLayer.interactive
@@ -34,14 +34,14 @@ function ensureHasNoInteractive(style: StyleSpecificationWithId) {
} }
} }
function ensureHasNoRefs(style: StyleSpecificationWithId) { function ensureHasNoRefs(style: StyleSpecification & {id: string}) {
return { return {
...style, ...style,
layers: derefLayers(style.layers) layers: derefLayers(style.layers)
} }
} }
function ensureStyleValidity(style: StyleSpecification): StyleSpecificationWithId { function ensureStyleValidity(style: StyleSpecification): StyleSpecification & { id: string } {
return ensureHasNoInteractive(ensureHasNoRefs(ensureHasId(style))) return ensureHasNoInteractive(ensureHasNoRefs(ensureHasId(style)))
} }
@@ -79,9 +79,6 @@ function replaceSourceAccessToken(mapStyle: StyleSpecification, sourceName: stri
// so we need to check the source URL. // so we need to check the source URL.
authSourceName = "stadia" authSourceName = "stadia"
} }
else if (("url" in source) && source.url?.match(/\.locationiq\.com/)) {
authSourceName = "locationiq"
}
const accessToken = getAccessToken(authSourceName, mapStyle, opts) const accessToken = getAccessToken(authSourceName, mapStyle, opts)
@@ -141,7 +138,6 @@ function stripAccessTokens(mapStyle: StyleSpecification) {
delete changedMetadata['maputnik:openmaptiles_access_token']; delete changedMetadata['maputnik:openmaptiles_access_token'];
delete changedMetadata['maputnik:thunderforest_access_token']; delete changedMetadata['maputnik:thunderforest_access_token'];
delete changedMetadata['maputnik:stadia_access_token']; delete changedMetadata['maputnik:stadia_access_token'];
delete changedMetadata['maputnik:locationiq_access_token'];
return { return {
...mapStyle, ...mapStyle,
metadata: changedMetadata metadata: changedMetadata
@@ -1,7 +1,7 @@
import style from '../style' import style from './style'
import {loadStyleUrl} from '../urlopen' import {loadStyleUrl} from './urlopen'
import publicSources from '../../config/styles.json' import publicSources from '../config/styles.json'
import type {IStyleStore, StyleSpecificationWithId} from '../definitions' import type {StyleSpecification} from 'maplibre-gl'
const storagePrefix = "maputnik" const storagePrefix = "maputnik"
const stylePrefix = 'style' const stylePrefix = 'style'
@@ -13,8 +13,8 @@ const storageKeys = {
const defaultStyleUrl = publicSources[0].url const defaultStyleUrl = publicSources[0].url
// Fetch a default style via URL and return it or a fallback style via callback // Fetch a default style via URL and return it or a fallback style via callback
export function loadDefaultStyle(): Promise<StyleSpecificationWithId> { export function loadDefaultStyle(cb: (...args: any[]) => void) {
return loadStyleUrl(defaultStyleUrl); loadStyleUrl(defaultStyleUrl, cb)
} }
// Return style ids and dates of all styles stored in local storage // Return style ids and dates of all styles stored in local storage
@@ -51,7 +51,7 @@ function styleKey(styleId: string) {
} }
// Manages many possible styles that are stored in the local storage // Manages many possible styles that are stored in the local storage
export class StyleStore implements IStyleStore { export class StyleStore {
/** /**
* List of style ids * List of style ids
*/ */
@@ -63,6 +63,10 @@ export class StyleStore implements IStyleStore {
this.mapStyles = loadStoredStyles(); this.mapStyles = loadStoredStyles();
} }
init(cb: (...args: any[]) => void) {
cb(null)
}
// Delete entire style history // Delete entire style history
purge() { purge() {
for (let i = 0; i < window.localStorage.length; i++) { for (let i = 0; i < window.localStorage.length; i++) {
@@ -74,21 +78,17 @@ export class StyleStore implements IStyleStore {
} }
// Find the last edited style // Find the last edited style
async getLatestStyle(): Promise<StyleSpecificationWithId> { latestStyle(cb: (...args: any[]) => void) {
if(this.mapStyles.length === 0) { if(this.mapStyles.length === 0) return loadDefaultStyle(cb)
return loadDefaultStyle();
}
const styleId = window.localStorage.getItem(storageKeys.latest) as string; const styleId = window.localStorage.getItem(storageKeys.latest) as string;
const styleItem = window.localStorage.getItem(styleKey(styleId)) const styleItem = window.localStorage.getItem(styleKey(styleId))
if (styleItem) { if(styleItem) return cb(JSON.parse(styleItem))
return JSON.parse(styleItem) as StyleSpecificationWithId; loadDefaultStyle(cb)
}
return loadDefaultStyle();
} }
// Save current style replacing previous version // Save current style replacing previous version
save(mapStyle: StyleSpecificationWithId) { save(mapStyle: StyleSpecification & { id: string }) {
mapStyle = style.ensureStyleValidity(mapStyle) mapStyle = style.ensureStyleValidity(mapStyle)
const key = styleKey(mapStyle.id) const key = styleKey(mapStyle.id)
+23 -20
View File
@@ -1,27 +1,30 @@
import style from './style' import style from './style'
import { StyleSpecificationWithId } from './definitions';
export function getStyleUrlFromAddressbarAndRemoveItIfNeeded(): string | null { export function initialStyleUrl() {
const initialUrl = new URL(window.location.href); const initialUrl = new URL(window.location.href);
const styleUrl = initialUrl.searchParams.get('style'); return initialUrl.searchParams.get('style');
if (styleUrl) {
initialUrl.searchParams.delete('style');
window.history.replaceState({}, document.title, initialUrl.toString())
}
return styleUrl;
} }
export async function loadStyleUrl(styleUrl: string): Promise<StyleSpecificationWithId> { export function loadStyleUrl(styleUrl: string, cb: (...args: any[]) => void) {
console.log('Loading style', styleUrl) console.log('Loading style', styleUrl)
try { fetch(styleUrl, {
const response = await fetch(styleUrl, { mode: 'cors',
mode: 'cors', credentials: "same-origin"
credentials: "same-origin" })
}); .then(function(response) {
const body = await response.json(); return response.json();
return style.ensureStyleValidity(body); })
} catch { .then(function(body) {
console.warn('Could not fetch default style: ' + styleUrl) cb(style.ensureStyleValidity(body))
return style.emptyStyle })
} .catch(function() {
console.warn('Could not fetch default style', styleUrl)
cb(style.emptyStyle)
})
}
export function removeStyleQuerystring() {
const initialUrl = new URL(window.location.href);
initialUrl.searchParams.delete('style');
window.history.replaceState({}, document.title, initialUrl.toString())
} }
+8 -10
View File
@@ -59,13 +59,6 @@
"Must provide protocol: <1>https://</1>": "Protokoll erforderlich: <1>https://</1>", "Must provide protocol: <1>https://</1>": "Protokoll erforderlich: <1>https://</1>",
"Must provide protocol: <1>http://</1> or <3>https://</3>": "Protokoll erforderlich: <1>http://</1> oder <3>https://</3>", "Must provide protocol: <1>http://</1> or <3>https://</3>": "Protokoll erforderlich: <1>http://</1> oder <3>https://</3>",
"CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "Die CORS-Politik erlaubt es nicht, Ressourcen über http von https zu laden, benutze eine <1>https://</1>-Domain", "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "Die CORS-Politik erlaubt es nicht, Ressourcen über http von https zu laden, benutze eine <1>https://</1>-Domain",
"General layout properties": "Allgemeine Layouteigenschaften",
"Text layout properties": "Text-Layouteigenschaften",
"Icon layout properties": "Icon-Layouteigenschaften",
"Text paint properties": "Text-Darstellungseigenschaften",
"Icon paint properties": "Icon-Darstellungseigenschaften",
"Paint properties": "Darstellungseigenschaften",
"Layout properties": "Layouteigenschaften",
"Layer": "Ebene", "Layer": "Ebene",
"JSON Editor": "JSON-Editor", "JSON Editor": "JSON-Editor",
"Delete": "Löschen", "Delete": "Löschen",
@@ -79,6 +72,7 @@
"Collapse": "Einklappen", "Collapse": "Einklappen",
"Expand": "Ausklappen", "Expand": "Ausklappen",
"Add Layer": "Ebene hinzufügen", "Add Layer": "Ebene hinzufügen",
"Layer ID already exists": "Layer-ID existiert bereits",
"Search": "Suche", "Search": "Suche",
"Zoom:": "Zoom:", "Zoom:": "Zoom:",
"Close popup": "Popup schließen", "Close popup": "Popup schließen",
@@ -86,7 +80,6 @@
"center:": "Zentrum:", "center:": "Zentrum:",
"rotation:": "Rotation:", "rotation:": "Rotation:",
"Close modal": "Modale Fenster schließen", "Close modal": "Modale Fenster schließen",
"Layer ID already exists": "Layer-ID existiert bereits",
"Debug": "Debug", "Debug": "Debug",
"Options": "Optionen", "Options": "Optionen",
"Save Style": "Stil Speichern", "Save Style": "Stil Speichern",
@@ -190,15 +183,20 @@
"Public access token for Thunderforest services.": "Öffentlicher Zugriffstoken für Thunderforest-Dienste.", "Public access token for Thunderforest services.": "Öffentlicher Zugriffstoken für Thunderforest-Dienste.",
"Stadia Maps API Key": "Stadia Maps API-Schlüssel", "Stadia Maps API Key": "Stadia Maps API-Schlüssel",
"API key for Stadia Maps.": "API-Schlüssel für Stadia Maps.", "API key for Stadia Maps.": "API-Schlüssel für Stadia Maps.",
"LocationIQ Access Token": "LocationIQ Zugriffstoken",
"Public access token for LocationIQ services.": "Öffentlicher Zugriffstoken für LocationIQ-Dienste.",
"Style Renderer": "Stil-Renderer", "Style Renderer": "Stil-Renderer",
"Choose the default Maputnik renderer for this style.": "Wähle den Standard-Renderer für diesen Stil aus.", "Choose the default Maputnik renderer for this style.": "Wähle den Standard-Renderer für diesen Stil aus.",
"Paint properties": "Darstellungseigenschaften",
"Opacity": "Deckkraft", "Opacity": "Deckkraft",
"Radius": "Radius", "Radius": "Radius",
"Text paint properties": "Text-Darstellungseigenschaften",
"Icon paint properties": "Icon-Darstellungseigenschaften",
"Text layout properties": "Text-Layouteigenschaften",
"Icon layout properties": "Icon-Layouteigenschaften",
"General layout properties": "Allgemeine Layouteigenschaften",
"Color": "Farbe", "Color": "Farbe",
"Outline color": "Umrissfarbe", "Outline color": "Umrissfarbe",
"Language": "Sprache", "Language": "Sprache",
"Layout properties": "Layouteigenschaften",
"Width": "Breite", "Width": "Breite",
"Height": "Höhe", "Height": "Höhe",
"Field": "Feld", "Field": "Feld",
+9 -11
View File
@@ -59,13 +59,6 @@
"Must provide protocol: <1>https://</1>": "Protocole requis : <1>https://</1>", "Must provide protocol: <1>https://</1>": "Protocole requis : <1>https://</1>",
"Must provide protocol: <1>http://</1> or <3>https://</3>": "Protocole requis : <1>http://</1> ou <3>https://</3>", "Must provide protocol: <1>http://</1> or <3>https://</3>": "Protocole requis : <1>http://</1> ou <3>https://</3>",
"CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "La politique CORS ne permet pas de récupérer des ressources servies sur http depuis https, utilisez un protocole <1>https://</1>", "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "La politique CORS ne permet pas de récupérer des ressources servies sur http depuis https, utilisez un protocole <1>https://</1>",
"General layout properties": "Propriétés générales de mise en page",
"Text layout properties": "Propriétés de mise en page du texte",
"Icon layout properties": "Propriétés de mise en page de l'icône",
"Text paint properties": "Propriétés de peinture du texte",
"Icon paint properties": "Propriétés de peinture de l'icône",
"Paint properties": "Propriétés de peinture",
"Layout properties": "Propriétés de mise en page",
"Layer": "Calque", "Layer": "Calque",
"JSON Editor": "Éditeur JSON", "JSON Editor": "Éditeur JSON",
"Delete": "Supprimer", "Delete": "Supprimer",
@@ -79,6 +72,7 @@
"Collapse": "Réduire", "Collapse": "Réduire",
"Expand": "Développer", "Expand": "Développer",
"Add Layer": "Ajouter un calque", "Add Layer": "Ajouter un calque",
"Layer ID already exists": "L'identifiant du calque existe déjà",
"Search": "Recherche", "Search": "Recherche",
"Zoom:": "Zoom :", "Zoom:": "Zoom :",
"Close popup": "Fermer la fenêtre", "Close popup": "Fermer la fenêtre",
@@ -86,7 +80,6 @@
"center:": "centre :", "center:": "centre :",
"rotation:": "rotation :", "rotation:": "rotation :",
"Close modal": "Fermer la fenêtre modale", "Close modal": "Fermer la fenêtre modale",
"Layer ID already exists": "L'identifiant du calque existe déjà",
"Debug": "Déboguer", "Debug": "Déboguer",
"Options": "Options", "Options": "Options",
"Save Style": "Enregistrer le style", "Save Style": "Enregistrer le style",
@@ -190,10 +183,15 @@
"Public access token for Thunderforest services.": "Jeton d'accès public pour les services Thunderforest.", "Public access token for Thunderforest services.": "Jeton d'accès public pour les services Thunderforest.",
"Stadia Maps API Key": "Clé d'API Stadia Maps", "Stadia Maps API Key": "Clé d'API Stadia Maps",
"API key for Stadia Maps.": "Clé d'API pour Stadia Maps.", "API key for Stadia Maps.": "Clé d'API pour Stadia Maps.",
"LocationIQ Access Token": "Jeton d'accès LocationIQ",
"Public access token for LocationIQ services.": "Jeton d'accès public pour les services LocationIQ.",
"Style Renderer": "Moteur de rendu pour le style", "Style Renderer": "Moteur de rendu pour le style",
"Choose the default Maputnik renderer for this style.": "Choisissez le moteur de rendu Maputnik par défaut pour ce style.", "Choose the default Maputnik renderer for this style.": "Choisissez le moteur de rendu Maputnik par défaut pour ce style.",
"Language": "Langue", "Language": "Langue",
"Layer options": "Options du calque" "Layer options": "Options du calque",
"Paint properties": "Propriétés de peinture",
"Layout properties": "Propriétés de mise en page",
"General layout properties": "Propriétés générales de mise en page",
"Text layout properties": "Propriétés de mise en page du texte",
"Icon layout properties": "Propriétés de mise en page de l'icône",
"Text paint properties": "Propriétés de peinture du texte",
"Icon paint properties": "Propriétés de peinture de l'icône"
} }
+1 -10
View File
@@ -59,13 +59,6 @@
"Must provide protocol: <1>https://</1>": "נדרש פרוטוקול: <1>https://</1>", "Must provide protocol: <1>https://</1>": "נדרש פרוטוקול: <1>https://</1>",
"Must provide protocol: <1>http://</1> or <3>https://</3>": "נדרשים פרוטוקולים: <1>http://</1> או <3>https://</3>", "Must provide protocol: <1>http://</1> or <3>https://</3>": "נדרשים פרוטוקולים: <1>http://</1> או <3>https://</3>",
"CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain", "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain",
"General layout properties": "תכונות פריסה כלליות",
"Text layout properties": "תכונות פריסה של טקסט",
"Icon layout properties": "תכונות פריסה של סמליל",
"Text paint properties": "תכונות ציור של טקסט",
"Icon paint properties": "תכונות ציור של סמליל",
"Paint properties": "תכונות ציור",
"Layout properties": "תכונות פריסה",
"Layer": "שכבה", "Layer": "שכבה",
"JSON Editor": "עורך JSON", "JSON Editor": "עורך JSON",
"Delete": "מחיקה", "Delete": "מחיקה",
@@ -79,6 +72,7 @@
"Collapse": "הקטנה", "Collapse": "הקטנה",
"Expand": "הגדלה", "Expand": "הגדלה",
"Add Layer": "הוספת שכבה", "Add Layer": "הוספת שכבה",
"Layer ID already exists": "מזהה השכבה כבר קיים",
"Search": "חיפוש", "Search": "חיפוש",
"Zoom:": "זום:", "Zoom:": "זום:",
"Close popup": "סגירת החלון", "Close popup": "סגירת החלון",
@@ -86,7 +80,6 @@
"center:": "מרכז:", "center:": "מרכז:",
"rotation:": "סיבוב:", "rotation:": "סיבוב:",
"Close modal": "סגירת חלונית", "Close modal": "סגירת חלונית",
"Layer ID already exists": "מזהה השכבה כבר קיים",
"Debug": "דיבאג", "Debug": "דיבאג",
"Options": "אפשרויות", "Options": "אפשרויות",
"Save Style": "שמירת הסטייל", "Save Style": "שמירת הסטייל",
@@ -190,8 +183,6 @@
"Public access token for Thunderforest services.": "Public access token for Thunderforest services.", "Public access token for Thunderforest services.": "Public access token for Thunderforest services.",
"Stadia Maps API Key": "Stadia Maps API Key", "Stadia Maps API Key": "Stadia Maps API Key",
"API key for Stadia Maps.": "API key for Stadia Maps", "API key for Stadia Maps.": "API key for Stadia Maps",
"LocationIQ Access Token": "LocationIQ Access Token",
"Public access token for LocationIQ services.": "Public access token for LocationIQ services.",
"Style Renderer": "צייר הסטייל", "Style Renderer": "צייר הסטייל",
"Choose the default Maputnik renderer for this style.": "בחירת צייר ברירת המחדל של מפוטניק עבור הסטייל הזה", "Choose the default Maputnik renderer for this style.": "בחירת צייר ברירת המחדל של מפוטניק עבור הסטייל הזה",
"Language": "שפה", "Language": "שפה",
+1 -10
View File
@@ -59,13 +59,6 @@
"Must provide protocol: <1>https://</1>": "Protocollo richiesto: <1>https://</1>", "Must provide protocol: <1>https://</1>": "Protocollo richiesto: <1>https://</1>",
"Must provide protocol: <1>http://</1> or <3>https://</3>": "Protocollo richiesto: <1>http://</1> o <3>https://</3>", "Must provide protocol: <1>http://</1> or <3>https://</3>": "Protocollo richiesto: <1>http://</1> o <3>https://</3>",
"CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "La politica CORS non permette di caricare risorse tramite http da https, utilizza un dominio <1>https://</1>.", "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "La politica CORS non permette di caricare risorse tramite http da https, utilizza un dominio <1>https://</1>.",
"General layout properties": "Proprietà generali del layout",
"Text layout properties": "Proprietà di layout del testo",
"Icon layout properties": "Proprietà di layout dell'icona",
"Text paint properties": "Proprietà di pittura del testo",
"Icon paint properties": "Proprietà di pittura dell'icona",
"Paint properties": "Proprietà di pittura",
"Layout properties": "Proprietà di layout",
"Layer": "Livello", "Layer": "Livello",
"JSON Editor": "Editor JSON", "JSON Editor": "Editor JSON",
"Delete": "Elimina", "Delete": "Elimina",
@@ -79,6 +72,7 @@
"Collapse": "Coprimi", "Collapse": "Coprimi",
"Expand": "Espandi", "Expand": "Espandi",
"Add Layer": "Aggiungi Livello", "Add Layer": "Aggiungi Livello",
"Layer ID already exists": "L'ID del layer esiste già",
"Search": "Cerca", "Search": "Cerca",
"Zoom:": "Zoom:", "Zoom:": "Zoom:",
"Close popup": "Chiudi popup", "Close popup": "Chiudi popup",
@@ -86,7 +80,6 @@
"center:": "centro:", "center:": "centro:",
"rotation:": "rotazione:", "rotation:": "rotazione:",
"Close modal": "Chiudi finestra modale", "Close modal": "Chiudi finestra modale",
"Layer ID already exists": "L'ID del layer esiste già",
"Debug": "Debug", "Debug": "Debug",
"Options": "Opzioni", "Options": "Opzioni",
"Save Style": "Opzioni stile", "Save Style": "Opzioni stile",
@@ -190,8 +183,6 @@
"Public access token for Thunderforest services.": "Token di accesso pubblico per i servizi Thunderforest.", "Public access token for Thunderforest services.": "Token di accesso pubblico per i servizi Thunderforest.",
"Stadia Maps API Key": "Chiave API di Stadia Maps.", "Stadia Maps API Key": "Chiave API di Stadia Maps.",
"API key for Stadia Maps.": "Chiave API per Stadia Maps.", "API key for Stadia Maps.": "Chiave API per Stadia Maps.",
"LocationIQ Access Token": "Token di accesso LocationIQ",
"Public access token for LocationIQ services.": "Token di accesso pubblico per i servizi LocationIQ.",
"Style Renderer": "Renderer dello stile", "Style Renderer": "Renderer dello stile",
"Choose the default Maputnik renderer for this style.": "Scegli il renderer predefinito di Maputnik per questo stile.", "Choose the default Maputnik renderer for this style.": "Scegli il renderer predefinito di Maputnik per questo stile.",
"Language": "Lingua", "Language": "Lingua",
+9 -11
View File
@@ -59,13 +59,6 @@
"Must provide protocol: <1>https://</1>": "プロトコルを指定してください: <1>https://</1>", "Must provide protocol: <1>https://</1>": "プロトコルを指定してください: <1>https://</1>",
"Must provide protocol: <1>http://</1> or <3>https://</3>": "プロトコルを指定してください: <1>http://</1> または <3>https://</3>", "Must provide protocol: <1>http://</1> or <3>https://</3>": "プロトコルを指定してください: <1>http://</1> または <3>https://</3>",
"CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "CORS使用時は、http経由で提供されるリソースをhttpsから取得することはできません。<1>https://</1> ドメインを使用してください。", "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "CORS使用時は、http経由で提供されるリソースをhttpsから取得することはできません。<1>https://</1> ドメインを使用してください。",
"General layout properties": "一般レイアウトプロパティ",
"Text layout properties": "文字レイアウトプロパティ",
"Icon layout properties": "アイコンレイアウトプロパティ",
"Text paint properties": "文字ペイントプロパティ",
"Icon paint properties": "アイコンペイントプロパティ",
"Paint properties": "ペイントプロパティ",
"Layout properties": "レイアウトプロパティ",
"Layer": "レイヤー", "Layer": "レイヤー",
"JSON Editor": "JSONエディタ", "JSON Editor": "JSONエディタ",
"Delete": "削除", "Delete": "削除",
@@ -79,6 +72,7 @@
"Collapse": "畳む", "Collapse": "畳む",
"Expand": "展開", "Expand": "展開",
"Add Layer": "レイヤー追加", "Add Layer": "レイヤー追加",
"Layer ID already exists": "レイヤーIDは既に存在します",
"Search": "検索", "Search": "検索",
"Zoom:": "ズーム:", "Zoom:": "ズーム:",
"Close popup": "ポップアップを閉じる", "Close popup": "ポップアップを閉じる",
@@ -86,7 +80,6 @@
"center:": "中央:", "center:": "中央:",
"rotation:": "回転角度:", "rotation:": "回転角度:",
"Close modal": "モーダルを閉じる", "Close modal": "モーダルを閉じる",
"Layer ID already exists": "レイヤーIDは既に存在します",
"Debug": "デバッグ", "Debug": "デバッグ",
"Options": "設定", "Options": "設定",
"Save Style": "スタイルを保存", "Save Style": "スタイルを保存",
@@ -190,11 +183,16 @@
"Public access token for Thunderforest services.": "Thunderforest サービスの公開用アクセストークン", "Public access token for Thunderforest services.": "Thunderforest サービスの公開用アクセストークン",
"Stadia Maps API Key": "Stadia Maps API キー", "Stadia Maps API Key": "Stadia Maps API キー",
"API key for Stadia Maps.": "Stadia Maps の API キー", "API key for Stadia Maps.": "Stadia Maps の API キー",
"LocationIQ Access Token": "LocationIQ アクセストークン",
"Public access token for LocationIQ services.": "LocationIQ サービス用のパブリックアクセストークン。",
"Style Renderer": "スタイルレンダラ", "Style Renderer": "スタイルレンダラ",
"Choose the default Maputnik renderer for this style.": "このスタイルのデフォルトの Maputnik レンダラを選択してください", "Choose the default Maputnik renderer for this style.": "このスタイルのデフォルトの Maputnik レンダラを選択してください",
"Language": "言語", "Language": "言語",
"<0>Open in OSM</0> — Opens the current view on openstreetmap.org": "現在のビューを <0>openstreetmap.org で開く</0>", "<0>Open in OSM</0> — Opens the current view on openstreetmap.org": "現在のビューを <0>openstreetmap.org で開く</0>",
"Layer options": "レイヤー設定" "Layer options": "レイヤー設定",
"Paint properties": "ペイントプロパティ",
"Layout properties": "レイアウトプロパティ",
"General layout properties": "一般レイアウトプロパティ",
"Text layout properties": "文字レイアウトプロパティ",
"Icon layout properties": "アイコンレイアウトプロパティ",
"Text paint properties": "文字ペイントプロパティ",
"Icon paint properties": "アイコンペイントプロパティ"
} }
+9 -11
View File
@@ -59,13 +59,6 @@
"Must provide protocol: <1>https://</1>": "必须提供协议:<1>https://</1>", "Must provide protocol: <1>https://</1>": "必须提供协议:<1>https://</1>",
"Must provide protocol: <1>http://</1> or <3>https://</3>": "必须提供协议:<1>http://</1> 或 <3>https://</3>", "Must provide protocol: <1>http://</1> or <3>https://</3>": "必须提供协议:<1>http://</1> 或 <3>https://</3>",
"CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "CORS 策略不允许从 https 访问通过 http 提供的资源,请使用 <1>https://</1> 域名。", "CORS policy won't allow fetching resources served over http from https, use a <1>https://</1> domain": "CORS 策略不允许从 https 访问通过 http 提供的资源,请使用 <1>https://</1> 域名。",
"General layout properties": "常规布局属性",
"Text layout properties": "文本布局属性",
"Icon layout properties": "图标布局属性",
"Text paint properties": "文本绘制属性",
"Icon paint properties": "图标绘制属性",
"Paint properties": "绘制属性",
"Layout properties": "布局属性",
"Layer": "图层", "Layer": "图层",
"JSON Editor": "JSON编辑器", "JSON Editor": "JSON编辑器",
"Delete": "删除", "Delete": "删除",
@@ -79,6 +72,7 @@
"Collapse": "折叠", "Collapse": "折叠",
"Expand": "展开", "Expand": "展开",
"Add Layer": "添加图层", "Add Layer": "添加图层",
"Layer ID already exists": "图层ID已存在",
"Search": "搜索", "Search": "搜索",
"Zoom:": "缩放:", "Zoom:": "缩放:",
"Close popup": "关闭弹出窗口", "Close popup": "关闭弹出窗口",
@@ -86,7 +80,6 @@
"center:": "中心:", "center:": "中心:",
"rotation:": "旋转:", "rotation:": "旋转:",
"Close modal": "关闭模态框", "Close modal": "关闭模态框",
"Layer ID already exists": "图层ID已存在",
"Debug": "调试", "Debug": "调试",
"Options": "选项", "Options": "选项",
"Save Style": "保存样式", "Save Style": "保存样式",
@@ -190,11 +183,16 @@
"Public access token for Thunderforest services.": "Thunderforest 服务的公共访问令牌。", "Public access token for Thunderforest services.": "Thunderforest 服务的公共访问令牌。",
"Stadia Maps API Key": "Stadia Maps API 密钥", "Stadia Maps API Key": "Stadia Maps API 密钥",
"API key for Stadia Maps.": "Stadia Maps 的 API 密钥", "API key for Stadia Maps.": "Stadia Maps 的 API 密钥",
"LocationIQ Access Token": "LocationIQ 访问令牌",
"Public access token for LocationIQ services.": "LocationIQ 服务的公共访问令牌。",
"Style Renderer": "样式渲染器", "Style Renderer": "样式渲染器",
"Choose the default Maputnik renderer for this style.": "为这种样式选择默认的Maputnik渲染器。", "Choose the default Maputnik renderer for this style.": "为这种样式选择默认的Maputnik渲染器。",
"Language": "语言", "Language": "语言",
"<0>Open in OSM</0> — Opens the current view on openstreetmap.org": "在 openstreetmap.org 打开当前视图", "<0>Open in OSM</0> — Opens the current view on openstreetmap.org": "在 openstreetmap.org 打开当前视图",
"Layer options": "图层选项" "Layer options": "图层选项",
"Paint properties": "绘制属性",
"Layout properties": "布局属性",
"General layout properties": "常规布局属性",
"Text layout properties": "文本布局属性",
"Icon layout properties": "图标布局属性",
"Text paint properties": "文本绘制属性",
"Icon paint properties": "图标绘制属性"
} }
+3 -4
View File
@@ -3,7 +3,7 @@ import react from "@vitejs/plugin-react";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import istanbul from "vite-plugin-istanbul"; import istanbul from "vite-plugin-istanbul";
export default defineConfig(({ mode }) => ({ export default defineConfig({
server: { server: {
port: 8888, port: 8888,
}, },
@@ -27,8 +27,7 @@ export default defineConfig(({ mode }) => ({
forceBuildInstrument: true, //Instrument the source code for cypress runs forceBuildInstrument: true, //Instrument the source code for cypress runs
}), }),
], ],
base: mode === "desktop" ? "/" : "/maputnik/",
define: { define: {
global: "window" global: "window",
}, },
})); });