feat: implement automatic static map image generation
- Add html-to-image for capturing map container with markers - Auto-generate map image on page/marker save via hooks - Use flag system (.regenerate-map-image) to trigger generation on Panel reload - Create file using Kirby API for proper indexing - Add mapStaticImage field in blueprint to display generated image - Wait for map to be fully loaded before capture - Capture entire container (map + custom markers) - Filter MapLibre controls from capture Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
1d74105910
commit
9193ac8900
8 changed files with 474 additions and 92 deletions
|
|
@ -19,6 +19,14 @@ columns:
|
||||||
defaultCenter: [43.836699, 4.360054]
|
defaultCenter: [43.836699, 4.360054]
|
||||||
defaultZoom: 13
|
defaultZoom: 13
|
||||||
maxMarkers: 50
|
maxMarkers: 50
|
||||||
|
mapStaticImage:
|
||||||
|
label: Image statique générée
|
||||||
|
type: files
|
||||||
|
multiple: false
|
||||||
|
query: page.files.filterBy("name", "map-static")
|
||||||
|
layout: cards
|
||||||
|
disabled: true
|
||||||
|
help: Cette image est automatiquement générée à la sauvegarde de la page ou d'un marqueur
|
||||||
sidebar:
|
sidebar:
|
||||||
width: 1/3
|
width: 1/3
|
||||||
sections:
|
sections:
|
||||||
|
|
|
||||||
|
|
@ -467,5 +467,189 @@ return [
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
],
|
||||||
|
|
||||||
|
[
|
||||||
|
'pattern' => 'map-editor/pages/(:all)/capture-image',
|
||||||
|
'method' => 'POST',
|
||||||
|
'auth' => false, // Allow Panel session auth
|
||||||
|
'action' => function (string $pageId) {
|
||||||
|
try {
|
||||||
|
// Get user from session (Panel context)
|
||||||
|
$user = kirby()->user();
|
||||||
|
|
||||||
|
if (!$user && !kirby()->option('debug', false)) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Unauthorized',
|
||||||
|
'code' => 401
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the map page
|
||||||
|
$mapPage = kirby()->page($pageId);
|
||||||
|
if (!$mapPage) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Map page not found',
|
||||||
|
'code' => 404
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user can update the page
|
||||||
|
if (!$mapPage->permissions()->can('update')) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Forbidden',
|
||||||
|
'code' => 403
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get image data from request
|
||||||
|
$data = kirby()->request()->data();
|
||||||
|
|
||||||
|
if (!isset($data['image'])) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Image data is required',
|
||||||
|
'code' => 400
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract base64 data (remove data:image/png;base64, prefix)
|
||||||
|
$imageData = $data['image'];
|
||||||
|
if (preg_match('/^data:image\/(png|jpeg|jpg);base64,(.+)$/', $imageData, $matches)) {
|
||||||
|
$imageData = $matches[2];
|
||||||
|
$extension = $matches[1] === 'jpeg' ? 'jpg' : $matches[1];
|
||||||
|
} else {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Invalid image format',
|
||||||
|
'code' => 400
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode base64
|
||||||
|
$decodedImage = base64_decode($imageData);
|
||||||
|
if ($decodedImage === false) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Failed to decode image',
|
||||||
|
'code' => 400
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create temporary file
|
||||||
|
$filename = 'map-static.' . $extension;
|
||||||
|
$tempPath = sys_get_temp_dir() . '/' . uniqid() . '.' . $extension;
|
||||||
|
file_put_contents($tempPath, $decodedImage);
|
||||||
|
|
||||||
|
// Delete existing map-static file if it exists
|
||||||
|
$existingFile = $mapPage->files()->filterBy('name', 'map-static')->first();
|
||||||
|
if ($existingFile) {
|
||||||
|
$existingFile->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create file using Kirby API (so it's properly indexed)
|
||||||
|
try {
|
||||||
|
$file = $mapPage->createFile([
|
||||||
|
'source' => $tempPath,
|
||||||
|
'filename' => $filename
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Clean up temp file
|
||||||
|
@unlink($tempPath);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
@unlink($tempPath);
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'success',
|
||||||
|
'data' => [
|
||||||
|
'message' => 'Image saved successfully',
|
||||||
|
'filename' => $filename,
|
||||||
|
'path' => $filepath
|
||||||
|
]
|
||||||
|
];
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
'code' => 500
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
|
||||||
|
[
|
||||||
|
'pattern' => 'map-editor/pages/(:all)/check-regenerate-flag',
|
||||||
|
'method' => 'GET',
|
||||||
|
'auth' => false,
|
||||||
|
'action' => function (string $pageId) {
|
||||||
|
try {
|
||||||
|
$page = kirby()->page($pageId);
|
||||||
|
if (!$page) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Page not found',
|
||||||
|
'code' => 404
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$markerFile = $page->root() . '/.regenerate-map-image';
|
||||||
|
$needsRegeneration = file_exists($markerFile);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'success',
|
||||||
|
'data' => [
|
||||||
|
'needsRegeneration' => $needsRegeneration
|
||||||
|
]
|
||||||
|
];
|
||||||
|
} catch (Exception $e) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
'code' => 500
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
|
||||||
|
[
|
||||||
|
'pattern' => 'map-editor/pages/(:all)/clear-regenerate-flag',
|
||||||
|
'method' => 'DELETE',
|
||||||
|
'auth' => false,
|
||||||
|
'action' => function (string $pageId) {
|
||||||
|
try {
|
||||||
|
$page = kirby()->page($pageId);
|
||||||
|
if (!$page) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => 'Page not found',
|
||||||
|
'code' => 404
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$markerFile = $page->root() . '/.regenerate-map-image';
|
||||||
|
if (file_exists($markerFile)) {
|
||||||
|
unlink($markerFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => 'success',
|
||||||
|
'data' => [
|
||||||
|
'message' => 'Flag cleared'
|
||||||
|
]
|
||||||
|
];
|
||||||
|
} catch (Exception $e) {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
'code' => 500
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -51,5 +51,23 @@ Kirby::plugin('geoproject/map-editor', [
|
||||||
],
|
],
|
||||||
'api' => [
|
'api' => [
|
||||||
'routes' => require __DIR__ . '/api/routes.php'
|
'routes' => require __DIR__ . '/api/routes.php'
|
||||||
|
],
|
||||||
|
'hooks' => [
|
||||||
|
'page.update:after' => function ($newPage, $oldPage) {
|
||||||
|
// Mark map page for image regeneration
|
||||||
|
if ($newPage->intendedTemplate()->name() === 'map') {
|
||||||
|
$markerFile = $newPage->root() . '/.regenerate-map-image';
|
||||||
|
file_put_contents($markerFile, time());
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a marker is updated, mark the parent map page for regeneration
|
||||||
|
if ($newPage->intendedTemplate()->name() === 'marker') {
|
||||||
|
$mapPage = $newPage->parent();
|
||||||
|
if ($mapPage && $mapPage->intendedTemplate()->name() === 'map') {
|
||||||
|
$markerFile = $mapPage->root() . '/.regenerate-map-image';
|
||||||
|
file_put_contents($markerFile, time());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
]);
|
]);
|
||||||
|
|
|
||||||
16
public/site/plugins/map-editor/package-lock.json
generated
16
public/site/plugins/map-editor/package-lock.json
generated
|
|
@ -8,8 +8,10 @@
|
||||||
"name": "map-editor",
|
"name": "map-editor",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"html-to-image": "^1.11.13",
|
||||||
"js-yaml": "^4.1.0",
|
"js-yaml": "^4.1.0",
|
||||||
"maplibre-gl": "^3.6.0"
|
"maplibre-gl": "^3.6.0",
|
||||||
|
"maplibre-gl-map-to-image": "^1.2.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"kirbyup": "^3.3.0"
|
"kirbyup": "^3.3.0"
|
||||||
|
|
@ -2410,6 +2412,12 @@
|
||||||
"node": ">=4"
|
"node": ">=4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/html-to-image": {
|
||||||
|
"version": "1.11.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/html-to-image/-/html-to-image-1.11.13.tgz",
|
||||||
|
"integrity": "sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/ieee754": {
|
"node_modules/ieee754": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||||
|
|
@ -3194,6 +3202,12 @@
|
||||||
"url": "https://github.com/maplibre/maplibre-gl-js?sponsor=1"
|
"url": "https://github.com/maplibre/maplibre-gl-js?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/maplibre-gl-map-to-image": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/maplibre-gl-map-to-image/-/maplibre-gl-map-to-image-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-U4IKKalUd/rudZMHDkpNWqHlOtdLOANDD/s7t8dBPiCAL14zmLAEJ/PE+yFRyl4ZsVymIPAhEPHg/n+7Rq47mA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/minimist": {
|
"node_modules/minimist": {
|
||||||
"version": "1.2.8",
|
"version": "1.2.8",
|
||||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,10 @@
|
||||||
"build": "npx -y kirbyup src/index.js"
|
"build": "npx -y kirbyup src/index.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"html-to-image": "^1.11.13",
|
||||||
|
"js-yaml": "^4.1.0",
|
||||||
"maplibre-gl": "^3.6.0",
|
"maplibre-gl": "^3.6.0",
|
||||||
"js-yaml": "^4.1.0"
|
"maplibre-gl-map-to-image": "^1.2.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"kirbyup": "^3.3.0"
|
"kirbyup": "^3.3.0"
|
||||||
|
|
|
||||||
|
|
@ -308,6 +308,11 @@ export default {
|
||||||
// Use nextTick to ensure all reactive updates from loadMapData are done
|
// Use nextTick to ensure all reactive updates from loadMapData are done
|
||||||
await nextTick();
|
await nextTick();
|
||||||
isInitialLoad.value = false;
|
isInitialLoad.value = false;
|
||||||
|
|
||||||
|
// Check if we need to regenerate the map image (multi mode only)
|
||||||
|
if (props.mode === 'multi') {
|
||||||
|
await checkAndRegenerateImage();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Watch center and zoom for automatic save (multi mode only)
|
// Watch center and zoom for automatic save (multi mode only)
|
||||||
|
|
@ -529,6 +534,111 @@ export default {
|
||||||
saveMapData();
|
saveMapData();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if map image needs regeneration and do it if needed
|
||||||
|
*/
|
||||||
|
async function checkAndRegenerateImage() {
|
||||||
|
if (!pageId.value) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check if regeneration flag exists
|
||||||
|
const checkResponse = await fetch(
|
||||||
|
`/api/map-editor/pages/${pageId.value}/check-regenerate-flag`
|
||||||
|
);
|
||||||
|
const checkResult = await checkResponse.json();
|
||||||
|
|
||||||
|
if (checkResult.status === 'success' && checkResult.data.needsRegeneration) {
|
||||||
|
console.log('Regeneration flag detected, waiting for map to be ready...');
|
||||||
|
|
||||||
|
// Wait for the map to be fully loaded with markers
|
||||||
|
await waitForMapReady();
|
||||||
|
|
||||||
|
console.log('Map ready, capturing image...');
|
||||||
|
|
||||||
|
// Capture and save the image
|
||||||
|
await captureAndSaveMapImage();
|
||||||
|
|
||||||
|
// Clear the flag
|
||||||
|
await fetch(
|
||||||
|
`/api/map-editor/pages/${pageId.value}/clear-regenerate-flag`,
|
||||||
|
{ method: 'DELETE' }
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log('Map image regenerated successfully');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking/regenerating map image:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wait for the map to be fully loaded and ready for capture
|
||||||
|
*/
|
||||||
|
async function waitForMapReady(maxAttempts = 10) {
|
||||||
|
for (let i = 0; i < maxAttempts; i++) {
|
||||||
|
// Check if map is loaded
|
||||||
|
if (mapPreview.value?.map?.loaded && mapPreview.value.map.loaded()) {
|
||||||
|
// Wait an additional 500ms for markers to render
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 500));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait 500ms before next attempt
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 500));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Map failed to load within timeout');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Capture map as image and send to server
|
||||||
|
*/
|
||||||
|
async function captureAndSaveMapImage() {
|
||||||
|
if (!mapPreview.value || !mapPreview.value.captureMapImage) {
|
||||||
|
console.warn('Map preview not ready for capture');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log('Starting image capture...');
|
||||||
|
|
||||||
|
// Capture the map as base64 image with timeout
|
||||||
|
const imageDataUrl = await Promise.race([
|
||||||
|
mapPreview.value.captureMapImage(),
|
||||||
|
new Promise((_, reject) =>
|
||||||
|
setTimeout(() => reject(new Error('Capture timeout after 10s')), 10000)
|
||||||
|
)
|
||||||
|
]);
|
||||||
|
console.log('Image captured, size:', imageDataUrl.length, 'bytes');
|
||||||
|
|
||||||
|
// Send to API
|
||||||
|
console.log('Sending to API:', `/api/map-editor/pages/${pageId.value}/capture-image`);
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/map-editor/pages/${pageId.value}/capture-image`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ image: imageDataUrl }),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log('Response status:', response.status);
|
||||||
|
const result = await response.json();
|
||||||
|
console.log('Response data:', result);
|
||||||
|
|
||||||
|
if (result.status === 'error') {
|
||||||
|
throw new Error(result.message || 'Failed to save map image');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Map image saved successfully:', result.data.filename);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error capturing and saving map image:', error);
|
||||||
|
throw error; // Re-throw to see the error in checkAndRegenerateImage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
// State
|
// State
|
||||||
center,
|
center,
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@
|
||||||
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
|
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
|
||||||
import maplibregl from "maplibre-gl";
|
import maplibregl from "maplibre-gl";
|
||||||
import "maplibre-gl/dist/maplibre-gl.css";
|
import "maplibre-gl/dist/maplibre-gl.css";
|
||||||
|
import { toPng } from "html-to-image";
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
props: {
|
props: {
|
||||||
|
|
@ -97,6 +98,7 @@ export default {
|
||||||
try {
|
try {
|
||||||
map.value = new maplibregl.Map({
|
map.value = new maplibregl.Map({
|
||||||
container: mapContainer.value,
|
container: mapContainer.value,
|
||||||
|
preserveDrawingBuffer: true, // Required for canvas.toDataURL()
|
||||||
style: {
|
style: {
|
||||||
version: 8,
|
version: 8,
|
||||||
sources: {
|
sources: {
|
||||||
|
|
@ -326,12 +328,55 @@ export default {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function captureMapImage() {
|
||||||
|
console.log('[MapPreview] captureMapImage called');
|
||||||
|
|
||||||
|
if (!map.value) {
|
||||||
|
throw new Error("Map is not initialized");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!map.value.loaded()) {
|
||||||
|
throw new Error("Map is not loaded");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mapContainer.value) {
|
||||||
|
throw new Error("Map container not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[MapPreview] Map is loaded, capturing container...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Capture the entire map container (includes canvas + markers)
|
||||||
|
const imageDataUrl = await toPng(mapContainer.value, {
|
||||||
|
quality: 0.95,
|
||||||
|
pixelRatio: 2, // Higher quality
|
||||||
|
cacheBust: true,
|
||||||
|
filter: (node) => {
|
||||||
|
// Exclude MapLibre controls (zoom buttons, etc.)
|
||||||
|
if (node.classList && node.classList.contains('maplibregl-ctrl')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[MapPreview] Container captured, image size:', imageDataUrl?.length);
|
||||||
|
|
||||||
|
return imageDataUrl;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[MapPreview] Error capturing map image:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
mapContainer,
|
mapContainer,
|
||||||
loading,
|
loading,
|
||||||
|
map,
|
||||||
getCurrentCenter,
|
getCurrentCenter,
|
||||||
getCurrentZoom,
|
getCurrentZoom,
|
||||||
centerOnPosition
|
centerOnPosition,
|
||||||
|
captureMapImage
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue