Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
402 changes: 402 additions & 0 deletions app/assets/stylesheets/docs.css

Large diffs are not rendered by default.

32 changes: 31 additions & 1 deletion app/controllers/docs_controller.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
class DocsController < ApplicationController
STYLE_SPEC = "geojson_style_spec".freeze

layout "map", only: :style_preview

# style_preview renders the map view, which renders its partials relative to app/views/maps
def self.local_prefixes
super + [ "maps" ]
end

def tutorials
end

Expand All @@ -7,9 +16,30 @@ def tutorial
respond_to do |format|
format.html do
@title = tutorial.title
@html_content = tutorial.to_html
if tutorial.name == STYLE_SPEC
@properties = StyleSpec.properties
render "styling"
else
@html_content = tutorial.to_html
end
end
format.md { render markdown: tutorial.markdown }
end
end

# The map of the styling playground iframe. The map is never saved, its one layer
# gets the features from the playground page through postMessage.
def style_preview
@map = Map.new(center: Map::DEFAULT_CENTER, zoom: 14)
@map_mode = "ro"
@map_properties = @map.properties
gon.map_mode = @map_mode
gon.rails_env = Rails.env
gon.map_keys = Map.provider_keys
gon.map_properties = @map_properties
gon.map_layers = [ { id: "preview", type: "geojson", name: "Preview", show: true,
geojson: { type: "FeatureCollection", features: [] } } ]
gon.style_preview = true
render "maps/maplibre"
end
end
25 changes: 23 additions & 2 deletions app/javascript/controllers/map_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import * as functions from 'helpers/functions'
import { initializeEditMode } from 'maplibre/edit'
import { moveFeatureTo, setHoveredFeature } from 'maplibre/feature'
import { showHoverInfo } from 'maplibre/feature/hover_info'
import { addFeature, resetInitializationState } from 'maplibre/layers/layers'
import { bbox } from '@turf/bbox'
import { addFeature, initializeLayers, layers, resetInitializationState } from 'maplibre/layers/layers'
import {
initializeMap,
initializeStaticMode,
Expand Down Expand Up @@ -37,12 +38,32 @@ export default class extends Controller {
} else {
initializeViewMode()
}
initializeSocket()
if (window.gon.style_preview) { this.listenForPreview() } else { initializeSocket() }
}
setBackgroundMapLayer()
}

// The styling docs page draws its edited feature on this map, see style_playground_controller.js
listenForPreview () {
this.previewListener = (event) => {
if (event.origin !== window.location.origin || event.data?.type !== 'style-preview' || !layers) { return }
layers[0].geojson = { type: 'FeatureCollection', features: [event.data.feature] }
layers[0].render()
if (event.data.fit) {
map.setPitch(event.data.pitch || 0)
map.fitBounds(bbox(event.data.feature), { padding: 80, maxZoom: 17, duration: 0 })
}
}
window.addEventListener('message', this.previewListener)
// The layers need the basemap style, which is in place on 'load'
map.once('load', async () => {
await initializeLayers()
window.parent.postMessage({ type: 'style-preview-ready' }, window.location.origin)
})
}

disconnect() {
if (this.previewListener) { window.removeEventListener('message', this.previewListener) }
// Clean up when navigating away from the map
console.log('Map controller disconnecting, cleaning up...')
// a revisit of the map would skip the hover of the same feature
Expand Down
206 changes: 206 additions & 0 deletions app/javascript/controllers/style_playground_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { Controller } from '@hotwired/stimulus'

const PRESETS = {
park: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[[11.0735, 49.4455], [11.0790, 49.4450], [11.0805, 49.4485], [11.0755, 49.4495], [11.0735, 49.4455]]]
},
properties: {
label: 'Stadtpark',
'label-background': 'shadow',
fill: '#9ccc65',
'fill-opacity': 0.7,
'fill-pattern': 'hatch',
stroke: '#33691e',
'stroke-width': 3
}
},
cafe: {
type: 'Feature',
geometry: { type: 'Point', coordinates: [11.077, 49.447] },
properties: { label: 'Café', 'marker-shape': 'pin', 'marker-color': '#b9531d', 'marker-symbol': '☕', 'marker-size': 20 }
},
trail: {
type: 'Feature',
geometry: { type: 'LineString', coordinates: [[11.070, 49.444], [11.074, 49.447], [11.079, 49.446], [11.084, 49.449]] },
properties: { label: 'Wanderweg', stroke: '#8e2a0b', 'stroke-width': 4, 'stroke-dasharray': true }
},
building: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[[11.0763, 49.4465], [11.0777, 49.4465], [11.0777, 49.4474], [11.0763, 49.4474], [11.0763, 49.4465]]]
},
properties: { label: 'Turm', fill: '#9ccc65', 'fill-extrusion-color': '#558b2f', 'fill-extrusion-height': 40 }
}
}

// "Load in playground" switches to this preset when the property does not apply to the current geometry
const GEOMETRY_PRESETS = { Point: 'cafe', LineString: 'trail', Polygon: 'park' }

// The value lists of the markdown are strings, the feature needs numbers and booleans
const typed = (value) => {
if (value === 'true' || value === 'false') { return value === 'true' }
return /^-?\d*\.?\d+$/.test(value) ? Number(value) : value
}

export default class extends Controller {
static targets = ['editor', 'status', 'preview', 'preset', 'cursorName', 'cursorChips', 'cursorDesc',
'cursorValues', 'cursorRelated', 'search', 'tab', 'card']

static values = { properties: Array, geometries: Object }

connect () {
this.properties = Object.fromEntries(this.propertiesValue.map(property => [property.name, property]))
this.group = 'All'
const shared = new URLSearchParams(window.location.search).get('feature')
if (shared) {
this.editorTarget.value = shared
this.edit()
} else {
this.loadPreset({ params: { preset: 'park' } })
}
}

previewMessage (event) {
if (event.origin !== window.location.origin || event.data?.type !== 'style-preview-ready') { return }
this.ready = true
this.post(true)
}

loadPreset ({ params: { preset } }) {
this.presetTargets.forEach(button => {
button.classList.toggle('active', button.dataset.stylePlaygroundPresetParam === preset)
})
this.setFeature(structuredClone(PRESETS[preset]), true)
}

// Properties first and the coordinates on one line, so that the style properties stay in view
setFeature (feature, fit = false) {
const { type, properties, geometry, ...rest } = feature
const ordered = { type, properties, geometry: { ...geometry, coordinates: '__coordinates__' }, ...rest }
this.editorTarget.value = JSON.stringify(ordered, null, 2)
.replace('"__coordinates__"', JSON.stringify(geometry.coordinates))
this.edit(fit)
}

edit (fit = false) {
try {
const feature = JSON.parse(this.editorTarget.value)
if (feature?.type !== 'Feature' || !feature.geometry?.type) { throw new Error(window.__('Not a GeoJSON feature')) }
this.feature = feature
this.setStatus('✓ ' + window.__('valid'))
this.post(fit === true)
} catch (error) {
this.setStatus(error.message, true)
}
this.showCursor()
}

setStatus (text, error = false) {
this.statusTarget.textContent = text
this.statusTarget.classList.toggle('error', error)
}

post (fit) {
if (!this.ready || !this.feature) { return }
const pitch = this.feature.properties?.['fill-extrusion-height'] ? 50 : 0
this.previewTarget.contentWindow.postMessage(
{ type: 'style-preview', feature: { ...this.feature, id: 'preview' }, fit, pitch }, window.location.origin)
}

geometryType () {
return (this.feature?.geometry?.type || '').replace('Multi', '')
}

showCursor () {
const { value, selectionStart } = this.editorTarget
const lineEnd = value.indexOf('\n', selectionStart)
const line = value.slice(value.lastIndexOf('\n', selectionStart - 1) + 1, lineEnd === -1 ? undefined : lineEnd)
const property = this.properties[line.match(/"([a-z-]+)"\s*:/)?.[1]]
if (property) { this.renderCursor(property) }
}

renderCursor (property) {
const geometries = property.geometries
const info = geometries[this.geometryType()] || geometries.All || Object.values(geometries)[0]
const current = this.feature?.properties?.[property.name]
this.cursorNameTarget.textContent = property.name
this.cursorChipsTarget.replaceChildren(
...Object.keys(geometries).map(geometry => this.chip(this.geometriesValue[geometry])),
...(info.default ? [this.chip(window.__('default: %{value}').replace('%{value}', info.default))] : []))
// The description is our own markdown from docs/tutorials, rendered on the server
this.cursorDescTarget.innerHTML = info.html
this.cursorValuesTarget.replaceChildren(...property.values.map(value => {
const button = document.createElement('button')
button.type = 'button'
button.className = 'styling-value'
button.classList.toggle('active', String(current) === value)
button.textContent = value
button.addEventListener('click', () => this.setProperty(property.name, typed(value)))
return button
}))
this.cursorRelatedTarget.replaceChildren(...this.propertiesValue
.filter(other => other.group === property.group && other.name !== property.name).slice(0, 5)
.map(other => {
const link = document.createElement('a')
link.href = `#property-${other.name}`
link.textContent = other.name
return link
}))
}

chip (text) {
const chip = document.createElement('span')
chip.className = 'styling-chip'
chip.textContent = text
return chip
}

setProperty (name, value) {
this.feature.properties = { ...this.feature.properties, [name]: value }
this.setFeature(this.feature)
// keep the cursor on the property, so that the panel stays on it
const position = this.editorTarget.value.indexOf(`"${name}"`) + 1
this.editorTarget.setSelectionRange(position, position)
this.showCursor()
}

loadProperty ({ params: { name } }) {
const property = this.properties[name]
if (!property.geometries.All && !property.geometries[this.geometryType()]) {
this.loadPreset({ params: { preset: GEOMETRY_PRESETS[Object.keys(property.geometries)[0]] } })
}
this.setProperty(name, property.example)
this.editorTarget.focus({ preventScroll: true })
}

async copy () {
await navigator.clipboard.writeText(this.editorTarget.value)
this.setStatus(window.__('Copied'))
}

async share () {
const url = `${window.location.origin}${window.location.pathname}?feature=` +
encodeURIComponent(JSON.stringify(this.feature))
window.history.replaceState(null, '', url)
await navigator.clipboard.writeText(url)
this.setStatus(window.__('Link copied'))
}

filterGroup ({ params: { group } }) {
this.group = group
this.tabTargets.forEach(tab => tab.classList.toggle('active', tab.dataset.stylePlaygroundGroupParam === group))
this.filter()
}

filter () {
const query = this.searchTarget.value.trim().toLowerCase()
this.cardTargets.forEach(card => {
const inGroup = this.group === 'All' || card.dataset.group === this.group
card.hidden = !inGroup || !card.textContent.toLowerCase().includes(query)
})
}
}
2 changes: 2 additions & 0 deletions app/javascript/maplibre/layers/layers.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ export function loadLayerDefinitions({ refetch = false } = {}) {
if (window.gon.map_properties.public_id !== data.properties.public_id) { return }
layers = data.layers.map(l => createLayerInstance(l))
layers.forEach(l => {
// Only the style preview map carries its features in the definition, it has no layer url
if (l.layer.geojson) { l.localData = true }
const previous = previousGeojson.get(l.id)
if (previous && !l.layer.geojson) { l.geojson = previous }
})
Expand Down
79 changes: 79 additions & 0 deletions app/models/style_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Property data for the styling docs page, parsed from the bullets of the style spec markdown
class StyleSpec
GEOMETRY_HEADING = /\A#### \*(\w+)\* geometr/
PROPERTY_BULLET = /\A\* `([a-z-]+)`: (.*)/
VALUE = /\A[a-z#][\w#.-]*\z/i
# Values for the properties that have no default and no value list in the markdown
EXAMPLES = { "label" => "Stadtpark", "label-title" => "Park", "label-font" => [ "SUSE" ], "label-offset" => [ 0, 1 ],
"min-zoom" => 10, "max-zoom" => 17, "level" => "0", "title" => "Stadtpark", "desc" => "Open **9 to 17**",
"onclick-target" => "https://mapforge.org", "marker-symbol" => "☕", "flat" => true, "marker-rotate" => 45,
"stroke-image-url" => "/icons/direction-arrow.png", "stroke-symbol" => "➤", "fill-extrusion-height" => 30,
"fill-extrusion-width" => 4, "fill-extrusion-shadow" => true,
"marker-image-url" => "/logo/mapforge-logo-icon.png", "fill-image-url" => "/logo/mapforge-logo-icon.png" }.freeze

def self.properties
new(Tutorial.find("geojson_style_spec").markdown).properties
end

def initialize(markdown)
@markdown = markdown
end

def properties
entries = {}
geometry = nil
@markdown.each_line do |line|
break if line.start_with?("### Label fonts")
if (heading = line[GEOMETRY_HEADING, 1])
geometry = heading
next
end
next unless geometry && (match = line.match(PROPERTY_BULLET))

name, text = match.captures
entry = entries[name] ||= { name: name, group: group(name), geometries: {}, values: [] }
entry[:geometries][geometry] = { html: Tutorial.render(text, inline: true), default: default(text) }
entry[:values] |= text.scan(/`([^`]+)`/).flatten.grep(VALUE)
end
entries.each_value { |entry| clean(entry, entries.keys) }
entries.values
end

private

def clean(entry, names)
entry[:values] -= names
entry[:geometries].each_value { |geometry| geometry[:default] = nil if names.include?(geometry[:default]) }
defaults = entry[:geometries].values.pluck(:default)
entry[:values] = %w[true false] if entry[:values].empty? && defaults.intersect?(%w[true false])
entry[:example] = EXAMPLES.fetch(entry[:name]) { typed(defaults.compact.first || entry[:values].first) }
end

def typed(value)
case value
when "true", "false" then value == "true"
when /\A-?\d+\z/ then value.to_i
when /\A-?\d*\.\d+\z/ then value.to_f
else value
end
end

# A default that is a sentence ("depends on marker size") has no single value, so it gets none
def default(text)
value = text[/([^\s,(]+) \(default\)/, 1] || text[/\(defaults?(?: to)?:?\s+([^\s,)]+)\s*[,)]/, 1] ||
text[/The default is (\S+?)\.?(?:\s|\z)/, 1]
value&.delete("`\"'")&.strip
end

def group(name)
case name
when /\Alabel/ then "Label"
when /\Amarker-/, "flat" then "Marker"
when /\Astroke/ then "Stroke"
when /\Afill-extrusion-/ then "Extrusion"
when /\Afill-/, "fill" then "Fill"
when "min-zoom", "max-zoom", "level", "sort-key" then "Visibility"
else "Content"
end
end
end
Loading
Loading