Fix: Expose all templates

This commit is contained in:
Pieter Vander Vennet 2023-06-04 23:58:29 +02:00
parent de20b00b8f
commit 09a3e7fba1
8 changed files with 187 additions and 154 deletions

View file

@ -23,8 +23,8 @@ export default class DownloadHelper {
private static cleanFeature(f: Feature): Feature {
f = {
type: f.type,
geometry: { ...f.geometry },
properties: { ...f.properties },
geometry: {...f.geometry},
properties: {...f.properties},
}
for (const key in f.properties) {
@ -48,8 +48,7 @@ export default class DownloadHelper {
public getCleanGeoJson(
includeMetaData: boolean
): FeatureCollection {
const state = this._state
): string | FeatureCollection {
const featuresPerLayer = this.getCleanGeoJsonPerLayer(includeMetaData)
const features = [].concat(...Array.from(featuresPerLayer.values()))
return {
@ -92,7 +91,7 @@ export default class DownloadHelper {
throw "Invalid width of height, they should be > 0"
}
const unit = options.unit ?? "px"
const mapExtent = { left: -180, bottom: -90, right: 180, top: 90 }
const mapExtent = {left: -180, bottom: -90, right: 180, top: 90}
if (options.mapExtent !== undefined) {
const bbox = options.mapExtent
mapExtent.left = bbox.minLon
@ -100,7 +99,7 @@ export default class DownloadHelper {
mapExtent.bottom = bbox.minLat
mapExtent.top = bbox.maxLat
}
console.log("Generateing svg, extent:", { mapExtent, width, height })
console.log("Generateing svg, extent:", {mapExtent, width, height})
const elements: string[] = []
for (const layer of Array.from(perLayer.keys())) {
@ -113,7 +112,7 @@ export default class DownloadHelper {
const rendering = layerDef?.lineRendering[0]
const converter = geojson2svg({
viewportSize: { width, height },
viewportSize: {width, height},
mapExtent,
output: "svg",
attributes: [
@ -133,11 +132,10 @@ export default class DownloadHelper {
for (const feature of features) {
const stroke =
rendering?.color?.GetRenderValue(feature.properties)?.txt ?? "#ff0000"
const color = Utils.colorAsHex(Utils.color(stroke))
feature.properties.stroke = color
feature.properties.stroke = Utils.colorAsHex(Utils.color(stroke))
}
const groupPaths: string[] = converter.convert({ type: "FeatureCollection", features })
const groupPaths: string[] = converter.convert({type: "FeatureCollection", features})
const group =
` <g id="${layer}" inkscape:groupmode="layer" inkscape:label="${layer}">\n` +
groupPaths.map((p) => " " + p).join("\n") +
@ -151,8 +149,6 @@ export default class DownloadHelper {
return header + "\n" + elements.join("\n") + "\n</svg>"
}
public getCleanGeoJsonPerLayer(
includeMetaData: boolean
): Map<string, Feature[]> {

View file

@ -7,13 +7,8 @@
import DownloadButton from "./DownloadButton.svelte";
import {GeoOperations} from "../../Logic/GeoOperations";
import {SvgToPdf} from "../../Utils/svgToPdf";
import Locale from "../i18n/Locale";
import ThemeViewState from "../../Models/ThemeViewState";
import {Utils} from "../../Utils";
import Constants from "../../Models/Constants";
import {Translation} from "../i18n/Translation";
import {AvailableRasterLayers} from "../../Models/RasterLayers";
import {UIEventSource} from "../../Logic/UIEventSource";
import DownloadPdf from "./DownloadPdf.svelte";
export let state: ThemeViewState
let isLoading = state.dataIsLoading
@ -37,29 +32,6 @@
})
}
async function constructPdf(_, title: string, status: UIEventSource<string>) {
const templateUrls = SvgToPdf.templates["current_view_a3"].pages
const templates: string[] = await Promise.all(templateUrls.map(url => Utils.download(url)))
console.log("Templates are", templates)
const bg = state.mapProperties.rasterLayer.data ?? AvailableRasterLayers.maplibre
const creator = new SvgToPdf(title, templates, {
state,
freeComponentId: "belowmap",
textSubstitutions: <Record<string, string>> {
"layout.title": state.layout.title,
title: state.layout.title,
layoutImg: state.layout.icon,
version: Constants.vNumber,
date: new Date().toISOString().substring(0,16),
background: new Translation(bg.properties.name).txt
}
})
const unsub = creator.status.addCallbackAndRunD(s => status?.setData(s))
await creator.ExportPdf(Locale.language.data)
unsub()
return undefined
}
</script>
@ -111,13 +83,14 @@
construct={_ => state.mapProperties.exportAsPng(4)}
/>
<DownloadButton {state}
mimetype="application/pdf"
extension="pdf"
mainText={t.downloadAsPdf}
helperText={t.downloadAsPdfHelper}
construct={constructPdf}
/>
<div class="flex flex-col">
{#each Object.keys(SvgToPdf.templates) as key}
{#if SvgToPdf.templates[key].isPublic}
<DownloadPdf {state} templateName={key}></DownloadPdf>
{/if}
{/each}
</div>
<Tr cls="link-underline" t={t.licenseInfo}/>

View file

@ -0,0 +1,57 @@
<script lang="ts">
import DownloadButton from "./DownloadButton.svelte";
import ThemeViewState from "../../Models/ThemeViewState";
import {SvgToPdf} from "../../Utils/svgToPdf";
import Translations from "../i18n/Translations";
import {Translation} from "../i18n/Translation";
import {Utils} from "../../Utils";
import {AvailableRasterLayers} from "../../Models/RasterLayers";
import Constants from "../../Models/Constants";
import Locale from "../i18n/Locale";
import {UIEventSource} from "../../Logic/UIEventSource";
import DownloadHelper from "./DownloadHelper";
export let templateName: string
export let state: ThemeViewState
const template = SvgToPdf.templates[templateName]
console.log("template", template )
let mainText: Translation = typeof template.description === "string" ? new Translation(template.description) : template.description
let t = Translations.t.general.download
const downloadHelper = new DownloadHelper(state)
async function constructPdf(_, title: string, status: UIEventSource<string>) {
const templateUrls = SvgToPdf.templates["current_view_a3"].pages
const templates: string[] = await Promise.all(templateUrls.map(url => Utils.download(url)))
console.log("Templates are", templates)
const bg = state.mapProperties.rasterLayer.data ?? AvailableRasterLayers.maplibre
const creator = new SvgToPdf(title, templates, {
state,
freeComponentId: "belowmap",
generateImage(key: string): HTMLImageElement {
downloadHelper.generateImage(key)
},
textSubstitutions: <Record<string, string>> {
"layout.title": state.layout.title,
title: state.layout.title,
layoutImg: state.layout.icon,
version: Constants.vNumber,
date: new Date().toISOString().substring(0,16),
background: new Translation(bg.properties.name).txt
}
})
const unsub = creator.status.addCallbackAndRunD(s => status?.setData(s))
await creator.ExportPdf(Locale.language.data)
unsub()
return undefined
}
</script>
<DownloadButton {state}
mimetype="application/pdf"
extension="pdf"
{mainText}
helperText={t.downloadAsPdfHelper}
construct={constructPdf}
/>

View file

@ -29,51 +29,55 @@ export class PngMapCreator {
div.id = "mapdiv-" + PngMapCreator.id
div.style.width = this._options.width + "mm"
div.style.height = this._options.height + "mm"
PngMapCreator.id++
const layout = this._state.layout
try {
const layout = this._state.layout
function setState(msg: string) {
status?.setData(layout.id + ": " + msg)
function setState(msg: string) {
status?.setData(layout.id + ": " + msg)
}
setState("Initializing map")
const settings = this._state.mapProperties
const l = settings.location.data
document.getElementById(freeComponentId).appendChild(div)
const mapElem = new MlMap({
container: div.id,
style: AvailableRasterLayers.maplibre.properties.url,
center: [l.lon, l.lat],
zoom: settings.zoom.data,
pixelRatio: 6
});
const map = new UIEventSource<MlMap>(mapElem)
const mla = new MapLibreAdaptor(map)
mla.zoom.setData(settings.zoom.data)
mla.location.setData(settings.location.data)
mla.rasterLayer.setData(settings.rasterLayer.data)
mla.allowZooming.setData(false)
mla.allowMoving.setData(false)
this._state?.showNormalDataOn(map)
console.log("Creating a map with size", this._options.width, this._options.height)
setState("Waiting for the data")
await this._state.dataIsLoading.AsPromise((loading) => !loading)
setState("Waiting for styles to be fully loaded")
while (!map?.data?.isStyleLoaded()) {
console.log("Waiting for the style to be loaded...")
await Utils.waitFor(250)
}
// Some extra buffer...
await Utils.waitFor(1000)
setState("Exporting png")
console.log("Loading for", this._state.layout.id, "is done")
const png = await mla.exportAsPng(6)
return png
} finally {
div.parentElement.removeChild(div)
}
setState("Initializing map")
const settings = this._state.mapProperties
const l = settings.location.data
document.getElementById(freeComponentId).appendChild(div)
const mapElem = new MlMap({
container: div.id,
style: AvailableRasterLayers.maplibre.properties.url,
center: [l.lon, l.lat],
zoom: settings.zoom.data,
pixelRatio: 6
});
const map = new UIEventSource<MlMap>(mapElem)
const mla = new MapLibreAdaptor(map)
mla.zoom.setData(settings.zoom.data)
mla.location.setData(settings.location.data)
mla.rasterLayer.setData(settings.rasterLayer.data)
this._state?.showNormalDataOn(map)
console.log("Creating a map with size", this._options.width, this._options.height)
setState("Waiting for the data")
await this._state.dataIsLoading.AsPromise((loading) => !loading)
setState("Waiting for styles to be fully loaded")
while (!map?.data?.isStyleLoaded()) {
console.log("Waiting for the style to be loaded...")
await Utils.waitFor(250)
}
// Some extra buffer...
await Utils.waitFor(1000)
setState("Exporting png")
console.log("Loading for", this._state.layout.id, "is done")
const png = await mla.exportAsPng(6)
div.parentElement.removeChild(div)
Utils.offerContentsAsDownloadableFile(png, "test.png")
return png
}
}

View file

@ -302,6 +302,7 @@ class SvgToPdfInternals {
return
}
private drawTspan(tspan: Element) {
const txt = tspan.textContent
if (txt == "") {
@ -310,27 +311,18 @@ class SvgToPdfInternals {
const x = SvgToPdfInternals.attrNumber(tspan, "x")
const y = SvgToPdfInternals.attrNumber(tspan, "y")
const css = SvgToPdfInternals.css(tspan)
const imageMatch = txt.match(/\$img\(([^)])+\)/)
if (imageMatch) {
const [key, width, height] = imageMatch[1].split(",").map(s => s.trim())
const url = key.startsWith("http") ? key : this.extractTranslation("${" + key + "}")
const img = this._images[url]
console.log("Drawing an injected image", {key, url, img: img.src})
this.doc.addImage(
img.src
, x, y, Number(width), Number(height)
)
return
}
let maxWidth: number = undefined
let maxHeight: number = undefined
const css = SvgToPdfInternals.css(tspan)
if (css["shape-inside"]) {
const matched = css["shape-inside"].match(/url\(#([a-zA-Z0-9-]+)\)/)
if (matched !== null) {
const rectId = matched[1]
const rect = this._rects[rectId]
maxWidth = SvgToPdfInternals.attrNumber(rect, "width", false)
maxHeight = SvgToPdfInternals.attrNumber(rect, "height", false)
}
}
@ -537,7 +529,7 @@ export interface SvgToPdfOptions {
/**
* Override all the maps to generate with this map
*/
state?: ThemeViewState
state?: ThemeViewState,
}
class SvgToPdfPage {
@ -553,11 +545,10 @@ class SvgToPdfPage {
*/
private readonly _state: UIEventSource<string>
private _isPrepared = false
private state: UIEventSource<string>
constructor(page: string, state: UIEventSource<string>, options?: SvgToPdfOptions) {
constructor(page: string, state: UIEventSource<string>, options: SvgToPdfOptions) {
this._state = state
this.options = options ?? <SvgToPdfOptions>{}
this.options = options
const parser = new DOMParser()
const xmlDoc = parser.parseFromString(page, "image/svg+xml")
this._svgRoot = xmlDoc.getElementsByTagName("svg")[0]
@ -613,13 +604,6 @@ class SvgToPdfPage {
if (element.tagName === "tspan" && element.childElementCount == 0) {
const specialValues = element.textContent.split(" ").filter((t) => t.startsWith("$"))
for (let specialValue of specialValues) {
const imageMatch = element.textContent.match(/\$img\(([^)])+\)/)
if (imageMatch) {
const key = imageMatch[1]
const url = key.startsWith("http") ? key : this.extractTranslation("${" + key + "}", `en`, false)
await this.loadImage(url)
continue
}
const importMatch = element.textContent.match(
/\$import ([a-zA-Z-_0-9.? ]+) as ([a-zA-Z0-9]+)/
@ -687,10 +671,10 @@ class SvgToPdfPage {
}
for (const mapSpec of mapSpecs) {
try{
try {
await this.prepareMap(mapSpec, !this.options?.disableDataLoading)
}catch(e){
await this.prepareMap(mapSpec, !this.options?.disableDataLoading)
} catch (e) {
console.error("Couldn't prepare a map:", e)
}
}
@ -706,7 +690,7 @@ class SvgToPdfPage {
}
const self = this
const internal = new SvgToPdfInternals(advancedApi, this.images, this.rects, (key) =>
self.extractTranslation(key, language)
self.extractTranslation(key, language)
)
for (let child of Array.from(this._svgRoot.children)) {
internal.handleElement(<any>child)
@ -863,7 +847,7 @@ class SvgToPdfPage {
if (this.options.state !== undefined) {
png = await (new PngMapCreator(this.options.state, {
width, height,
}).CreatePng(this.options.freeComponentId))
}).CreatePng(this.options.freeComponentId, this._state))
} else {
const match = spec.match(/\$map\(([^)]*)\)$/)
if (match === null) {
@ -959,7 +943,7 @@ class SvgToPdfPage {
height: 4 * height,
})
png = await pngCreator.CreatePng(this.options.freeComponentId, this._state)
if(!png){
if (!png) {
throw "PngCreator did not output anything..."
}
}
@ -1005,12 +989,13 @@ export class SvgToPdf {
},
current_view_a4: {
pages: ["./assets/templates/CurrentMapWithHeaderA4.svg"],
description: "Export a PDF (A4, landscape) of the current view",
description: Translations.t.general.download.pdf.current_view_a4,
isPublic: true
},
current_view_a3: {
pages: ["./assets/templates/CurrentMapWithHeaderA3.svg"],
description: "Export a PDF (A3, portrait) of the current view",
description: Translations.t.general.download.pdf.current_view_a3,
isPublic: true
}
}
@ -1019,16 +1004,13 @@ export class SvgToPdf {
private readonly _title: string
private readonly _pages: SvgToPdfPage[]
constructor(title: string, pages: string[], options?: SvgToPdfOptions) {
constructor(title: string, pages: string[], options) {
this._title = title
options = options ?? <SvgToPdfOptions>{}
options.textSubstitutions = options.textSubstitutions ?? {}
const mapCount =
"" +
options.textSubstitutions["mapCount"] = "" +
Array.from(AllKnownLayouts.allKnownLayouts.values()).filter(
(th) => !th.hideFromOverview
).length
options.textSubstitutions["mapCount"] = mapCount
const state = new UIEventSource<string>("Initializing...")
this.status = state
@ -1054,7 +1036,6 @@ export class SvgToPdf {
const doc = new jsPDF(mode, undefined, [width, height])
doc.advancedAPI((advancedApi) => {
const canvas = advancedApi.canvas
for (let i = 0; i < this._pages.length; i++) {
console.log("Rendering page", i)
if (i > 0) {

View file

@ -183,6 +183,10 @@
"includeMetaData": "Include metadata (last editor, calculated values, …)",
"licenseInfo": "<h3>Copyright notice</h3>The provided data is available under ODbL. Reusing it is gratis for any purpose, but <ul><li>the attribution <b>© OpenStreetMap contributors</b> must be shown<li><li>Any change must be published under the same license</li></ul> Please read the full <a href='https://www.openstreetmap.org/copyright' target='_blank'>copyright notice</a> for details.",
"noDataLoaded": "No data is loaded yet. Download will be available soon",
"pdf": {
"current_view_a3": "Export a PDF (A3, portrait) of the current view",
"current_view_a4": "Export a PDF (A4, landscape) of the current view"
},
"title": "Download",
"uploadGpx": "Upload your track to OpenStreetMap"
},

View file

@ -15,6 +15,12 @@
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs33">
<rect
x="39.439771"
y="61.24773"
width="104.91111"
height="99.590532"
id="rect7785" />
<rect
x="41.547712"
y="103.43336"
@ -35,14 +41,14 @@
borderopacity="1"
inkscape:pageshadow="0"
inkscape:pageopacity="1"
inkscape:pagecheckerboard="1"
inkscape:pagecheckerboard="true"
inkscape:document-units="mm"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="0.48119622"
inkscape:cx="338.73915"
inkscape:cy="424.98255"
inkscape:zoom="1.3296534"
inkscape:cx="4.5124542"
inkscape:cy="96.641727"
inkscape:window-width="1920"
inkscape:window-height="995"
inkscape:window-x="0"
@ -89,33 +95,33 @@
style="font-style:normal;font-weight:normal;font-size:40px;line-height:0.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect56707);display:inline;fill:#000000;fill-opacity:1;stroke:#000000;stroke-opacity:1"><tspan
x="0"
y="0"
id="tspan28903"><tspan
id="tspan2018"><tspan
style="font-size:13.3333px;-inkscape-font-specification:'sans-serif, Normal'"
id="tspan28901">$map(current)</tspan></tspan></text>
id="tspan2016">$map(current)</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(0.26458333,0,0,0.26458333,12.08115,27.672609)"
transform="matrix(0.26458333,0,0,0.26458333,38.20272,27.672609)"
id="text3510"
style="font-style:normal;font-weight:normal;font-size:40px;line-height:0;font-family:sans-serif;white-space:pre;shape-inside:url(#rect3512);fill:#000000;fill-opacity:1;stroke:#000000;stroke-opacity:1"><tspan
x="0"
y="0"
id="tspan28907"><tspan
id="tspan2022"><tspan
style="font-size:16px;line-height:1.05;-inkscape-font-specification:'sans-serif, Normal'"
id="tspan28905">$general.pdf.attr
id="tspan2020">$general.pdf.attr
</tspan></tspan><tspan
x="0"
y="16.799999"
id="tspan28911"><tspan
id="tspan2026"><tspan
style="font-size:16px;line-height:1.05;-inkscape-font-specification:'sans-serif, Normal'"
id="tspan28909">$general.pdf.attrBackground
id="tspan2024">$general.pdf.attrBackground
</tspan></tspan><tspan
x="0"
y="35.692733"
id="tspan28917"><tspan
id="tspan2032"><tspan
style="font-size:16px;line-height:1.05;-inkscape-font-specification:'sans-serif, Normal'"
id="tspan28913">$general.pdf.generatedWith</tspan><tspan
id="tspan2028">$general.pdf.generatedWith</tspan><tspan
style="font-size:18.6667px;line-height:1.05;-inkscape-font-specification:'sans-serif, Normal'"
id="tspan28915">
id="tspan2030">
</tspan></tspan></text>
<text
xml:space="preserve"
@ -129,9 +135,21 @@
style="font-size:16px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';text-align:end;white-space:pre;shape-inside:url(#rect10143);fill:#000000;fill-opacity:0.914749;stroke:#ff0000;stroke-width:3.77953;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none"><tspan
x="1182.4844"
y="871.91602"
id="tspan28921"><tspan
id="tspan2036"><tspan
style="fill-opacity:1;stroke:none"
id="tspan28919">$general.pdf.versionInfo</tspan></tspan></text>
id="tspan2034">$general.pdf.versionInfo</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(0.26458333,0,0,0.26458333,-1.5395742,-2.3571711)"
id="text7783"
style="font-size:16px;line-height:1.05;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';text-align:start;white-space:pre;shape-inside:url(#rect7785);fill:#000000;stroke-width:3.77953;stroke-linecap:round;stroke-linejoin:round"
x="-98.273438"
y="0"><tspan
x="39.439453"
y="73.804296"
id="tspan2040"><tspan
style="font-size:8px"
id="tspan2038">$img(layouticon)</tspan></tspan></text>
</g>
<g
inkscape:label="Layer 1"
@ -161,14 +179,14 @@
style="font-style:normal;font-weight:normal;font-size:40px;line-height:1.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect81706);fill:#000000;fill-opacity:1;stroke:none" />
<text
xml:space="preserve"
transform="matrix(0.26458333,0,0,0.26458333,11.738978,20.267151)"
transform="matrix(0.26458333,0,0,0.26458333,37.860548,20.267151)"
id="text135030"
style="font-style:normal;font-weight:normal;font-size:40px;line-height:1.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect135032);fill:#000000;fill-opacity:1;stroke:none"><tspan
x="0"
y="0"
id="tspan28925"><tspan
id="tspan2044"><tspan
style="font-weight:bold;font-size:34.6667px;-inkscape-font-specification:'sans-serif, Bold'"
id="tspan28923">${title}</tspan></tspan></text>
id="tspan2042">${title}</tspan></tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

View file

@ -42,11 +42,11 @@
<div id="default-main h-full">
<div class="w-full h-screen flex flex-col items-center justify-between p-8">
<div class="w-full h-full flex flex-col items-center">
<div id="default-title">
Loading MapComplete, hang on...
</div>
<p class="text-xl" id="descriptions-while-loading">
<!-- DESCRIPTION START -->
MapComplete is an easy to use map viewer and map editor
@ -56,14 +56,14 @@
Made with OpenStreetMap
</p>
</div>
<!-- IMAGE-START -->
<img class="p-8 h-32 w-32 self-start" src="./assets/svg/add.svg">
<img class="p-8 h-32 w-32 self-start" src="./assets/svg/add.svg">
<!-- IMAGE-END -->
</div>
</div>
</div>
<div id="belowmap" style="z-index: -1">Below</div>
<div id="belowmap" class="absolute top-0 left-0" style="z-index: -1;">Below</div>
<script>