Compare commits

...

10 Commits

Author SHA1 Message Date
dc53b79d84 Enhance map update handling and connection stability
- Introduced mechanisms to detect stale connections in the map updates, allowing for automatic reconnection if no messages are received within a specified timeframe.
- Updated the `refresh` method in `SmartTileLayer` to return a boolean indicating whether the tile was refreshed, improving the handling of tile updates.
- Enhanced the `Send` method in the `Topic` struct to drop messages for full subscribers while keeping them subscribed, ensuring continuous delivery of future updates.
- Added a keepalive mechanism in the `WatchGridUpdates` handler to maintain the connection and prevent timeouts.
2026-03-04 21:29:53 +03:00
179357bc93 Refactor Dockerignore and enhance Leaflet styles for improved map functionality
- Updated .dockerignore to streamline build context by ensuring unnecessary files are excluded.
- Refined CSS styles in leaflet-overrides.css to enhance visual consistency and user experience for map tooltips and popups.
- Improved map initialization and update handling in useMapApi and useMapUpdates composables for better performance and reliability.
2026-03-04 18:16:41 +03:00
3968bdc76f Enhance API documentation and improve marker functionality
- Updated API documentation for clarity and consistency, including detailed descriptions of authentication and user account endpoints.
- Added a new cave marker image to enhance visual representation in the frontend.
- Implemented normalization for cave marker images during upload to ensure consistent storage format.
- Expanded test coverage for client services, including new tests for marker uploads and image normalization.
2026-03-04 16:57:43 +03:00
40945c818b Enhance character marker functionality and tooltip integration
- Updated character icon properties for improved visual representation.
- Introduced tooltip binding to character markers, displaying coordinates and character names.
- Implemented smooth position animation for character markers during updates.
- Added tests to verify tooltip content updates and animation cancellation on removal.
2026-03-04 16:02:54 +03:00
7fcdde3657 Remove coordinates display from MapSearch component for cleaner UI 2026-03-04 14:19:07 +03:00
1a0db9baf0 Update project conventions and introduce linting skill documentation
- Revised project-conventions.mdc to include a new section for running lint before tests, enhancing the development workflow.
- Added run-lint skill documentation in a new SKILL.md file, detailing usage for backend and frontend linting processes in the hnh-map monorepo.
2026-03-04 14:15:51 +03:00
337386caa8 Enhance Vitest configuration and improve Vue integration
- Added Vue plugin to vitest.config.ts for better component testing.
- Introduced vitest.setup.ts to expose Vue reactivity and lifecycle methods globally, ensuring compatibility with .vue components.
- Updated mock implementations in nuxt-imports.ts to include readonly for improved reactivity handling.
- Refactored useMapBookmarks and useToast composables to utilize readonly from Vue for better state management.
2026-03-04 14:12:48 +03:00
fd624c2357 Refactor frontend components for improved functionality and accessibility
- Consolidated global error handling in app.vue to redirect users to the login page on API authentication failure.
- Enhanced MapView component by reintroducing event listeners for selected map and marker updates, improving interactivity.
- Updated PasswordInput and various modal components to ensure proper input handling and accessibility compliance.
- Refactored MapControls and MapControlsContent to streamline prop management and enhance user experience.
- Improved error handling in local storage operations within useMapBookmarks and useRecentLocations composables.
- Standardized input elements across forms for consistency in user interaction.
2026-03-04 14:06:27 +03:00
761fbaed55 Refactor Docker and Makefile configurations for improved build processes
- Updated docker-compose.tools.yml to mount source code at /src and set working directory for backend tools, ensuring proper Go module caching.
- Modified Dockerfile.tools to install the latest golangci-lint version compatible with Go 1.24 and adjusted working directory for build-time operations.
- Enhanced Makefile to build backend tools before running tests and linting, ensuring dependencies are up-to-date and improving overall workflow efficiency.
- Refactored test and handler files to include error handling for database operations, enhancing reliability and debugging capabilities.
2026-03-04 13:59:00 +03:00
fc42d86ca0 Enhance map components and improve build processes
- Updated Makefile to include `--build` flag for `docker-compose.dev.yml` and `--no-cache` for `docker-compose.prod.yml` to ensure fresh builds.
- Added new CSS styles for Leaflet tooltips and popups to utilize theme colors, enhancing visual consistency.
- Enhanced MapView component with new props for markers and current zoom level, improving marker management and zoom functionality.
- Introduced new icons for copy and info actions to improve user interface clarity.
- Updated MapBookmarks and MapControls components to support new features and improve user experience with bookmarks and zoom controls.
- Refactored MapSearch to display coordinates and improve marker search functionality.
2026-03-04 12:49:31 +03:00
72 changed files with 5354 additions and 4621 deletions

View File

@@ -11,4 +11,5 @@ alwaysApply: true
- **Local run / build:** [docs/development.md](docs/development.md), [CONTRIBUTING.md](CONTRIBUTING.md). Dev ports: frontend 3000, backend 3080; prod: 8080. Build, test, lint, and format run via Docker (Makefile + docker-compose.tools.yml).
- **Docs:** [docs/](docs/) (architecture, API, configuration, development, deployment). Some docs are in Russian.
- **Coding:** Write tests first before implementing any functionality.
- **Running tests:** When the user asks to run tests or to verify changes, use the run-tests skill: [.cursor/skills/run-tests/SKILL.md](.cursor/skills/run-tests/SKILL.md).
- **Running lint:** When the user asks to run the linter or to verify changes, use the run-lint skill: [.cursor/skills/run-lint/SKILL.md](.cursor/skills/run-lint/SKILL.md).
- **Running tests:** When the user asks to run tests or to verify changes, run lint first (run-lint skill), then use the run-tests skill: [.cursor/skills/run-tests/SKILL.md](.cursor/skills/run-tests/SKILL.md).

View File

@@ -0,0 +1,29 @@
---
name: run-lint
description: Runs backend (golangci-lint) and frontend (ESLint) linters for the hnh-map monorepo. Use when the user asks to run the linter, lint, or to check code style and lint errors.
---
# Run linter
## When to run
- User asks to run the linter, run lint, or check lint/style.
- After making code changes that should be validated by the project linters.
## What to run
Lint runs **in Docker** via the Makefile; no local Go or Node is required.
From the repo root:
- **Both backend and frontend:** `make lint` (runs golangci-lint then frontend ESLint in Docker).
Uses `docker-compose.tools.yml`; the first run may build the backend-tools and frontend-tools images.
## Scope
- **Backend-only changes** (e.g. `internal/`, `cmd/`): `make lint` still runs both; backend lint runs first.
- **Frontend-only changes** (e.g. `frontend-nuxt/`): `make lint` runs both; frontend lint runs second.
- **Both or unclear**: run `make lint`.
Report pass/fail and any linter errors or file/line references so the user can fix them.

View File

@@ -1,27 +1,27 @@
# Git and IDE
.git
.gitignore
.cursor
.cursorignore
*.md
*.plan.md
# Old Vue 2 frontend (not used in build)
frontend/node_modules
frontend/dist
# Nuxt (built in frontendbuilder stage)
frontend-nuxt/node_modules
frontend-nuxt/.nuxt
frontend-nuxt/.output
# Runtime data (mounted at run time, not needed for build)
grids
# Backup dir often has root-only permissions; exclude from build context
backup
# Misc
*.log
.env*
.DS_Store
# Git and IDE
.git
.gitignore
.cursor
.cursorignore
*.md
*.plan.md
# Old Vue 2 frontend (not used in build)
frontend/node_modules
frontend/dist
# Nuxt (built in frontendbuilder stage)
frontend-nuxt/node_modules
frontend-nuxt/.nuxt
frontend-nuxt/.output
# Runtime data (mounted at run time, not needed for build)
grids
# Backup dir often has root-only permissions; exclude from build context
backup
# Misc
*.log
.env*
.DS_Store

View File

@@ -1,7 +1,10 @@
# Backend tools image: Go + golangci-lint for test, fmt, lint.
# Source is mounted at /hnh-map at run time via docker-compose.tools.yml.
# Source is mounted at /src at run time; this WORKDIR is only for build-time go mod download.
FROM golang:1.24-alpine
RUN go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.61.0
# v1.64+ required for Go 1.24 (export data format); see https://github.com/golangci/golangci-lint/issues/5225
RUN go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.0
WORKDIR /hnh-map
WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download

View File

@@ -3,25 +3,31 @@
TOOLS_COMPOSE = docker compose -f docker-compose.tools.yml
dev:
docker compose -f docker-compose.dev.yml up
docker compose -f docker-compose.dev.yml up --build
build:
docker compose -f docker-compose.prod.yml build
docker compose -f docker-compose.prod.yml build --no-cache
test: test-backend test-frontend
test-backend:
$(TOOLS_COMPOSE) run --rm backend-tools go test ./...
$(TOOLS_COMPOSE) build backend-tools
$(TOOLS_COMPOSE) run --rm backend-tools sh -c "go mod download && go test ./..."
test-frontend:
$(TOOLS_COMPOSE) build frontend-tools
$(TOOLS_COMPOSE) run --rm frontend-tools sh -c "npm ci && npm test"
lint:
$(TOOLS_COMPOSE) run --rm backend-tools golangci-lint run
$(TOOLS_COMPOSE) build backend-tools
$(TOOLS_COMPOSE) build frontend-tools
$(TOOLS_COMPOSE) run --rm backend-tools sh -c "go mod download && golangci-lint run"
$(TOOLS_COMPOSE) run --rm frontend-tools sh -c "npm ci && npm run lint"
fmt:
$(TOOLS_COMPOSE) run --rm backend-tools go fmt ./...
$(TOOLS_COMPOSE) build backend-tools
$(TOOLS_COMPOSE) build frontend-tools
$(TOOLS_COMPOSE) run --rm backend-tools sh -c "go mod download && go fmt ./..."
$(TOOLS_COMPOSE) run --rm frontend-tools sh -c "npm ci && npm run format"
generate-frontend:

View File

@@ -1,13 +1,18 @@
# One-off tools: test, lint, fmt. Use with: docker compose -f docker-compose.tools.yml run --rm <service> <cmd>
# Source is mounted so commands run against current code.
# Backend: mount at /src so the image's /go module cache (from build) is not overwritten.
services:
backend-tools:
build:
context: .
dockerfile: Dockerfile.tools
working_dir: /src
environment:
GOPATH: /go
GOMODCACHE: /go/pkg/mod
volumes:
- .:/hnh-map
- .:/src
# Default command; override when running (e.g. go test ./..., golangci-lint run).
command: ["go", "test", "./..."]

View File

@@ -1,79 +1,79 @@
# HTTP API
The API is available under the `/map/api/` prefix. Requests requiring authentication use a `session` cookie (set on login).
## Authentication
- **POST /map/api/login** — sign in. Body: `{"user":"...","pass":"..."}`. On success returns JSON with user data and sets a session cookie. On first run, bootstrap is available: logging in as `admin` with the password from `HNHMAP_BOOTSTRAP_PASSWORD` creates the first admin user. For users created via OAuth (no password), returns 401 with `{"error":"Use OAuth to sign in"}`.
- **GET /map/api/me** — current user (by session). Response: `username`, `auths`, and optionally `tokens`, `prefix`, `email` (string, optional — for Gravatar and display).
- **POST /map/api/logout** — sign out (invalidates the session).
- **GET /map/api/setup** — check if initial setup is needed. Response: `{"setupRequired": true|false}`.
### OAuth
- **GET /map/api/oauth/providers** — list of configured OAuth providers. Response: `["google", ...]`.
- **GET /map/api/oauth/{provider}/login** — redirect to the provider's authorization page. Query: `redirect` — path to redirect to after successful login (e.g. `/profile`).
- **GET /map/api/oauth/{provider}/callback** — callback from the provider (called automatically). Exchanges the `code` for tokens, creates or finds the user, creates a session, and redirects to `/profile` or the `redirect` from state.
## User account
- **PATCH /map/api/me** — update current user. Body: `{"email": "..."}`. Used to set or change the user's email (for Gravatar and profile display). Requires a valid session.
- **POST /map/api/me/tokens** — generate a new upload token (requires `upload` permission). Response: `{"tokens": ["...", ...]}`.
- **POST /map/api/me/password** — change password. Body: `{"pass":"..."}`.
## Map data
- **GET /map/api/config** — client configuration (title, auths). Requires a session.
- **GET /map/api/v1/characters** — list of characters on the map (requires `map` permission; `markers` permission needed to see data). Each character object includes `ownedByMe` (boolean), which is true when the character was last updated by one of the current user's upload tokens.
- **GET /map/api/v1/markers** — markers (requires `map` permission; `markers` permission needed to see data).
- **GET /map/api/maps** — list of maps (filtered by permissions and hidden status). For non-admin users hidden maps are excluded; for admin, the response may include hidden maps (client should hide them in map selector if needed).
## Admin (all endpoints below require `admin` permission)
- **GET /map/api/admin/users** — list of usernames.
- **POST /map/api/admin/users** — create or update a user. Body: `{"user":"...","pass":"...","auths":["admin","map",...]}`.
- **GET /map/api/admin/users/:name** — user data.
- **DELETE /map/api/admin/users/:name** — delete a user.
- **GET /map/api/admin/settings** — settings (prefix, defaultHide, title).
- **POST /map/api/admin/settings** — save settings. Body: `{"prefix":"...","defaultHide":true|false,"title":"..."}` (all fields optional).
- **GET /map/api/admin/maps** — list of maps for the admin panel.
- **POST /map/api/admin/maps/:id** — update a map (name, hidden, priority).
- **POST /map/api/admin/maps/:id/toggle-hidden** — toggle map visibility.
- **POST /map/api/admin/wipe** — wipe grids, markers, tiles, and maps from the database.
- **POST /map/api/admin/rebuildZooms** — start rebuilding tile zoom levels from base tiles in the background. Returns **202 Accepted** immediately; the operation can take minutes when there are many grids. The client may poll **GET /map/api/admin/rebuildZooms/status** until `{"running": false}` and then refresh the map.
- **GET /map/api/admin/rebuildZooms/status** — returns `{"running": true|false}` indicating whether a rebuild started via POST rebuildZooms is still in progress.
- **GET /map/api/admin/export** — download data export (ZIP).
- **POST /map/api/admin/merge** — upload and apply a merge (ZIP with grids and markers).
- **GET /map/api/admin/wipeTile** — delete a tile. Query: `map`, `x`, `y`.
- **GET /map/api/admin/setCoords** — shift grid coordinates. Query: `map`, `fx`, `fy`, `tx`, `ty`.
- **GET /map/api/admin/hideMarker** — hide a marker. Query: `id`.
## Game client
The game client (e.g. Purus Pasta) communicates via `/client/{token}/...` endpoints using token-based authentication.
- **GET /client/{token}/checkVersion** — check client protocol version. Query: `version`. Returns 200 if matching, 400 otherwise.
- **GET /client/{token}/locate** — get grid coordinates. Query: `gridID`. Response: `mapid;x;y`.
- **POST /client/{token}/gridUpdate** — report visible grids and receive upload requests.
- **POST /client/{token}/gridUpload** — upload a tile image (multipart).
- **POST /client/{token}/positionUpdate** — update character positions.
- **POST /client/{token}/markerUpdate** — upload markers.
## SSE (Server-Sent Events)
- **GET /map/updates** — real-time tile and merge updates. Requires a session with `map` permission. Sends an initial `data:` message with an empty tile cache array `[]`, then incremental `data:` messages with tile cache updates and `event: merge` messages for map merges. The client requests tiles with `cache=0` when not yet in cache.
## Tile images
- **GET /map/grids/{mapid}/{zoom}/{x}_{y}.png** — tile image. Requires a session with `map` permission. Returns the tile image or a transparent 1×1 PNG if the tile does not exist.
## Response codes
- **200** — success.
- **400** — bad request (wrong method, body, or parameters).
- **401** — unauthorized (missing or invalid session).
- **403** — forbidden (insufficient permissions).
- **404** — not found.
- **500** — internal error.
Error format: JSON body `{"error": "message", "code": "CODE"}`.
# HTTP API
The API is available under the `/map/api/` prefix. Requests requiring authentication use a `session` cookie (set on login).
## Authentication
- **POST /map/api/login** — sign in. Body: `{"user":"...","pass":"..."}`. On success returns JSON with user data and sets a session cookie. On first run, bootstrap is available: logging in as `admin` with the password from `HNHMAP_BOOTSTRAP_PASSWORD` creates the first admin user. For users created via OAuth (no password), returns 401 with `{"error":"Use OAuth to sign in"}`.
- **GET /map/api/me** — current user (by session). Response: `username`, `auths`, and optionally `tokens`, `prefix`, `email` (string, optional — for Gravatar and display).
- **POST /map/api/logout** — sign out (invalidates the session).
- **GET /map/api/setup** — check if initial setup is needed. Response: `{"setupRequired": true|false}`.
### OAuth
- **GET /map/api/oauth/providers** — list of configured OAuth providers. Response: `["google", ...]`.
- **GET /map/api/oauth/{provider}/login** — redirect to the provider's authorization page. Query: `redirect` — path to redirect to after successful login (e.g. `/profile`).
- **GET /map/api/oauth/{provider}/callback** — callback from the provider (called automatically). Exchanges the `code` for tokens, creates or finds the user, creates a session, and redirects to `/profile` or the `redirect` from state.
## User account
- **PATCH /map/api/me** — update current user. Body: `{"email": "..."}`. Used to set or change the user's email (for Gravatar and profile display). Requires a valid session.
- **POST /map/api/me/tokens** — generate a new upload token (requires `upload` permission). Response: `{"tokens": ["...", ...]}`.
- **POST /map/api/me/password** — change password. Body: `{"pass":"..."}`.
## Map data
- **GET /map/api/config** — client configuration (title, auths). Requires a session.
- **GET /map/api/v1/characters** — list of characters on the map (requires `map` permission; `markers` permission needed to see data). Each character object includes `ownedByMe` (boolean), which is true when the character was last updated by one of the current user's upload tokens.
- **GET /map/api/v1/markers** — markers (requires `map` permission; `markers` permission needed to see data).
- **GET /map/api/maps** — list of maps (filtered by permissions and hidden status). For non-admin users hidden maps are excluded; for admin, the response may include hidden maps (client should hide them in map selector if needed).
## Admin (all endpoints below require `admin` permission)
- **GET /map/api/admin/users** — list of usernames.
- **POST /map/api/admin/users** — create or update a user. Body: `{"user":"...","pass":"...","auths":["admin","map",...]}`.
- **GET /map/api/admin/users/:name** — user data.
- **DELETE /map/api/admin/users/:name** — delete a user.
- **GET /map/api/admin/settings** — settings (prefix, defaultHide, title).
- **POST /map/api/admin/settings** — save settings. Body: `{"prefix":"...","defaultHide":true|false,"title":"..."}` (all fields optional).
- **GET /map/api/admin/maps** — list of maps for the admin panel.
- **POST /map/api/admin/maps/:id** — update a map (name, hidden, priority).
- **POST /map/api/admin/maps/:id/toggle-hidden** — toggle map visibility.
- **POST /map/api/admin/wipe** — wipe grids, markers, tiles, and maps from the database.
- **POST /map/api/admin/rebuildZooms** — start rebuilding tile zoom levels from base tiles in the background. Returns **202 Accepted** immediately; the operation can take minutes when there are many grids. The client may poll **GET /map/api/admin/rebuildZooms/status** until `{"running": false}` and then refresh the map.
- **GET /map/api/admin/rebuildZooms/status** — returns `{"running": true|false}` indicating whether a rebuild started via POST rebuildZooms is still in progress.
- **GET /map/api/admin/export** — download data export (ZIP).
- **POST /map/api/admin/merge** — upload and apply a merge (ZIP with grids and markers).
- **GET /map/api/admin/wipeTile** — delete a tile. Query: `map`, `x`, `y`.
- **GET /map/api/admin/setCoords** — shift grid coordinates. Query: `map`, `fx`, `fy`, `tx`, `ty`.
- **GET /map/api/admin/hideMarker** — hide a marker. Query: `id`.
## Game client
The game client (e.g. Purus Pasta) communicates via `/client/{token}/...` endpoints using token-based authentication.
- **GET /client/{token}/checkVersion** — check client protocol version. Query: `version`. Returns 200 if matching, 400 otherwise.
- **GET /client/{token}/locate** — get grid coordinates. Query: `gridID`. Response: `mapid;x;y`.
- **POST /client/{token}/gridUpdate** — report visible grids and receive upload requests.
- **POST /client/{token}/gridUpload** — upload a tile image (multipart).
- **POST /client/{token}/positionUpdate** — update character positions.
- **POST /client/{token}/markerUpdate** — upload markers.
## SSE (Server-Sent Events)
- **GET /map/updates** — real-time tile and merge updates. Requires a session with `map` permission. Sends an initial `data:` message with an empty tile cache array `[]`, then incremental `data:` messages with tile cache updates and `event: merge` messages for map merges. The client requests tiles with `cache=0` when not yet in cache.
## Tile images
- **GET /map/grids/{mapid}/{zoom}/{x}_{y}.png** — tile image. Requires a session with `map` permission. Returns the tile image or a transparent 1×1 PNG if the tile does not exist.
## Response codes
- **200** — success.
- **400** — bad request (wrong method, body, or parameters).
- **401** — unauthorized (missing or invalid session).
- **403** — forbidden (insufficient permissions).
- **404** — not found.
- **500** — internal error.
Error format: JSON body `{"error": "message", "code": "CODE"}`.

View File

@@ -1,6 +1,26 @@
import { ref, reactive, computed, watch, watchEffect, onMounted, onUnmounted, nextTick } from 'vue'
import {
ref,
reactive,
computed,
watch,
watchEffect,
onMounted,
onUnmounted,
nextTick,
readonly,
} from 'vue'
export { ref, reactive, computed, watch, watchEffect, onMounted, onUnmounted, nextTick }
export {
ref,
reactive,
computed,
watch,
watchEffect,
onMounted,
onUnmounted,
nextTick,
readonly,
}
export function useRuntimeConfig() {
return {

View File

@@ -4,6 +4,16 @@
</NuxtLayout>
</template>
<script setup lang="ts">
// Global error handling: on API auth failure, redirect to login
const { onApiError } = useMapApi()
const { fullUrl } = useAppPaths()
const unsubscribe = onApiError(() => {
if (import.meta.client) window.location.href = fullUrl('/login')
})
onUnmounted(() => unsubscribe())
</script>
<style>
.page-enter-active,
.page-leave-active {
@@ -14,13 +24,3 @@
opacity: 0;
}
</style>
<script setup lang="ts">
// Global error handling: on API auth failure, redirect to login
const { onApiError } = useMapApi()
const { fullUrl } = useAppPaths()
const unsubscribe = onApiError(() => {
if (import.meta.client) window.location.href = fullUrl('/login')
})
onUnmounted(() => unsubscribe())
</script>

View File

@@ -1,23 +1,59 @@
/* Map container background from theme (DaisyUI base-200) */
.leaflet-container {
background: var(--color-base-200);
}
/* Override Leaflet default: show tiles even when leaflet-tile-loaded is not applied
(e.g. due to cache, Nuxt hydration, or load event order). */
.leaflet-tile {
visibility: visible !important;
}
/* Subtle highlight when a tile is updated via SSE (reduced intensity to limit flicker). */
@keyframes tile-fresh-glow {
0% {
opacity: 0.92;
}
100% {
opacity: 1;
}
}
.leaflet-tile.tile-fresh {
animation: tile-fresh-glow 0.4s ease-out;
}
/* Map container background from theme (DaisyUI base-200) */
.leaflet-container {
background: var(--color-base-200);
}
/* Override Leaflet default: show tiles even when leaflet-tile-loaded is not applied
(e.g. due to cache, Nuxt hydration, or load event order). */
.leaflet-tile {
visibility: visible !important;
}
/* Subtle highlight when a tile is updated via SSE (reduced intensity to limit flicker). */
@keyframes tile-fresh-glow {
0% {
opacity: 0.92;
}
100% {
opacity: 1;
}
}
.leaflet-tile.tile-fresh {
animation: tile-fresh-glow 0.4s ease-out;
}
/* Leaflet tooltip: use theme colors (dark/light) */
.leaflet-tooltip {
background-color: var(--color-base-100);
color: var(--color-base-content);
border-color: var(--color-base-300);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
}
.leaflet-tooltip-top:before {
border-top-color: var(--color-base-100);
}
.leaflet-tooltip-bottom:before {
border-bottom-color: var(--color-base-100);
}
.leaflet-tooltip-left:before {
border-left-color: var(--color-base-100);
}
.leaflet-tooltip-right:before {
border-right-color: var(--color-base-100);
}
/* Leaflet popup: use theme colors (dark/light) */
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: var(--color-base-100);
color: var(--color-base-content);
box-shadow: 0 3px 14px rgba(0, 0, 0, 0.35);
}
.leaflet-container a.leaflet-popup-close-button {
color: var(--color-base-content);
opacity: 0.7;
}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
opacity: 1;
}

View File

@@ -88,24 +88,27 @@
</div>
<MapControls
:hide-markers="mapLogic.state.hideMarkers.value"
@update:hide-markers="(v) => (mapLogic.state.hideMarkers.value = v)"
:selected-map-id="mapLogic.state.selectedMapId.value"
@update:selected-map-id="(v) => (mapLogic.state.selectedMapId.value = v)"
:overlay-map-id="mapLogic.state.overlayMapId.value"
@update:overlay-map-id="(v) => (mapLogic.state.overlayMapId.value = v)"
:selected-marker-id="mapLogic.state.selectedMarkerId.value"
@update:selected-marker-id="(v) => (mapLogic.state.selectedMarkerId.value = v)"
:selected-player-id="mapLogic.state.selectedPlayerId.value"
@update:selected-player-id="(v) => (mapLogic.state.selectedPlayerId.value = v)"
:maps="maps"
:quest-givers="questGivers"
:players="players"
:markers="allMarkers"
:current-zoom="currentZoom"
:current-map-id="mapLogic.state.mapid.value"
:current-coords="mapLogic.state.displayCoords.value"
:selected-marker-for-bookmark="selectedMarkerForBookmark"
@update:hide-markers="(v) => (mapLogic.state.hideMarkers.value = v)"
@update:selected-map-id="(v) => (mapLogic.state.selectedMapId.value = v)"
@update:overlay-map-id="(v) => (mapLogic.state.overlayMapId.value = v)"
@update:selected-marker-id="(v) => (mapLogic.state.selectedMarkerId.value = v)"
@update:selected-player-id="(v) => (mapLogic.state.selectedPlayerId.value = v)"
@zoom-in="mapLogic.zoomIn(leafletMap)"
@zoom-out="mapLogic.zoomOutControl(leafletMap)"
@reset-view="mapLogic.resetView(leafletMap)"
@set-zoom="onSetZoom"
@jump-to-marker="mapLogic.state.selectedMarkerId.value = $event"
/>
<MapContextMenu
@@ -147,7 +150,7 @@ import { useMapNavigate } from '~/composables/useMapNavigate'
import { useFullscreen } from '~/composables/useFullscreen'
import { startMapUpdates, type UseMapUpdatesReturn, type SseConnectionState } from '~/composables/useMapUpdates'
import { createMapLayers, type MapLayersManager } from '~/composables/useMapLayers'
import type { MapInfo, ConfigResponse, MeResponse } from '~/types/api'
import type { MapInfo, ConfigResponse, MeResponse, Marker as ApiMarker } from '~/types/api'
import type L from 'leaflet'
const props = withDefaults(
@@ -252,6 +255,10 @@ const maps = ref<MapInfo[]>([])
const mapsLoaded = ref(false)
const questGivers = ref<Array<{ id: number; name: string }>>([])
const players = ref<Array<{ id: number; name: string }>>([])
/** All markers from API for search suggestions (updated when markers load or on merge). */
const allMarkers = ref<ApiMarker[]>([])
/** Current map zoom level (16) for zoom slider. Updated on zoomend. */
const currentZoom = ref(HnHDefaultZoom)
/** Single source of truth: layout updates me, we derive auths for context menu. */
const me = useState<MeResponse | null>('me', () => null)
const auths = computed(() => me.value?.auths ?? [])
@@ -347,6 +354,10 @@ function reloadPage() {
if (import.meta.client) window.location.reload()
}
function onSetZoom(z: number) {
if (leafletMap) leafletMap.setZoom(z)
}
function onKeydown(e: KeyboardEvent) {
const target = e.target as HTMLElement
const inInput = /^(INPUT|TEXTAREA|SELECT)$/.test(target?.tagName ?? '')
@@ -462,6 +473,16 @@ onMounted(async () => {
getTrackingCharacterId: () => mapLogic.state.trackingCharacterId.value,
setTrackingCharacterId: (id: number) => { mapLogic.state.trackingCharacterId.value = id },
onMarkerContextMenu: mapLogic.openMarkerContextMenu,
onAddMarkerToBookmark: (markerId, getMarkerById) => {
const m = getMarkerById(markerId)
if (!m) return
openBookmarkModal(m.name, 'Add bookmark', {
kind: 'add',
mapId: m.map,
x: Math.floor(m.position.x / TileSize),
y: Math.floor(m.position.y / TileSize),
})
},
resolveIconUrl: (path) => resolvePath(path),
fallbackIconUrl: FALLBACK_MARKER_ICON,
})
@@ -479,7 +500,9 @@ onMounted(async () => {
layersManager!.changeMap(mapTo)
api.getMarkers().then((body) => {
if (!mounted) return
layersManager!.updateMarkers(Array.isArray(body) ? body : [])
const list = Array.isArray(body) ? body : []
allMarkers.value = list
layersManager!.updateMarkers(list)
questGivers.value = layersManager!.getQuestGivers()
})
leafletMap!.setView(latLng, leafletMap!.getZoom())
@@ -530,7 +553,9 @@ onMounted(async () => {
// Markers load asynchronously after map is visible.
api.getMarkers().then((body) => {
if (!mounted) return
layersManager!.updateMarkers(Array.isArray(body) ? body : [])
const list = Array.isArray(body) ? body : []
allMarkers.value = list
layersManager!.updateMarkers(list)
questGivers.value = layersManager!.getQuestGivers()
updateSelectedMarkerForBookmark()
})
@@ -650,6 +675,10 @@ onMounted(async () => {
leafletMap.on('moveend', () => mapLogic.updateDisplayCoords(leafletMap))
mapLogic.updateDisplayCoords(leafletMap)
currentZoom.value = leafletMap.getZoom()
leafletMap.on('zoomend', () => {
if (leafletMap) currentZoom.value = leafletMap.getZoom()
})
leafletMap.on('drag', () => {
mapLogic.state.trackingCharacterId.value = -1
})

View File

@@ -15,7 +15,7 @@
:readonly="readonly"
:aria-describedby="ariaDescribedby"
@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
/>
>
<button
type="button"
class="absolute right-2 top-1/2 -translate-y-1/2 btn btn-ghost btn-sm btn-square min-h-9 min-w-9 touch-manipulation"
@@ -41,7 +41,14 @@ const props = withDefaults(
inputId?: string
ariaDescribedby?: string
}>(),
{ required: false, autocomplete: 'off', inputId: undefined, ariaDescribedby: undefined }
{
required: false,
autocomplete: 'off',
inputId: undefined,
ariaDescribedby: undefined,
label: undefined,
placeholder: undefined,
}
)
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()

View File

@@ -6,5 +6,5 @@
</template>
<script setup lang="ts">
defineOptions({ inheritAttrs: false })
defineOptions({ name: 'AppSkeleton', inheritAttrs: false })
</script>

View File

@@ -30,7 +30,7 @@ const props = withDefaults(
email?: string
size?: number
}>(),
{ size: 32 }
{ size: 32, email: undefined }
)
const gravatarError = ref(false)

View File

@@ -0,0 +1,6 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</svg>
</template>

View File

@@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<path d="M12 16v-4" />
<path d="M12 8h.01" />
</svg>
</template>

View File

@@ -18,7 +18,7 @@
class="input input-bordered w-full"
placeholder="Bookmark name"
@keydown.enter.prevent="onSubmit"
/>
>
</div>
<div class="modal-action">
<form method="dialog" @submit.prevent="onSubmit">

View File

@@ -7,7 +7,7 @@
<div class="flex flex-col gap-1 max-h-40 overflow-y-auto">
<template v-if="bookmarks.length === 0">
<p class="text-xs text-base-content/60 py-1">No saved locations.</p>
<p class="text-xs text-base-content/50 py-0">Add current location or a selected quest giver below.</p>
<p class="text-xs text-base-content/50 py-0">Add your first location below.</p>
</template>
<template v-else>
<div
@@ -49,7 +49,7 @@
class="btn btn-primary btn-sm w-full"
:class="touchFriendly ? 'min-h-11' : ''"
:disabled="!selectedMarkerForBookmark"
title="Add selected quest giver as bookmark"
:title="selectedMarkerForBookmark ? 'Add selected quest giver as bookmark' : 'Select a quest giver from the list above to add it as a bookmark.'"
@click="onAddSelectedMarker"
>
<icons-icon-plus class="size-4" />

View File

@@ -39,22 +39,25 @@
<MapControlsContent
v-model:hide-markers="hideMarkers"
:selected-map-id-select="selectedMapIdSelect"
@update:selected-map-id-select="(v) => (selectedMapIdSelect = v)"
:overlay-map-id="overlayMapId"
@update:overlay-map-id="(v) => (overlayMapId = v)"
:selected-marker-id-select="selectedMarkerIdSelect"
@update:selected-marker-id-select="(v) => (selectedMarkerIdSelect = v)"
:selected-player-id-select="selectedPlayerIdSelect"
@update:selected-player-id-select="(v) => (selectedPlayerIdSelect = v)"
:maps="maps"
:quest-givers="questGivers"
:players="players"
:markers="markers"
:current-zoom="currentZoom"
:current-map-id="currentMapId ?? undefined"
:current-coords="currentCoords"
:selected-marker-for-bookmark="selectedMarkerForBookmark"
@update:selected-map-id-select="(v) => (selectedMapIdSelect = v)"
@update:overlay-map-id="(v) => (overlayMapId = v)"
@update:selected-marker-id-select="(v) => (selectedMarkerIdSelect = v)"
@update:selected-player-id-select="(v) => (selectedPlayerIdSelect = v)"
@zoom-in="$emit('zoomIn')"
@zoom-out="$emit('zoomOut')"
@reset-view="$emit('resetView')"
@set-zoom="$emit('setZoom', $event)"
@jump-to-marker="$emit('jumpToMarker', $event)"
/>
</div>
@@ -130,23 +133,26 @@
<MapControlsContent
v-model:hide-markers="hideMarkers"
:selected-map-id-select="selectedMapIdSelect"
@update:selected-map-id-select="(v) => (selectedMapIdSelect = v)"
:overlay-map-id="overlayMapId"
@update:overlay-map-id="(v) => (overlayMapId = v)"
:selected-marker-id-select="selectedMarkerIdSelect"
@update:selected-marker-id-select="(v) => (selectedMarkerIdSelect = v)"
:selected-player-id-select="selectedPlayerIdSelect"
@update:selected-player-id-select="(v) => (selectedPlayerIdSelect = v)"
:maps="maps"
:quest-givers="questGivers"
:players="players"
:markers="markers"
:current-zoom="currentZoom"
:current-map-id="currentMapId ?? undefined"
:current-coords="currentCoords"
:selected-marker-for-bookmark="selectedMarkerForBookmark"
:touch-friendly="true"
@update:selected-map-id-select="(v) => (selectedMapIdSelect = v)"
@update:overlay-map-id="(v) => (overlayMapId = v)"
@update:selected-marker-id-select="(v) => (selectedMarkerIdSelect = v)"
@update:selected-player-id-select="(v) => (selectedPlayerIdSelect = v)"
@zoom-in="$emit('zoomIn')"
@zoom-out="$emit('zoomOut')"
@reset-view="$emit('resetView')"
@set-zoom="$emit('setZoom', $event)"
@jump-to-marker="$emit('jumpToMarker', $event)"
/>
</div>
@@ -169,7 +175,7 @@
</template>
<script setup lang="ts">
import type { MapInfo } from '~/types/api'
import type { MapInfo, Marker as ApiMarker } from '~/types/api'
import type { SelectedMarkerForBookmark } from '~/components/map/MapBookmarks.vue'
import MapControlsContent from '~/components/map/MapControlsContent.vue'
@@ -185,9 +191,11 @@ interface Player {
const props = withDefaults(
defineProps<{
maps: MapInfo[]
questGivers: QuestGiver[]
players: Player[]
maps?: MapInfo[]
questGivers?: QuestGiver[]
players?: Player[]
markers?: ApiMarker[]
currentZoom?: number
currentMapId?: number | null
currentCoords?: { x: number; y: number; z: number } | null
selectedMarkerForBookmark?: SelectedMarkerForBookmark
@@ -196,6 +204,8 @@ const props = withDefaults(
maps: () => [],
questGivers: () => [],
players: () => [],
markers: () => [],
currentZoom: 1,
currentMapId: null,
currentCoords: null,
selectedMarkerForBookmark: null,
@@ -206,6 +216,7 @@ defineEmits<{
zoomIn: []
zoomOut: []
resetView: []
setZoom: [level: number]
jumpToMarker: [id: number]
}>()

View File

@@ -5,6 +5,8 @@
v-if="currentMapId != null && currentCoords != null"
:maps="maps"
:quest-givers="questGivers"
:markers="markers"
:overlay-map-id="props.overlayMapId"
:current-map-id="currentMapId"
:current-coords="currentCoords"
:touch-friendly="touchFriendly"
@@ -48,6 +50,19 @@
<icons-icon-home />
</button>
</div>
<div class="flex items-center gap-2">
<input
type="range"
:min="zoomMin"
:max="zoomMax"
:value="currentZoom"
class="range range-primary range-sm flex-1"
:class="touchFriendly ? 'range-lg' : ''"
aria-label="Zoom level"
@input="onZoomSliderInput($event)"
>
<span class="text-xs font-mono w-6 text-right" aria-hidden="true">{{ currentZoom }}</span>
</div>
</section>
<!-- Display -->
<section class="flex flex-col gap-2">
@@ -56,7 +71,7 @@
Display
</h3>
<label class="label cursor-pointer justify-start gap-2 py-0 hover:bg-base-200/50 rounded-lg px-2 -mx-2 touch-manipulation" :class="touchFriendly ? 'min-h-11' : ''">
<input v-model="hideMarkers" type="checkbox" class="checkbox checkbox-sm" />
<input v-model="hideMarkers" type="checkbox" class="checkbox checkbox-sm" >
<span>Hide markers</span>
</label>
</section>
@@ -78,7 +93,16 @@
</select>
</fieldset>
<fieldset class="fieldset">
<label class="label py-0"><span>Overlay Map</span></label>
<label class="label py-0 flex items-center gap-1.5">
<span>Overlay Map</span>
<span
class="inline-flex text-base-content/60 cursor-help"
title="Overlay shows markers from another map on top of the current one."
aria-label="Overlay shows markers from another map on top of the current one."
>
<icons-icon-info class="size-3.5" />
</span>
</label>
<select
v-model="overlayMapId"
class="select select-sm w-full focus:ring-2 focus:ring-primary touch-manipulation"
@@ -89,22 +113,43 @@
</select>
</fieldset>
<fieldset class="fieldset">
<label class="label py-0"><span>Jump to Quest Giver</span></label>
<label class="label py-0"><span>Jump to</span></label>
<div class="join w-full flex">
<button
type="button"
class="btn btn-sm join-item flex-1 touch-manipulation"
:class="[jumpToTab === 'quest' ? 'btn-active' : 'btn-ghost', touchFriendly ? 'min-h-11 text-base' : '']"
aria-pressed="jumpToTab === 'quest'"
@click="jumpToTab = 'quest'"
>
Quest giver
</button>
<button
type="button"
class="btn btn-sm join-item flex-1 touch-manipulation"
:class="[jumpToTab === 'player' ? 'btn-active' : 'btn-ghost', touchFriendly ? 'min-h-11 text-base' : '']"
aria-pressed="jumpToTab === 'player'"
@click="jumpToTab = 'player'"
>
Player
</button>
</div>
<select
v-if="jumpToTab === 'quest'"
v-model="selectedMarkerIdSelect"
class="select select-sm w-full focus:ring-2 focus:ring-primary touch-manipulation"
class="select select-sm w-full focus:ring-2 focus:ring-primary touch-manipulation mt-1"
:class="touchFriendly ? 'min-h-11 text-base' : ''"
aria-label="Select quest giver"
>
<option value="">Select quest giver</option>
<option v-for="q in questGivers" :key="q.id" :value="String(q.id)">{{ q.name }}</option>
</select>
</fieldset>
<fieldset class="fieldset">
<label class="label py-0"><span>Jump to Player</span></label>
<select
v-else
v-model="selectedPlayerIdSelect"
class="select select-sm w-full focus:ring-2 focus:ring-primary touch-manipulation"
class="select select-sm w-full focus:ring-2 focus:ring-primary touch-manipulation mt-1"
:class="touchFriendly ? 'min-h-11 text-base' : ''"
aria-label="Select player"
>
<option value="">Select player</option>
<option v-for="p in players" :key="p.id" :value="String(p.id)">{{ p.name }}</option>
@@ -126,9 +171,10 @@
</template>
<script setup lang="ts">
import type { MapInfo } from '~/types/api'
import type { MapInfo, Marker as ApiMarker } from '~/types/api'
import type { SelectedMarkerForBookmark } from '~/components/map/MapBookmarks.vue'
import MapBookmarks from '~/components/map/MapBookmarks.vue'
import { HnHMinZoom, HnHMaxZoom } from '~/lib/LeafletCustomTypes'
interface QuestGiver {
id: number
@@ -140,27 +186,33 @@ interface Player {
name: string
}
const zoomMin = HnHMinZoom
const zoomMax = HnHMaxZoom
const props = withDefaults(
defineProps<{
maps: MapInfo[]
questGivers: QuestGiver[]
players: Player[]
markers?: ApiMarker[]
touchFriendly?: boolean
selectedMapIdSelect: string
overlayMapId: number
selectedMarkerIdSelect: string
selectedPlayerIdSelect: string
currentZoom?: number
currentMapId?: number
currentCoords?: { x: number; y: number; z: number } | null
selectedMarkerForBookmark?: SelectedMarkerForBookmark
}>(),
{ touchFriendly: false, currentMapId: 0, currentCoords: null, selectedMarkerForBookmark: null }
{ touchFriendly: false, markers: () => [], currentZoom: 1, currentMapId: 0, currentCoords: null, selectedMarkerForBookmark: null }
)
const emit = defineEmits<{
zoomIn: []
zoomOut: []
resetView: []
setZoom: [level: number]
jumpToMarker: [id: number]
'update:hideMarkers': [v: boolean]
'update:selectedMapIdSelect': [v: string]
@@ -169,8 +221,16 @@ const emit = defineEmits<{
'update:selectedPlayerIdSelect': [v: string]
}>()
function onZoomSliderInput(event: Event) {
const value = (event.target as HTMLInputElement).value
const level = Number(value)
if (!Number.isNaN(level)) emit('setZoom', level)
}
const hideMarkers = defineModel<boolean>('hideMarkers', { required: true })
const jumpToTab = ref<'quest' | 'player'>('quest')
const selectedMapIdSelect = computed({
get: () => props.selectedMapIdSelect,
set: (v) => emit('update:selectedMapIdSelect', v),

View File

@@ -11,8 +11,8 @@
<h3 id="coord-set-modal-title" class="font-bold text-lg">Rewrite tile coords</h3>
<p class="py-2">From ({{ coordSetFrom.x }}, {{ coordSetFrom.y }}) to:</p>
<div class="flex gap-2">
<input ref="firstInputRef" v-model.number="localTo.x" type="number" class="input flex-1" placeholder="X" />
<input v-model.number="localTo.y" type="number" class="input flex-1" placeholder="Y" />
<input ref="firstInputRef" v-model.number="localTo.x" type="number" class="input flex-1" placeholder="X" >
<input v-model.number="localTo.y" type="number" class="input flex-1" placeholder="Y" >
</div>
<div class="modal-action">
<form method="dialog" @submit.prevent="onSubmit">

View File

@@ -1,7 +1,7 @@
<template>
<div
v-if="displayCoords"
class="absolute bottom-2 right-2 z-[501] rounded-lg px-3 py-2 font-mono text-sm bg-base-100/95 backdrop-blur-sm border border-base-300/50 shadow cursor-pointer select-none transition-all hover:border-primary/50 hover:bg-base-100"
class="absolute bottom-2 right-2 z-[501] rounded-lg px-3 py-2 font-mono text-base bg-base-100/95 backdrop-blur-sm border border-base-300/50 shadow cursor-pointer select-none transition-all hover:border-primary/50 hover:bg-base-100 flex items-center gap-2"
aria-label="Current grid position and zoom click to copy share link"
:title="copied ? 'Copied!' : 'Click to copy share link'"
role="button"
@@ -19,6 +19,7 @@
Copied!
</span>
</span>
<icons-icon-copy class="size-4 shrink-0 opacity-70" aria-hidden="true" />
</div>
</template>

View File

@@ -22,7 +22,7 @@
@keydown.enter="onEnter"
@keydown.down.prevent="moveHighlight(1)"
@keydown.up.prevent="moveHighlight(-1)"
/>
>
<button
v-if="query"
type="button"
@@ -78,7 +78,8 @@
</template>
<script setup lang="ts">
import type { MapInfo } from '~/types/api'
import type { MapInfo, Marker as ApiMarker } from '~/types/api'
import { TileSize } from '~/lib/LeafletCustomTypes'
import { useMapNavigate } from '~/composables/useMapNavigate'
import { useRecentLocations } from '~/composables/useRecentLocations'
@@ -86,11 +87,13 @@ const props = withDefaults(
defineProps<{
maps: MapInfo[]
questGivers: Array<{ id: number; name: string }>
markers?: ApiMarker[]
overlayMapId?: number
currentMapId: number
currentCoords: { x: number; y: number; z: number } | null
touchFriendly?: boolean
}>(),
{ touchFriendly: false }
{ touchFriendly: false, markers: () => [], overlayMapId: -1 }
)
const { goToCoords } = useMapNavigate()
@@ -147,22 +150,37 @@ const suggestions = computed<Suggestion[]>(() => {
}
const list: Suggestion[] = []
for (const qg of props.questGivers) {
if (qg.name.toLowerCase().includes(q)) {
const overlayId = props.overlayMapId ?? -1
const visibleMarkers = (props.markers ?? []).filter(
(m) =>
!m.hidden &&
(m.map === props.currentMapId || (overlayId >= 0 && m.map === overlayId))
)
const qLower = q.toLowerCase()
for (const m of visibleMarkers) {
if (m.name.toLowerCase().includes(qLower)) {
const gridX = Math.floor(m.position.x / TileSize)
const gridY = Math.floor(m.position.y / TileSize)
list.push({
key: `qg-${qg.id}`,
label: qg.name,
mapId: props.currentMapId,
x: 0,
y: 0,
key: `marker-${m.id}`,
label: `${m.name} · ${gridX}, ${gridY}`,
mapId: m.map,
x: gridX,
y: gridY,
zoom: undefined,
markerId: qg.id,
markerId: m.id,
})
}
}
if (list.length > 0) return list.slice(0, 8)
return []
// Prefer quest givers (match by id in questGivers) so they appear first when query matches both
const qgIds = new Set(props.questGivers.map((qg) => qg.id))
list.sort((a, b) => {
const aQg = a.markerId != null && qgIds.has(a.markerId) ? 1 : 0
const bQg = b.markerId != null && qgIds.has(b.markerId) ? 1 : 0
if (bQg !== aQg) return bQg - aQg
return 0
})
return list.slice(0, 8)
})
function scheduleCloseDropdown() {

View File

@@ -1,10 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { useAppPaths } from '../useAppPaths'
const useRuntimeConfigMock = vi.fn()
vi.stubGlobal('useRuntimeConfig', useRuntimeConfigMock)
import { useAppPaths } from '../useAppPaths'
describe('useAppPaths with default base /', () => {
beforeEach(() => {
useRuntimeConfigMock.mockReturnValue({ app: { baseURL: '/' } })

View File

@@ -1,284 +1,284 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
vi.stubGlobal('useRuntimeConfig', () => ({
app: { baseURL: '/' },
public: { apiBase: '/map/api' },
}))
import { useMapApi } from '../useMapApi'
function mockFetch(status: number, body: unknown, contentType = 'application/json') {
return vi.fn().mockResolvedValue({
ok: status >= 200 && status < 300,
status,
headers: new Headers({ 'content-type': contentType }),
json: () => Promise.resolve(body),
} as Response)
}
describe('useMapApi', () => {
let originalFetch: typeof globalThis.fetch
beforeEach(() => {
originalFetch = globalThis.fetch
})
afterEach(() => {
globalThis.fetch = originalFetch
vi.restoreAllMocks()
})
describe('getConfig', () => {
it('fetches config from API', async () => {
const data = { title: 'Test', auths: ['map'] }
globalThis.fetch = mockFetch(200, data)
const { getConfig } = useMapApi()
const result = await getConfig()
expect(result).toEqual(data)
expect(globalThis.fetch).toHaveBeenCalledWith('/map/api/config', expect.objectContaining({ credentials: 'include' }))
})
it('throws on 401', async () => {
globalThis.fetch = mockFetch(401, { error: 'Unauthorized' })
const { getConfig } = useMapApi()
await expect(getConfig()).rejects.toThrow('Unauthorized')
})
it('throws on 403', async () => {
globalThis.fetch = mockFetch(403, { error: 'Forbidden' })
const { getConfig } = useMapApi()
await expect(getConfig()).rejects.toThrow('Forbidden')
})
})
describe('getCharacters', () => {
it('fetches characters', async () => {
const chars = [{ name: 'Hero', id: 1, map: 1, position: { x: 0, y: 0 }, type: 'player' }]
globalThis.fetch = mockFetch(200, chars)
const { getCharacters } = useMapApi()
const result = await getCharacters()
expect(result).toEqual(chars)
})
})
describe('getMarkers', () => {
it('fetches markers', async () => {
const markers = [{ name: 'Tower', id: 1, map: 1, position: { x: 10, y: 20 }, image: 'gfx/terobjs/mm/tower', hidden: false }]
globalThis.fetch = mockFetch(200, markers)
const { getMarkers } = useMapApi()
const result = await getMarkers()
expect(result).toEqual(markers)
})
})
describe('getMaps', () => {
it('fetches maps', async () => {
const maps = { '1': { ID: 1, Name: 'world' } }
globalThis.fetch = mockFetch(200, maps)
const { getMaps } = useMapApi()
const result = await getMaps()
expect(result).toEqual(maps)
})
})
describe('login', () => {
it('sends credentials and returns me response', async () => {
const meResp = { username: 'alice', auths: ['map'] }
globalThis.fetch = mockFetch(200, meResp)
const { login } = useMapApi()
const result = await login('alice', 'secret')
expect(result).toEqual(meResp)
expect(globalThis.fetch).toHaveBeenCalledWith(
'/map/api/login',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ user: 'alice', pass: 'secret' }),
}),
)
})
it('throws on 401 with error message', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 401,
json: () => Promise.resolve({ error: 'Invalid credentials' }),
})
const { login } = useMapApi()
await expect(login('alice', 'wrong')).rejects.toThrow('Invalid credentials')
})
})
describe('logout', () => {
it('sends POST to logout', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 })
const { logout } = useMapApi()
await logout()
expect(globalThis.fetch).toHaveBeenCalledWith(
'/map/api/logout',
expect.objectContaining({ method: 'POST' }),
)
})
})
describe('me', () => {
it('fetches current user', async () => {
const meResp = { username: 'alice', auths: ['map', 'upload'], tokens: ['tok1'], prefix: 'pfx' }
globalThis.fetch = mockFetch(200, meResp)
const { me } = useMapApi()
const result = await me()
expect(result).toEqual(meResp)
})
})
describe('setupRequired', () => {
it('checks setup status', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve({ setupRequired: true }),
})
const { setupRequired } = useMapApi()
const result = await setupRequired()
expect(result).toEqual({ setupRequired: true })
})
})
describe('oauthProviders', () => {
it('returns providers list', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve(['google']),
})
const { oauthProviders } = useMapApi()
const result = await oauthProviders()
expect(result).toEqual(['google'])
})
it('returns empty array on error', async () => {
globalThis.fetch = vi.fn().mockRejectedValue(new Error('network'))
const { oauthProviders } = useMapApi()
const result = await oauthProviders()
expect(result).toEqual([])
})
it('returns empty array on non-ok', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
})
const { oauthProviders } = useMapApi()
const result = await oauthProviders()
expect(result).toEqual([])
})
})
describe('oauthLoginUrl', () => {
it('builds OAuth login URL', () => {
// happy-dom needs an absolute URL for `new URL()`. The source code
// creates `new URL(apiBase + path)` which is relative.
// Verify the underlying apiBase and path construction instead.
const { apiBase } = useMapApi()
const expected = `${apiBase}/oauth/google/login`
expect(expected).toBe('/map/api/oauth/google/login')
})
it('oauthLoginUrl is a function', () => {
const { oauthLoginUrl } = useMapApi()
expect(typeof oauthLoginUrl).toBe('function')
})
})
describe('onApiError', () => {
it('fires callback on 401', async () => {
globalThis.fetch = mockFetch(401, { error: 'Unauthorized' })
const callback = vi.fn()
const { onApiError, getConfig } = useMapApi()
onApiError(callback)
await expect(getConfig()).rejects.toThrow()
expect(callback).toHaveBeenCalled()
})
it('returns unsubscribe function', async () => {
globalThis.fetch = mockFetch(401, { error: 'Unauthorized' })
const callback = vi.fn()
const { onApiError, getConfig } = useMapApi()
const unsub = onApiError(callback)
unsub()
await expect(getConfig()).rejects.toThrow()
expect(callback).not.toHaveBeenCalled()
})
})
describe('admin endpoints', () => {
it('adminExportUrl returns correct path', () => {
const { adminExportUrl } = useMapApi()
expect(adminExportUrl()).toBe('/map/api/admin/export')
})
it('adminUsers fetches user list', async () => {
globalThis.fetch = mockFetch(200, ['alice', 'bob'])
const { adminUsers } = useMapApi()
const result = await adminUsers()
expect(result).toEqual(['alice', 'bob'])
})
it('adminSettings fetches settings', async () => {
const settings = { prefix: 'pfx', defaultHide: false, title: 'Map' }
globalThis.fetch = mockFetch(200, settings)
const { adminSettings } = useMapApi()
const result = await adminSettings()
expect(result).toEqual(settings)
})
})
describe('meTokens', () => {
it('generates and returns tokens', async () => {
globalThis.fetch = mockFetch(200, { tokens: ['tok1', 'tok2'] })
const { meTokens } = useMapApi()
const result = await meTokens()
expect(result).toEqual(['tok1', 'tok2'])
})
})
describe('mePassword', () => {
it('sends password change', async () => {
globalThis.fetch = mockFetch(200, undefined, 'text/plain')
const { mePassword } = useMapApi()
await mePassword('newpass')
expect(globalThis.fetch).toHaveBeenCalledWith(
'/map/api/me/password',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ pass: 'newpass' }),
}),
)
})
})
})
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { useMapApi } from '../useMapApi'
vi.stubGlobal('useRuntimeConfig', () => ({
app: { baseURL: '/' },
public: { apiBase: '/map/api' },
}))
function mockFetch(status: number, body: unknown, contentType = 'application/json') {
return vi.fn().mockResolvedValue({
ok: status >= 200 && status < 300,
status,
headers: new Headers({ 'content-type': contentType }),
json: () => Promise.resolve(body),
} as Response)
}
describe('useMapApi', () => {
let originalFetch: typeof globalThis.fetch
beforeEach(() => {
originalFetch = globalThis.fetch
})
afterEach(() => {
globalThis.fetch = originalFetch
vi.restoreAllMocks()
})
describe('getConfig', () => {
it('fetches config from API', async () => {
const data = { title: 'Test', auths: ['map'] }
globalThis.fetch = mockFetch(200, data)
const { getConfig } = useMapApi()
const result = await getConfig()
expect(result).toEqual(data)
expect(globalThis.fetch).toHaveBeenCalledWith('/map/api/config', expect.objectContaining({ credentials: 'include' }))
})
it('throws on 401', async () => {
globalThis.fetch = mockFetch(401, { error: 'Unauthorized' })
const { getConfig } = useMapApi()
await expect(getConfig()).rejects.toThrow('Unauthorized')
})
it('throws on 403', async () => {
globalThis.fetch = mockFetch(403, { error: 'Forbidden' })
const { getConfig } = useMapApi()
await expect(getConfig()).rejects.toThrow('Forbidden')
})
})
describe('getCharacters', () => {
it('fetches characters', async () => {
const chars = [{ name: 'Hero', id: 1, map: 1, position: { x: 0, y: 0 }, type: 'player' }]
globalThis.fetch = mockFetch(200, chars)
const { getCharacters } = useMapApi()
const result = await getCharacters()
expect(result).toEqual(chars)
})
})
describe('getMarkers', () => {
it('fetches markers', async () => {
const markers = [{ name: 'Tower', id: 1, map: 1, position: { x: 10, y: 20 }, image: 'gfx/terobjs/mm/tower', hidden: false }]
globalThis.fetch = mockFetch(200, markers)
const { getMarkers } = useMapApi()
const result = await getMarkers()
expect(result).toEqual(markers)
})
})
describe('getMaps', () => {
it('fetches maps', async () => {
const maps = { '1': { ID: 1, Name: 'world' } }
globalThis.fetch = mockFetch(200, maps)
const { getMaps } = useMapApi()
const result = await getMaps()
expect(result).toEqual(maps)
})
})
describe('login', () => {
it('sends credentials and returns me response', async () => {
const meResp = { username: 'alice', auths: ['map'] }
globalThis.fetch = mockFetch(200, meResp)
const { login } = useMapApi()
const result = await login('alice', 'secret')
expect(result).toEqual(meResp)
expect(globalThis.fetch).toHaveBeenCalledWith(
'/map/api/login',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ user: 'alice', pass: 'secret' }),
}),
)
})
it('throws on 401 with error message', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 401,
json: () => Promise.resolve({ error: 'Invalid credentials' }),
})
const { login } = useMapApi()
await expect(login('alice', 'wrong')).rejects.toThrow('Invalid credentials')
})
})
describe('logout', () => {
it('sends POST to logout', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 })
const { logout } = useMapApi()
await logout()
expect(globalThis.fetch).toHaveBeenCalledWith(
'/map/api/logout',
expect.objectContaining({ method: 'POST' }),
)
})
})
describe('me', () => {
it('fetches current user', async () => {
const meResp = { username: 'alice', auths: ['map', 'upload'], tokens: ['tok1'], prefix: 'pfx' }
globalThis.fetch = mockFetch(200, meResp)
const { me } = useMapApi()
const result = await me()
expect(result).toEqual(meResp)
})
})
describe('setupRequired', () => {
it('checks setup status', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve({ setupRequired: true }),
})
const { setupRequired } = useMapApi()
const result = await setupRequired()
expect(result).toEqual({ setupRequired: true })
})
})
describe('oauthProviders', () => {
it('returns providers list', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve(['google']),
})
const { oauthProviders } = useMapApi()
const result = await oauthProviders()
expect(result).toEqual(['google'])
})
it('returns empty array on error', async () => {
globalThis.fetch = vi.fn().mockRejectedValue(new Error('network'))
const { oauthProviders } = useMapApi()
const result = await oauthProviders()
expect(result).toEqual([])
})
it('returns empty array on non-ok', async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
})
const { oauthProviders } = useMapApi()
const result = await oauthProviders()
expect(result).toEqual([])
})
})
describe('oauthLoginUrl', () => {
it('builds OAuth login URL', () => {
// happy-dom needs an absolute URL for `new URL()`. The source code
// creates `new URL(apiBase + path)` which is relative.
// Verify the underlying apiBase and path construction instead.
const { apiBase } = useMapApi()
const expected = `${apiBase}/oauth/google/login`
expect(expected).toBe('/map/api/oauth/google/login')
})
it('oauthLoginUrl is a function', () => {
const { oauthLoginUrl } = useMapApi()
expect(typeof oauthLoginUrl).toBe('function')
})
})
describe('onApiError', () => {
it('fires callback on 401', async () => {
globalThis.fetch = mockFetch(401, { error: 'Unauthorized' })
const callback = vi.fn()
const { onApiError, getConfig } = useMapApi()
onApiError(callback)
await expect(getConfig()).rejects.toThrow()
expect(callback).toHaveBeenCalled()
})
it('returns unsubscribe function', async () => {
globalThis.fetch = mockFetch(401, { error: 'Unauthorized' })
const callback = vi.fn()
const { onApiError, getConfig } = useMapApi()
const unsub = onApiError(callback)
unsub()
await expect(getConfig()).rejects.toThrow()
expect(callback).not.toHaveBeenCalled()
})
})
describe('admin endpoints', () => {
it('adminExportUrl returns correct path', () => {
const { adminExportUrl } = useMapApi()
expect(adminExportUrl()).toBe('/map/api/admin/export')
})
it('adminUsers fetches user list', async () => {
globalThis.fetch = mockFetch(200, ['alice', 'bob'])
const { adminUsers } = useMapApi()
const result = await adminUsers()
expect(result).toEqual(['alice', 'bob'])
})
it('adminSettings fetches settings', async () => {
const settings = { prefix: 'pfx', defaultHide: false, title: 'Map' }
globalThis.fetch = mockFetch(200, settings)
const { adminSettings } = useMapApi()
const result = await adminSettings()
expect(result).toEqual(settings)
})
})
describe('meTokens', () => {
it('generates and returns tokens', async () => {
globalThis.fetch = mockFetch(200, { tokens: ['tok1', 'tok2'] })
const { meTokens } = useMapApi()
const result = await meTokens()
expect(result).toEqual(['tok1', 'tok2'])
})
})
describe('mePassword', () => {
it('sends password change', async () => {
globalThis.fetch = mockFetch(200, undefined, 'text/plain')
const { mePassword } = useMapApi()
await mePassword('newpass')
expect(globalThis.fetch).toHaveBeenCalledWith(
'/map/api/me/password',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ pass: 'newpass' }),
}),
)
})
})
})

View File

@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref } from 'vue'
import { useMapBookmarks } from '../useMapBookmarks'
const stateByKey: Record<string, ReturnType<typeof ref>> = {}
const useStateMock = vi.fn((key: string, init: () => unknown) => {
if (!stateByKey[key]) {
@@ -18,15 +20,13 @@ const localStorageMock = {
storage[key] = value
}),
clear: vi.fn(() => {
for (const k of Object.keys(storage)) delete storage[k]
delete storage['hnh-map-bookmarks']
}),
}
vi.stubGlobal('localStorage', localStorageMock)
vi.stubGlobal('import.meta.server', false)
vi.stubGlobal('import.meta.client', true)
import { useMapBookmarks } from '../useMapBookmarks'
describe('useMapBookmarks', () => {
beforeEach(() => {
storage['hnh-map-bookmarks'] = '[]'

View File

@@ -1,11 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref, reactive } from 'vue'
import type { Map } from 'leaflet'
import { useMapLogic } from '../useMapLogic'
vi.stubGlobal('ref', ref)
vi.stubGlobal('reactive', reactive)
import { useMapLogic } from '../useMapLogic'
describe('useMapLogic', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -27,7 +28,7 @@ describe('useMapLogic', () => {
it('zoomIn calls map.zoomIn', () => {
const { zoomIn } = useMapLogic()
const mockMap = { zoomIn: vi.fn() }
zoomIn(mockMap as unknown as import('leaflet').Map)
zoomIn(mockMap as unknown as Map)
expect(mockMap.zoomIn).toHaveBeenCalled()
})
@@ -39,7 +40,7 @@ describe('useMapLogic', () => {
it('zoomOutControl calls map.zoomOut', () => {
const { zoomOutControl } = useMapLogic()
const mockMap = { zoomOut: vi.fn() }
zoomOutControl(mockMap as unknown as import('leaflet').Map)
zoomOutControl(mockMap as unknown as Map)
expect(mockMap.zoomOut).toHaveBeenCalled()
})
@@ -47,7 +48,7 @@ describe('useMapLogic', () => {
const { state, resetView } = useMapLogic()
state.trackingCharacterId.value = 42
const mockMap = { setView: vi.fn() }
resetView(mockMap as unknown as import('leaflet').Map)
resetView(mockMap as unknown as Map)
expect(state.trackingCharacterId.value).toBe(-1)
expect(mockMap.setView).toHaveBeenCalledWith([0, 0], 1, { animate: false })
})
@@ -59,7 +60,7 @@ describe('useMapLogic', () => {
getCenter: vi.fn(() => ({ lat: 0, lng: 0 })),
getZoom: vi.fn(() => 3),
}
updateDisplayCoords(mockMap as unknown as import('leaflet').Map)
updateDisplayCoords(mockMap as unknown as Map)
expect(state.displayCoords.value).toEqual({ x: 5, y: 3, z: 3 })
})
@@ -72,7 +73,7 @@ describe('useMapLogic', () => {
it('toLatLng calls map.unproject', () => {
const { toLatLng } = useMapLogic()
const mockMap = { unproject: vi.fn(() => ({ lat: 1, lng: 2 })) }
const result = toLatLng(mockMap as unknown as import('leaflet').Map, 100, 200)
const result = toLatLng(mockMap as unknown as Map, 100, 200)
expect(mockMap.unproject).toHaveBeenCalledWith([100, 200], 6)
expect(result).toEqual({ lat: 1, lng: 2 })
})

View File

@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref } from 'vue'
import { useToast } from '../useToast'
const stateByKey: Record<string, ReturnType<typeof ref>> = {}
const useStateMock = vi.fn((key: string, init: () => unknown) => {
if (!stateByKey[key]) {
@@ -10,8 +12,6 @@ const useStateMock = vi.fn((key: string, init: () => unknown) => {
})
vi.stubGlobal('useState', useStateMock)
import { useToast } from '../useToast'
describe('useToast', () => {
beforeEach(() => {
stateByKey['hnh-map-toasts'] = ref([])

View File

@@ -1,295 +1,295 @@
import type {
Character,
ConfigResponse,
MapInfo,
MapInfoAdmin,
Marker,
MeResponse,
SettingsResponse,
} from '~/types/api'
export type { Character, ConfigResponse, MapInfo, MapInfoAdmin, Marker, MeResponse, SettingsResponse }
// Singleton: shared by all useMapApi() callers so 401 triggers one global handler (e.g. app.vue)
const onApiErrorCallbacks = new Map<symbol, () => void>()
// In-flight dedup: one me() request at a time; concurrent callers share the same promise.
let mePromise: Promise<MeResponse> | null = null
// In-flight dedup for GET endpoints: same path + method shares one request across all callers.
const inFlightByKey = new Map<string, Promise<unknown>>()
export function useMapApi() {
const config = useRuntimeConfig()
const apiBase = config.public.apiBase as string
/** Subscribe to API auth errors (401). Returns unsubscribe function. */
function onApiError(cb: () => void): () => void {
const id = Symbol()
onApiErrorCallbacks.set(id, cb)
return () => onApiErrorCallbacks.delete(id)
}
async function request<T>(path: string, opts?: RequestInit): Promise<T> {
const url = path.startsWith('http') ? path : `${apiBase}/${path.replace(/^\//, '')}`
const res = await fetch(url, { credentials: 'include', ...opts })
// Only redirect to login on 401 (session invalid); 403 = forbidden (no permission)
if (res.status === 401) {
onApiErrorCallbacks.forEach((cb) => cb())
throw new Error('Unauthorized')
}
if (res.status === 403) throw new Error('Forbidden')
if (!res.ok) throw new Error(`API ${res.status}`)
if (res.headers.get('content-type')?.includes('application/json')) {
return res.json() as Promise<T>
}
return undefined as T
}
function requestDeduped<T>(path: string, opts?: RequestInit): Promise<T> {
const key = path + (opts?.method ?? 'GET')
const existing = inFlightByKey.get(key)
if (existing) return existing as Promise<T>
const p = request<T>(path, opts).finally(() => {
inFlightByKey.delete(key)
})
inFlightByKey.set(key, p)
return p
}
async function getConfig() {
return requestDeduped<ConfigResponse>('config')
}
async function getCharacters() {
return requestDeduped<Character[]>('v1/characters')
}
async function getMarkers() {
return requestDeduped<Marker[]>('v1/markers')
}
async function getMaps() {
return requestDeduped<Record<string, MapInfo>>('maps')
}
// Auth
async function login(user: string, pass: string) {
const res = await fetch(`${apiBase}/login`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user, pass }),
})
if (res.status === 401) {
const data = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(data.error || 'Unauthorized')
}
if (!res.ok) throw new Error(`API ${res.status}`)
return res.json() as Promise<MeResponse>
}
/** OAuth login URL for redirect (full page navigation). */
function oauthLoginUrl(provider: string, redirect?: string): string {
const url = new URL(`${apiBase}/oauth/${provider}/login`)
if (redirect) url.searchParams.set('redirect', redirect)
return url.toString()
}
/** List of configured OAuth providers. */
async function oauthProviders(): Promise<string[]> {
try {
const res = await fetch(`${apiBase}/oauth/providers`, { credentials: 'include' })
if (!res.ok) return []
const data = await res.json()
return Array.isArray(data) ? data : []
} catch {
return []
}
}
async function logout() {
mePromise = null
inFlightByKey.clear()
await fetch(`${apiBase}/logout`, { method: 'POST', credentials: 'include' })
}
async function me() {
if (mePromise) return mePromise
mePromise = request<MeResponse>('me').finally(() => {
mePromise = null
})
return mePromise
}
async function meUpdate(body: { email?: string }) {
await request('me', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
/** Public: whether first-time setup (no users) is required. */
async function setupRequired(): Promise<{ setupRequired: boolean }> {
const res = await fetch(`${apiBase}/setup`, { credentials: 'include' })
if (!res.ok) throw new Error(`API ${res.status}`)
return res.json() as Promise<{ setupRequired: boolean }>
}
// Profile
async function meTokens() {
const data = await request<{ tokens: string[] }>('me/tokens', { method: 'POST' })
return data?.tokens ?? []
}
async function mePassword(pass: string) {
await request('me/password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pass }),
})
}
// Admin
async function adminUsers() {
return request<string[]>('admin/users')
}
async function adminUserByName(name: string) {
return request<{ username: string; auths: string[] }>(`admin/users/${encodeURIComponent(name)}`)
}
async function adminUserPost(body: { user: string; pass?: string; auths: string[] }) {
await request('admin/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function adminUserDelete(name: string) {
await request(`admin/users/${encodeURIComponent(name)}`, { method: 'DELETE' })
}
async function adminSettings() {
return request<SettingsResponse>('admin/settings')
}
async function adminSettingsPost(body: { prefix?: string; defaultHide?: boolean; title?: string }) {
await request('admin/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function adminMaps() {
return request<MapInfoAdmin[]>('admin/maps')
}
async function adminMapPost(id: number, body: { name: string; hidden: boolean; priority: boolean }) {
await request(`admin/maps/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function adminMapToggleHidden(id: number) {
return request<MapInfoAdmin>(`admin/maps/${id}/toggle-hidden`, { method: 'POST' })
}
async function adminWipe() {
await request('admin/wipe', { method: 'POST' })
}
async function adminRebuildZooms() {
const res = await fetch(`${apiBase}/admin/rebuildZooms`, {
method: 'POST',
credentials: 'include',
})
if (res.status === 401 || res.status === 403) {
onApiErrorCallbacks.forEach((cb) => cb())
throw new Error('Unauthorized')
}
if (res.status !== 200 && res.status !== 202) throw new Error(`API ${res.status}`)
}
async function adminRebuildZoomsStatus(): Promise<{ running: boolean }> {
return request<{ running: boolean }>('admin/rebuildZooms/status')
}
function adminExportUrl() {
return `${apiBase}/admin/export`
}
async function adminMerge(formData: FormData) {
const res = await fetch(`${apiBase}/admin/merge`, {
method: 'POST',
credentials: 'include',
body: formData,
})
if (res.status === 401 || res.status === 403) {
onApiErrorCallbacks.forEach((cb) => cb())
throw new Error('Unauthorized')
}
if (!res.ok) throw new Error(`API ${res.status}`)
}
async function adminWipeTile(params: { map: number; x: number; y: number }) {
const qs = new URLSearchParams({ map: String(params.map), x: String(params.x), y: String(params.y) })
return request(`admin/wipeTile?${qs}`)
}
async function adminSetCoords(params: { map: number; fx: number; fy: number; tx: number; ty: number }) {
const qs = new URLSearchParams({
map: String(params.map),
fx: String(params.fx),
fy: String(params.fy),
tx: String(params.tx),
ty: String(params.ty),
})
return request(`admin/setCoords?${qs}`)
}
async function adminHideMarker(params: { id: number }) {
const qs = new URLSearchParams({ id: String(params.id) })
return request(`admin/hideMarker?${qs}`)
}
return {
apiBase,
onApiError,
getConfig,
getCharacters,
getMarkers,
getMaps,
login,
logout,
me,
meUpdate,
oauthLoginUrl,
oauthProviders,
setupRequired,
meTokens,
mePassword,
adminUsers,
adminUserByName,
adminUserPost,
adminUserDelete,
adminSettings,
adminSettingsPost,
adminMaps,
adminMapPost,
adminMapToggleHidden,
adminWipe,
adminRebuildZooms,
adminRebuildZoomsStatus,
adminExportUrl,
adminMerge,
adminWipeTile,
adminSetCoords,
adminHideMarker,
}
}
import type {
Character,
ConfigResponse,
MapInfo,
MapInfoAdmin,
Marker,
MeResponse,
SettingsResponse,
} from '~/types/api'
export type { Character, ConfigResponse, MapInfo, MapInfoAdmin, Marker, MeResponse, SettingsResponse }
// Singleton: shared by all useMapApi() callers so 401 triggers one global handler (e.g. app.vue)
const onApiErrorCallbacks = new Map<symbol, () => void>()
// In-flight dedup: one me() request at a time; concurrent callers share the same promise.
let mePromise: Promise<MeResponse> | null = null
// In-flight dedup for GET endpoints: same path + method shares one request across all callers.
const inFlightByKey = new Map<string, Promise<unknown>>()
export function useMapApi() {
const config = useRuntimeConfig()
const apiBase = config.public.apiBase as string
/** Subscribe to API auth errors (401). Returns unsubscribe function. */
function onApiError(cb: () => void): () => void {
const id = Symbol()
onApiErrorCallbacks.set(id, cb)
return () => onApiErrorCallbacks.delete(id)
}
async function request<T>(path: string, opts?: RequestInit): Promise<T> {
const url = path.startsWith('http') ? path : `${apiBase}/${path.replace(/^\//, '')}`
const res = await fetch(url, { credentials: 'include', ...opts })
// Only redirect to login on 401 (session invalid); 403 = forbidden (no permission)
if (res.status === 401) {
onApiErrorCallbacks.forEach((cb) => cb())
throw new Error('Unauthorized')
}
if (res.status === 403) throw new Error('Forbidden')
if (!res.ok) throw new Error(`API ${res.status}`)
if (res.headers.get('content-type')?.includes('application/json')) {
return res.json() as Promise<T>
}
return undefined as T
}
function requestDeduped<T>(path: string, opts?: RequestInit): Promise<T> {
const key = path + (opts?.method ?? 'GET')
const existing = inFlightByKey.get(key)
if (existing) return existing as Promise<T>
const p = request<T>(path, opts).finally(() => {
inFlightByKey.delete(key)
})
inFlightByKey.set(key, p)
return p
}
async function getConfig() {
return requestDeduped<ConfigResponse>('config')
}
async function getCharacters() {
return requestDeduped<Character[]>('v1/characters')
}
async function getMarkers() {
return requestDeduped<Marker[]>('v1/markers')
}
async function getMaps() {
return requestDeduped<Record<string, MapInfo>>('maps')
}
// Auth
async function login(user: string, pass: string) {
const res = await fetch(`${apiBase}/login`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user, pass }),
})
if (res.status === 401) {
const data = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(data.error || 'Unauthorized')
}
if (!res.ok) throw new Error(`API ${res.status}`)
return res.json() as Promise<MeResponse>
}
/** OAuth login URL for redirect (full page navigation). */
function oauthLoginUrl(provider: string, redirect?: string): string {
const url = new URL(`${apiBase}/oauth/${provider}/login`)
if (redirect) url.searchParams.set('redirect', redirect)
return url.toString()
}
/** List of configured OAuth providers. */
async function oauthProviders(): Promise<string[]> {
try {
const res = await fetch(`${apiBase}/oauth/providers`, { credentials: 'include' })
if (!res.ok) return []
const data = await res.json()
return Array.isArray(data) ? data : []
} catch {
return []
}
}
async function logout() {
mePromise = null
inFlightByKey.clear()
await fetch(`${apiBase}/logout`, { method: 'POST', credentials: 'include' })
}
async function me() {
if (mePromise) return mePromise
mePromise = request<MeResponse>('me').finally(() => {
mePromise = null
})
return mePromise
}
async function meUpdate(body: { email?: string }) {
await request('me', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
/** Public: whether first-time setup (no users) is required. */
async function setupRequired(): Promise<{ setupRequired: boolean }> {
const res = await fetch(`${apiBase}/setup`, { credentials: 'include' })
if (!res.ok) throw new Error(`API ${res.status}`)
return res.json() as Promise<{ setupRequired: boolean }>
}
// Profile
async function meTokens() {
const data = await request<{ tokens: string[] }>('me/tokens', { method: 'POST' })
return data?.tokens ?? []
}
async function mePassword(pass: string) {
await request('me/password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pass }),
})
}
// Admin
async function adminUsers() {
return request<string[]>('admin/users')
}
async function adminUserByName(name: string) {
return request<{ username: string; auths: string[] }>(`admin/users/${encodeURIComponent(name)}`)
}
async function adminUserPost(body: { user: string; pass?: string; auths: string[] }) {
await request('admin/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function adminUserDelete(name: string) {
await request(`admin/users/${encodeURIComponent(name)}`, { method: 'DELETE' })
}
async function adminSettings() {
return request<SettingsResponse>('admin/settings')
}
async function adminSettingsPost(body: { prefix?: string; defaultHide?: boolean; title?: string }) {
await request('admin/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function adminMaps() {
return request<MapInfoAdmin[]>('admin/maps')
}
async function adminMapPost(id: number, body: { name: string; hidden: boolean; priority: boolean }) {
await request(`admin/maps/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function adminMapToggleHidden(id: number) {
return request<MapInfoAdmin>(`admin/maps/${id}/toggle-hidden`, { method: 'POST' })
}
async function adminWipe() {
await request('admin/wipe', { method: 'POST' })
}
async function adminRebuildZooms() {
const res = await fetch(`${apiBase}/admin/rebuildZooms`, {
method: 'POST',
credentials: 'include',
})
if (res.status === 401 || res.status === 403) {
onApiErrorCallbacks.forEach((cb) => cb())
throw new Error('Unauthorized')
}
if (res.status !== 200 && res.status !== 202) throw new Error(`API ${res.status}`)
}
async function adminRebuildZoomsStatus(): Promise<{ running: boolean }> {
return request<{ running: boolean }>('admin/rebuildZooms/status')
}
function adminExportUrl() {
return `${apiBase}/admin/export`
}
async function adminMerge(formData: FormData) {
const res = await fetch(`${apiBase}/admin/merge`, {
method: 'POST',
credentials: 'include',
body: formData,
})
if (res.status === 401 || res.status === 403) {
onApiErrorCallbacks.forEach((cb) => cb())
throw new Error('Unauthorized')
}
if (!res.ok) throw new Error(`API ${res.status}`)
}
async function adminWipeTile(params: { map: number; x: number; y: number }) {
const qs = new URLSearchParams({ map: String(params.map), x: String(params.x), y: String(params.y) })
return request(`admin/wipeTile?${qs}`)
}
async function adminSetCoords(params: { map: number; fx: number; fy: number; tx: number; ty: number }) {
const qs = new URLSearchParams({
map: String(params.map),
fx: String(params.fx),
fy: String(params.fy),
tx: String(params.tx),
ty: String(params.ty),
})
return request(`admin/setCoords?${qs}`)
}
async function adminHideMarker(params: { id: number }) {
const qs = new URLSearchParams({ id: String(params.id) })
return request(`admin/hideMarker?${qs}`)
}
return {
apiBase,
onApiError,
getConfig,
getCharacters,
getMarkers,
getMaps,
login,
logout,
me,
meUpdate,
oauthLoginUrl,
oauthProviders,
setupRequired,
meTokens,
mePassword,
adminUsers,
adminUserByName,
adminUserPost,
adminUserDelete,
adminSettings,
adminSettingsPost,
adminMaps,
adminMapPost,
adminMapToggleHidden,
adminWipe,
adminRebuildZooms,
adminRebuildZoomsStatus,
adminExportUrl,
adminMerge,
adminWipeTile,
adminSetCoords,
adminHideMarker,
}
}

View File

@@ -1,3 +1,5 @@
import { readonly } from 'vue'
export interface MapBookmark {
id: string
name: string
@@ -29,7 +31,7 @@ function saveBookmarks(bookmarks: MapBookmark[]) {
if (import.meta.server) return
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(bookmarks.slice(0, MAX_BOOKMARKS)))
} catch (_) {}
} catch { /* ignore */ }
}
export function useMapBookmarks() {

View File

@@ -1,111 +1,111 @@
import type L from 'leaflet'
import { HnHCRS, HnHMaxZoom, HnHMinZoom, TileSize } from '~/lib/LeafletCustomTypes'
import { SmartTileLayer } from '~/lib/SmartTileLayer'
import type { MapInfo } from '~/types/api'
type SmartTileLayerInstance = InstanceType<typeof SmartTileLayer>
/** Known marker icon paths (without .png) to preload so markers render without broken images. */
const MARKER_ICON_PATHS = [
'gfx/terobjs/mm/custom',
'gfx/terobjs/mm/tower',
'gfx/terobjs/mm/village',
'gfx/terobjs/mm/dungeon',
'gfx/terobjs/mm/cave',
'gfx/terobjs/mm/settlement',
'gfx/invobjs/small/bush',
'gfx/invobjs/small/bumling',
]
/**
* Preloads marker icon images so they are in the browser cache before markers render.
* Call from client only. resolvePath should produce absolute URLs for static assets.
*/
export function preloadMarkerIcons(resolvePath: (path: string) => string): void {
if (import.meta.server) return
for (const base of MARKER_ICON_PATHS) {
const url = resolvePath(`${base}.png`)
const img = new Image()
img.src = url
}
}
export interface MapInitResult {
map: L.Map
layer: SmartTileLayerInstance
overlayLayer: SmartTileLayerInstance
markerLayer: L.LayerGroup
backendBase: string
}
export async function initLeafletMap(
element: HTMLElement,
mapsList: MapInfo[],
initialMapId: number
): Promise<MapInitResult> {
const L = (await import('leaflet')).default
const map = L.map(element, {
minZoom: HnHMinZoom,
maxZoom: HnHMaxZoom,
crs: HnHCRS,
attributionControl: false,
zoomControl: false,
inertia: true,
zoomAnimation: true,
fadeAnimation: true,
markerZoomAnimation: true,
})
const runtimeConfig = useRuntimeConfig()
const apiBase = (runtimeConfig.public.apiBase as string) ?? '/map/api'
const backendBase = apiBase.replace(/\/api\/?$/, '') || '/map'
const tileUrl = `${backendBase}/grids/{map}/{z}/{x}_{y}.png?{cache}`
const layer = new SmartTileLayer(tileUrl, {
minZoom: 1,
maxZoom: 6,
maxNativeZoom: 6,
zoomOffset: 0,
zoomReverse: true,
tileSize: TileSize,
updateWhenIdle: true,
keepBuffer: 4,
})
layer.map = initialMapId
layer.invalidTile =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='
layer.addTo(map)
const overlayLayer = new SmartTileLayer(tileUrl, {
minZoom: 1,
maxZoom: 6,
maxNativeZoom: 6,
zoomOffset: 0,
zoomReverse: true,
tileSize: TileSize,
opacity: 0.5,
updateWhenIdle: true,
keepBuffer: 4,
})
overlayLayer.map = -1
overlayLayer.invalidTile =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='
overlayLayer.addTo(map)
const markerLayer = L.layerGroup()
markerLayer.addTo(map)
markerLayer.setZIndex(600)
const baseURL = useRuntimeConfig().app.baseURL ?? '/'
const markerIconPath = baseURL.endsWith('/') ? baseURL : baseURL + '/'
L.Icon.Default.imagePath = markerIconPath
const resolvePath = (path: string) => {
const p = path.startsWith('/') ? path : `/${path}`
return baseURL === '/' ? p : `${baseURL.replace(/\/$/, '')}${p}`
}
preloadMarkerIcons(resolvePath)
return { map, layer, overlayLayer, markerLayer, backendBase }
}
import type L from 'leaflet'
import { HnHCRS, HnHMaxZoom, HnHMinZoom, TileSize } from '~/lib/LeafletCustomTypes'
import { SmartTileLayer } from '~/lib/SmartTileLayer'
import type { MapInfo } from '~/types/api'
type SmartTileLayerInstance = InstanceType<typeof SmartTileLayer>
/** Known marker icon paths (without .png) to preload so markers render without broken images. */
const MARKER_ICON_PATHS = [
'gfx/terobjs/mm/custom',
'gfx/terobjs/mm/tower',
'gfx/terobjs/mm/village',
'gfx/terobjs/mm/dungeon',
'gfx/terobjs/mm/cave',
'gfx/terobjs/mm/settlement',
'gfx/invobjs/small/bush',
'gfx/invobjs/small/bumling',
]
/**
* Preloads marker icon images so they are in the browser cache before markers render.
* Call from client only. resolvePath should produce absolute URLs for static assets.
*/
export function preloadMarkerIcons(resolvePath: (path: string) => string): void {
if (import.meta.server) return
for (const base of MARKER_ICON_PATHS) {
const url = resolvePath(`${base}.png`)
const img = new Image()
img.src = url
}
}
export interface MapInitResult {
map: L.Map
layer: SmartTileLayerInstance
overlayLayer: SmartTileLayerInstance
markerLayer: L.LayerGroup
backendBase: string
}
export async function initLeafletMap(
element: HTMLElement,
mapsList: MapInfo[],
initialMapId: number
): Promise<MapInitResult> {
const L = (await import('leaflet')).default
const map = L.map(element, {
minZoom: HnHMinZoom,
maxZoom: HnHMaxZoom,
crs: HnHCRS,
attributionControl: false,
zoomControl: false,
inertia: true,
zoomAnimation: true,
fadeAnimation: true,
markerZoomAnimation: true,
})
const runtimeConfig = useRuntimeConfig()
const apiBase = (runtimeConfig.public.apiBase as string) ?? '/map/api'
const backendBase = apiBase.replace(/\/api\/?$/, '') || '/map'
const tileUrl = `${backendBase}/grids/{map}/{z}/{x}_{y}.png?{cache}`
const layer = new SmartTileLayer(tileUrl, {
minZoom: 1,
maxZoom: 6,
maxNativeZoom: 6,
zoomOffset: 0,
zoomReverse: true,
tileSize: TileSize,
updateWhenIdle: true,
keepBuffer: 4,
})
layer.map = initialMapId
layer.invalidTile =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='
layer.addTo(map)
const overlayLayer = new SmartTileLayer(tileUrl, {
minZoom: 1,
maxZoom: 6,
maxNativeZoom: 6,
zoomOffset: 0,
zoomReverse: true,
tileSize: TileSize,
opacity: 0.5,
updateWhenIdle: true,
keepBuffer: 4,
})
overlayLayer.map = -1
overlayLayer.invalidTile =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='
overlayLayer.addTo(map)
const markerLayer = L.layerGroup()
markerLayer.addTo(map)
markerLayer.setZIndex(600)
const baseURL = useRuntimeConfig().app.baseURL ?? '/'
const markerIconPath = baseURL.endsWith('/') ? baseURL : baseURL + '/'
L.Icon.Default.imagePath = markerIconPath
const resolvePath = (path: string) => {
const p = path.startsWith('/') ? path : `/${path}`
return baseURL === '/' ? p : `${baseURL.replace(/\/$/, '')}${p}`
}
preloadMarkerIcons(resolvePath)
return { map, layer, overlayLayer, markerLayer, backendBase }
}

View File

@@ -1,5 +1,5 @@
import type L from 'leaflet'
import { HnHMaxZoom } from '~/lib/LeafletCustomTypes'
import { HnHMaxZoom, TileSize } from '~/lib/LeafletCustomTypes'
import { createMarker, type MapMarker, type MarkerData, type MapViewRef } from '~/lib/Marker'
import { createCharacter, type MapCharacter, type CharacterData, type CharacterMapViewRef } from '~/lib/Character'
import {
@@ -12,11 +12,21 @@ import {
import type { SmartTileLayer } from '~/lib/SmartTileLayer'
import type { Marker as ApiMarker, Character as ApiCharacter } from '~/types/api'
type LeafletModule = L
type SmartTileLayerInstance = InstanceType<typeof SmartTileLayer>
function escapeHtml(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
export interface MapLayersOptions {
/** Leaflet API (from dynamic import). Required for creating markers and characters without static leaflet import. */
L: typeof import('leaflet')
L: LeafletModule
map: L.Map
markerLayer: L.LayerGroup
layer: SmartTileLayerInstance
@@ -24,10 +34,12 @@ export interface MapLayersOptions {
getCurrentMapId: () => number
setCurrentMapId: (id: number) => void
setSelectedMapId: (id: number) => void
getAuths: () => string[]
getAuths?: () => string[]
getTrackingCharacterId: () => number
setTrackingCharacterId: (id: number) => void
onMarkerContextMenu: (clientX: number, clientY: number, id: number, name: string) => void
/** Called when user clicks "Add to saved locations" in marker popup. Receives marker id and getter to resolve marker. */
onAddMarkerToBookmark?: (markerId: number, getMarkerById: (id: number) => MapMarker | undefined) => void
/** Resolves relative marker icon path to absolute URL. If omitted, relative paths are used. */
resolveIconUrl?: (path: string) => string
/** Fallback icon URL when a marker image fails to load. */
@@ -58,10 +70,11 @@ export function createMapLayers(options: MapLayersOptions): MapLayersManager {
getCurrentMapId,
setCurrentMapId,
setSelectedMapId,
getAuths,
getAuths: _getAuths,
getTrackingCharacterId,
setTrackingCharacterId,
onMarkerContextMenu,
onAddMarkerToBookmark,
resolveIconUrl,
fallbackIconUrl,
} = options
@@ -112,7 +125,30 @@ export function createMapLayers(options: MapLayersOptions): MapLayersManager {
(marker: MapMarker) => {
if (marker.map === getCurrentMapId() || marker.map === overlayLayer.map) marker.add(ctx)
marker.setClickCallback(() => {
if (marker.leafletMarker) map.setView(marker.leafletMarker.getLatLng(), HnHMaxZoom)
if (marker.leafletMarker) {
if (onAddMarkerToBookmark) {
const gridX = Math.floor(marker.position.x / TileSize)
const gridY = Math.floor(marker.position.y / TileSize)
const div = document.createElement('div')
div.className = 'map-marker-popup text-sm'
div.innerHTML = `
<p class="font-medium mb-1">${escapeHtml(marker.name)}</p>
<p class="text-base-content/70 text-xs mb-2 font-mono">${gridX}, ${gridY}</p>
<button type="button" class="btn btn-primary btn-xs w-full">Add to saved locations</button>
`
const btn = div.querySelector('button')
if (btn) {
btn.addEventListener('click', () => {
onAddMarkerToBookmark(marker.id, findMarkerById)
marker.leafletMarker?.closePopup()
})
}
marker.leafletMarker.unbindPopup()
marker.leafletMarker.bindPopup(div, { minWidth: 140, autoPan: true }).openPopup()
} else {
map.setView(marker.leafletMarker.getLatLng(), HnHMaxZoom)
}
}
})
marker.setContextMenu((mev: L.LeafletMouseEvent) => {
mev.originalEvent.preventDefault()

View File

@@ -1,171 +1,206 @@
import type { Ref } from 'vue'
import type { SmartTileLayer } from '~/lib/SmartTileLayer'
import { TileSize } from '~/lib/LeafletCustomTypes'
import type L from 'leaflet'
type SmartTileLayerInstance = InstanceType<typeof SmartTileLayer>
export type SseConnectionState = 'connecting' | 'open' | 'error'
interface TileUpdate {
M: number
X: number
Y: number
Z: number
T: number
}
interface MergeEvent {
From: number
To: number
Shift: { x: number; y: number }
}
export interface UseMapUpdatesOptions {
backendBase: string
layer: SmartTileLayerInstance
overlayLayer: SmartTileLayerInstance
map: L.Map
getCurrentMapId: () => number
onMerge: (mapTo: number, shift: { x: number; y: number }) => void
/** Optional ref updated with SSE connection state for reconnection indicator. */
connectionStateRef?: Ref<SseConnectionState>
}
export interface UseMapUpdatesReturn {
cleanup: () => void
}
const RECONNECT_INITIAL_MS = 1000
const RECONNECT_MAX_MS = 30000
export function startMapUpdates(options: UseMapUpdatesOptions): UseMapUpdatesReturn {
const { backendBase, layer, overlayLayer, map, getCurrentMapId, onMerge, connectionStateRef } = options
const updatesPath = `${backendBase}/updates`
const updatesUrl = import.meta.client ? `${window.location.origin}${updatesPath}` : updatesPath
const BATCH_MS = 50
let batch: TileUpdate[] = []
let batchScheduled = false
let source: EventSource | null = null
let reconnectTimeoutId: ReturnType<typeof setTimeout> | null = null
let reconnectDelayMs = RECONNECT_INITIAL_MS
let destroyed = false
const VISIBLE_TILE_BUFFER = 1
function getVisibleTileBounds() {
const zoom = map.getZoom()
const px = map.getPixelBounds()
if (!px) return null
return {
zoom,
minX: Math.floor(px.min.x / TileSize) - VISIBLE_TILE_BUFFER,
maxX: Math.ceil(px.max.x / TileSize) + VISIBLE_TILE_BUFFER,
minY: Math.floor(px.min.y / TileSize) - VISIBLE_TILE_BUFFER,
maxY: Math.ceil(px.max.y / TileSize) + VISIBLE_TILE_BUFFER,
}
}
function applyBatch() {
batchScheduled = false
if (batch.length === 0) return
const updates = batch
batch = []
for (const u of updates) {
const key = `${u.M}:${u.X}:${u.Y}:${u.Z}`
layer.cache[key] = u.T
overlayLayer.cache[key] = u.T
}
const visible = getVisibleTileBounds()
for (const u of updates) {
if (visible && u.Z !== visible.zoom) continue
if (
visible &&
(u.X < visible.minX || u.X > visible.maxX || u.Y < visible.minY || u.Y > visible.maxY)
)
continue
if (layer.map === u.M) layer.refresh(u.X, u.Y, u.Z)
if (overlayLayer.map === u.M) overlayLayer.refresh(u.X, u.Y, u.Z)
}
}
function scheduleBatch() {
if (batchScheduled) return
batchScheduled = true
setTimeout(applyBatch, BATCH_MS)
}
function connect() {
if (destroyed || !import.meta.client) return
source = new EventSource(updatesUrl)
if (connectionStateRef) connectionStateRef.value = 'connecting'
source.onopen = () => {
if (connectionStateRef) connectionStateRef.value = 'open'
reconnectDelayMs = RECONNECT_INITIAL_MS
}
source.onerror = () => {
if (destroyed || !source) return
if (connectionStateRef) connectionStateRef.value = 'error'
source.close()
source = null
if (destroyed) return
reconnectTimeoutId = setTimeout(() => {
reconnectTimeoutId = null
connect()
reconnectDelayMs = Math.min(reconnectDelayMs * 2, RECONNECT_MAX_MS)
}, reconnectDelayMs)
}
source.onmessage = (event: MessageEvent) => {
if (connectionStateRef) connectionStateRef.value = 'open'
try {
const raw: unknown = event?.data
if (raw == null || typeof raw !== 'string' || raw.trim() === '') return
const updates: unknown = JSON.parse(raw)
if (!Array.isArray(updates)) return
for (const u of updates as TileUpdate[]) {
batch.push(u)
}
scheduleBatch()
} catch {
// Ignore parse errors from SSE
}
}
source.addEventListener('merge', (e: MessageEvent) => {
try {
const merge: MergeEvent = JSON.parse((e?.data as string) ?? '{}')
if (getCurrentMapId() === merge.From) {
const point = map.project(map.getCenter(), 6)
const shift = {
x: Math.floor(point.x / TileSize) + merge.Shift.x,
y: Math.floor(point.y / TileSize) + merge.Shift.y,
}
onMerge(merge.To, shift)
}
} catch {
// Ignore merge parse errors
}
})
}
connect()
function cleanup() {
destroyed = true
if (reconnectTimeoutId != null) {
clearTimeout(reconnectTimeoutId)
reconnectTimeoutId = null
}
if (source) {
source.close()
source = null
}
}
return { cleanup }
}
import type { Ref } from 'vue'
import type { SmartTileLayer } from '~/lib/SmartTileLayer'
import { TileSize } from '~/lib/LeafletCustomTypes'
import type L from 'leaflet'
type SmartTileLayerInstance = InstanceType<typeof SmartTileLayer>
export type SseConnectionState = 'connecting' | 'open' | 'error'
interface TileUpdate {
M: number
X: number
Y: number
Z: number
T: number
}
interface MergeEvent {
From: number
To: number
Shift: { x: number; y: number }
}
export interface UseMapUpdatesOptions {
backendBase: string
layer: SmartTileLayerInstance
overlayLayer: SmartTileLayerInstance
map: L.Map
getCurrentMapId: () => number
onMerge: (mapTo: number, shift: { x: number; y: number }) => void
/** Optional ref updated with SSE connection state for reconnection indicator. */
connectionStateRef?: Ref<SseConnectionState>
}
export interface UseMapUpdatesReturn {
cleanup: () => void
}
const RECONNECT_INITIAL_MS = 1000
const RECONNECT_MAX_MS = 30000
/** If no SSE message received for this long, treat connection as stale and reconnect. */
const STALE_CONNECTION_MS = 65000
const STALE_CHECK_INTERVAL_MS = 30000
export function startMapUpdates(options: UseMapUpdatesOptions): UseMapUpdatesReturn {
const { backendBase, layer, overlayLayer, map, getCurrentMapId, onMerge, connectionStateRef } = options
const updatesPath = `${backendBase}/updates`
const updatesUrl = import.meta.client ? `${window.location.origin}${updatesPath}` : updatesPath
const BATCH_MS = 50
let batch: TileUpdate[] = []
let batchScheduled = false
let source: EventSource | null = null
let reconnectTimeoutId: ReturnType<typeof setTimeout> | null = null
let staleCheckIntervalId: ReturnType<typeof setInterval> | null = null
let lastMessageTime = 0
let reconnectDelayMs = RECONNECT_INITIAL_MS
let destroyed = false
const VISIBLE_TILE_BUFFER = 1
function getVisibleTileBounds() {
const zoom = map.getZoom()
const px = map.getPixelBounds()
if (!px) return null
return {
zoom,
minX: Math.floor(px.min.x / TileSize) - VISIBLE_TILE_BUFFER,
maxX: Math.ceil(px.max.x / TileSize) + VISIBLE_TILE_BUFFER,
minY: Math.floor(px.min.y / TileSize) - VISIBLE_TILE_BUFFER,
maxY: Math.ceil(px.max.y / TileSize) + VISIBLE_TILE_BUFFER,
}
}
function applyBatch() {
batchScheduled = false
if (batch.length === 0) return
const updates = batch
batch = []
for (const u of updates) {
const key = `${u.M}:${u.X}:${u.Y}:${u.Z}`
layer.cache[key] = u.T
overlayLayer.cache[key] = u.T
}
const visible = getVisibleTileBounds()
// u.Z is backend storage zoom (0..5); visible.zoom is map zoom (1..6). With zoomReverse, current backend Z = maxZoom - mapZoom.
const currentBackendZ = visible ? layer.options.maxZoom - visible.zoom : null
let needRedraw = false
for (const u of updates) {
if (visible && currentBackendZ != null && u.Z !== currentBackendZ) continue
if (
visible &&
(u.X < visible.minX || u.X > visible.maxX || u.Y < visible.minY || u.Y > visible.maxY)
)
continue
if (layer.map === u.M && !layer.refresh(u.X, u.Y, u.Z)) needRedraw = true
if (overlayLayer.map === u.M && !overlayLayer.refresh(u.X, u.Y, u.Z)) needRedraw = true
}
if (needRedraw) {
layer.redraw()
overlayLayer.redraw()
}
}
function scheduleBatch() {
if (batchScheduled) return
batchScheduled = true
setTimeout(applyBatch, BATCH_MS)
}
function connect() {
if (destroyed || !import.meta.client) return
if (staleCheckIntervalId != null) {
clearInterval(staleCheckIntervalId)
staleCheckIntervalId = null
}
source = new EventSource(updatesUrl)
if (connectionStateRef) connectionStateRef.value = 'connecting'
source.onopen = () => {
if (connectionStateRef) connectionStateRef.value = 'open'
lastMessageTime = Date.now()
reconnectDelayMs = RECONNECT_INITIAL_MS
staleCheckIntervalId = setInterval(() => {
if (destroyed || !source) return
if (Date.now() - lastMessageTime > STALE_CONNECTION_MS) {
if (staleCheckIntervalId != null) {
clearInterval(staleCheckIntervalId)
staleCheckIntervalId = null
}
source.close()
source = null
if (connectionStateRef) connectionStateRef.value = 'error'
connect()
}
}, STALE_CHECK_INTERVAL_MS)
}
source.onerror = () => {
if (destroyed || !source) return
if (connectionStateRef) connectionStateRef.value = 'error'
source.close()
source = null
if (destroyed) return
reconnectTimeoutId = setTimeout(() => {
reconnectTimeoutId = null
connect()
reconnectDelayMs = Math.min(reconnectDelayMs * 2, RECONNECT_MAX_MS)
}, reconnectDelayMs)
}
source.onmessage = (event: MessageEvent) => {
lastMessageTime = Date.now()
if (connectionStateRef) connectionStateRef.value = 'open'
try {
const raw: unknown = event?.data
if (raw == null || typeof raw !== 'string' || raw.trim() === '') return
const updates: unknown = JSON.parse(raw)
if (!Array.isArray(updates)) return
for (const u of updates as TileUpdate[]) {
batch.push(u)
}
scheduleBatch()
} catch {
// Ignore parse errors from SSE
}
}
source.addEventListener('merge', (e: MessageEvent) => {
try {
const merge: MergeEvent = JSON.parse((e?.data as string) ?? '{}')
if (getCurrentMapId() === merge.From) {
const point = map.project(map.getCenter(), 6)
const shift = {
x: Math.floor(point.x / TileSize) + merge.Shift.x,
y: Math.floor(point.y / TileSize) + merge.Shift.y,
}
onMerge(merge.To, shift)
}
} catch {
// Ignore merge parse errors
}
})
}
connect()
function cleanup() {
destroyed = true
if (staleCheckIntervalId != null) {
clearInterval(staleCheckIntervalId)
staleCheckIntervalId = null
}
if (reconnectTimeoutId != null) {
clearTimeout(reconnectTimeoutId)
reconnectTimeoutId = null
}
if (source) {
source.close()
source = null
}
}
return { cleanup }
}

View File

@@ -26,7 +26,7 @@ function saveRecent(list: RecentLocation[]) {
if (import.meta.server) return
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(list.slice(0, MAX_RECENT)))
} catch (_) {}
} catch { /* ignore */ }
}
export function useRecentLocations() {

View File

@@ -1,3 +1,5 @@
import { readonly } from 'vue'
export type ToastType = 'success' | 'error' | 'info'
export interface Toast {

View File

@@ -1,11 +1,14 @@
// @ts-check
import withNuxt from './.nuxt/eslint.config.mjs'
export default withNuxt({
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
'@typescript-eslint/no-require-imports': 'off',
export default withNuxt(
{ ignores: ['eslint.config.mjs'] },
{
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
'@typescript-eslint/no-require-imports': 'off',
},
},
})
)

View File

@@ -12,7 +12,7 @@
type="checkbox"
class="drawer-toggle"
@change="onDrawerChange"
/>
>
<div class="drawer-content flex flex-col h-screen overflow-hidden">
<header class="navbar relative z-[1100] bg-base-100/80 backdrop-blur-xl border-b border-base-300/50 px-4 gap-2 shrink-0">
<NuxtLink to="/" class="flex items-center gap-2 text-lg font-semibold hover:opacity-80 transition-all duration-200">
@@ -87,7 +87,7 @@
class="toggle toggle-sm toggle-primary shrink-0"
:checked="dark"
@change="onThemeToggle"
/>
>
</label>
</li>
<li>
@@ -177,7 +177,7 @@
class="toggle toggle-sm toggle-primary shrink-0"
:checked="dark"
@change="onThemeToggle"
/>
>
</label>
</li>
<li>
@@ -296,7 +296,7 @@ async function loadConfig(loadToken: number) {
const config = await useMapApi().getConfig()
if (loadToken !== loadId) return
if (config?.title) title.value = config.title
} catch (_) {}
} catch { /* ignore */ }
}
onMounted(() => {

View File

@@ -1,130 +1,192 @@
import type L from 'leaflet'
import { getColorForCharacterId, type CharacterColors } from '~/lib/characterColors'
import { HnHMaxZoom } from '~/lib/LeafletCustomTypes'
export type LeafletApi = typeof import('leaflet')
function buildCharacterIconUrl(colors: CharacterColors): string {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 32" width="24" height="32">' +
`<path fill="${colors.fill}" stroke="${colors.stroke}" stroke-width="1" d="M12 2a6 6 0 0 1 6 6c0 4-6 10-6 10s-6-6-6-10a6 6 0 0 1 6-6z"/>` +
'<circle cx="12" cy="8" r="2.5" fill="white"/>' +
'</svg>'
return 'data:image/svg+xml,' + encodeURIComponent(svg)
}
export function createCharacterIcon(L: LeafletApi, colors: CharacterColors): L.Icon {
return new L.Icon({
iconUrl: buildCharacterIconUrl(colors),
iconSize: [24, 32],
iconAnchor: [12, 32],
popupAnchor: [0, -32],
})
}
export interface CharacterData {
name: string
position: { x: number; y: number }
type: string
id: number
map: number
/** True when this character was last updated by one of the current user's tokens. */
ownedByMe?: boolean
}
export interface CharacterMapViewRef {
map: L.Map
mapid: number
markerLayer?: L.LayerGroup
}
export interface MapCharacter {
id: number
name: string
position: { x: number; y: number }
type: string
map: number
text: string
value: number
ownedByMe?: boolean
leafletMarker: L.Marker | null
remove: (mapview: CharacterMapViewRef) => void
add: (mapview: CharacterMapViewRef) => void
update: (mapview: CharacterMapViewRef, updated: CharacterData | MapCharacter) => void
setClickCallback: (callback: (e: L.LeafletMouseEvent) => void) => void
}
export function createCharacter(data: CharacterData, L: LeafletApi): MapCharacter {
let leafletMarker: L.Marker | null = null
let onClick: ((e: L.LeafletMouseEvent) => void) | null = null
let ownedByMe = data.ownedByMe ?? false
const colors = getColorForCharacterId(data.id, { ownedByMe })
let characterIcon = createCharacterIcon(L, colors)
const character: MapCharacter = {
id: data.id,
name: data.name,
position: { ...data.position },
type: data.type,
map: data.map,
text: data.name,
value: data.id,
get ownedByMe() {
return ownedByMe
},
set ownedByMe(v: boolean | undefined) {
ownedByMe = v ?? false
},
get leafletMarker() {
return leafletMarker
},
remove(mapview: CharacterMapViewRef): void {
if (leafletMarker) {
const layer = mapview.markerLayer ?? mapview.map
layer.removeLayer(leafletMarker)
leafletMarker = null
}
},
add(mapview: CharacterMapViewRef): void {
if (character.map === mapview.mapid) {
const position = mapview.map.unproject([character.position.x, character.position.y], HnHMaxZoom)
leafletMarker = L.marker(position, { icon: characterIcon, title: character.name })
leafletMarker.on('click', (e: L.LeafletMouseEvent) => {
if (onClick) onClick(e)
})
const targetLayer = mapview.markerLayer ?? mapview.map
leafletMarker.addTo(targetLayer)
}
},
update(mapview: CharacterMapViewRef, updated: CharacterData | MapCharacter): void {
const updatedOwnedByMe = (updated as { ownedByMe?: boolean }).ownedByMe ?? false
if (ownedByMe !== updatedOwnedByMe) {
ownedByMe = updatedOwnedByMe
characterIcon = createCharacterIcon(L, getColorForCharacterId(character.id, { ownedByMe }))
if (leafletMarker) leafletMarker.setIcon(characterIcon)
}
if (character.map !== updated.map) {
character.remove(mapview)
}
character.map = updated.map
character.position = { ...updated.position }
if (!leafletMarker && character.map === mapview.mapid) {
character.add(mapview)
}
if (leafletMarker) {
const position = mapview.map.unproject([updated.position.x, updated.position.y], HnHMaxZoom)
leafletMarker.setLatLng(position)
}
},
setClickCallback(callback: (e: L.LeafletMouseEvent) => void): void {
onClick = callback
},
}
return character
}
import type L from 'leaflet'
import { getColorForCharacterId, type CharacterColors } from '~/lib/characterColors'
import { HnHMaxZoom, TileSize } from '~/lib/LeafletCustomTypes'
export type LeafletApi = L
function buildCharacterIconUrl(colors: CharacterColors): string {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 32" width="24" height="32">' +
`<path fill="${colors.fill}" stroke="${colors.stroke}" stroke-width="1" d="M12 2a6 6 0 0 1 6 6c0 4-6 10-6 10s-6-6-6-10a6 6 0 0 1 6-6z"/>` +
'<circle cx="12" cy="8" r="2.5" fill="white"/>' +
'</svg>'
return 'data:image/svg+xml,' + encodeURIComponent(svg)
}
export function createCharacterIcon(L: LeafletApi, colors: CharacterColors): L.Icon {
return new L.Icon({
iconUrl: buildCharacterIconUrl(colors),
iconSize: [25, 32],
iconAnchor: [12, 17],
popupAnchor: [0, -32],
tooltipAnchor: [12, 0],
})
}
export interface CharacterData {
name: string
position: { x: number; y: number }
type: string
id: number
map: number
/** True when this character was last updated by one of the current user's tokens. */
ownedByMe?: boolean
}
export interface CharacterMapViewRef {
map: L.Map
mapid: number
markerLayer?: L.LayerGroup
}
export interface MapCharacter {
id: number
name: string
position: { x: number; y: number }
type: string
map: number
text: string
value: number
ownedByMe?: boolean
leafletMarker: L.Marker | null
remove: (mapview: CharacterMapViewRef) => void
add: (mapview: CharacterMapViewRef) => void
update: (mapview: CharacterMapViewRef, updated: CharacterData | MapCharacter) => void
setClickCallback: (callback: (e: L.LeafletMouseEvent) => void) => void
}
const CHARACTER_MOVE_DURATION_MS = 280
function easeOutQuad(t: number): number {
return t * (2 - t)
}
export function createCharacter(data: CharacterData, L: LeafletApi): MapCharacter {
let leafletMarker: L.Marker | null = null
let onClick: ((e: L.LeafletMouseEvent) => void) | null = null
let ownedByMe = data.ownedByMe ?? false
let animationFrameId: number | null = null
const colors = getColorForCharacterId(data.id, { ownedByMe })
let characterIcon = createCharacterIcon(L, colors)
const character: MapCharacter = {
id: data.id,
name: data.name,
position: { ...data.position },
type: data.type,
map: data.map,
text: data.name,
value: data.id,
get ownedByMe() {
return ownedByMe
},
set ownedByMe(v: boolean | undefined) {
ownedByMe = v ?? false
},
get leafletMarker() {
return leafletMarker
},
remove(mapview: CharacterMapViewRef): void {
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId)
animationFrameId = null
}
if (leafletMarker) {
const layer = mapview.markerLayer ?? mapview.map
layer.removeLayer(leafletMarker)
leafletMarker = null
}
},
add(mapview: CharacterMapViewRef): void {
if (character.map === mapview.mapid) {
const position = mapview.map.unproject([character.position.x, character.position.y], HnHMaxZoom)
leafletMarker = L.marker(position, { icon: characterIcon })
const gridX = Math.floor(character.position.x / TileSize)
const gridY = Math.floor(character.position.y / TileSize)
const tooltipContent = `${character.name} · ${gridX}, ${gridY}`
leafletMarker.bindTooltip(tooltipContent, {
direction: 'top',
permanent: false,
offset: L.point(-10.5, -18),
})
leafletMarker.on('click', (e: L.LeafletMouseEvent) => {
if (onClick) onClick(e)
})
const targetLayer = mapview.markerLayer ?? mapview.map
leafletMarker.addTo(targetLayer)
const markerEl = (leafletMarker as unknown as { getElement?: () => HTMLElement }).getElement?.()
if (markerEl) markerEl.setAttribute('aria-label', character.name)
}
},
update(mapview: CharacterMapViewRef, updated: CharacterData | MapCharacter): void {
const updatedOwnedByMe = (updated as { ownedByMe?: boolean }).ownedByMe ?? false
if (ownedByMe !== updatedOwnedByMe) {
ownedByMe = updatedOwnedByMe
characterIcon = createCharacterIcon(L, getColorForCharacterId(character.id, { ownedByMe }))
if (leafletMarker) leafletMarker.setIcon(characterIcon)
}
if (character.map !== updated.map) {
character.remove(mapview)
}
character.map = updated.map
character.position = { ...updated.position }
if (!leafletMarker && character.map === mapview.mapid) {
character.add(mapview)
return
}
if (!leafletMarker) return
const newLatLng = mapview.map.unproject([updated.position.x, updated.position.y], HnHMaxZoom)
const updateTooltip = (): void => {
const gridX = Math.floor(character.position.x / TileSize)
const gridY = Math.floor(character.position.y / TileSize)
leafletMarker?.setTooltipContent(`${character.name} · ${gridX}, ${gridY}`)
}
const from = leafletMarker.getLatLng()
const latDelta = newLatLng.lat - from.lat
const lngDelta = newLatLng.lng - from.lng
const distSq = latDelta * latDelta + lngDelta * lngDelta
if (distSq < 1e-12) {
updateTooltip()
return
}
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId)
animationFrameId = null
}
const start = typeof performance !== 'undefined' ? performance.now() : Date.now()
const duration = CHARACTER_MOVE_DURATION_MS
const tick = (): void => {
const elapsed = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - start
const t = Math.min(1, elapsed / duration)
const eased = easeOutQuad(t)
leafletMarker?.setLatLng({
lat: from.lat + latDelta * eased,
lng: from.lng + lngDelta * eased,
})
if (t >= 1) {
animationFrameId = null
leafletMarker?.setLatLng(newLatLng)
updateTooltip()
return
}
animationFrameId = requestAnimationFrame(tick)
}
animationFrameId = requestAnimationFrame(tick)
},
setClickCallback(callback: (e: L.LeafletMouseEvent) => void): void {
onClick = callback
},
}
return character
}

View File

@@ -1,148 +1,165 @@
import type L from 'leaflet'
import { HnHMaxZoom, ImageIcon } from '~/lib/LeafletCustomTypes'
export interface MarkerData {
id: number
position: { x: number; y: number }
name: string
image: string
hidden: boolean
map: number
}
export interface MapViewRef {
map: L.Map
mapid: number
markerLayer: L.LayerGroup
}
export interface MapMarker {
id: number
position: { x: number; y: number }
name: string
image: string
type: string
text: string
value: number
hidden: boolean
map: number
leafletMarker: L.Marker | null
remove: (mapview: MapViewRef) => void
add: (mapview: MapViewRef) => void
update: (mapview: MapViewRef, updated: MarkerData | MapMarker) => void
jumpTo: (map: L.Map) => void
setClickCallback: (callback: (e: L.LeafletMouseEvent) => void) => void
setContextMenu: (callback: (e: L.LeafletMouseEvent) => void) => void
}
function detectType(name: string): string {
if (name === 'gfx/invobjs/small/bush' || name === 'gfx/invobjs/small/bumling') return 'quest'
if (name === 'custom') return 'custom'
return name.substring('gfx/terobjs/mm/'.length)
}
export interface MarkerIconOptions {
/** Resolves relative icon path to absolute URL (e.g. with app base path). */
resolveIconUrl: (path: string) => string
/** Optional fallback URL when the icon image fails to load. */
fallbackIconUrl?: string
}
export type LeafletApi = typeof import('leaflet')
export function createMarker(
data: MarkerData,
iconOptions: MarkerIconOptions | undefined,
L: LeafletApi
): MapMarker {
let leafletMarker: L.Marker | null = null
let onClick: ((e: L.LeafletMouseEvent) => void) | null = null
let onContext: ((e: L.LeafletMouseEvent) => void) | null = null
const marker: MapMarker = {
id: data.id,
position: { ...data.position },
name: data.name,
image: data.image,
type: detectType(data.image),
text: data.name,
value: data.id,
hidden: data.hidden,
map: data.map,
get leafletMarker() {
return leafletMarker
},
remove(_mapview: MapViewRef): void {
if (leafletMarker) {
leafletMarker.remove()
leafletMarker = null
}
},
add(mapview: MapViewRef): void {
if (!marker.hidden) {
const resolve = iconOptions?.resolveIconUrl ?? ((path: string) => path)
const fallback = iconOptions?.fallbackIconUrl
let icon: L.Icon
if (marker.image === 'gfx/terobjs/mm/custom') {
icon = new ImageIcon({
iconUrl: resolve('gfx/terobjs/mm/custom.png'),
iconSize: [21, 23],
iconAnchor: [11, 21],
popupAnchor: [1, 3],
tooltipAnchor: [1, 3],
fallbackIconUrl: fallback,
})
} else {
icon = new ImageIcon({
iconUrl: resolve(`${marker.image}.png`),
iconSize: [32, 32],
fallbackIconUrl: fallback,
})
}
const position = mapview.map.unproject([marker.position.x, marker.position.y], HnHMaxZoom)
leafletMarker = L.marker(position, { icon, title: marker.name })
leafletMarker.addTo(mapview.markerLayer)
const markerEl = (leafletMarker as unknown as { getElement?: () => HTMLElement }).getElement?.()
if (markerEl) markerEl.setAttribute('aria-label', marker.name)
leafletMarker.on('click', (e: L.LeafletMouseEvent) => {
if (onClick) onClick(e)
})
leafletMarker.on('contextmenu', (e: L.LeafletMouseEvent) => {
if (onContext) onContext(e)
})
}
},
update(mapview: MapViewRef, updated: MarkerData | MapMarker): void {
marker.position = { ...updated.position }
marker.name = updated.name
marker.hidden = updated.hidden
marker.map = updated.map
if (leafletMarker) {
const position = mapview.map.unproject([updated.position.x, updated.position.y], HnHMaxZoom)
leafletMarker.setLatLng(position)
}
},
jumpTo(map: L.Map): void {
if (leafletMarker) {
const position = map.unproject([marker.position.x, marker.position.y], HnHMaxZoom)
leafletMarker.setLatLng(position)
}
},
setClickCallback(callback: (e: L.LeafletMouseEvent) => void): void {
onClick = callback
},
setContextMenu(callback: (e: L.LeafletMouseEvent) => void): void {
onContext = callback
},
}
return marker
}
import type L from 'leaflet'
import { HnHMaxZoom, ImageIcon, TileSize } from '~/lib/LeafletCustomTypes'
export interface MarkerData {
id: number
position: { x: number; y: number }
name: string
image: string
hidden: boolean
map: number
}
export interface MapViewRef {
map: L.Map
mapid: number
markerLayer: L.LayerGroup
}
export interface MapMarker {
id: number
position: { x: number; y: number }
name: string
image: string
type: string
text: string
value: number
hidden: boolean
map: number
leafletMarker: L.Marker | null
remove: (mapview: MapViewRef) => void
add: (mapview: MapViewRef) => void
update: (mapview: MapViewRef, updated: MarkerData | MapMarker) => void
jumpTo: (map: L.Map) => void
setClickCallback: (callback: (e: L.LeafletMouseEvent) => void) => void
setContextMenu: (callback: (e: L.LeafletMouseEvent) => void) => void
}
function detectType(name: string): string {
if (name === 'gfx/invobjs/small/bush' || name === 'gfx/invobjs/small/bumling') return 'quest'
if (name === 'custom') return 'custom'
return name.substring('gfx/terobjs/mm/'.length)
}
export interface MarkerIconOptions {
/** Resolves relative icon path to absolute URL (e.g. with app base path). */
resolveIconUrl: (path: string) => string
/** Optional fallback URL when the icon image fails to load. */
fallbackIconUrl?: string
}
export type LeafletApi = L
export function createMarker(
data: MarkerData,
iconOptions: MarkerIconOptions | undefined,
L: LeafletApi
): MapMarker {
let leafletMarker: L.Marker | null = null
let onClick: ((e: L.LeafletMouseEvent) => void) | null = null
let onContext: ((e: L.LeafletMouseEvent) => void) | null = null
const marker: MapMarker = {
id: data.id,
position: { ...data.position },
name: data.name,
image: data.image,
type: detectType(data.image),
text: data.name,
value: data.id,
hidden: data.hidden,
map: data.map,
get leafletMarker() {
return leafletMarker
},
remove(_mapview: MapViewRef): void {
if (leafletMarker) {
leafletMarker.remove()
leafletMarker = null
}
},
add(mapview: MapViewRef): void {
if (!marker.hidden) {
const resolve = iconOptions?.resolveIconUrl ?? ((path: string) => path)
const fallback = iconOptions?.fallbackIconUrl
const iconUrl =
marker.name === 'Cave' && marker.image === 'gfx/terobjs/mm/custom'
? resolve('gfx/terobjs/mm/cave.png')
: marker.image === 'gfx/terobjs/mm/custom'
? resolve('gfx/terobjs/mm/custom.png')
: resolve(`${marker.image}.png`)
let icon: L.Icon
if (marker.image === 'gfx/terobjs/mm/custom' && marker.name !== 'Cave') {
icon = new ImageIcon({
iconUrl,
iconSize: [21, 23],
iconAnchor: [11, 21],
popupAnchor: [1, 3],
tooltipAnchor: [1, 3],
fallbackIconUrl: fallback,
})
} else {
icon = new ImageIcon({
iconUrl,
iconSize: [32, 32],
fallbackIconUrl: fallback,
})
}
const position = mapview.map.unproject([marker.position.x, marker.position.y], HnHMaxZoom)
leafletMarker = L.marker(position, { icon })
const gridX = Math.floor(marker.position.x / TileSize)
const gridY = Math.floor(marker.position.y / TileSize)
const tooltipContent = `${marker.name} · ${gridX}, ${gridY}`
leafletMarker.bindTooltip(tooltipContent, {
direction: 'top',
permanent: false,
offset: L.point(0, -14),
})
leafletMarker.addTo(mapview.markerLayer)
const markerEl = (leafletMarker as unknown as { getElement?: () => HTMLElement }).getElement?.()
if (markerEl) markerEl.setAttribute('aria-label', marker.name)
leafletMarker.on('click', (e: L.LeafletMouseEvent) => {
if (onClick) onClick(e)
})
leafletMarker.on('contextmenu', (e: L.LeafletMouseEvent) => {
if (onContext) onContext(e)
})
}
},
update(mapview: MapViewRef, updated: MarkerData | MapMarker): void {
marker.position = { ...updated.position }
marker.name = updated.name
marker.hidden = updated.hidden
marker.map = updated.map
if (leafletMarker) {
const position = mapview.map.unproject([updated.position.x, updated.position.y], HnHMaxZoom)
leafletMarker.setLatLng(position)
const gridX = Math.floor(updated.position.x / TileSize)
const gridY = Math.floor(updated.position.y / TileSize)
leafletMarker.setTooltipContent(`${marker.name} · ${gridX}, ${gridY}`)
}
},
jumpTo(map: L.Map): void {
if (leafletMarker) {
const position = map.unproject([marker.position.x, marker.position.y], HnHMaxZoom)
leafletMarker.setLatLng(position)
}
},
setClickCallback(callback: (e: L.LeafletMouseEvent) => void): void {
onClick = callback
},
setContextMenu(callback: (e: L.LeafletMouseEvent) => void): void {
onContext = callback
},
}
return marker
}

View File

@@ -58,7 +58,7 @@ export const SmartTileLayer = L.TileLayer.extend({
return Util.template(this._url, Util.extend(data, this.options))
},
refresh(x: number, y: number, z: number) {
refresh(x: number, y: number, z: number): boolean {
let zoom = z
const maxZoom = this.options.maxZoom
const zoomReverse = this.options.zoomReverse
@@ -71,19 +71,20 @@ export const SmartTileLayer = L.TileLayer.extend({
const key = `${x}:${y}:${zoom}`
const tile = this._tiles[key]
if (!tile?.el) return
if (!tile?.el) return false
const newUrl = this.getTrueTileUrl({ x, y }, z)
if (tile.el.dataset.tileUrl === newUrl) return
if (tile.el.dataset.tileUrl === newUrl) return true
tile.el.dataset.tileUrl = newUrl
tile.el.src = newUrl
tile.el.classList.add('tile-fresh')
const el = tile.el
setTimeout(() => el.classList.remove('tile-fresh'), 400)
return true
},
}) as unknown as new (urlTemplate: string, options?: L.TileLayerOptions) => L.TileLayer & {
cache: SmartTileLayerCache
invalidTile: string
map: number
getTrueTileUrl: (coords: { x: number; y: number }, zoom: number) => string
refresh: (x: number, y: number, z: number) => void
refresh: (x: number, y: number, z: number) => boolean
}

View File

@@ -39,7 +39,10 @@ export function uniqueListUpdate<T extends Identifiable>(
if (addCallback) {
elementsToAdd.forEach((it) => addCallback(it))
}
elementsToRemove.forEach((it) => delete list.elements[String(it.id)])
const toRemove = new Set(elementsToRemove.map((it) => String(it.id)))
list.elements = Object.fromEntries(
Object.entries(list.elements).filter(([id]) => !toRemove.has(id))
) as Record<string, T>
elementsToAdd.forEach((it) => (list.elements[String(it.id)] = it))
}

View File

@@ -1,127 +1,187 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('leaflet', () => {
const markerMock = {
on: vi.fn().mockReturnThis(),
addTo: vi.fn().mockReturnThis(),
setLatLng: vi.fn().mockReturnThis(),
setIcon: vi.fn().mockReturnThis(),
}
return {
default: {
marker: vi.fn(() => markerMock),
Icon: vi.fn().mockImplementation(() => ({})),
},
marker: vi.fn(() => markerMock),
Icon: vi.fn().mockImplementation(() => ({})),
}
})
vi.mock('~/lib/LeafletCustomTypes', () => ({
HnHMaxZoom: 6,
}))
import type L from 'leaflet'
import { createCharacter, type CharacterData, type CharacterMapViewRef } from '../Character'
function getL(): L {
return require('leaflet').default
}
function makeCharData(overrides: Partial<CharacterData> = {}): CharacterData {
return {
name: 'Hero',
position: { x: 100, y: 200 },
type: 'player',
id: 1,
map: 1,
...overrides,
}
}
function makeMapViewRef(mapid = 1): CharacterMapViewRef {
return {
map: {
unproject: vi.fn(() => ({ lat: 0, lng: 0 })),
removeLayer: vi.fn(),
} as unknown as import('leaflet').Map,
mapid,
markerLayer: {
removeLayer: vi.fn(),
addLayer: vi.fn(),
} as unknown as import('leaflet').LayerGroup,
}
}
describe('createCharacter', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('creates character with correct properties', () => {
const char = createCharacter(makeCharData(), getL())
expect(char.id).toBe(1)
expect(char.name).toBe('Hero')
expect(char.position).toEqual({ x: 100, y: 200 })
expect(char.type).toBe('player')
expect(char.map).toBe(1)
expect(char.text).toBe('Hero')
expect(char.value).toBe(1)
})
it('starts with null leaflet marker', () => {
const char = createCharacter(makeCharData(), getL())
expect(char.leafletMarker).toBeNull()
})
it('add creates marker when character is on correct map', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
expect(mapview.map.unproject).toHaveBeenCalled()
})
it('add does not create marker for different map', () => {
const char = createCharacter(makeCharData({ map: 2 }), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
expect(mapview.map.unproject).not.toHaveBeenCalled()
})
it('update changes position and map', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.update(mapview, {
...makeCharData(),
position: { x: 300, y: 400 },
map: 2,
})
expect(char.position).toEqual({ x: 300, y: 400 })
expect(char.map).toBe(2)
})
it('remove on a character without leaflet marker does nothing', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.remove(mapview) // should not throw
expect(char.leafletMarker).toBeNull()
})
it('setClickCallback works', () => {
const char = createCharacter(makeCharData(), getL())
const cb = vi.fn()
char.setClickCallback(cb)
})
it('update with changed ownedByMe updates marker icon', () => {
const char = createCharacter(makeCharData({ ownedByMe: false }), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
const marker = char.leafletMarker as { setIcon: ReturnType<typeof vi.fn> }
expect(marker.setIcon).not.toHaveBeenCalled()
char.update(mapview, makeCharData({ ownedByMe: true }))
expect(marker.setIcon).toHaveBeenCalledTimes(1)
})
})
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type L from 'leaflet'
import type { Map, LayerGroup } from 'leaflet'
import { createCharacter, type CharacterData, type CharacterMapViewRef } from '../Character'
const { leafletMock } = vi.hoisted(() => {
const markerMock = {
on: vi.fn().mockReturnThis(),
addTo: vi.fn().mockReturnThis(),
setLatLng: vi.fn().mockReturnThis(),
setIcon: vi.fn().mockReturnThis(),
bindTooltip: vi.fn().mockReturnThis(),
setTooltipContent: vi.fn().mockReturnThis(),
getLatLng: vi.fn().mockReturnValue({ lat: 0, lng: 0 }),
}
const Icon = vi.fn().mockImplementation(function (this: unknown) {
return {}
})
const L = {
marker: vi.fn(() => markerMock),
Icon,
point: vi.fn((x: number, y: number) => ({ x, y })),
}
return { leafletMock: L }
})
vi.mock('leaflet', () => ({
__esModule: true,
default: leafletMock,
marker: leafletMock.marker,
Icon: leafletMock.Icon,
}))
vi.mock('~/lib/LeafletCustomTypes', () => ({
HnHMaxZoom: 6,
TileSize: 100,
}))
function getL(): L {
return leafletMock as unknown as L
}
function makeCharData(overrides: Partial<CharacterData> = {}): CharacterData {
return {
name: 'Hero',
position: { x: 100, y: 200 },
type: 'player',
id: 1,
map: 1,
...overrides,
}
}
function makeMapViewRef(mapid = 1): CharacterMapViewRef {
return {
map: {
unproject: vi.fn(() => ({ lat: 0, lng: 0 })),
removeLayer: vi.fn(),
} as unknown as Map,
mapid,
markerLayer: {
removeLayer: vi.fn(),
addLayer: vi.fn(),
} as unknown as LayerGroup,
}
}
describe('createCharacter', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('creates character with correct properties', () => {
const char = createCharacter(makeCharData(), getL())
expect(char.id).toBe(1)
expect(char.name).toBe('Hero')
expect(char.position).toEqual({ x: 100, y: 200 })
expect(char.type).toBe('player')
expect(char.map).toBe(1)
expect(char.text).toBe('Hero')
expect(char.value).toBe(1)
})
it('starts with null leaflet marker', () => {
const char = createCharacter(makeCharData(), getL())
expect(char.leafletMarker).toBeNull()
})
it('add creates marker when character is on correct map', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
expect(mapview.map.unproject).toHaveBeenCalled()
})
it('add creates marker without title and binds Leaflet tooltip', () => {
const char = createCharacter(makeCharData({ position: { x: 100, y: 200 } }), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
expect(leafletMock.marker).toHaveBeenCalledWith(
expect.anything(),
expect.not.objectContaining({ title: expect.anything() })
)
const marker = char.leafletMarker as { bindTooltip: ReturnType<typeof vi.fn> }
expect(marker.bindTooltip).toHaveBeenCalledWith(
'Hero · 1, 2',
expect.objectContaining({ direction: 'top', permanent: false })
)
})
it('add does not create marker for different map', () => {
const char = createCharacter(makeCharData({ map: 2 }), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
expect(mapview.map.unproject).not.toHaveBeenCalled()
})
it('update changes position and map', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.update(mapview, {
...makeCharData(),
position: { x: 300, y: 400 },
map: 2,
})
expect(char.position).toEqual({ x: 300, y: 400 })
expect(char.map).toBe(2)
})
it('remove on a character without leaflet marker does nothing', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.remove(mapview) // should not throw
expect(char.leafletMarker).toBeNull()
})
it('setClickCallback works', () => {
const char = createCharacter(makeCharData(), getL())
const cb = vi.fn()
char.setClickCallback(cb)
})
it('update with changed ownedByMe updates marker icon', () => {
const char = createCharacter(makeCharData({ ownedByMe: false }), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
const marker = char.leafletMarker as { setIcon: ReturnType<typeof vi.fn> }
expect(marker.setIcon).not.toHaveBeenCalled()
char.update(mapview, makeCharData({ ownedByMe: true }))
expect(marker.setIcon).toHaveBeenCalledTimes(1)
})
it('update with position change updates tooltip content when marker exists', () => {
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
char.add(mapview)
const marker = char.leafletMarker as { setTooltipContent: ReturnType<typeof vi.fn> }
marker.setTooltipContent.mockClear()
char.update(mapview, makeCharData({ position: { x: 350, y: 450 } }))
expect(marker.setTooltipContent).toHaveBeenCalledWith('Hero · 3, 4')
})
it('remove cancels active position animation', () => {
const cancelSpy = vi.spyOn(global, 'cancelAnimationFrame').mockImplementation(() => {})
let rafCallback: (() => void) | null = null
vi.spyOn(global, 'requestAnimationFrame').mockImplementation((cb: (() => void) | (FrameRequestCallback)) => {
rafCallback = typeof cb === 'function' ? cb : () => {}
return 1
})
const char = createCharacter(makeCharData(), getL())
const mapview = makeMapViewRef(1)
mapview.map.unproject = vi.fn(() => ({ lat: 1, lng: 1 }))
char.add(mapview)
const marker = char.leafletMarker as { getLatLng: ReturnType<typeof vi.fn> }
marker.getLatLng.mockReturnValue({ lat: 0, lng: 0 })
char.update(mapview, makeCharData({ position: { x: 200, y: 200 } }))
expect(rafCallback).not.toBeNull()
cancelSpy.mockClear()
char.remove(mapview)
expect(cancelSpy).toHaveBeenCalledWith(1)
cancelSpy.mockRestore()
vi.restoreAllMocks()
})
})

View File

@@ -1,31 +1,35 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import L from 'leaflet'
import type { Map, LayerGroup } from 'leaflet'
import { createMarker, type MarkerData, type MapViewRef } from '../Marker'
vi.mock('leaflet', () => {
const markerMock = {
on: vi.fn().mockReturnThis(),
addTo: vi.fn().mockReturnThis(),
setLatLng: vi.fn().mockReturnThis(),
remove: vi.fn().mockReturnThis(),
bindTooltip: vi.fn().mockReturnThis(),
setTooltipContent: vi.fn().mockReturnThis(),
openPopup: vi.fn().mockReturnThis(),
closePopup: vi.fn().mockReturnThis(),
}
return {
default: {
marker: vi.fn(() => markerMock),
Icon: class {},
},
const point = (x: number, y: number) => ({ x, y })
const L = {
marker: vi.fn(() => markerMock),
Icon: class {},
Icon: vi.fn(),
point,
}
return { __esModule: true, default: L, ...L }
})
vi.mock('~/lib/LeafletCustomTypes', () => ({
HnHMaxZoom: 6,
ImageIcon: class {
constructor(_opts: Record<string, unknown>) {}
},
TileSize: 100,
ImageIcon: vi.fn(),
}))
import { createMarker, type MarkerData, type MapViewRef } from '../Marker'
function makeMarkerData(overrides: Partial<MarkerData> = {}): MarkerData {
return {
id: 1,
@@ -42,12 +46,12 @@ function makeMapViewRef(): MapViewRef {
return {
map: {
unproject: vi.fn(() => ({ lat: 0, lng: 0 })),
} as unknown as import('leaflet').Map,
} as unknown as Map,
mapid: 1,
markerLayer: {
removeLayer: vi.fn(),
addLayer: vi.fn(),
} as unknown as import('leaflet').LayerGroup,
} as unknown as LayerGroup,
}
}
@@ -57,7 +61,7 @@ describe('createMarker', () => {
})
it('creates a marker with correct properties', () => {
const marker = createMarker(makeMarkerData())
const marker = createMarker(makeMarkerData(), undefined, L)
expect(marker.id).toBe(1)
expect(marker.name).toBe('Tower')
expect(marker.position).toEqual({ x: 100, y: 200 })
@@ -69,46 +73,46 @@ describe('createMarker', () => {
})
it('detects quest type', () => {
const marker = createMarker(makeMarkerData({ image: 'gfx/invobjs/small/bush' }))
const marker = createMarker(makeMarkerData({ image: 'gfx/invobjs/small/bush' }), undefined, L)
expect(marker.type).toBe('quest')
})
it('detects quest type for bumling', () => {
const marker = createMarker(makeMarkerData({ image: 'gfx/invobjs/small/bumling' }))
const marker = createMarker(makeMarkerData({ image: 'gfx/invobjs/small/bumling' }), undefined, L)
expect(marker.type).toBe('quest')
})
it('detects custom type', () => {
const marker = createMarker(makeMarkerData({ image: 'custom' }))
const marker = createMarker(makeMarkerData({ image: 'custom' }), undefined, L)
expect(marker.type).toBe('custom')
})
it('extracts type from gfx path', () => {
const marker = createMarker(makeMarkerData({ image: 'gfx/terobjs/mm/village' }))
const marker = createMarker(makeMarkerData({ image: 'gfx/terobjs/mm/village' }), undefined, L)
expect(marker.type).toBe('village')
})
it('starts with null leaflet marker', () => {
const marker = createMarker(makeMarkerData())
const marker = createMarker(makeMarkerData(), undefined, L)
expect(marker.leafletMarker).toBeNull()
})
it('add creates a leaflet marker for non-hidden markers', () => {
const marker = createMarker(makeMarkerData())
const marker = createMarker(makeMarkerData(), undefined, L)
const mapview = makeMapViewRef()
marker.add(mapview)
expect(mapview.map.unproject).toHaveBeenCalled()
})
it('add does nothing for hidden markers', () => {
const marker = createMarker(makeMarkerData({ hidden: true }))
const marker = createMarker(makeMarkerData({ hidden: true }), undefined, L)
const mapview = makeMapViewRef()
marker.add(mapview)
expect(mapview.map.unproject).not.toHaveBeenCalled()
})
it('update changes position and name', () => {
const marker = createMarker(makeMarkerData())
const marker = createMarker(makeMarkerData(), undefined, L)
const mapview = makeMapViewRef()
marker.update(mapview, {
@@ -122,7 +126,7 @@ describe('createMarker', () => {
})
it('setClickCallback and setContextMenu work', () => {
const marker = createMarker(makeMarkerData())
const marker = createMarker(makeMarkerData(), undefined, L)
const clickCb = vi.fn()
const contextCb = vi.fn()
@@ -131,7 +135,7 @@ describe('createMarker', () => {
})
it('remove on a marker without leaflet marker does nothing', () => {
const marker = createMarker(makeMarkerData())
const marker = createMarker(makeMarkerData(), undefined, L)
const mapview = makeMapViewRef()
marker.remove(mapview) // should not throw
expect(marker.leafletMarker).toBeNull()

View File

@@ -58,7 +58,7 @@
placeholder="Search users…"
class="input input-sm input-bordered w-full min-h-11 touch-manipulation"
aria-label="Search users"
/>
>
</div>
<div class="flex flex-col gap-2 max-h-[60vh] overflow-y-auto">
<div
@@ -101,7 +101,7 @@
placeholder="Search maps…"
class="input input-sm input-bordered w-full min-h-11 touch-manipulation"
aria-label="Search maps"
/>
>
</div>
<div class="overflow-x-auto max-h-[60vh] overflow-y-auto">
<table class="table table-sm table-zebra min-w-[32rem]">
@@ -121,7 +121,7 @@
</th>
<th scope="col">Hidden</th>
<th scope="col">Priority</th>
<th scope="col" class="text-right"></th>
<th scope="col" class="text-right"/>
</tr>
</thead>
<tbody>
@@ -159,7 +159,7 @@
v-model="settings.prefix"
type="text"
class="input input-sm w-full min-h-11 touch-manipulation"
/>
>
</fieldset>
<fieldset class="fieldset w-full max-w-xs">
<label class="label" for="admin-settings-title">Title</label>
@@ -168,7 +168,7 @@
v-model="settings.title"
type="text"
class="input input-sm w-full min-h-11 touch-manipulation"
/>
>
</fieldset>
<fieldset class="fieldset">
<label class="label gap-2 cursor-pointer justify-start min-h-11 touch-manipulation" for="admin-settings-default-hide">
@@ -177,7 +177,7 @@
v-model="settings.defaultHide"
type="checkbox"
class="checkbox checkbox-sm"
/>
>
Default hide new maps
</label>
</fieldset>
@@ -211,7 +211,7 @@
</div>
<div class="flex flex-col gap-2">
<div class="flex flex-wrap items-center gap-2">
<input ref="mergeFileRef" type="file" accept=".zip" class="hidden" @change="onMergeFile" />
<input ref="mergeFileRef" type="file" accept=".zip" class="hidden" @change="onMergeFile" >
<button type="button" class="btn btn-sm min-h-11 touch-manipulation" @click="mergeFileRef?.click()">
Choose merge file
</button>

View File

@@ -1,90 +1,90 @@
<template>
<div class="container mx-auto p-4 max-w-2xl min-w-0">
<h1 class="text-2xl font-bold mb-6">Edit map {{ id }}</h1>
<form v-if="map" @submit.prevent="submit" class="flex flex-col gap-4">
<fieldset class="fieldset">
<label class="label" for="name">Name</label>
<input id="name" v-model="form.name" type="text" class="input min-h-11 touch-manipulation" required />
</fieldset>
<fieldset class="fieldset">
<label class="label cursor-pointer gap-2">
<input v-model="form.hidden" type="checkbox" class="checkbox" />
<span>Hidden</span>
</label>
</fieldset>
<fieldset class="fieldset">
<label class="label cursor-pointer gap-2">
<input v-model="form.priority" type="checkbox" class="checkbox" />
<span>Priority</span>
</label>
</fieldset>
<p v-if="error" class="text-error text-sm">{{ error }}</p>
<div class="flex gap-2">
<button type="submit" class="btn btn-primary min-h-11 touch-manipulation" :disabled="loading">
<span v-if="loading" class="loading loading-spinner loading-sm" />
<span v-else>Save</span>
</button>
<NuxtLink to="/admin" class="btn btn-ghost min-h-11 touch-manipulation">Back</NuxtLink>
</div>
</form>
<template v-else-if="mapsLoaded">
<p class="text-base-content/70">Map not found.</p>
<NuxtLink to="/admin" class="btn btn-ghost mt-2 min-h-11 touch-manipulation">Back to Admin</NuxtLink>
</template>
<p v-else class="text-base-content/70">Loading</p>
</div>
</template>
<script setup lang="ts">
import type { MapInfoAdmin } from '~/types/api'
definePageMeta({ middleware: 'admin' })
useHead({ title: 'Edit map HnH Map' })
const route = useRoute()
const router = useRouter()
const api = useMapApi()
const id = computed(() => parseInt(route.params.id as string, 10))
const map = ref<MapInfoAdmin | null>(null)
const mapsLoaded = ref(false)
const form = ref({ name: '', hidden: false, priority: false })
const loading = ref(false)
const error = ref('')
const adminMapName = useState<string | null>('admin-breadcrumb-map-name', () => null)
onMounted(async () => {
adminMapName.value = null
try {
const maps = await api.adminMaps()
mapsLoaded.value = true
const found = maps.find((m) => m.ID === id.value)
if (found) {
map.value = found
form.value = { name: found.Name, hidden: found.Hidden, priority: found.Priority }
adminMapName.value = found.Name
}
} catch {
mapsLoaded.value = true
error.value = 'Failed to load map'
}
})
onUnmounted(() => {
adminMapName.value = null
})
async function submit() {
if (!map.value) return
error.value = ''
loading.value = true
try {
await api.adminMapPost(map.value.ID, form.value)
await router.push('/admin')
} catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed'
} finally {
loading.value = false
}
}
</script>
<template>
<div class="container mx-auto p-4 max-w-2xl min-w-0">
<h1 class="text-2xl font-bold mb-6">Edit map {{ id }}</h1>
<form v-if="map" class="flex flex-col gap-4" @submit.prevent="submit">
<fieldset class="fieldset">
<label class="label" for="name">Name</label>
<input id="name" v-model="form.name" type="text" class="input min-h-11 touch-manipulation" required >
</fieldset>
<fieldset class="fieldset">
<label class="label cursor-pointer gap-2">
<input v-model="form.hidden" type="checkbox" class="checkbox" >
<span>Hidden</span>
</label>
</fieldset>
<fieldset class="fieldset">
<label class="label cursor-pointer gap-2">
<input v-model="form.priority" type="checkbox" class="checkbox" >
<span>Priority</span>
</label>
</fieldset>
<p v-if="error" class="text-error text-sm">{{ error }}</p>
<div class="flex gap-2">
<button type="submit" class="btn btn-primary min-h-11 touch-manipulation" :disabled="loading">
<span v-if="loading" class="loading loading-spinner loading-sm" />
<span v-else>Save</span>
</button>
<NuxtLink to="/admin" class="btn btn-ghost min-h-11 touch-manipulation">Back</NuxtLink>
</div>
</form>
<template v-else-if="mapsLoaded">
<p class="text-base-content/70">Map not found.</p>
<NuxtLink to="/admin" class="btn btn-ghost mt-2 min-h-11 touch-manipulation">Back to Admin</NuxtLink>
</template>
<p v-else class="text-base-content/70">Loading</p>
</div>
</template>
<script setup lang="ts">
import type { MapInfoAdmin } from '~/types/api'
definePageMeta({ middleware: 'admin' })
useHead({ title: 'Edit map HnH Map' })
const route = useRoute()
const router = useRouter()
const api = useMapApi()
const id = computed(() => parseInt(route.params.id as string, 10))
const map = ref<MapInfoAdmin | null>(null)
const mapsLoaded = ref(false)
const form = ref({ name: '', hidden: false, priority: false })
const loading = ref(false)
const error = ref('')
const adminMapName = useState<string | null>('admin-breadcrumb-map-name', () => null)
onMounted(async () => {
adminMapName.value = null
try {
const maps = await api.adminMaps()
mapsLoaded.value = true
const found = maps.find((m) => m.ID === id.value)
if (found) {
map.value = found
form.value = { name: found.Name, hidden: found.Hidden, priority: found.Priority }
adminMapName.value = found.Name
}
} catch {
mapsLoaded.value = true
error.value = 'Failed to load map'
}
})
onUnmounted(() => {
adminMapName.value = null
})
async function submit() {
if (!map.value) return
error.value = ''
loading.value = true
try {
await api.adminMapPost(map.value.ID, form.value)
await router.push('/admin')
} catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed'
} finally {
loading.value = false
}
}
</script>

View File

@@ -2,7 +2,7 @@
<div class="container mx-auto p-4 max-w-2xl min-w-0">
<h1 class="text-2xl font-bold mb-6">{{ isNew ? 'New user' : `Edit ${username}` }}</h1>
<form @submit.prevent="submit" class="flex flex-col gap-4">
<form class="flex flex-col gap-4" @submit.prevent="submit">
<fieldset class="fieldset">
<label class="label" for="user">Username</label>
<input
@@ -12,7 +12,7 @@
class="input min-h-11 touch-manipulation"
required
:readonly="!isNew"
/>
>
</fieldset>
<p id="admin-user-password-hint" class="text-sm text-base-content/60 mb-1">Leave blank to keep current password.</p>
<PasswordInput
@@ -25,7 +25,7 @@
<label class="label">Auths</label>
<div class="flex flex-wrap gap-2">
<label v-for="a of authOptions" :key="a" class="label cursor-pointer gap-2" :for="`auth-${a}`">
<input :id="`auth-${a}`" v-model="form.auths" type="checkbox" :value="a" class="checkbox checkbox-sm" />
<input :id="`auth-${a}`" v-model="form.auths" type="checkbox" :value="a" class="checkbox checkbox-sm" >
<span>{{ a }}</span>
</label>
</div>

View File

@@ -14,18 +14,18 @@
</a>
<div class="divider text-sm">or</div>
</div>
<form @submit.prevent="submit" class="flex flex-col gap-4">
<form class="flex flex-col gap-4" @submit.prevent="submit">
<fieldset class="fieldset">
<label class="label" for="user">User</label>
<input
ref="userInputRef"
id="user"
ref="userInputRef"
v-model="user"
type="text"
class="input min-h-11 touch-manipulation"
required
autocomplete="username"
/>
>
</fieldset>
<PasswordInput
v-model="pass"

View File

@@ -115,7 +115,7 @@
<icons-icon-settings />
Change password
</h2>
<form @submit.prevent="changePass" class="flex flex-col gap-2">
<form class="flex flex-col gap-2" @submit.prevent="changePass">
<PasswordInput
v-model="newPass"
placeholder="New password"

View File

@@ -6,7 +6,7 @@
This is the first run. Create the administrator account using the bootstrap password
from the server configuration (e.g. <code class="text-xs">HNHMAP_BOOTSTRAP_PASSWORD</code>).
</p>
<form @submit.prevent="submit" class="flex flex-col gap-4">
<form class="flex flex-col gap-4" @submit.prevent="submit">
<PasswordInput
v-model="pass"
label="Bootstrap password"

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@@ -1,11 +1,14 @@
import { defineConfig } from 'vitest/config'
import Vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [Vue()],
test: {
environment: 'happy-dom',
include: ['**/__tests__/**/*.test.ts', '**/*.test.ts'],
globals: true,
setupFiles: ['./vitest.setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html'],

View File

@@ -0,0 +1,27 @@
/**
* Expose Vue reactivity and lifecycle on globalThis so that .vue components
* that rely on Nuxt auto-imports (ref, computed, etc.) work in Vitest.
*/
import {
ref,
computed,
reactive,
watch,
watchEffect,
onMounted,
onUnmounted,
nextTick,
readonly,
} from 'vue'
Object.assign(globalThis, {
ref,
computed,
reactive,
watch,
watchEffect,
onMounted,
onUnmounted,
nextTick,
readonly,
})

View File

@@ -26,9 +26,10 @@ const (
MultipartMaxMemory = 100 << 20 // 100 MB
MergeMaxMemory = 500 << 20 // 500 MB
ClientVersion = "4"
SSETickInterval = 5 * time.Second
SSETileChannelSize = 1000
SSEMergeChannelSize = 5
SSETickInterval = 1 * time.Second
SSEKeepaliveInterval = 30 * time.Second
SSETileChannelSize = 2000
SSEMergeChannelSize = 5
)
// App is the main application (map server) state.

View File

@@ -93,16 +93,41 @@ func TestTopicClose(t *testing.T) {
}
}
func TestTopicDropsSlowSubscriber(t *testing.T) {
func TestTopicSkipsFullChannel(t *testing.T) {
topic := &app.Topic[int]{}
slow := make(chan *int) // unbuffered, will block
slow := make(chan *int) // unbuffered, so Send will skip this subscriber
fast := make(chan *int, 10)
topic.Watch(slow)
topic.Watch(fast)
val := 42
topic.Send(&val) // should drop the slow subscriber
topic.Send(&val) // slow is full (unbuffered), message dropped for slow only; fast receives
topic.Send(&val)
// Fast subscriber got both messages
for i := 0; i < 2; i++ {
select {
case got := <-fast:
if *got != 42 {
t.Fatalf("fast got %d", *got)
}
default:
t.Fatalf("expected fast to have message %d", i+1)
}
}
// Slow subscriber was skipped (channel full), not closed - channel still open and empty
select {
case _, ok := <-slow:
if !ok {
t.Fatal("slow channel should not be closed when subscriber is skipped")
}
t.Fatal("slow should have received no message")
default:
// slow is open and empty, which is correct
}
topic.Close()
_, ok := <-slow
if ok {
t.Fatal("expected slow subscriber channel to be closed")
t.Fatal("expected slow channel closed after topic.Close()")
}
}

View File

@@ -1,450 +1,450 @@
package handlers
import (
"archive/zip"
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/andyleap/hnh-map/internal/app"
)
type mapInfoJSON struct {
ID int `json:"ID"`
Name string `json:"Name"`
Hidden bool `json:"Hidden"`
Priority bool `json:"Priority"`
}
// APIAdminUsers handles GET/POST /map/api/admin/users.
func (h *Handlers) APIAdminUsers(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if req.Method == http.MethodGet {
if h.requireAdmin(rw, req) == nil {
return
}
list, err := h.Admin.ListUsers(ctx)
if err != nil {
HandleServiceError(rw, err)
return
}
JSON(rw, http.StatusOK, list)
return
}
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
s := h.requireAdmin(rw, req)
if s == nil {
return
}
var body struct {
User string `json:"user"`
Pass string `json:"pass"`
Auths []string `json:"auths"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil || body.User == "" {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
adminCreated, err := h.Admin.CreateOrUpdateUser(ctx, body.User, body.Pass, body.Auths)
if err != nil {
HandleServiceError(rw, err)
return
}
if body.User == s.Username {
s.Auths = body.Auths
}
if adminCreated && s.Username == "admin" {
h.Auth.DeleteSession(ctx, s)
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminUserByName handles GET /map/api/admin/users/:name.
func (h *Handlers) APIAdminUserByName(rw http.ResponseWriter, req *http.Request, name string) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
auths, found, err := h.Admin.GetUser(req.Context(), name)
if err != nil {
HandleServiceError(rw, err)
return
}
out := struct {
Username string `json:"username"`
Auths []string `json:"auths"`
}{Username: name}
if found {
out.Auths = auths
}
JSON(rw, http.StatusOK, out)
}
// APIAdminUserDelete handles DELETE /map/api/admin/users/:name.
func (h *Handlers) APIAdminUserDelete(rw http.ResponseWriter, req *http.Request, name string) {
if !h.requireMethod(rw, req, http.MethodDelete) {
return
}
s := h.requireAdmin(rw, req)
if s == nil {
return
}
ctx := req.Context()
if err := h.Admin.DeleteUser(ctx, name); err != nil {
HandleServiceError(rw, err)
return
}
if name == s.Username {
h.Auth.DeleteSession(ctx, s)
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminSettingsGet handles GET /map/api/admin/settings.
func (h *Handlers) APIAdminSettingsGet(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
prefix, defaultHide, title, err := h.Admin.GetSettings(req.Context())
if err != nil {
HandleServiceError(rw, err)
return
}
JSON(rw, http.StatusOK, struct {
Prefix string `json:"prefix"`
DefaultHide bool `json:"defaultHide"`
Title string `json:"title"`
}{Prefix: prefix, DefaultHide: defaultHide, Title: title})
}
// APIAdminSettingsPost handles POST /map/api/admin/settings.
func (h *Handlers) APIAdminSettingsPost(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
var body struct {
Prefix *string `json:"prefix"`
DefaultHide *bool `json:"defaultHide"`
Title *string `json:"title"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if err := h.Admin.UpdateSettings(req.Context(), body.Prefix, body.DefaultHide, body.Title); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminMaps handles GET /map/api/admin/maps.
func (h *Handlers) APIAdminMaps(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
maps, err := h.Admin.ListMaps(req.Context())
if err != nil {
HandleServiceError(rw, err)
return
}
out := make([]mapInfoJSON, len(maps))
for i, m := range maps {
out[i] = mapInfoJSON{ID: m.ID, Name: m.Name, Hidden: m.Hidden, Priority: m.Priority}
}
JSON(rw, http.StatusOK, out)
}
// APIAdminMapByID handles POST /map/api/admin/maps/:id.
func (h *Handlers) APIAdminMapByID(rw http.ResponseWriter, req *http.Request, idStr string) {
id, err := strconv.Atoi(idStr)
if err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
var body struct {
Name string `json:"name"`
Hidden bool `json:"hidden"`
Priority bool `json:"priority"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if err := h.Admin.UpdateMap(req.Context(), id, body.Name, body.Hidden, body.Priority); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminMapToggleHidden handles POST /map/api/admin/maps/:id/toggle-hidden.
func (h *Handlers) APIAdminMapToggleHidden(rw http.ResponseWriter, req *http.Request, idStr string) {
id, err := strconv.Atoi(idStr)
if err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
mi, err := h.Admin.ToggleMapHidden(req.Context(), id)
if err != nil {
HandleServiceError(rw, err)
return
}
JSON(rw, http.StatusOK, mapInfoJSON{
ID: mi.ID,
Name: mi.Name,
Hidden: mi.Hidden,
Priority: mi.Priority,
})
}
// APIAdminWipe handles POST /map/api/admin/wipe.
func (h *Handlers) APIAdminWipe(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
if err := h.Admin.Wipe(req.Context()); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminWipeTile handles POST /map/api/admin/wipeTile.
func (h *Handlers) APIAdminWipeTile(rw http.ResponseWriter, req *http.Request) {
if h.requireAdmin(rw, req) == nil {
return
}
mapid, err := strconv.Atoi(req.FormValue("map"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
x, err := strconv.Atoi(req.FormValue("x"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
y, err := strconv.Atoi(req.FormValue("y"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
if err := h.Admin.WipeTile(req.Context(), mapid, x, y); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminSetCoords handles POST /map/api/admin/setCoords.
func (h *Handlers) APIAdminSetCoords(rw http.ResponseWriter, req *http.Request) {
if h.requireAdmin(rw, req) == nil {
return
}
mapid, err := strconv.Atoi(req.FormValue("map"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
fx, err := strconv.Atoi(req.FormValue("fx"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
fy, err := strconv.Atoi(req.FormValue("fy"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
tx, err := strconv.Atoi(req.FormValue("tx"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
ty, err := strconv.Atoi(req.FormValue("ty"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
if err := h.Admin.SetCoords(req.Context(), mapid, fx, fy, tx, ty); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminHideMarker handles POST /map/api/admin/hideMarker.
func (h *Handlers) APIAdminHideMarker(rw http.ResponseWriter, req *http.Request) {
if h.requireAdmin(rw, req) == nil {
return
}
markerID := req.FormValue("id")
if markerID == "" {
JSONError(rw, http.StatusBadRequest, "missing id", "BAD_REQUEST")
return
}
if err := h.Admin.HideMarker(req.Context(), markerID); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminRebuildZooms handles POST /map/api/admin/rebuildZooms.
// It starts the rebuild in the background and returns 202 Accepted immediately.
func (h *Handlers) APIAdminRebuildZooms(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
h.Admin.StartRebuildZooms()
rw.WriteHeader(http.StatusAccepted)
}
// APIAdminRebuildZoomsStatus handles GET /map/api/admin/rebuildZooms/status.
// Returns {"running": true|false} so the client can poll until the rebuild finishes.
func (h *Handlers) APIAdminRebuildZoomsStatus(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
JSONError(rw, http.StatusMethodNotAllowed, "method not allowed", "METHOD_NOT_ALLOWED")
return
}
if h.requireAdmin(rw, req) == nil {
return
}
running := h.Admin.RebuildZoomsRunning()
JSON(rw, http.StatusOK, map[string]bool{"running": running})
}
// APIAdminExport handles GET /map/api/admin/export.
func (h *Handlers) APIAdminExport(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
rw.Header().Set("Content-Type", "application/zip")
rw.Header().Set("Content-Disposition", `attachment; filename="griddata.zip"`)
if err := h.Export.Export(req.Context(), rw); err != nil {
HandleServiceError(rw, err)
}
}
// APIAdminMerge handles POST /map/api/admin/merge.
func (h *Handlers) APIAdminMerge(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
if err := req.ParseMultipartForm(app.MergeMaxMemory); err != nil {
JSONError(rw, http.StatusBadRequest, "request error", "BAD_REQUEST")
return
}
mergef, hdr, err := req.FormFile("merge")
if err != nil {
JSONError(rw, http.StatusBadRequest, "request error", "BAD_REQUEST")
return
}
zr, err := zip.NewReader(mergef, hdr.Size)
if err != nil {
JSONError(rw, http.StatusBadRequest, "request error", "BAD_REQUEST")
return
}
if err := h.Export.Merge(req.Context(), zr); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminRoute routes /map/api/admin/* sub-paths.
func (h *Handlers) APIAdminRoute(rw http.ResponseWriter, req *http.Request, path string) {
switch {
case path == "wipeTile":
h.APIAdminWipeTile(rw, req)
case path == "setCoords":
h.APIAdminSetCoords(rw, req)
case path == "hideMarker":
h.APIAdminHideMarker(rw, req)
case path == "users":
h.APIAdminUsers(rw, req)
case strings.HasPrefix(path, "users/"):
name := strings.TrimPrefix(path, "users/")
if name == "" {
JSONError(rw, http.StatusNotFound, "not found", "NOT_FOUND")
return
}
if req.Method == http.MethodDelete {
h.APIAdminUserDelete(rw, req, name)
} else {
h.APIAdminUserByName(rw, req, name)
}
case path == "settings":
if req.Method == http.MethodGet {
h.APIAdminSettingsGet(rw, req)
} else {
h.APIAdminSettingsPost(rw, req)
}
case path == "maps":
h.APIAdminMaps(rw, req)
case strings.HasPrefix(path, "maps/"):
rest := strings.TrimPrefix(path, "maps/")
parts := strings.SplitN(rest, "/", 2)
idStr := parts[0]
if len(parts) == 2 && parts[1] == "toggle-hidden" {
h.APIAdminMapToggleHidden(rw, req, idStr)
return
}
if len(parts) == 1 {
h.APIAdminMapByID(rw, req, idStr)
return
}
JSONError(rw, http.StatusNotFound, "not found", "NOT_FOUND")
case path == "wipe":
h.APIAdminWipe(rw, req)
case path == "rebuildZooms":
h.APIAdminRebuildZooms(rw, req)
case path == "rebuildZooms/status":
h.APIAdminRebuildZoomsStatus(rw, req)
case path == "export":
h.APIAdminExport(rw, req)
case path == "merge":
h.APIAdminMerge(rw, req)
default:
JSONError(rw, http.StatusNotFound, "not found", "NOT_FOUND")
}
}
package handlers
import (
"archive/zip"
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/andyleap/hnh-map/internal/app"
)
type mapInfoJSON struct {
ID int `json:"ID"`
Name string `json:"Name"`
Hidden bool `json:"Hidden"`
Priority bool `json:"Priority"`
}
// APIAdminUsers handles GET/POST /map/api/admin/users.
func (h *Handlers) APIAdminUsers(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if req.Method == http.MethodGet {
if h.requireAdmin(rw, req) == nil {
return
}
list, err := h.Admin.ListUsers(ctx)
if err != nil {
HandleServiceError(rw, err)
return
}
JSON(rw, http.StatusOK, list)
return
}
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
s := h.requireAdmin(rw, req)
if s == nil {
return
}
var body struct {
User string `json:"user"`
Pass string `json:"pass"`
Auths []string `json:"auths"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil || body.User == "" {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
adminCreated, err := h.Admin.CreateOrUpdateUser(ctx, body.User, body.Pass, body.Auths)
if err != nil {
HandleServiceError(rw, err)
return
}
if body.User == s.Username {
s.Auths = body.Auths
}
if adminCreated && s.Username == "admin" {
h.Auth.DeleteSession(ctx, s)
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminUserByName handles GET /map/api/admin/users/:name.
func (h *Handlers) APIAdminUserByName(rw http.ResponseWriter, req *http.Request, name string) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
auths, found, err := h.Admin.GetUser(req.Context(), name)
if err != nil {
HandleServiceError(rw, err)
return
}
out := struct {
Username string `json:"username"`
Auths []string `json:"auths"`
}{Username: name}
if found {
out.Auths = auths
}
JSON(rw, http.StatusOK, out)
}
// APIAdminUserDelete handles DELETE /map/api/admin/users/:name.
func (h *Handlers) APIAdminUserDelete(rw http.ResponseWriter, req *http.Request, name string) {
if !h.requireMethod(rw, req, http.MethodDelete) {
return
}
s := h.requireAdmin(rw, req)
if s == nil {
return
}
ctx := req.Context()
if err := h.Admin.DeleteUser(ctx, name); err != nil {
HandleServiceError(rw, err)
return
}
if name == s.Username {
h.Auth.DeleteSession(ctx, s)
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminSettingsGet handles GET /map/api/admin/settings.
func (h *Handlers) APIAdminSettingsGet(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
prefix, defaultHide, title, err := h.Admin.GetSettings(req.Context())
if err != nil {
HandleServiceError(rw, err)
return
}
JSON(rw, http.StatusOK, struct {
Prefix string `json:"prefix"`
DefaultHide bool `json:"defaultHide"`
Title string `json:"title"`
}{Prefix: prefix, DefaultHide: defaultHide, Title: title})
}
// APIAdminSettingsPost handles POST /map/api/admin/settings.
func (h *Handlers) APIAdminSettingsPost(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
var body struct {
Prefix *string `json:"prefix"`
DefaultHide *bool `json:"defaultHide"`
Title *string `json:"title"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if err := h.Admin.UpdateSettings(req.Context(), body.Prefix, body.DefaultHide, body.Title); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminMaps handles GET /map/api/admin/maps.
func (h *Handlers) APIAdminMaps(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
maps, err := h.Admin.ListMaps(req.Context())
if err != nil {
HandleServiceError(rw, err)
return
}
out := make([]mapInfoJSON, len(maps))
for i, m := range maps {
out[i] = mapInfoJSON{ID: m.ID, Name: m.Name, Hidden: m.Hidden, Priority: m.Priority}
}
JSON(rw, http.StatusOK, out)
}
// APIAdminMapByID handles POST /map/api/admin/maps/:id.
func (h *Handlers) APIAdminMapByID(rw http.ResponseWriter, req *http.Request, idStr string) {
id, err := strconv.Atoi(idStr)
if err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
var body struct {
Name string `json:"name"`
Hidden bool `json:"hidden"`
Priority bool `json:"priority"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if err := h.Admin.UpdateMap(req.Context(), id, body.Name, body.Hidden, body.Priority); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminMapToggleHidden handles POST /map/api/admin/maps/:id/toggle-hidden.
func (h *Handlers) APIAdminMapToggleHidden(rw http.ResponseWriter, req *http.Request, idStr string) {
id, err := strconv.Atoi(idStr)
if err != nil {
JSONError(rw, http.StatusBadRequest, "bad request", "BAD_REQUEST")
return
}
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
mi, err := h.Admin.ToggleMapHidden(req.Context(), id)
if err != nil {
HandleServiceError(rw, err)
return
}
JSON(rw, http.StatusOK, mapInfoJSON{
ID: mi.ID,
Name: mi.Name,
Hidden: mi.Hidden,
Priority: mi.Priority,
})
}
// APIAdminWipe handles POST /map/api/admin/wipe.
func (h *Handlers) APIAdminWipe(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
if err := h.Admin.Wipe(req.Context()); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminWipeTile handles POST /map/api/admin/wipeTile.
func (h *Handlers) APIAdminWipeTile(rw http.ResponseWriter, req *http.Request) {
if h.requireAdmin(rw, req) == nil {
return
}
mapid, err := strconv.Atoi(req.FormValue("map"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
x, err := strconv.Atoi(req.FormValue("x"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
y, err := strconv.Atoi(req.FormValue("y"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
if err := h.Admin.WipeTile(req.Context(), mapid, x, y); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminSetCoords handles POST /map/api/admin/setCoords.
func (h *Handlers) APIAdminSetCoords(rw http.ResponseWriter, req *http.Request) {
if h.requireAdmin(rw, req) == nil {
return
}
mapid, err := strconv.Atoi(req.FormValue("map"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
fx, err := strconv.Atoi(req.FormValue("fx"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
fy, err := strconv.Atoi(req.FormValue("fy"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
tx, err := strconv.Atoi(req.FormValue("tx"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
ty, err := strconv.Atoi(req.FormValue("ty"))
if err != nil {
JSONError(rw, http.StatusBadRequest, "coord parse failed", "BAD_REQUEST")
return
}
if err := h.Admin.SetCoords(req.Context(), mapid, fx, fy, tx, ty); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminHideMarker handles POST /map/api/admin/hideMarker.
func (h *Handlers) APIAdminHideMarker(rw http.ResponseWriter, req *http.Request) {
if h.requireAdmin(rw, req) == nil {
return
}
markerID := req.FormValue("id")
if markerID == "" {
JSONError(rw, http.StatusBadRequest, "missing id", "BAD_REQUEST")
return
}
if err := h.Admin.HideMarker(req.Context(), markerID); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminRebuildZooms handles POST /map/api/admin/rebuildZooms.
// It starts the rebuild in the background and returns 202 Accepted immediately.
func (h *Handlers) APIAdminRebuildZooms(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
h.Admin.StartRebuildZooms()
rw.WriteHeader(http.StatusAccepted)
}
// APIAdminRebuildZoomsStatus handles GET /map/api/admin/rebuildZooms/status.
// Returns {"running": true|false} so the client can poll until the rebuild finishes.
func (h *Handlers) APIAdminRebuildZoomsStatus(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
JSONError(rw, http.StatusMethodNotAllowed, "method not allowed", "METHOD_NOT_ALLOWED")
return
}
if h.requireAdmin(rw, req) == nil {
return
}
running := h.Admin.RebuildZoomsRunning()
JSON(rw, http.StatusOK, map[string]bool{"running": running})
}
// APIAdminExport handles GET /map/api/admin/export.
func (h *Handlers) APIAdminExport(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodGet) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
rw.Header().Set("Content-Type", "application/zip")
rw.Header().Set("Content-Disposition", `attachment; filename="griddata.zip"`)
if err := h.Export.Export(req.Context(), rw); err != nil {
HandleServiceError(rw, err)
}
}
// APIAdminMerge handles POST /map/api/admin/merge.
func (h *Handlers) APIAdminMerge(rw http.ResponseWriter, req *http.Request) {
if !h.requireMethod(rw, req, http.MethodPost) {
return
}
if h.requireAdmin(rw, req) == nil {
return
}
if err := req.ParseMultipartForm(app.MergeMaxMemory); err != nil {
JSONError(rw, http.StatusBadRequest, "request error", "BAD_REQUEST")
return
}
mergef, hdr, err := req.FormFile("merge")
if err != nil {
JSONError(rw, http.StatusBadRequest, "request error", "BAD_REQUEST")
return
}
zr, err := zip.NewReader(mergef, hdr.Size)
if err != nil {
JSONError(rw, http.StatusBadRequest, "request error", "BAD_REQUEST")
return
}
if err := h.Export.Merge(req.Context(), zr); err != nil {
HandleServiceError(rw, err)
return
}
rw.WriteHeader(http.StatusOK)
}
// APIAdminRoute routes /map/api/admin/* sub-paths.
func (h *Handlers) APIAdminRoute(rw http.ResponseWriter, req *http.Request, path string) {
switch {
case path == "wipeTile":
h.APIAdminWipeTile(rw, req)
case path == "setCoords":
h.APIAdminSetCoords(rw, req)
case path == "hideMarker":
h.APIAdminHideMarker(rw, req)
case path == "users":
h.APIAdminUsers(rw, req)
case strings.HasPrefix(path, "users/"):
name := strings.TrimPrefix(path, "users/")
if name == "" {
JSONError(rw, http.StatusNotFound, "not found", "NOT_FOUND")
return
}
if req.Method == http.MethodDelete {
h.APIAdminUserDelete(rw, req, name)
} else {
h.APIAdminUserByName(rw, req, name)
}
case path == "settings":
if req.Method == http.MethodGet {
h.APIAdminSettingsGet(rw, req)
} else {
h.APIAdminSettingsPost(rw, req)
}
case path == "maps":
h.APIAdminMaps(rw, req)
case strings.HasPrefix(path, "maps/"):
rest := strings.TrimPrefix(path, "maps/")
parts := strings.SplitN(rest, "/", 2)
idStr := parts[0]
if len(parts) == 2 && parts[1] == "toggle-hidden" {
h.APIAdminMapToggleHidden(rw, req, idStr)
return
}
if len(parts) == 1 {
h.APIAdminMapByID(rw, req, idStr)
return
}
JSONError(rw, http.StatusNotFound, "not found", "NOT_FOUND")
case path == "wipe":
h.APIAdminWipe(rw, req)
case path == "rebuildZooms":
h.APIAdminRebuildZooms(rw, req)
case path == "rebuildZooms/status":
h.APIAdminRebuildZoomsStatus(rw, req)
case path == "export":
h.APIAdminExport(rw, req)
case path == "merge":
h.APIAdminMerge(rw, req)
default:
JSONError(rw, http.StatusNotFound, "not found", "NOT_FOUND")
}
}

View File

@@ -66,7 +66,7 @@ func (h *Handlers) clientLocate(rw http.ResponseWriter, req *http.Request) {
}
rw.Header().Set("Content-Type", "text/plain")
rw.WriteHeader(http.StatusOK)
rw.Write([]byte(result))
_, _ = rw.Write([]byte(result))
}
func (h *Handlers) clientGridUpdate(rw http.ResponseWriter, req *http.Request) {
@@ -85,7 +85,7 @@ func (h *Handlers) clientGridUpdate(rw http.ResponseWriter, req *http.Request) {
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
json.NewEncoder(rw).Encode(result.Response)
_ = json.NewEncoder(rw).Encode(result.Response)
}
func (h *Handlers) clientGridUpload(rw http.ResponseWriter, req *http.Request) {

File diff suppressed because it is too large Load Diff

View File

@@ -55,14 +55,23 @@ func (h *Handlers) WatchGridUpdates(rw http.ResponseWriter, req *http.Request) {
tileCache := []services.TileCache{}
raw, _ := json.Marshal(tileCache)
fmt.Fprint(rw, "data: ")
rw.Write(raw)
_, _ = rw.Write(raw)
fmt.Fprint(rw, "\n\n")
flusher.Flush()
ticker := time.NewTicker(app.SSETickInterval)
defer ticker.Stop()
keepaliveTicker := time.NewTicker(app.SSEKeepaliveInterval)
defer keepaliveTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-keepaliveTicker.C:
if _, err := fmt.Fprint(rw, ": keepalive\n\n"); err != nil {
return
}
flusher.Flush()
case e, ok := <-c:
if !ok {
return
@@ -93,13 +102,15 @@ func (h *Handlers) WatchGridUpdates(rw http.ResponseWriter, req *http.Request) {
}
fmt.Fprint(rw, "event: merge\n")
fmt.Fprint(rw, "data: ")
rw.Write(raw)
_, _ = rw.Write(raw)
fmt.Fprint(rw, "\n\n")
flusher.Flush()
case <-ticker.C:
raw, _ := json.Marshal(tileCache)
fmt.Fprint(rw, "data: ")
rw.Write(raw)
if _, err := rw.Write(raw); err != nil {
return
}
fmt.Fprint(rw, "\n\n")
tileCache = tileCache[:0]
flusher.Flush()
@@ -152,7 +163,7 @@ func (h *Handlers) GridTile(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "image/png")
rw.Header().Set("Cache-Control", "private, max-age=3600")
rw.WriteHeader(http.StatusOK)
rw.Write(transparentPNG)
_, _ = rw.Write(transparentPNG)
return
}

View File

@@ -172,7 +172,9 @@ var migrations = []func(tx *bbolt.Tx) error{
if err != nil {
return err
}
users.Put(k, raw)
if err := users.Put(k, raw); err != nil {
return err
}
}
return nil
})

View File

@@ -26,7 +26,7 @@ func TestRunMigrations_FreshDB(t *testing.T) {
t.Fatalf("migrations failed on fresh DB: %v", err)
}
db.View(func(tx *bbolt.Tx) error {
if err := db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(store.BucketConfig)
if b == nil {
t.Fatal("expected config bucket after migrations")
@@ -40,13 +40,15 @@ func TestRunMigrations_FreshDB(t *testing.T) {
t.Fatalf("expected default title, got %s", title)
}
return nil
})
}); err != nil {
t.Fatal(err)
}
if tx, _ := db.Begin(false); tx != nil {
if tx.Bucket(store.BucketOAuthStates) == nil {
t.Fatal("expected oauth_states bucket after migrations")
}
tx.Rollback()
_ = tx.Rollback()
}
}
@@ -61,7 +63,7 @@ func TestRunMigrations_Idempotent(t *testing.T) {
t.Fatalf("second run failed: %v", err)
}
db.View(func(tx *bbolt.Tx) error {
if err := db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(store.BucketConfig)
if b == nil {
t.Fatal("expected config bucket")
@@ -71,7 +73,9 @@ func TestRunMigrations_Idempotent(t *testing.T) {
t.Fatal("expected version key")
}
return nil
})
}); err != nil {
t.Fatal(err)
}
}
func TestRunMigrations_SetsVersion(t *testing.T) {
@@ -81,11 +85,13 @@ func TestRunMigrations_SetsVersion(t *testing.T) {
}
var version string
db.View(func(tx *bbolt.Tx) error {
if err := db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(store.BucketConfig)
version = string(b.Get([]byte("version")))
return nil
})
}); err != nil {
t.Fatal(err)
}
if version == "" || version == "0" {
t.Fatalf("expected non-zero version, got %q", version)

View File

@@ -1,407 +1,423 @@
package services
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strconv"
"sync"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
"golang.org/x/crypto/bcrypt"
)
// AdminService handles admin business logic (users, settings, maps, wipe, tile ops).
type AdminService struct {
st *store.Store
mapSvc *MapService
rebuildMu sync.Mutex
rebuildRunning bool
}
// NewAdminService creates an AdminService with the given store and map service.
// Uses direct args (two dependencies) rather than a deps struct.
func NewAdminService(st *store.Store, mapSvc *MapService) *AdminService {
return &AdminService{st: st, mapSvc: mapSvc}
}
// ListUsers returns all usernames.
func (s *AdminService) ListUsers(ctx context.Context) ([]string, error) {
var list []string
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachUser(tx, func(k, _ []byte) error {
list = append(list, string(k))
return nil
})
})
return list, err
}
// GetUser returns a user's permissions by username.
func (s *AdminService) GetUser(ctx context.Context, username string) (auths app.Auths, found bool, err error) {
err = s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetUser(tx, username)
if raw == nil {
return nil
}
var u app.User
if err := json.Unmarshal(raw, &u); err != nil {
return err
}
auths = u.Auths
found = true
return nil
})
return auths, found, err
}
// CreateOrUpdateUser creates or updates a user.
// Returns (true, nil) when admin user was created fresh (temp admin bootstrap).
func (s *AdminService) CreateOrUpdateUser(ctx context.Context, username string, pass string, auths app.Auths) (adminCreated bool, err error) {
err = s.st.Update(ctx, func(tx *bbolt.Tx) error {
existed := s.st.GetUser(tx, username) != nil
u := app.User{}
raw := s.st.GetUser(tx, username)
if raw != nil {
if err := json.Unmarshal(raw, &u); err != nil {
return err
}
}
if pass != "" {
hash, e := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
if e != nil {
return e
}
u.Pass = hash
}
u.Auths = auths
raw, _ = json.Marshal(u)
if e := s.st.PutUser(tx, username, raw); e != nil {
return e
}
if username == "admin" && !existed {
adminCreated = true
}
return nil
})
return adminCreated, err
}
// DeleteUser removes a user and their tokens.
func (s *AdminService) DeleteUser(ctx context.Context, username string) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
uRaw := s.st.GetUser(tx, username)
if uRaw != nil {
var u app.User
if err := json.Unmarshal(uRaw, &u); err != nil {
return err
}
for _, tok := range u.Tokens {
s.st.DeleteToken(tx, tok)
}
}
return s.st.DeleteUser(tx, username)
})
}
// GetSettings returns the current server settings.
func (s *AdminService) GetSettings(ctx context.Context) (prefix string, defaultHide bool, title string, err error) {
err = s.st.View(ctx, func(tx *bbolt.Tx) error {
if v := s.st.GetConfig(tx, "prefix"); v != nil {
prefix = string(v)
}
if v := s.st.GetConfig(tx, "defaultHide"); v != nil {
defaultHide = true
}
if v := s.st.GetConfig(tx, "title"); v != nil {
title = string(v)
}
return nil
})
return prefix, defaultHide, title, err
}
// UpdateSettings updates the specified server settings (nil fields are skipped).
func (s *AdminService) UpdateSettings(ctx context.Context, prefix *string, defaultHide *bool, title *string) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
if prefix != nil {
s.st.PutConfig(tx, "prefix", []byte(*prefix))
}
if defaultHide != nil {
if *defaultHide {
s.st.PutConfig(tx, "defaultHide", []byte("1"))
} else {
s.st.DeleteConfig(tx, "defaultHide")
}
}
if title != nil {
s.st.PutConfig(tx, "title", []byte(*title))
}
return nil
})
}
// ListMaps returns all maps for the admin panel.
func (s *AdminService) ListMaps(ctx context.Context) ([]app.MapInfo, error) {
var maps []app.MapInfo
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachMap(tx, func(k, v []byte) error {
mi := app.MapInfo{}
if err := json.Unmarshal(v, &mi); err != nil {
return err
}
if id, err := strconv.Atoi(string(k)); err == nil {
mi.ID = id
}
maps = append(maps, mi)
return nil
})
})
return maps, err
}
// GetMap returns a map by ID.
func (s *AdminService) GetMap(ctx context.Context, id int) (*app.MapInfo, bool, error) {
var mi *app.MapInfo
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetMap(tx, id)
if raw != nil {
mi = &app.MapInfo{}
return json.Unmarshal(raw, mi)
}
return nil
})
if err != nil {
return nil, false, err
}
if mi != nil {
mi.ID = id
}
return mi, mi != nil, nil
}
// UpdateMap updates a map's name, hidden, and priority fields.
func (s *AdminService) UpdateMap(ctx context.Context, id int, name string, hidden, priority bool) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
mi := app.MapInfo{}
raw := s.st.GetMap(tx, id)
if raw != nil {
if err := json.Unmarshal(raw, &mi); err != nil {
return err
}
}
mi.ID = id
mi.Name = name
mi.Hidden = hidden
mi.Priority = priority
raw, _ = json.Marshal(mi)
return s.st.PutMap(tx, id, raw)
})
}
// ToggleMapHidden toggles the hidden flag of a map and returns the updated map.
func (s *AdminService) ToggleMapHidden(ctx context.Context, id int) (*app.MapInfo, error) {
var mi *app.MapInfo
err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetMap(tx, id)
mi = &app.MapInfo{}
if raw != nil {
if err := json.Unmarshal(raw, mi); err != nil {
return err
}
}
mi.ID = id
mi.Hidden = !mi.Hidden
raw, _ = json.Marshal(mi)
return s.st.PutMap(tx, id, raw)
})
return mi, err
}
// Wipe deletes all grids, markers, tiles, and maps from the database.
func (s *AdminService) Wipe(ctx context.Context) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
for _, b := range [][]byte{
store.BucketGrids,
store.BucketMarkers,
store.BucketTiles,
store.BucketMaps,
} {
if s.st.BucketExists(tx, b) {
if err := s.st.DeleteBucket(tx, b); err != nil {
return err
}
}
}
return nil
})
}
// WipeTile removes a tile at the given coordinates and rebuilds zoom levels.
func (s *AdminService) WipeTile(ctx context.Context, mapid, x, y int) error {
c := app.Coord{X: x, Y: y}
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
grids := tx.Bucket(store.BucketGrids)
if grids == nil {
return nil
}
var ids [][]byte
err := grids.ForEach(func(k, v []byte) error {
g := app.GridData{}
if err := json.Unmarshal(v, &g); err != nil {
return err
}
if g.Coord == c && g.Map == mapid {
ids = append(ids, k)
}
return nil
})
if err != nil {
return err
}
for _, id := range ids {
grids.Delete(id)
}
return nil
}); err != nil {
return err
}
s.mapSvc.SaveTile(ctx, mapid, c, 0, "", -1)
zc := c
for z := 1; z <= app.MaxZoomLevel; z++ {
zc = zc.Parent()
s.mapSvc.UpdateZoomLevel(ctx, mapid, zc, z)
}
return nil
}
// SetCoords shifts all grid and tile coordinates by a delta.
func (s *AdminService) SetCoords(ctx context.Context, mapid, fx, fy, tx2, ty int) error {
fc := app.Coord{X: fx, Y: fy}
tc := app.Coord{X: tx2, Y: ty}
diff := app.Coord{X: tc.X - fc.X, Y: tc.Y - fc.Y}
var tds []*app.TileData
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
grids := tx.Bucket(store.BucketGrids)
if grids == nil {
return nil
}
tiles := tx.Bucket(store.BucketTiles)
if tiles == nil {
return nil
}
mapZooms := tiles.Bucket([]byte(strconv.Itoa(mapid)))
if mapZooms == nil {
return nil
}
mapTiles := mapZooms.Bucket([]byte("0"))
if err := grids.ForEach(func(k, v []byte) error {
g := app.GridData{}
if err := json.Unmarshal(v, &g); err != nil {
return err
}
if g.Map == mapid {
g.Coord.X += diff.X
g.Coord.Y += diff.Y
raw, _ := json.Marshal(g)
grids.Put(k, raw)
}
return nil
}); err != nil {
return err
}
if err := mapTiles.ForEach(func(k, v []byte) error {
td := &app.TileData{}
if err := json.Unmarshal(v, td); err != nil {
return err
}
td.Coord.X += diff.X
td.Coord.Y += diff.Y
tds = append(tds, td)
return nil
}); err != nil {
return err
}
return tiles.DeleteBucket([]byte(strconv.Itoa(mapid)))
}); err != nil {
return err
}
ops := make([]TileOp, len(tds))
for i, td := range tds {
ops[i] = TileOp{MapID: td.MapID, X: td.Coord.X, Y: td.Coord.Y, File: td.File}
}
s.mapSvc.ProcessZoomLevels(ctx, ops)
return nil
}
// HideMarker marks a marker as hidden.
func (s *AdminService) HideMarker(ctx context.Context, markerID string) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
_, idB, err := s.st.CreateMarkersBuckets(tx)
if err != nil {
return err
}
grid := s.st.GetMarkersGridBucket(tx)
if grid == nil {
return fmt.Errorf("markers grid bucket not found")
}
key := idB.Get([]byte(markerID))
if key == nil {
slog.Warn("marker not found", "id", markerID)
return nil
}
raw := grid.Get(key)
if raw == nil {
return nil
}
m := app.Marker{}
if err := json.Unmarshal(raw, &m); err != nil {
return err
}
m.Hidden = true
raw, _ = json.Marshal(m)
grid.Put(key, raw)
return nil
})
}
// RebuildZooms delegates to MapService.
func (s *AdminService) RebuildZooms(ctx context.Context) error {
return s.mapSvc.RebuildZooms(ctx)
}
// StartRebuildZooms starts RebuildZooms in a goroutine and returns immediately.
// RebuildZoomsRunning returns true while the rebuild is in progress.
func (s *AdminService) StartRebuildZooms() {
s.rebuildMu.Lock()
if s.rebuildRunning {
s.rebuildMu.Unlock()
return
}
s.rebuildRunning = true
s.rebuildMu.Unlock()
go func() {
defer func() {
s.rebuildMu.Lock()
s.rebuildRunning = false
s.rebuildMu.Unlock()
}()
if err := s.mapSvc.RebuildZooms(context.Background()); err != nil {
slog.Error("RebuildZooms background failed", "error", err)
}
}()
}
// RebuildZoomsRunning returns true if a rebuild is currently in progress.
func (s *AdminService) RebuildZoomsRunning() bool {
s.rebuildMu.Lock()
defer s.rebuildMu.Unlock()
return s.rebuildRunning
}
package services
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strconv"
"sync"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
"golang.org/x/crypto/bcrypt"
)
// AdminService handles admin business logic (users, settings, maps, wipe, tile ops).
type AdminService struct {
st *store.Store
mapSvc *MapService
rebuildMu sync.Mutex
rebuildRunning bool
}
// NewAdminService creates an AdminService with the given store and map service.
// Uses direct args (two dependencies) rather than a deps struct.
func NewAdminService(st *store.Store, mapSvc *MapService) *AdminService {
return &AdminService{st: st, mapSvc: mapSvc}
}
// ListUsers returns all usernames.
func (s *AdminService) ListUsers(ctx context.Context) ([]string, error) {
var list []string
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachUser(tx, func(k, _ []byte) error {
list = append(list, string(k))
return nil
})
})
return list, err
}
// GetUser returns a user's permissions by username.
func (s *AdminService) GetUser(ctx context.Context, username string) (auths app.Auths, found bool, err error) {
err = s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetUser(tx, username)
if raw == nil {
return nil
}
var u app.User
if err := json.Unmarshal(raw, &u); err != nil {
return err
}
auths = u.Auths
found = true
return nil
})
return auths, found, err
}
// CreateOrUpdateUser creates or updates a user.
// Returns (true, nil) when admin user was created fresh (temp admin bootstrap).
func (s *AdminService) CreateOrUpdateUser(ctx context.Context, username string, pass string, auths app.Auths) (adminCreated bool, err error) {
err = s.st.Update(ctx, func(tx *bbolt.Tx) error {
existed := s.st.GetUser(tx, username) != nil
u := app.User{}
raw := s.st.GetUser(tx, username)
if raw != nil {
if err := json.Unmarshal(raw, &u); err != nil {
return err
}
}
if pass != "" {
hash, e := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
if e != nil {
return e
}
u.Pass = hash
}
u.Auths = auths
raw, _ = json.Marshal(u)
if e := s.st.PutUser(tx, username, raw); e != nil {
return e
}
if username == "admin" && !existed {
adminCreated = true
}
return nil
})
return adminCreated, err
}
// DeleteUser removes a user and their tokens.
func (s *AdminService) DeleteUser(ctx context.Context, username string) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
uRaw := s.st.GetUser(tx, username)
if uRaw != nil {
var u app.User
if err := json.Unmarshal(uRaw, &u); err != nil {
return err
}
for _, tok := range u.Tokens {
if err := s.st.DeleteToken(tx, tok); err != nil {
return err
}
}
}
return s.st.DeleteUser(tx, username)
})
}
// GetSettings returns the current server settings.
func (s *AdminService) GetSettings(ctx context.Context) (prefix string, defaultHide bool, title string, err error) {
err = s.st.View(ctx, func(tx *bbolt.Tx) error {
if v := s.st.GetConfig(tx, "prefix"); v != nil {
prefix = string(v)
}
if v := s.st.GetConfig(tx, "defaultHide"); v != nil {
defaultHide = true
}
if v := s.st.GetConfig(tx, "title"); v != nil {
title = string(v)
}
return nil
})
return prefix, defaultHide, title, err
}
// UpdateSettings updates the specified server settings (nil fields are skipped).
func (s *AdminService) UpdateSettings(ctx context.Context, prefix *string, defaultHide *bool, title *string) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
if prefix != nil {
if err := s.st.PutConfig(tx, "prefix", []byte(*prefix)); err != nil {
return err
}
}
if defaultHide != nil {
if *defaultHide {
if err := s.st.PutConfig(tx, "defaultHide", []byte("1")); err != nil {
return err
}
} else {
if err := s.st.DeleteConfig(tx, "defaultHide"); err != nil {
return err
}
}
}
if title != nil {
if err := s.st.PutConfig(tx, "title", []byte(*title)); err != nil {
return err
}
}
return nil
})
}
// ListMaps returns all maps for the admin panel.
func (s *AdminService) ListMaps(ctx context.Context) ([]app.MapInfo, error) {
var maps []app.MapInfo
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachMap(tx, func(k, v []byte) error {
mi := app.MapInfo{}
if err := json.Unmarshal(v, &mi); err != nil {
return err
}
if id, err := strconv.Atoi(string(k)); err == nil {
mi.ID = id
}
maps = append(maps, mi)
return nil
})
})
return maps, err
}
// GetMap returns a map by ID.
func (s *AdminService) GetMap(ctx context.Context, id int) (*app.MapInfo, bool, error) {
var mi *app.MapInfo
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetMap(tx, id)
if raw != nil {
mi = &app.MapInfo{}
return json.Unmarshal(raw, mi)
}
return nil
})
if err != nil {
return nil, false, err
}
if mi != nil {
mi.ID = id
}
return mi, mi != nil, nil
}
// UpdateMap updates a map's name, hidden, and priority fields.
func (s *AdminService) UpdateMap(ctx context.Context, id int, name string, hidden, priority bool) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
mi := app.MapInfo{}
raw := s.st.GetMap(tx, id)
if raw != nil {
if err := json.Unmarshal(raw, &mi); err != nil {
return err
}
}
mi.ID = id
mi.Name = name
mi.Hidden = hidden
mi.Priority = priority
raw, _ = json.Marshal(mi)
return s.st.PutMap(tx, id, raw)
})
}
// ToggleMapHidden toggles the hidden flag of a map and returns the updated map.
func (s *AdminService) ToggleMapHidden(ctx context.Context, id int) (*app.MapInfo, error) {
var mi *app.MapInfo
err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetMap(tx, id)
mi = &app.MapInfo{}
if raw != nil {
if err := json.Unmarshal(raw, mi); err != nil {
return err
}
}
mi.ID = id
mi.Hidden = !mi.Hidden
raw, _ = json.Marshal(mi)
return s.st.PutMap(tx, id, raw)
})
return mi, err
}
// Wipe deletes all grids, markers, tiles, and maps from the database.
func (s *AdminService) Wipe(ctx context.Context) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
for _, b := range [][]byte{
store.BucketGrids,
store.BucketMarkers,
store.BucketTiles,
store.BucketMaps,
} {
if s.st.BucketExists(tx, b) {
if err := s.st.DeleteBucket(tx, b); err != nil {
return err
}
}
}
return nil
})
}
// WipeTile removes a tile at the given coordinates and rebuilds zoom levels.
func (s *AdminService) WipeTile(ctx context.Context, mapid, x, y int) error {
c := app.Coord{X: x, Y: y}
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
grids := tx.Bucket(store.BucketGrids)
if grids == nil {
return nil
}
var ids [][]byte
err := grids.ForEach(func(k, v []byte) error {
g := app.GridData{}
if err := json.Unmarshal(v, &g); err != nil {
return err
}
if g.Coord == c && g.Map == mapid {
ids = append(ids, k)
}
return nil
})
if err != nil {
return err
}
for _, id := range ids {
if err := grids.Delete(id); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
s.mapSvc.SaveTile(ctx, mapid, c, 0, "", -1)
zc := c
for z := 1; z <= app.MaxZoomLevel; z++ {
zc = zc.Parent()
s.mapSvc.UpdateZoomLevel(ctx, mapid, zc, z)
}
return nil
}
// SetCoords shifts all grid and tile coordinates by a delta.
func (s *AdminService) SetCoords(ctx context.Context, mapid, fx, fy, tx2, ty int) error {
fc := app.Coord{X: fx, Y: fy}
tc := app.Coord{X: tx2, Y: ty}
diff := app.Coord{X: tc.X - fc.X, Y: tc.Y - fc.Y}
var tds []*app.TileData
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
grids := tx.Bucket(store.BucketGrids)
if grids == nil {
return nil
}
tiles := tx.Bucket(store.BucketTiles)
if tiles == nil {
return nil
}
mapZooms := tiles.Bucket([]byte(strconv.Itoa(mapid)))
if mapZooms == nil {
return nil
}
mapTiles := mapZooms.Bucket([]byte("0"))
if err := grids.ForEach(func(k, v []byte) error {
g := app.GridData{}
if err := json.Unmarshal(v, &g); err != nil {
return err
}
if g.Map == mapid {
g.Coord.X += diff.X
g.Coord.Y += diff.Y
raw, _ := json.Marshal(g)
if err := grids.Put(k, raw); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
if err := mapTiles.ForEach(func(k, v []byte) error {
td := &app.TileData{}
if err := json.Unmarshal(v, td); err != nil {
return err
}
td.Coord.X += diff.X
td.Coord.Y += diff.Y
tds = append(tds, td)
return nil
}); err != nil {
return err
}
return tiles.DeleteBucket([]byte(strconv.Itoa(mapid)))
}); err != nil {
return err
}
ops := make([]TileOp, len(tds))
for i, td := range tds {
ops[i] = TileOp{MapID: td.MapID, X: td.Coord.X, Y: td.Coord.Y, File: td.File}
}
s.mapSvc.ProcessZoomLevels(ctx, ops)
return nil
}
// HideMarker marks a marker as hidden.
func (s *AdminService) HideMarker(ctx context.Context, markerID string) error {
return s.st.Update(ctx, func(tx *bbolt.Tx) error {
_, idB, err := s.st.CreateMarkersBuckets(tx)
if err != nil {
return err
}
grid := s.st.GetMarkersGridBucket(tx)
if grid == nil {
return fmt.Errorf("markers grid bucket not found")
}
key := idB.Get([]byte(markerID))
if key == nil {
slog.Warn("marker not found", "id", markerID)
return nil
}
raw := grid.Get(key)
if raw == nil {
return nil
}
m := app.Marker{}
if err := json.Unmarshal(raw, &m); err != nil {
return err
}
m.Hidden = true
raw, _ = json.Marshal(m)
if err := grid.Put(key, raw); err != nil {
return err
}
return nil
})
}
// RebuildZooms delegates to MapService.
func (s *AdminService) RebuildZooms(ctx context.Context) error {
return s.mapSvc.RebuildZooms(ctx)
}
// StartRebuildZooms starts RebuildZooms in a goroutine and returns immediately.
// RebuildZoomsRunning returns true while the rebuild is in progress.
func (s *AdminService) StartRebuildZooms() {
s.rebuildMu.Lock()
if s.rebuildRunning {
s.rebuildMu.Unlock()
return
}
s.rebuildRunning = true
s.rebuildMu.Unlock()
go func() {
defer func() {
s.rebuildMu.Lock()
s.rebuildRunning = false
s.rebuildMu.Unlock()
}()
if err := s.mapSvc.RebuildZooms(context.Background()); err != nil {
slog.Error("RebuildZooms background failed", "error", err)
}
}()
}
// RebuildZoomsRunning returns true if a rebuild is currently in progress.
func (s *AdminService) RebuildZoomsRunning() bool {
s.rebuildMu.Lock()
defer s.rebuildMu.Unlock()
return s.rebuildRunning
}

View File

@@ -1,298 +1,308 @@
package services_test
import (
"context"
"testing"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/services"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
)
func newTestAdmin(t *testing.T) (*services.AdminService, *store.Store) {
t.Helper()
db := newTestDB(t)
st := store.New(db)
mapSvc := services.NewMapService(services.MapServiceDeps{
Store: st,
GridStorage: t.TempDir(),
GridUpdates: &app.Topic[app.TileData]{},
})
return services.NewAdminService(st, mapSvc), st
}
func TestListUsers_Empty(t *testing.T) {
admin, _ := newTestAdmin(t)
users, err := admin.ListUsers(context.Background())
if err != nil {
t.Fatal(err)
}
if len(users) != 0 {
t.Fatalf("expected 0 users, got %d", len(users))
}
}
func TestListUsers_WithUsers(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
createUser(t, st, "alice", "pass", nil)
createUser(t, st, "bob", "pass", nil)
users, err := admin.ListUsers(ctx)
if err != nil {
t.Fatal(err)
}
if len(users) != 2 {
t.Fatalf("expected 2 users, got %d", len(users))
}
}
func TestAdminGetUser_Found(t *testing.T) {
admin, st := newTestAdmin(t)
createUser(t, st, "alice", "pass", app.Auths{app.AUTH_MAP, app.AUTH_UPLOAD})
auths, found, err := admin.GetUser(context.Background(), "alice")
if err != nil || !found {
t.Fatalf("expected found, err=%v", err)
}
if !auths.Has(app.AUTH_MAP) {
t.Fatal("expected map auth")
}
}
func TestAdminGetUser_NotFound(t *testing.T) {
admin, _ := newTestAdmin(t)
_, found, err := admin.GetUser(context.Background(), "ghost")
if err != nil {
t.Fatal(err)
}
if found {
t.Fatal("expected not found")
}
}
func TestCreateOrUpdateUser_New(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
_, err := admin.CreateOrUpdateUser(ctx, "bob", "secret", app.Auths{app.AUTH_MAP})
if err != nil {
t.Fatal(err)
}
auths, found, err := admin.GetUser(ctx, "bob")
if err != nil || !found {
t.Fatalf("expected user to exist, err=%v", err)
}
if !auths.Has(app.AUTH_MAP) {
t.Fatal("expected map auth")
}
}
func TestCreateOrUpdateUser_Update(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
createUser(t, st, "alice", "old", app.Auths{app.AUTH_MAP})
_, err := admin.CreateOrUpdateUser(ctx, "alice", "new", app.Auths{app.AUTH_ADMIN, app.AUTH_MAP})
if err != nil {
t.Fatal(err)
}
auths, found, err := admin.GetUser(ctx, "alice")
if err != nil || !found {
t.Fatalf("expected user, err=%v", err)
}
if !auths.Has(app.AUTH_ADMIN) {
t.Fatal("expected admin auth after update")
}
}
func TestCreateOrUpdateUser_AdminBootstrap(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
adminCreated, err := admin.CreateOrUpdateUser(ctx, "admin", "pass", app.Auths{app.AUTH_ADMIN})
if err != nil {
t.Fatal(err)
}
if !adminCreated {
t.Fatal("expected adminCreated=true for new admin user")
}
adminCreated, err = admin.CreateOrUpdateUser(ctx, "admin", "pass2", app.Auths{app.AUTH_ADMIN})
if err != nil {
t.Fatal(err)
}
if adminCreated {
t.Fatal("expected adminCreated=false for existing admin user")
}
}
func TestDeleteUser(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
createUser(t, st, "alice", "pass", app.Auths{app.AUTH_UPLOAD})
auth := services.NewAuthService(st)
auth.GenerateTokenForUser(ctx, "alice")
if err := admin.DeleteUser(ctx, "alice"); err != nil {
t.Fatal(err)
}
_, found, err := admin.GetUser(ctx, "alice")
if err != nil || found {
t.Fatalf("expected user to be deleted, err=%v", err)
}
}
func TestGetSettings_Defaults(t *testing.T) {
admin, _ := newTestAdmin(t)
prefix, defaultHide, title, err := admin.GetSettings(context.Background())
if err != nil {
t.Fatal(err)
}
if prefix != "" || defaultHide || title != "" {
t.Fatalf("expected empty defaults, got prefix=%q defaultHide=%v title=%q", prefix, defaultHide, title)
}
}
func TestUpdateSettings(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
p := "pfx"
dh := true
ti := "My Map"
if err := admin.UpdateSettings(ctx, &p, &dh, &ti); err != nil {
t.Fatal(err)
}
prefix, defaultHide, title, err := admin.GetSettings(ctx)
if err != nil {
t.Fatal(err)
}
if prefix != "pfx" {
t.Fatalf("expected pfx, got %s", prefix)
}
if !defaultHide {
t.Fatal("expected defaultHide=true")
}
if title != "My Map" {
t.Fatalf("expected My Map, got %s", title)
}
dh2 := false
if err := admin.UpdateSettings(ctx, nil, &dh2, nil); err != nil {
t.Fatal(err)
}
_, defaultHide2, _, _ := admin.GetSettings(ctx)
if defaultHide2 {
t.Fatal("expected defaultHide=false after update")
}
}
func TestListMaps_Empty(t *testing.T) {
admin, _ := newTestAdmin(t)
maps, err := admin.ListMaps(context.Background())
if err != nil {
t.Fatal(err)
}
if len(maps) != 0 {
t.Fatalf("expected 0 maps, got %d", len(maps))
}
}
func TestMapCRUD(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
if err := admin.UpdateMap(ctx, 1, "world", false, false); err != nil {
t.Fatal(err)
}
mi, found, err := admin.GetMap(ctx, 1)
if err != nil || !found || mi == nil {
t.Fatalf("expected map, err=%v", err)
}
if mi.Name != "world" {
t.Fatalf("expected world, got %s", mi.Name)
}
maps, err := admin.ListMaps(ctx)
if err != nil {
t.Fatal(err)
}
if len(maps) != 1 {
t.Fatalf("expected 1 map, got %d", len(maps))
}
}
func TestToggleMapHidden(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
admin.UpdateMap(ctx, 1, "world", false, false)
mi, err := admin.ToggleMapHidden(ctx, 1)
if err != nil {
t.Fatal(err)
}
if !mi.Hidden {
t.Fatal("expected hidden=true after toggle")
}
mi, err = admin.ToggleMapHidden(ctx, 1)
if err != nil {
t.Fatal(err)
}
if mi.Hidden {
t.Fatal("expected hidden=false after second toggle")
}
}
func TestWipe(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutGrid(tx, "g1", []byte("data"))
st.PutMap(tx, 1, []byte("data"))
st.PutTile(tx, 1, 0, "0_0", []byte("data"))
st.CreateMarkersBuckets(tx)
return nil
})
if err := admin.Wipe(ctx); err != nil {
t.Fatal(err)
}
st.View(ctx, func(tx *bbolt.Tx) error {
if st.GetGrid(tx, "g1") != nil {
t.Fatal("expected grids wiped")
}
if st.GetMap(tx, 1) != nil {
t.Fatal("expected maps wiped")
}
if st.GetTile(tx, 1, 0, "0_0") != nil {
t.Fatal("expected tiles wiped")
}
if st.GetMarkersGridBucket(tx) != nil {
t.Fatal("expected markers wiped")
}
return nil
})
}
func TestGetMap_NotFound(t *testing.T) {
admin, _ := newTestAdmin(t)
_, found, err := admin.GetMap(context.Background(), 999)
if err != nil {
t.Fatal(err)
}
if found {
t.Fatal("expected not found")
}
}
package services_test
import (
"context"
"testing"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/services"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
)
func newTestAdmin(t *testing.T) (*services.AdminService, *store.Store) {
t.Helper()
db := newTestDB(t)
st := store.New(db)
mapSvc := services.NewMapService(services.MapServiceDeps{
Store: st,
GridStorage: t.TempDir(),
GridUpdates: &app.Topic[app.TileData]{},
})
return services.NewAdminService(st, mapSvc), st
}
func TestListUsers_Empty(t *testing.T) {
admin, _ := newTestAdmin(t)
users, err := admin.ListUsers(context.Background())
if err != nil {
t.Fatal(err)
}
if len(users) != 0 {
t.Fatalf("expected 0 users, got %d", len(users))
}
}
func TestListUsers_WithUsers(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
createUser(t, st, "alice", "pass", nil)
createUser(t, st, "bob", "pass", nil)
users, err := admin.ListUsers(ctx)
if err != nil {
t.Fatal(err)
}
if len(users) != 2 {
t.Fatalf("expected 2 users, got %d", len(users))
}
}
func TestAdminGetUser_Found(t *testing.T) {
admin, st := newTestAdmin(t)
createUser(t, st, "alice", "pass", app.Auths{app.AUTH_MAP, app.AUTH_UPLOAD})
auths, found, err := admin.GetUser(context.Background(), "alice")
if err != nil || !found {
t.Fatalf("expected found, err=%v", err)
}
if !auths.Has(app.AUTH_MAP) {
t.Fatal("expected map auth")
}
}
func TestAdminGetUser_NotFound(t *testing.T) {
admin, _ := newTestAdmin(t)
_, found, err := admin.GetUser(context.Background(), "ghost")
if err != nil {
t.Fatal(err)
}
if found {
t.Fatal("expected not found")
}
}
func TestCreateOrUpdateUser_New(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
_, err := admin.CreateOrUpdateUser(ctx, "bob", "secret", app.Auths{app.AUTH_MAP})
if err != nil {
t.Fatal(err)
}
auths, found, err := admin.GetUser(ctx, "bob")
if err != nil || !found {
t.Fatalf("expected user to exist, err=%v", err)
}
if !auths.Has(app.AUTH_MAP) {
t.Fatal("expected map auth")
}
}
func TestCreateOrUpdateUser_Update(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
createUser(t, st, "alice", "old", app.Auths{app.AUTH_MAP})
_, err := admin.CreateOrUpdateUser(ctx, "alice", "new", app.Auths{app.AUTH_ADMIN, app.AUTH_MAP})
if err != nil {
t.Fatal(err)
}
auths, found, err := admin.GetUser(ctx, "alice")
if err != nil || !found {
t.Fatalf("expected user, err=%v", err)
}
if !auths.Has(app.AUTH_ADMIN) {
t.Fatal("expected admin auth after update")
}
}
func TestCreateOrUpdateUser_AdminBootstrap(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
adminCreated, err := admin.CreateOrUpdateUser(ctx, "admin", "pass", app.Auths{app.AUTH_ADMIN})
if err != nil {
t.Fatal(err)
}
if !adminCreated {
t.Fatal("expected adminCreated=true for new admin user")
}
adminCreated, err = admin.CreateOrUpdateUser(ctx, "admin", "pass2", app.Auths{app.AUTH_ADMIN})
if err != nil {
t.Fatal(err)
}
if adminCreated {
t.Fatal("expected adminCreated=false for existing admin user")
}
}
func TestDeleteUser(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
createUser(t, st, "alice", "pass", app.Auths{app.AUTH_UPLOAD})
auth := services.NewAuthService(st)
auth.GenerateTokenForUser(ctx, "alice")
if err := admin.DeleteUser(ctx, "alice"); err != nil {
t.Fatal(err)
}
_, found, err := admin.GetUser(ctx, "alice")
if err != nil || found {
t.Fatalf("expected user to be deleted, err=%v", err)
}
}
func TestGetSettings_Defaults(t *testing.T) {
admin, _ := newTestAdmin(t)
prefix, defaultHide, title, err := admin.GetSettings(context.Background())
if err != nil {
t.Fatal(err)
}
if prefix != "" || defaultHide || title != "" {
t.Fatalf("expected empty defaults, got prefix=%q defaultHide=%v title=%q", prefix, defaultHide, title)
}
}
func TestUpdateSettings(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
p := "pfx"
dh := true
ti := "My Map"
if err := admin.UpdateSettings(ctx, &p, &dh, &ti); err != nil {
t.Fatal(err)
}
prefix, defaultHide, title, err := admin.GetSettings(ctx)
if err != nil {
t.Fatal(err)
}
if prefix != "pfx" {
t.Fatalf("expected pfx, got %s", prefix)
}
if !defaultHide {
t.Fatal("expected defaultHide=true")
}
if title != "My Map" {
t.Fatalf("expected My Map, got %s", title)
}
dh2 := false
if err := admin.UpdateSettings(ctx, nil, &dh2, nil); err != nil {
t.Fatal(err)
}
_, defaultHide2, _, _ := admin.GetSettings(ctx)
if defaultHide2 {
t.Fatal("expected defaultHide=false after update")
}
}
func TestListMaps_Empty(t *testing.T) {
admin, _ := newTestAdmin(t)
maps, err := admin.ListMaps(context.Background())
if err != nil {
t.Fatal(err)
}
if len(maps) != 0 {
t.Fatalf("expected 0 maps, got %d", len(maps))
}
}
func TestMapCRUD(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
if err := admin.UpdateMap(ctx, 1, "world", false, false); err != nil {
t.Fatal(err)
}
mi, found, err := admin.GetMap(ctx, 1)
if err != nil || !found || mi == nil {
t.Fatalf("expected map, err=%v", err)
}
if mi.Name != "world" {
t.Fatalf("expected world, got %s", mi.Name)
}
maps, err := admin.ListMaps(ctx)
if err != nil {
t.Fatal(err)
}
if len(maps) != 1 {
t.Fatalf("expected 1 map, got %d", len(maps))
}
}
func TestToggleMapHidden(t *testing.T) {
admin, _ := newTestAdmin(t)
ctx := context.Background()
_ = admin.UpdateMap(ctx, 1, "world", false, false)
mi, err := admin.ToggleMapHidden(ctx, 1)
if err != nil {
t.Fatal(err)
}
if !mi.Hidden {
t.Fatal("expected hidden=true after toggle")
}
mi, err = admin.ToggleMapHidden(ctx, 1)
if err != nil {
t.Fatal(err)
}
if mi.Hidden {
t.Fatal("expected hidden=false after second toggle")
}
}
func TestWipe(t *testing.T) {
admin, st := newTestAdmin(t)
ctx := context.Background()
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutGrid(tx, "g1", []byte("data")); err != nil {
return err
}
if err := st.PutMap(tx, 1, []byte("data")); err != nil {
return err
}
if err := st.PutTile(tx, 1, 0, "0_0", []byte("data")); err != nil {
return err
}
_, _, err := st.CreateMarkersBuckets(tx)
return err
}); err != nil {
t.Fatal(err)
}
if err := admin.Wipe(ctx); err != nil {
t.Fatal(err)
}
if err := st.View(ctx, func(tx *bbolt.Tx) error {
if st.GetGrid(tx, "g1") != nil {
t.Fatal("expected grids wiped")
}
if st.GetMap(tx, 1) != nil {
t.Fatal("expected maps wiped")
}
if st.GetTile(tx, 1, 0, "0_0") != nil {
t.Fatal("expected tiles wiped")
}
if st.GetMarkersGridBucket(tx) != nil {
t.Fatal("expected markers wiped")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestGetMap_NotFound(t *testing.T) {
admin, _ := newTestAdmin(t)
_, found, err := admin.GetMap(context.Background(), 999)
if err != nil {
t.Fatal(err)
}
if found {
t.Fatal("expected not found")
}
}

View File

@@ -53,7 +53,7 @@ func (s *AuthService) GetSession(ctx context.Context, req *http.Request) *app.Se
return nil
}
var sess *app.Session
s.st.View(ctx, func(tx *bbolt.Tx) error {
if err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetSession(tx, c.Value)
if raw == nil {
return nil
@@ -77,7 +77,9 @@ func (s *AuthService) GetSession(ctx context.Context, req *http.Request) *app.Se
}
sess.Auths = u.Auths
return nil
})
}); err != nil {
return nil
}
return sess
}
@@ -165,7 +167,7 @@ func (s *AuthService) GetUserByUsername(ctx context.Context, username string) *a
// SetupRequired returns true if no users exist (first run).
func (s *AuthService) SetupRequired(ctx context.Context) bool {
var required bool
s.st.View(ctx, func(tx *bbolt.Tx) error {
_ = s.st.View(ctx, func(tx *bbolt.Tx) error {
if s.st.UserCount(tx) == 0 {
required = true
}
@@ -181,7 +183,7 @@ func (s *AuthService) BootstrapAdmin(ctx context.Context, username, pass, bootst
}
var created bool
var u *app.User
s.st.Update(ctx, func(tx *bbolt.Tx) error {
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
if s.st.GetUser(tx, "admin") != nil {
return nil
}
@@ -200,7 +202,9 @@ func (s *AuthService) BootstrapAdmin(ctx context.Context, username, pass, bootst
created = true
u = &user
return nil
})
}); err != nil {
return nil
}
if created {
return u
}
@@ -239,7 +243,7 @@ func (s *AuthService) GenerateTokenForUser(ctx context.Context, username string)
}
token := hex.EncodeToString(tokenRaw)
var tokens []string
s.st.Update(ctx, func(tx *bbolt.Tx) error {
_ = s.st.Update(ctx, func(tx *bbolt.Tx) error {
uRaw := s.st.GetUser(tx, username)
u := app.User{}
if uRaw != nil {
@@ -250,7 +254,9 @@ func (s *AuthService) GenerateTokenForUser(ctx context.Context, username string)
u.Tokens = append(u.Tokens, token)
tokens = u.Tokens
buf, _ := json.Marshal(u)
s.st.PutUser(tx, username, buf)
if err := s.st.PutUser(tx, username, buf); err != nil {
return err
}
return s.st.PutToken(tx, token, username)
})
return tokens
@@ -522,7 +528,9 @@ func (s *AuthService) findOrCreateOAuthUser(ctx context.Context, provider, sub,
user.Email = email
}
raw, _ = json.Marshal(user)
s.st.PutUser(tx, username, raw)
if err := s.st.PutUser(tx, username, raw); err != nil {
return err
}
}
return nil
}

View File

@@ -41,9 +41,11 @@ func createUser(t *testing.T, st *store.Store, username, password string, auths
}
u := app.User{Pass: hash, Auths: auths}
raw, _ := json.Marshal(u)
st.Update(context.Background(), func(tx *bbolt.Tx) error {
if err := st.Update(context.Background(), func(tx *bbolt.Tx) error {
return st.PutUser(tx, username, raw)
})
}); err != nil {
t.Fatal(err)
}
}
func TestSetupRequired_EmptyDB(t *testing.T) {
@@ -246,9 +248,11 @@ func TestGetUserTokensAndPrefix(t *testing.T) {
ctx := context.Background()
createUser(t, st, "alice", "pass", app.Auths{app.AUTH_UPLOAD})
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutConfig(tx, "prefix", []byte("myprefix"))
})
}); err != nil {
t.Fatal(err)
}
auth.GenerateTokenForUser(ctx, "alice")
tokens, prefix := auth.GetUserTokensAndPrefix(ctx, "alice")
@@ -288,9 +292,11 @@ func TestValidateClientToken_NoUploadPerm(t *testing.T) {
ctx := context.Background()
createUser(t, st, "alice", "pass", app.Auths{app.AUTH_MAP})
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutToken(tx, "tok123", "alice")
})
}); err != nil {
t.Fatal(err)
}
_, err := auth.ValidateClientToken(ctx, "tok123")
if err == nil {

File diff suppressed because it is too large Load Diff

View File

@@ -1,91 +1,121 @@
package services_test
import (
"context"
"encoding/json"
"testing"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/services"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
)
func TestFixMultipartContentType_NeedsQuoting(t *testing.T) {
ct := "multipart/form-data; boundary=----WebKitFormBoundary=abc123"
got := services.FixMultipartContentType(ct)
want := `multipart/form-data; boundary="----WebKitFormBoundary=abc123"`
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFixMultipartContentType_AlreadyQuoted(t *testing.T) {
ct := `multipart/form-data; boundary="----WebKitFormBoundary"`
got := services.FixMultipartContentType(ct)
if got != ct {
t.Fatalf("expected unchanged, got %q", got)
}
}
func TestFixMultipartContentType_Normal(t *testing.T) {
ct := "multipart/form-data; boundary=----WebKitFormBoundary"
got := services.FixMultipartContentType(ct)
if got != ct {
t.Fatalf("expected unchanged, got %q", got)
}
}
func newTestClientService(t *testing.T) (*services.ClientService, *store.Store) {
t.Helper()
db := newTestDB(t)
st := store.New(db)
mapSvc := services.NewMapService(services.MapServiceDeps{
Store: st,
GridStorage: t.TempDir(),
GridUpdates: &app.Topic[app.TileData]{},
})
client := services.NewClientService(services.ClientServiceDeps{
Store: st,
MapSvc: mapSvc,
WithChars: func(fn func(chars map[string]app.Character)) { fn(map[string]app.Character{}) },
})
return client, st
}
func TestClientLocate_Found(t *testing.T) {
client, st := newTestClientService(t)
ctx := context.Background()
gd := app.GridData{ID: "g1", Map: 1, Coord: app.Coord{X: 2, Y: 3}}
raw, _ := json.Marshal(gd)
st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutGrid(tx, "g1", raw)
})
result, err := client.Locate(ctx, "g1")
if err != nil {
t.Fatal(err)
}
if result != "1;2;3" {
t.Fatalf("expected 1;2;3, got %q", result)
}
}
func TestClientLocate_NotFound(t *testing.T) {
client, _ := newTestClientService(t)
_, err := client.Locate(context.Background(), "ghost")
if err == nil {
t.Fatal("expected error for unknown grid")
}
}
func TestClientProcessGridUpdate_EmptyGrids(t *testing.T) {
client, _ := newTestClientService(t)
ctx := context.Background()
result, err := client.ProcessGridUpdate(ctx, services.GridUpdate{Grids: [][]string{}})
if err != nil {
t.Fatal(err)
}
if result == nil {
t.Fatal("expected non-nil result")
}
}
package services_test
import (
"context"
"encoding/json"
"testing"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/services"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
)
func TestFixMultipartContentType_NeedsQuoting(t *testing.T) {
ct := "multipart/form-data; boundary=----WebKitFormBoundary=abc123"
got := services.FixMultipartContentType(ct)
want := `multipart/form-data; boundary="----WebKitFormBoundary=abc123"`
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFixMultipartContentType_AlreadyQuoted(t *testing.T) {
ct := `multipart/form-data; boundary="----WebKitFormBoundary"`
got := services.FixMultipartContentType(ct)
if got != ct {
t.Fatalf("expected unchanged, got %q", got)
}
}
func TestFixMultipartContentType_Normal(t *testing.T) {
ct := "multipart/form-data; boundary=----WebKitFormBoundary"
got := services.FixMultipartContentType(ct)
if got != ct {
t.Fatalf("expected unchanged, got %q", got)
}
}
func newTestClientService(t *testing.T) (*services.ClientService, *store.Store) {
t.Helper()
db := newTestDB(t)
st := store.New(db)
mapSvc := services.NewMapService(services.MapServiceDeps{
Store: st,
GridStorage: t.TempDir(),
GridUpdates: &app.Topic[app.TileData]{},
})
client := services.NewClientService(services.ClientServiceDeps{
Store: st,
MapSvc: mapSvc,
WithChars: func(fn func(chars map[string]app.Character)) { fn(map[string]app.Character{}) },
})
return client, st
}
func TestClientLocate_Found(t *testing.T) {
client, st := newTestClientService(t)
ctx := context.Background()
gd := app.GridData{ID: "g1", Map: 1, Coord: app.Coord{X: 2, Y: 3}}
raw, _ := json.Marshal(gd)
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutGrid(tx, "g1", raw)
}); err != nil {
t.Fatal(err)
}
result, err := client.Locate(ctx, "g1")
if err != nil {
t.Fatal(err)
}
if result != "1;2;3" {
t.Fatalf("expected 1;2;3, got %q", result)
}
}
func TestClientLocate_NotFound(t *testing.T) {
client, _ := newTestClientService(t)
_, err := client.Locate(context.Background(), "ghost")
if err == nil {
t.Fatal("expected error for unknown grid")
}
}
func TestClientProcessGridUpdate_EmptyGrids(t *testing.T) {
client, _ := newTestClientService(t)
ctx := context.Background()
result, err := client.ProcessGridUpdate(ctx, services.GridUpdate{Grids: [][]string{}})
if err != nil {
t.Fatal(err)
}
if result == nil {
t.Fatal("expected non-nil result")
}
}
func TestUploadMarkers_NormalizesCaveImage(t *testing.T) {
client, st := newTestClientService(t)
ctx := context.Background()
body := []byte(`[{"Name":"Cave","GridID":"g1","X":10,"Y":20,"Image":"gfx/terobjs/mm/custom"}]`)
if err := client.UploadMarkers(ctx, body); err != nil {
t.Fatal(err)
}
var stored app.Marker
if err := st.View(ctx, func(tx *bbolt.Tx) error {
grid := st.GetMarkersGridBucket(tx)
if grid == nil {
t.Fatal("markers grid bucket not found")
return nil
}
v := grid.Get([]byte("g1_10_20"))
if v == nil {
t.Fatal("marker g1_10_20 not found")
return nil
}
return json.Unmarshal(v, &stored)
}); err != nil {
t.Fatal(err)
}
if stored.Image != "gfx/terobjs/mm/cave" {
t.Fatalf("expected stored marker Image gfx/terobjs/mm/cave, got %q", stored.Image)
}
}

View File

@@ -111,7 +111,7 @@ func (s *ExportService) Export(ctx context.Context, w io.Writer) error {
if markersb != nil {
markersgrid := markersb.Bucket(store.BucketMarkersGrid)
if markersgrid != nil {
markersgrid.ForEach(func(k, v []byte) error {
if err := markersgrid.ForEach(func(k, v []byte) error {
select {
case <-ctx.Done():
return ctx.Err()
@@ -125,7 +125,9 @@ func (s *ExportService) Export(ctx context.Context, w io.Writer) error {
maps[gridMap[marker.GridID]].Markers[marker.GridID] = append(maps[gridMap[marker.GridID]].Markers[marker.GridID], marker)
}
return nil
})
}); err != nil {
return err
}
}
}
return nil
@@ -218,7 +220,11 @@ func (s *ExportService) Merge(ctx context.Context, zr *zip.Reader) error {
f.Close()
return err
}
io.Copy(f, r)
if _, err := io.Copy(f, r); err != nil {
r.Close()
f.Close()
return err
}
r.Close()
f.Close()
newTiles[strings.TrimSuffix(filepath.Base(fhdr.Name), ".png")] = struct{}{}
@@ -290,8 +296,12 @@ func (s *ExportService) processMergeJSON(
Image: img,
}
raw, _ := json.Marshal(m)
mgrid.Put(key, raw)
idB.Put(idKey, key)
if err := mgrid.Put(key, raw); err != nil {
return err
}
if err := idB.Put(idKey, key); err != nil {
return err
}
}
}
@@ -333,7 +343,9 @@ func (s *ExportService) processMergeJSON(
if err != nil {
return err
}
grids.Put([]byte(grid), raw)
if err := grids.Put([]byte(grid), raw); err != nil {
return err
}
}
return nil
}
@@ -372,11 +384,13 @@ func (s *ExportService) processMergeJSON(
if err != nil {
return err
}
grids.Put([]byte(grid), raw)
if err := grids.Put([]byte(grid), raw); err != nil {
return err
}
}
if len(existingMaps) > 1 {
grids.ForEach(func(k, v []byte) error {
if err := grids.ForEach(func(k, v []byte) error {
gd := app.GridData{}
if err := json.Unmarshal(v, &gd); err != nil {
return err
@@ -413,16 +427,22 @@ func (s *ExportService) processMergeJSON(
File: td.File,
})
}
grids.Put(k, raw)
if err := grids.Put(k, raw); err != nil {
return err
}
}
return nil
})
}); err != nil {
return err
}
}
for mergeid, merge := range existingMaps {
if mapid == mergeid {
continue
}
mapB.Delete([]byte(strconv.Itoa(mergeid)))
if err := mapB.Delete([]byte(strconv.Itoa(mergeid))); err != nil {
return err
}
slog.Info("reporting merge", "from", mergeid, "to", mapid)
s.mapSvc.ReportMerge(mergeid, mapid, app.Coord{X: offset.X - merge.X, Y: offset.Y - merge.Y})
}

View File

@@ -47,12 +47,14 @@ func TestExport_WithGrid(t *testing.T) {
gdRaw, _ := json.Marshal(gd)
mi := app.MapInfo{ID: 1, Name: "test", Hidden: false}
miRaw, _ := json.Marshal(mi)
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutGrid(tx, "g1", gdRaw); err != nil {
return err
}
return st.PutMap(tx, 1, miRaw)
})
}); err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
err := export.Export(ctx, &buf)
if err != nil {

View File

@@ -1,418 +1,422 @@
package services
import (
"context"
"encoding/json"
"fmt"
"image"
"image/png"
"log/slog"
"os"
"path/filepath"
"strconv"
"time"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
"golang.org/x/image/draw"
)
type zoomproc struct {
c app.Coord
m int
}
// MapService handles map, markers, grids, tiles business logic.
type MapService struct {
st *store.Store
gridStorage string
gridUpdates *app.Topic[app.TileData]
mergeUpdates *app.Topic[app.Merge]
getChars func() []app.Character
}
// MapServiceDeps holds dependencies for MapService construction.
type MapServiceDeps struct {
Store *store.Store
GridStorage string
GridUpdates *app.Topic[app.TileData]
MergeUpdates *app.Topic[app.Merge]
GetChars func() []app.Character
}
// NewMapService creates a MapService with the given dependencies.
func NewMapService(d MapServiceDeps) *MapService {
return &MapService{
st: d.Store,
gridStorage: d.GridStorage,
gridUpdates: d.GridUpdates,
mergeUpdates: d.MergeUpdates,
getChars: d.GetChars,
}
}
// GridStorage returns the grid storage directory path.
func (s *MapService) GridStorage() string { return s.gridStorage }
// GetCharacters returns all current characters.
func (s *MapService) GetCharacters() []app.Character {
if s.getChars == nil {
return nil
}
return s.getChars()
}
// GetMarkers returns all markers with computed map positions.
func (s *MapService) GetMarkers(ctx context.Context) ([]app.FrontendMarker, error) {
var markers []app.FrontendMarker
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
grid := s.st.GetMarkersGridBucket(tx)
if grid == nil {
return nil
}
grids := tx.Bucket(store.BucketGrids)
if grids == nil {
return nil
}
return grid.ForEach(func(k, v []byte) error {
marker := app.Marker{}
if err := json.Unmarshal(v, &marker); err != nil {
return err
}
graw := grids.Get([]byte(marker.GridID))
if graw == nil {
return nil
}
g := app.GridData{}
if err := json.Unmarshal(graw, &g); err != nil {
return err
}
markers = append(markers, app.FrontendMarker{
Image: marker.Image,
Hidden: marker.Hidden,
ID: marker.ID,
Name: marker.Name,
Map: g.Map,
Position: app.Position{
X: marker.Position.X + g.Coord.X*app.GridSize,
Y: marker.Position.Y + g.Coord.Y*app.GridSize,
},
})
return nil
})
})
return markers, err
}
// GetMaps returns all maps, optionally including hidden ones.
func (s *MapService) GetMaps(ctx context.Context, showHidden bool) (map[int]*app.MapInfo, error) {
maps := make(map[int]*app.MapInfo)
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachMap(tx, func(k, v []byte) error {
mapid, err := strconv.Atoi(string(k))
if err != nil {
return nil
}
mi := &app.MapInfo{}
if err := json.Unmarshal(v, mi); err != nil {
return err
}
if mi.Hidden && !showHidden {
return nil
}
maps[mapid] = mi
return nil
})
})
return maps, err
}
// GetConfig returns the application config for the frontend.
func (s *MapService) GetConfig(ctx context.Context, auths app.Auths) (app.Config, error) {
config := app.Config{Auths: auths}
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
title := s.st.GetConfig(tx, "title")
if title != nil {
config.Title = string(title)
}
return nil
})
return config, err
}
// GetPage returns page metadata (title).
func (s *MapService) GetPage(ctx context.Context) (app.Page, error) {
p := app.Page{}
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
title := s.st.GetConfig(tx, "title")
if title != nil {
p.Title = string(title)
}
return nil
})
return p, err
}
// GetGrid returns a grid by its ID.
func (s *MapService) GetGrid(ctx context.Context, id string) (*app.GridData, error) {
var gd *app.GridData
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetGrid(tx, id)
if raw == nil {
return nil
}
gd = &app.GridData{}
return json.Unmarshal(raw, gd)
})
return gd, err
}
// GetTile returns a tile by map ID, coordinate, and zoom level.
func (s *MapService) GetTile(ctx context.Context, mapID int, c app.Coord, zoom int) *app.TileData {
var td *app.TileData
if err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetTile(tx, mapID, zoom, c.Name())
if raw != nil {
td = &app.TileData{}
return json.Unmarshal(raw, td)
}
return nil
}); err != nil {
return nil
}
return td
}
// getSubTiles returns up to 4 tile data for the given parent coord at zoom z-1 (sub-tiles at z).
// Order: (0,0), (1,0), (0,1), (1,1) to match the 2x2 loop in UpdateZoomLevel.
func (s *MapService) getSubTiles(ctx context.Context, mapid int, c app.Coord, z int) []*app.TileData {
coords := []app.Coord{
{X: c.X*2 + 0, Y: c.Y*2 + 0},
{X: c.X*2 + 1, Y: c.Y*2 + 0},
{X: c.X*2 + 0, Y: c.Y*2 + 1},
{X: c.X*2 + 1, Y: c.Y*2 + 1},
}
keys := make([]string, len(coords))
for i := range coords {
keys[i] = coords[i].Name()
}
var rawMap map[string][]byte
if err := s.st.View(ctx, func(tx *bbolt.Tx) error {
rawMap = s.st.GetTiles(tx, mapid, z-1, keys)
return nil
}); err != nil {
return nil
}
result := make([]*app.TileData, 4)
for i, k := range keys {
if raw, ok := rawMap[k]; ok && len(raw) > 0 {
td := &app.TileData{}
if json.Unmarshal(raw, td) == nil {
result[i] = td
}
}
}
return result
}
// SaveTile persists a tile and broadcasts the update.
func (s *MapService) SaveTile(ctx context.Context, mapid int, c app.Coord, z int, f string, t int64) {
s.st.Update(ctx, func(tx *bbolt.Tx) error {
td := &app.TileData{
MapID: mapid,
Coord: c,
Zoom: z,
File: f,
Cache: t,
}
raw, err := json.Marshal(td)
if err != nil {
return err
}
s.gridUpdates.Send(td)
return s.st.PutTile(tx, mapid, z, c.Name(), raw)
})
}
// UpdateZoomLevel composes a zoom tile from 4 sub-tiles (one View for all 4 tile reads).
func (s *MapService) UpdateZoomLevel(ctx context.Context, mapid int, c app.Coord, z int) {
subTiles := s.getSubTiles(ctx, mapid, c, z)
img := image.NewNRGBA(image.Rect(0, 0, app.GridSize, app.GridSize))
draw.Draw(img, img.Bounds(), image.Transparent, image.Point{}, draw.Src)
for i := 0; i < 4; i++ {
td := subTiles[i]
if td == nil || td.File == "" {
continue
}
x := i % 2
y := i / 2
subf, err := os.Open(filepath.Join(s.gridStorage, td.File))
if err != nil {
continue
}
subimg, _, err := image.Decode(subf)
subf.Close()
if err != nil {
continue
}
draw.BiLinear.Scale(img, image.Rect(50*x, 50*y, 50*x+50, 50*y+50), subimg, subimg.Bounds(), draw.Src, nil)
}
if err := os.MkdirAll(fmt.Sprintf("%s/%d/%d", s.gridStorage, mapid, z), 0755); err != nil {
slog.Error("failed to create zoom dir", "error", err)
return
}
path := fmt.Sprintf("%s/%d/%d/%s.png", s.gridStorage, mapid, z, c.Name())
relPath := fmt.Sprintf("%d/%d/%s.png", mapid, z, c.Name())
f, err := os.Create(path)
if err != nil {
slog.Error("failed to create tile file", "path", path, "error", err)
return
}
if err := png.Encode(f, img); err != nil {
f.Close()
os.Remove(path)
slog.Error("failed to encode tile PNG", "path", path, "error", err)
return
}
if err := f.Close(); err != nil {
slog.Error("failed to close tile file", "path", path, "error", err)
return
}
s.SaveTile(ctx, mapid, c, z, relPath, time.Now().UnixNano())
}
// RebuildZooms rebuilds all zoom levels from base tiles.
// It can take a long time for many grids; the client should account for request timeouts.
func (s *MapService) RebuildZooms(ctx context.Context) error {
needProcess := map[zoomproc]struct{}{}
saveGrid := map[zoomproc]string{}
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
b := tx.Bucket(store.BucketGrids)
if b == nil {
return nil
}
b.ForEach(func(k, v []byte) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
grid := app.GridData{}
if err := json.Unmarshal(v, &grid); err != nil {
return err
}
needProcess[zoomproc{grid.Coord.Parent(), grid.Map}] = struct{}{}
saveGrid[zoomproc{grid.Coord, grid.Map}] = grid.ID
return nil
})
tx.DeleteBucket(store.BucketTiles)
return nil
}); err != nil {
slog.Error("RebuildZooms: failed to update store", "error", err)
return err
}
for g, id := range saveGrid {
if ctx.Err() != nil {
return ctx.Err()
}
f := fmt.Sprintf("%s/grids/%s.png", s.gridStorage, id)
if _, err := os.Stat(f); err != nil {
continue
}
s.SaveTile(ctx, g.m, g.c, 0, fmt.Sprintf("grids/%s.png", id), time.Now().UnixNano())
}
for z := 1; z <= app.MaxZoomLevel; z++ {
if ctx.Err() != nil {
return ctx.Err()
}
process := needProcess
needProcess = map[zoomproc]struct{}{}
for p := range process {
s.UpdateZoomLevel(ctx, p.m, p.c, z)
needProcess[zoomproc{p.c.Parent(), p.m}] = struct{}{}
}
}
return nil
}
// ReportMerge sends a merge event.
func (s *MapService) ReportMerge(from, to int, shift app.Coord) {
s.mergeUpdates.Send(&app.Merge{
From: from,
To: to,
Shift: shift,
})
}
// WatchTiles creates a channel that receives tile updates.
func (s *MapService) WatchTiles() chan *app.TileData {
c := make(chan *app.TileData, app.SSETileChannelSize)
s.gridUpdates.Watch(c)
return c
}
// WatchMerges creates a channel that receives merge updates.
func (s *MapService) WatchMerges() chan *app.Merge {
c := make(chan *app.Merge, app.SSEMergeChannelSize)
s.mergeUpdates.Watch(c)
return c
}
// GetAllTileCache returns all tiles for the initial SSE cache dump.
func (s *MapService) GetAllTileCache(ctx context.Context) []TileCache {
var cache []TileCache
s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachTile(tx, func(mapK, zoomK, coordK, v []byte) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
td := app.TileData{}
if err := json.Unmarshal(v, &td); err != nil {
return err
}
cache = append(cache, TileCache{
M: td.MapID,
X: td.Coord.X,
Y: td.Coord.Y,
Z: td.Zoom,
T: int(td.Cache),
})
return nil
})
})
return cache
}
// TileCache represents a minimal tile entry for SSE streaming.
type TileCache struct {
M, X, Y, Z, T int
}
// ProcessZoomLevels processes zoom levels for a set of tile operations.
func (s *MapService) ProcessZoomLevels(ctx context.Context, ops []TileOp) {
needProcess := map[zoomproc]struct{}{}
for _, op := range ops {
s.SaveTile(ctx, op.MapID, app.Coord{X: op.X, Y: op.Y}, 0, op.File, time.Now().UnixNano())
needProcess[zoomproc{c: app.Coord{X: op.X, Y: op.Y}.Parent(), m: op.MapID}] = struct{}{}
}
for z := 1; z <= app.MaxZoomLevel; z++ {
process := needProcess
needProcess = map[zoomproc]struct{}{}
for p := range process {
s.UpdateZoomLevel(ctx, p.m, p.c, z)
needProcess[zoomproc{p.c.Parent(), p.m}] = struct{}{}
}
}
}
// TileOp represents a tile save operation.
type TileOp struct {
MapID int
X, Y int
File string
}
package services
import (
"context"
"encoding/json"
"fmt"
"image"
"image/png"
"log/slog"
"os"
"path/filepath"
"strconv"
"time"
"github.com/andyleap/hnh-map/internal/app"
"github.com/andyleap/hnh-map/internal/app/store"
"go.etcd.io/bbolt"
"golang.org/x/image/draw"
)
type zoomproc struct {
c app.Coord
m int
}
// MapService handles map, markers, grids, tiles business logic.
type MapService struct {
st *store.Store
gridStorage string
gridUpdates *app.Topic[app.TileData]
mergeUpdates *app.Topic[app.Merge]
getChars func() []app.Character
}
// MapServiceDeps holds dependencies for MapService construction.
type MapServiceDeps struct {
Store *store.Store
GridStorage string
GridUpdates *app.Topic[app.TileData]
MergeUpdates *app.Topic[app.Merge]
GetChars func() []app.Character
}
// NewMapService creates a MapService with the given dependencies.
func NewMapService(d MapServiceDeps) *MapService {
return &MapService{
st: d.Store,
gridStorage: d.GridStorage,
gridUpdates: d.GridUpdates,
mergeUpdates: d.MergeUpdates,
getChars: d.GetChars,
}
}
// GridStorage returns the grid storage directory path.
func (s *MapService) GridStorage() string { return s.gridStorage }
// GetCharacters returns all current characters.
func (s *MapService) GetCharacters() []app.Character {
if s.getChars == nil {
return nil
}
return s.getChars()
}
// GetMarkers returns all markers with computed map positions.
func (s *MapService) GetMarkers(ctx context.Context) ([]app.FrontendMarker, error) {
var markers []app.FrontendMarker
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
grid := s.st.GetMarkersGridBucket(tx)
if grid == nil {
return nil
}
grids := tx.Bucket(store.BucketGrids)
if grids == nil {
return nil
}
return grid.ForEach(func(k, v []byte) error {
marker := app.Marker{}
if err := json.Unmarshal(v, &marker); err != nil {
return err
}
graw := grids.Get([]byte(marker.GridID))
if graw == nil {
return nil
}
g := app.GridData{}
if err := json.Unmarshal(graw, &g); err != nil {
return err
}
markers = append(markers, app.FrontendMarker{
Image: marker.Image,
Hidden: marker.Hidden,
ID: marker.ID,
Name: marker.Name,
Map: g.Map,
Position: app.Position{
X: marker.Position.X + g.Coord.X*app.GridSize,
Y: marker.Position.Y + g.Coord.Y*app.GridSize,
},
})
return nil
})
})
return markers, err
}
// GetMaps returns all maps, optionally including hidden ones.
func (s *MapService) GetMaps(ctx context.Context, showHidden bool) (map[int]*app.MapInfo, error) {
maps := make(map[int]*app.MapInfo)
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachMap(tx, func(k, v []byte) error {
mapid, err := strconv.Atoi(string(k))
if err != nil {
return nil
}
mi := &app.MapInfo{}
if err := json.Unmarshal(v, mi); err != nil {
return err
}
if mi.Hidden && !showHidden {
return nil
}
maps[mapid] = mi
return nil
})
})
return maps, err
}
// GetConfig returns the application config for the frontend.
func (s *MapService) GetConfig(ctx context.Context, auths app.Auths) (app.Config, error) {
config := app.Config{Auths: auths}
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
title := s.st.GetConfig(tx, "title")
if title != nil {
config.Title = string(title)
}
return nil
})
return config, err
}
// GetPage returns page metadata (title).
func (s *MapService) GetPage(ctx context.Context) (app.Page, error) {
p := app.Page{}
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
title := s.st.GetConfig(tx, "title")
if title != nil {
p.Title = string(title)
}
return nil
})
return p, err
}
// GetGrid returns a grid by its ID.
func (s *MapService) GetGrid(ctx context.Context, id string) (*app.GridData, error) {
var gd *app.GridData
err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetGrid(tx, id)
if raw == nil {
return nil
}
gd = &app.GridData{}
return json.Unmarshal(raw, gd)
})
return gd, err
}
// GetTile returns a tile by map ID, coordinate, and zoom level.
func (s *MapService) GetTile(ctx context.Context, mapID int, c app.Coord, zoom int) *app.TileData {
var td *app.TileData
if err := s.st.View(ctx, func(tx *bbolt.Tx) error {
raw := s.st.GetTile(tx, mapID, zoom, c.Name())
if raw != nil {
td = &app.TileData{}
return json.Unmarshal(raw, td)
}
return nil
}); err != nil {
return nil
}
return td
}
// getSubTiles returns up to 4 tile data for the given parent coord at zoom z-1 (sub-tiles at z).
// Order: (0,0), (1,0), (0,1), (1,1) to match the 2x2 loop in UpdateZoomLevel.
func (s *MapService) getSubTiles(ctx context.Context, mapid int, c app.Coord, z int) []*app.TileData {
coords := []app.Coord{
{X: c.X*2 + 0, Y: c.Y*2 + 0},
{X: c.X*2 + 1, Y: c.Y*2 + 0},
{X: c.X*2 + 0, Y: c.Y*2 + 1},
{X: c.X*2 + 1, Y: c.Y*2 + 1},
}
keys := make([]string, len(coords))
for i := range coords {
keys[i] = coords[i].Name()
}
var rawMap map[string][]byte
if err := s.st.View(ctx, func(tx *bbolt.Tx) error {
rawMap = s.st.GetTiles(tx, mapid, z-1, keys)
return nil
}); err != nil {
return nil
}
result := make([]*app.TileData, 4)
for i, k := range keys {
if raw, ok := rawMap[k]; ok && len(raw) > 0 {
td := &app.TileData{}
if json.Unmarshal(raw, td) == nil {
result[i] = td
}
}
}
return result
}
// SaveTile persists a tile and broadcasts the update.
func (s *MapService) SaveTile(ctx context.Context, mapid int, c app.Coord, z int, f string, t int64) {
_ = s.st.Update(ctx, func(tx *bbolt.Tx) error {
td := &app.TileData{
MapID: mapid,
Coord: c,
Zoom: z,
File: f,
Cache: t,
}
raw, err := json.Marshal(td)
if err != nil {
return err
}
s.gridUpdates.Send(td)
return s.st.PutTile(tx, mapid, z, c.Name(), raw)
})
}
// UpdateZoomLevel composes a zoom tile from 4 sub-tiles (one View for all 4 tile reads).
func (s *MapService) UpdateZoomLevel(ctx context.Context, mapid int, c app.Coord, z int) {
subTiles := s.getSubTiles(ctx, mapid, c, z)
img := image.NewNRGBA(image.Rect(0, 0, app.GridSize, app.GridSize))
draw.Draw(img, img.Bounds(), image.Transparent, image.Point{}, draw.Src)
for i := 0; i < 4; i++ {
td := subTiles[i]
if td == nil || td.File == "" {
continue
}
x := i % 2
y := i / 2
subf, err := os.Open(filepath.Join(s.gridStorage, td.File))
if err != nil {
continue
}
subimg, _, err := image.Decode(subf)
subf.Close()
if err != nil {
continue
}
draw.BiLinear.Scale(img, image.Rect(50*x, 50*y, 50*x+50, 50*y+50), subimg, subimg.Bounds(), draw.Src, nil)
}
if err := os.MkdirAll(fmt.Sprintf("%s/%d/%d", s.gridStorage, mapid, z), 0755); err != nil {
slog.Error("failed to create zoom dir", "error", err)
return
}
path := fmt.Sprintf("%s/%d/%d/%s.png", s.gridStorage, mapid, z, c.Name())
relPath := fmt.Sprintf("%d/%d/%s.png", mapid, z, c.Name())
f, err := os.Create(path)
if err != nil {
slog.Error("failed to create tile file", "path", path, "error", err)
return
}
if err := png.Encode(f, img); err != nil {
f.Close()
os.Remove(path)
slog.Error("failed to encode tile PNG", "path", path, "error", err)
return
}
if err := f.Close(); err != nil {
slog.Error("failed to close tile file", "path", path, "error", err)
return
}
s.SaveTile(ctx, mapid, c, z, relPath, time.Now().UnixNano())
}
// RebuildZooms rebuilds all zoom levels from base tiles.
// It can take a long time for many grids; the client should account for request timeouts.
func (s *MapService) RebuildZooms(ctx context.Context) error {
needProcess := map[zoomproc]struct{}{}
saveGrid := map[zoomproc]string{}
if err := s.st.Update(ctx, func(tx *bbolt.Tx) error {
b := tx.Bucket(store.BucketGrids)
if b == nil {
return nil
}
if err := b.ForEach(func(k, v []byte) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
grid := app.GridData{}
if err := json.Unmarshal(v, &grid); err != nil {
return err
}
needProcess[zoomproc{grid.Coord.Parent(), grid.Map}] = struct{}{}
saveGrid[zoomproc{grid.Coord, grid.Map}] = grid.ID
return nil
}); err != nil {
return err
}
if err := tx.DeleteBucket(store.BucketTiles); err != nil {
return err
}
return nil
}); err != nil {
slog.Error("RebuildZooms: failed to update store", "error", err)
return err
}
for g, id := range saveGrid {
if ctx.Err() != nil {
return ctx.Err()
}
f := fmt.Sprintf("%s/grids/%s.png", s.gridStorage, id)
if _, err := os.Stat(f); err != nil {
continue
}
s.SaveTile(ctx, g.m, g.c, 0, fmt.Sprintf("grids/%s.png", id), time.Now().UnixNano())
}
for z := 1; z <= app.MaxZoomLevel; z++ {
if ctx.Err() != nil {
return ctx.Err()
}
process := needProcess
needProcess = map[zoomproc]struct{}{}
for p := range process {
s.UpdateZoomLevel(ctx, p.m, p.c, z)
needProcess[zoomproc{p.c.Parent(), p.m}] = struct{}{}
}
}
return nil
}
// ReportMerge sends a merge event.
func (s *MapService) ReportMerge(from, to int, shift app.Coord) {
s.mergeUpdates.Send(&app.Merge{
From: from,
To: to,
Shift: shift,
})
}
// WatchTiles creates a channel that receives tile updates.
func (s *MapService) WatchTiles() chan *app.TileData {
c := make(chan *app.TileData, app.SSETileChannelSize)
s.gridUpdates.Watch(c)
return c
}
// WatchMerges creates a channel that receives merge updates.
func (s *MapService) WatchMerges() chan *app.Merge {
c := make(chan *app.Merge, app.SSEMergeChannelSize)
s.mergeUpdates.Watch(c)
return c
}
// GetAllTileCache returns all tiles for the initial SSE cache dump.
func (s *MapService) GetAllTileCache(ctx context.Context) []TileCache {
var cache []TileCache
_ = s.st.View(ctx, func(tx *bbolt.Tx) error {
return s.st.ForEachTile(tx, func(mapK, zoomK, coordK, v []byte) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
td := app.TileData{}
if err := json.Unmarshal(v, &td); err != nil {
return err
}
cache = append(cache, TileCache{
M: td.MapID,
X: td.Coord.X,
Y: td.Coord.Y,
Z: td.Zoom,
T: int(td.Cache),
})
return nil
})
})
return cache
}
// TileCache represents a minimal tile entry for SSE streaming.
type TileCache struct {
M, X, Y, Z, T int
}
// ProcessZoomLevels processes zoom levels for a set of tile operations.
func (s *MapService) ProcessZoomLevels(ctx context.Context, ops []TileOp) {
needProcess := map[zoomproc]struct{}{}
for _, op := range ops {
s.SaveTile(ctx, op.MapID, app.Coord{X: op.X, Y: op.Y}, 0, op.File, time.Now().UnixNano())
needProcess[zoomproc{c: app.Coord{X: op.X, Y: op.Y}.Parent(), m: op.MapID}] = struct{}{}
}
for z := 1; z <= app.MaxZoomLevel; z++ {
process := needProcess
needProcess = map[zoomproc]struct{}{}
for p := range process {
s.UpdateZoomLevel(ctx, p.m, p.c, z)
needProcess[zoomproc{p.c.Parent(), p.m}] = struct{}{}
}
}
}
// TileOp represents a tile save operation.
type TileOp struct {
MapID int
X, Y int
File string
}

View File

@@ -57,9 +57,11 @@ func TestGetConfig(t *testing.T) {
svc, st := newTestMapService(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutConfig(tx, "title", []byte("Test Map"))
})
}); err != nil {
t.Fatal(err)
}
config, err := svc.GetConfig(ctx, app.Auths{app.AUTH_MAP})
if err != nil {
@@ -93,9 +95,11 @@ func TestGetConfig_Empty(t *testing.T) {
func TestGetPage(t *testing.T) {
svc, st := newTestMapService(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutConfig(tx, "title", []byte("Map Page"))
})
}); err != nil {
t.Fatal(err)
}
page, err := svc.GetPage(ctx)
if err != nil {
@@ -112,9 +116,11 @@ func TestGetGrid(t *testing.T) {
gd := app.GridData{ID: "g1", Map: 1, Coord: app.Coord{X: 5, Y: 10}}
raw, _ := json.Marshal(gd)
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutGrid(tx, "g1", raw)
})
}); err != nil {
t.Fatal(err)
}
got, err := svc.GetGrid(ctx, "g1")
if err != nil {
@@ -158,11 +164,17 @@ func TestGetMaps_HiddenFilter(t *testing.T) {
mi2 := app.MapInfo{ID: 2, Name: "hidden", Hidden: true}
raw1, _ := json.Marshal(mi1)
raw2, _ := json.Marshal(mi2)
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutMap(tx, 1, raw1)
st.PutMap(tx, 2, raw2)
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutMap(tx, 1, raw1); err != nil {
return err
}
if err := st.PutMap(tx, 2, raw2); err != nil {
return err
}
return nil
})
}); err != nil {
t.Fatal(err)
}
maps, err := svc.GetMaps(ctx, false)
if err != nil {
@@ -201,14 +213,18 @@ func TestGetMarkers_WithData(t *testing.T) {
m := app.Marker{Name: "Tower", ID: 1, GridID: "g1", Position: app.Position{X: 10, Y: 20}, Image: "gfx/terobjs/mm/tower"}
mRaw, _ := json.Marshal(m)
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutGrid(tx, "g1", gdRaw)
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutGrid(tx, "g1", gdRaw); err != nil {
return err
}
grid, _, err := st.CreateMarkersBuckets(tx)
if err != nil {
return err
}
return grid.Put([]byte("g1_10_20"), mRaw)
})
}); err != nil {
t.Fatal(err)
}
markers, err := svc.GetMarkers(ctx)
if err != nil {
@@ -233,9 +249,11 @@ func TestGetTile(t *testing.T) {
td := app.TileData{MapID: 1, Coord: app.Coord{X: 0, Y: 0}, Zoom: 0, File: "grids/g1.png", Cache: 12345}
raw, _ := json.Marshal(td)
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutTile(tx, 1, 0, "0_0", raw)
})
}); err != nil {
t.Fatal(err)
}
got := svc.GetTile(ctx, 1, app.Coord{X: 0, Y: 0}, 0)
if got == nil {
@@ -287,9 +305,11 @@ func TestGetAllTileCache_WithData(t *testing.T) {
td := app.TileData{MapID: 1, Coord: app.Coord{X: 1, Y: 2}, Zoom: 0, Cache: 999}
raw, _ := json.Marshal(td)
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
return st.PutTile(tx, 1, 0, "1_2", raw)
})
}); err != nil {
t.Fatal(err)
}
cache := svc.GetAllTileCache(ctx)
if len(cache) != 1 {

View File

@@ -25,12 +25,14 @@ func TestUserCRUD(t *testing.T) {
ctx := context.Background()
// Verify user doesn't exist on empty DB.
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
if got := st.GetUser(tx, "alice"); got != nil {
t.Fatal("expected nil user before creation")
}
return nil
})
}); err != nil {
t.Fatal(err)
}
// Create user.
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
@@ -40,7 +42,7 @@ func TestUserCRUD(t *testing.T) {
}
// Verify user exists and count is correct (separate transaction for accurate Stats).
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
got := st.GetUser(tx, "alice")
if got == nil || string(got) != `{"pass":"hash"}` {
t.Fatalf("expected user data, got %s", got)
@@ -49,7 +51,9 @@ func TestUserCRUD(t *testing.T) {
t.Fatalf("expected 1 user, got %d", c)
}
return nil
})
}); err != nil {
t.Fatal(err)
}
// Delete user.
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
@@ -58,31 +62,41 @@ func TestUserCRUD(t *testing.T) {
t.Fatal(err)
}
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
if got := st.GetUser(tx, "alice"); got != nil {
t.Fatal("expected nil user after deletion")
}
return nil
})
}); err != nil {
t.Fatal(err)
}
}
func TestForEachUser(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutUser(tx, "alice", []byte("1"))
st.PutUser(tx, "bob", []byte("2"))
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutUser(tx, "alice", []byte("1")); err != nil {
return err
}
if err := st.PutUser(tx, "bob", []byte("2")); err != nil {
return err
}
return nil
})
}); err != nil {
t.Fatal(err)
}
var names []string
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
return st.ForEachUser(tx, func(k, _ []byte) error {
names = append(names, string(k))
return nil
})
})
}); err != nil {
t.Fatal(err)
}
if len(names) != 2 {
t.Fatalf("expected 2 users, got %d", len(names))
}
@@ -91,12 +105,14 @@ func TestForEachUser(t *testing.T) {
func TestUserCountEmptyBucket(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
if c := st.UserCount(tx); c != 0 {
t.Fatalf("expected 0 users on empty db, got %d", c)
}
return nil
})
}); err != nil {
t.Fatal(err)
}
}
func TestSessionCRUD(t *testing.T) {
@@ -211,19 +227,27 @@ func TestForEachMap(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutMap(tx, 1, []byte("a"))
st.PutMap(tx, 2, []byte("b"))
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutMap(tx, 1, []byte("a")); err != nil {
return err
}
if err := st.PutMap(tx, 2, []byte("b")); err != nil {
return err
}
return nil
})
}); err != nil {
t.Fatal(err)
}
var count int
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
return st.ForEachMap(tx, func(_, _ []byte) error {
count++
return nil
})
})
}); err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("expected 2 maps, got %d", count)
}
@@ -290,20 +314,30 @@ func TestForEachTile(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutTile(tx, 1, 0, "0_0", []byte("a"))
st.PutTile(tx, 1, 1, "0_0", []byte("b"))
st.PutTile(tx, 2, 0, "1_1", []byte("c"))
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutTile(tx, 1, 0, "0_0", []byte("a")); err != nil {
return err
}
if err := st.PutTile(tx, 1, 1, "0_0", []byte("b")); err != nil {
return err
}
if err := st.PutTile(tx, 2, 0, "1_1", []byte("c")); err != nil {
return err
}
return nil
})
}); err != nil {
t.Fatal(err)
}
var count int
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
return st.ForEachTile(tx, func(_, _, _, _ []byte) error {
count++
return nil
})
})
}); err != nil {
t.Fatal(err)
}
if count != 3 {
t.Fatalf("expected 3 tiles, got %d", count)
}
@@ -313,7 +347,7 @@ func TestTilesMapBucket(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if b := st.GetTilesMapBucket(tx, 1); b != nil {
t.Fatal("expected nil bucket before creation")
}
@@ -328,31 +362,39 @@ func TestTilesMapBucket(t *testing.T) {
t.Fatal("expected non-nil after create")
}
return st.DeleteTilesMapBucket(tx, 1)
})
}); err != nil {
t.Fatal(err)
}
}
func TestDeleteTilesBucket(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
st.PutTile(tx, 1, 0, "0_0", []byte("a"))
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.PutTile(tx, 1, 0, "0_0", []byte("a")); err != nil {
return err
}
return st.DeleteTilesBucket(tx)
})
}); err != nil {
t.Fatal(err)
}
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
if got := st.GetTile(tx, 1, 0, "0_0"); got != nil {
t.Fatal("expected nil after bucket deletion")
}
return nil
})
}); err != nil {
t.Fatal(err)
}
}
func TestMarkerBuckets(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if b := st.GetMarkersGridBucket(tx); b != nil {
t.Fatal("expected nil grid bucket before creation")
}
@@ -376,7 +418,9 @@ func TestMarkerBuckets(t *testing.T) {
t.Fatal("expected non-zero sequence")
}
return nil
})
}); err != nil {
t.Fatal(err)
}
}
func TestOAuthStateCRUD(t *testing.T) {
@@ -408,23 +452,29 @@ func TestBucketExistsAndDelete(t *testing.T) {
st := newTestStore(t)
ctx := context.Background()
st.Update(ctx, func(tx *bbolt.Tx) error {
if err := st.Update(ctx, func(tx *bbolt.Tx) error {
if st.BucketExists(tx, store.BucketUsers) {
t.Fatal("expected bucket to not exist")
}
st.PutUser(tx, "alice", []byte("x"))
if err := st.PutUser(tx, "alice", []byte("x")); err != nil {
return err
}
if !st.BucketExists(tx, store.BucketUsers) {
t.Fatal("expected bucket to exist")
}
return st.DeleteBucket(tx, store.BucketUsers)
})
}); err != nil {
t.Fatal(err)
}
st.View(ctx, func(tx *bbolt.Tx) error {
if err := st.View(ctx, func(tx *bbolt.Tx) error {
if st.BucketExists(tx, store.BucketUsers) {
t.Fatal("expected bucket to be deleted")
}
return nil
})
}); err != nil {
t.Fatal(err)
}
}
func TestDeleteBucketNonExistent(t *testing.T) {

View File

@@ -15,7 +15,9 @@ func (t *Topic[T]) Watch(c chan *T) {
t.c = append(t.c, c)
}
// Send broadcasts to all subscribers.
// Send broadcasts to all subscribers. If a subscriber's channel is full,
// the message is dropped for that subscriber only; the subscriber is not
// removed, so the connection stays alive and later updates are still delivered.
func (t *Topic[T]) Send(b *T) {
t.mu.Lock()
defer t.mu.Unlock()
@@ -23,9 +25,7 @@ func (t *Topic[T]) Send(b *T) {
select {
case t.c[i] <- b:
default:
close(t.c[i])
t.c[i] = t.c[len(t.c)-1]
t.c = t.c[:len(t.c)-1]
// Channel full: drop this message for this subscriber, keep them subscribed
}
}
}