diff options
Diffstat (limited to '')
19 files changed, 1838 insertions, 1741 deletions
diff --git a/assets/static/vendor/leaflet-elevation/src/components/chart.js b/assets/static/vendor/leaflet-elevation/src/components/chart.js index b0b5458..d5ffe93 100644 --- a/assets/static/vendor/leaflet-elevation/src/components/chart.js +++ b/assets/static/vendor/leaflet-elevation/src/components/chart.js @@ -1,444 +1,361 @@ -import * as D3 from './d3.js'; - const _ = L.Control.Elevation.Utils; -export var Chart = L.Control.Elevation.Chart = L.Class.extend({ - - includes: L.Evented ? L.Evented.prototype : L.Mixin.Events, +export var Chart = L.Control.Elevation.Chart = L.Evented.extend({ initialize(opts, control) { - this.options = opts; - this.control = control; - - this._data = control._data || []; - - // cache registered components - this._props = { - scales : {}, - paths : {}, - areas : {}, - grids : {}, - axes : {}, - legendItems : {}, - tooltipItems: {}, - }; - - this._scales = {}; - this._domains = {}; - this._ranges = {}; - this._paths = {}; - + this.options = opts; + this.control = control; + this._data = control._data || []; + this._props = { scales: {}, paths: {}, areas: {}, grids: {}, axes: {}, legendItems: {}, tooltipItems: {} }; + this._scales = {}; + this._domains = {}; + this._ranges = {}; + this._paths = {}; this._brushEnabled = opts.dragging; - this._zoomEnabled = opts.zooming; - - opts.xTicks = this._xTicks(); - opts.yTicks = this._yTicks(); - - let chart = this._chart = D3.Chart(opts); - - // SVG Container + this._zoomEnabled = opts.zooming; + this.__xTicks = opts.xTicks; + this.__yTicks = opts.yTicks; + this._transform = { k: 1, x: 0 }; + const { width, height, margins = {}, ruler, preferCanvas } = opts; + const svg = _.create('svg:svg', '', { class: 'background' }); + const defs = _.create('svg:defs', '', {}, svg); + const g = _.create('svg:g', '', {}, svg); + const panes = {}; + for (const name of ['grid', 'area', 'axis', 'point', 'brush', 'tooltip', 'ruler', 'legend']) panes[name] = _.create('svg:g', '', { class: name }, g); + panes.tooltip.setAttribute('display', 'none'); + const mask = _.create('svg:mask', '', { id: 'elevation-clipper-' + _.randomId(), 'fill-opacity': 1 }, panes.area); + const maskRect = _.create('svg:rect', '', { class: 'zoom', fill: 'white' }, mask); + const foreignObject = _.create('svg:foreignObject', '', { mask: `url(#${mask.id})` }, panes.area); + const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'); + canvas.className = 'canvas-plot'; + foreignObject.appendChild(canvas); + const context = canvas.getContext('2d'); + const webkitCanvas = preferCanvas && /Mac|iPod|iPhone|iPad/.test(navigator.platform) && + /AppleWebkit/i.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent); + const canvasImage = webkitCanvas ? _.create('svg:image', '', { mask: `url(#${mask.id})`, 'pointer-events': 'none' }, panes.area) : null; + if (canvasImage) foreignObject.remove(); + const overlay = _.create('svg:rect', '', { class: 'overlay', fill: 'none', 'pointer-events': 'all' }, panes.brush); + const selection = _.create('svg:rect', '', { class: 'selection', fill: '#777', 'fill-opacity': 0.3, stroke: '#fff', display: 'none' }, panes.brush); + for (const edge of ['w', 'e']) _.create('svg:rect', '', { class: `handle handle--${edge}`, fill: 'none', 'pointer-events': 'all', display: 'none', cursor: 'ew-resize' }, panes.brush); + const chart = this._chart = { svg, g, panes, utils: { defs, mask, canvas, context }, pane: name => panes[name] || (panes[name] = _.create('svg:g', '', { class: name }, g)) }; + chart.get = name => chart.utils[name]; + // ponytail: Safari encodes one PNG per redraw; use a separate HTML canvas layer if encoding becomes a bottleneck. + chart._renderCanvas = () => { if (canvasImage) canvasImage.setAttribute('href', canvas.toDataURL()); }; + chart._resize = ({ width, height, margins = {}, ruler }) => { + const w = width - margins.left - margins.right, h = height - margins.top - margins.bottom; + _.setAttributes(svg, { width, height, viewBox: `0 0 ${width} ${height}` }); + g.setAttribute('transform', `translate(${margins.left},${margins.top})`); + _.setAttributes(maskRect, { width: w, height: h, x: 0, y: 0 }); + _.setAttributes(foreignObject, { width: w, height: h }); + _.setAttributes(canvas, { width: w, height: h }); + if (canvasImage) { _.setAttributes(canvasImage, { width: w, height: h }); canvasImage.removeAttribute('href'); } + _.setAttributes(overlay, { x: 0, y: 0, width: w, height: h }); + selection.setAttribute('display', 'none'); + for (const handle of panes.brush.querySelectorAll('.handle')) handle.setAttribute('display', 'none'); + if (ruler) { + const group = panes.ruler; + group.replaceChildren(); + group.dataset.y = h; + group.setAttribute('transform', `translate(0,${h})`); + _.create('svg:rect', '', { class: 'horizontal-drag-rect', x: 0, y: -8, width: w, height: 8, fill: 'none', 'pointer-events': 'all' }, group); + _.create('svg:line', '', { class: 'horizontal-drag-line', x1: 0, x2: w }, group); + _.create('svg:text', '', { class: 'horizontal-drag-label', 'text-anchor': 'end', x: w - 8, y: -8 }, group); + _.create('svg:path', '', { class: 'horizontal-drag-symbol', d: 'M0,-6L5,3L-5,3Z', transform: `translate(${w + 7},0) rotate(-90)` }, group); + } + chart._width = w; + chart._height = h; + svg.dispatchEvent(new CustomEvent('resize', { detail: { width: w, height: h } })); + }; + chart._resize({ width, height, margins, ruler }); this._container = chart.svg; - - // Panes - this._grid = chart.pane('grid'); - this._area = chart.pane('area'); - this._point = chart.pane('point'); - this._axis = chart.pane('axis'); - this._legend = chart.pane('legend'); - this._tooltip = chart.pane('tooltip'); - this._ruler = chart.pane('ruler'); - - // Scales - this._initScale(); - - // Helpers - this._mask = chart.get('mask'); - this._context = chart.get('context'); - this._brush = chart.get('brush'); - - this._zoom = d3.zoom(); - this._drag = d3.drag(); - - // Interactions - this._initInteractions(); - - // svg.on('resize', (e)=>console.log(e.detail)); - - // Handle multi-track segments + for (const name of ['grid', 'area', 'point', 'axis', 'legend', 'tooltip', 'ruler']) this['_' + name] = chart.pane(name); + this._mask = chart.get('mask'); + this._context = chart.get('context'); + this._registerAxisScale({ axis: 'x', position: 'bottom', attr: opts.xAttr, min: opts.xAxisMin, max: opts.xAxisMax, name: 'distance' }); + this._registerAxisScale({ axis: 'y', position: 'left', attr: opts.yAttr, min: opts.yAxisMin, max: opts.yAxisMax, name: 'altitude' }); + this._x = this._scales.distance; + this._y = this._scales.altitude; this._maskGaps = []; - control.on('eletrack_added', ({index}) => { + control.on('eletrack_added', ({ index }) => { this._maskGaps.push(index); - control.once('elepoint_added', ({index}) => this._maskGaps.push(index)); + control.once('elepoint_added', ({ index }) => this._maskGaps.push(index)); }); - - }, - - update(props) { - if (props) { - if (props.data) this._data = props.data; - if (props.options) this.options = props.options; - } - - this.options.xTicks = this._xTicks(); - this.options.yTicks = this._yTicks(); - - this._updateScale(); - this._updateAxis(); - this._updateMargins(); - this._updateLegend(); - this._updateClipper(); - this._updateArea(); - - return this; - }, - - render() { - return container => container.append(() => this._container.node()); - }, - - clear() { - this._resetDrag(); - this._hideDiagramIndicator() - this._area.selectAll('path').attr("d", "M0 0"); - this._context.clearRect(0, 0, this._width(), this._height()); - this._mask.selectAll(".gap").remove(); - this._maskGaps = []; - - // if (this._path) { - // this._x.domain([0, 1]); - // this._y.domain([0, 1]); - // } - }, - - _drawPath(name) { - let path = this._paths[name]; - let area = this._props.areas[name]; - - path.datum(this._data).attr("d", - D3.Area( - L.extend({}, area, { - width : this._width(), - height : this._height(), - scaleX : this._scales[area.scaleX], - scaleY : this._scales[area.scaleY] - }) - ) - ); - - if (!path.classed('leaflet-hidden')) { - this.options.preferCanvas - ? _.drawCanvas(this._context, path) - : _.append(this._area.node(), path.node()); - } - }, - - _hasActiveLayers() { - const paths = this._paths; - for (var i in paths) { - if (!paths[i].classed('leaflet-hidden')) { - return true; - } - } - return false; - }, - - /** - * Initialize "d3-brush". - */ - _initBrush(e) { - const brush = ({selection}) => { - if (selection && this._data.length) { - let start = this._findIndexForXCoord(selection[0]); - let end = this._findIndexForXCoord(selection[1]); - this.fire('dragged', { dragstart: this._data[start], dragend: this._data[end] }); + const brush = panes.brush; + const focus = event => { + if (!this.options.detached) event.stopPropagation(); + if (!this._data.length) return; + const xCoord = _.clamp(_.pointer(event, this._area)[0], [0, this._width()]); + this.fire('mouse_move', { item: this._data[this._findIndexForXCoord(xCoord)], xCoord }); + }; + const rulerLabel = () => { + const y = +this._ruler.dataset.y; + if (y <= 0 || y >= this._height()) this._ruler.querySelector('text').textContent = ''; + this._hideDiagramIndicator(); + }; + brush.style.touchAction = 'none'; + this._ruler.style.touchAction = 'none'; + brush.addEventListener('pointerenter', () => this.fire('mouse_enter')); + brush.addEventListener('pointerleave', () => { if (!this._gesture) this.fire('mouse_out'); }); + brush.addEventListener('pointermove', event => { if (!this._gesture) focus(event); }); + brush.addEventListener('mousemove', event => { + if (!this.options.detached) event.stopPropagation(); + }); + svg.addEventListener('pointerdown', event => { + if (this._gesture || !event.isPrimary) return; + const [x] = _.pointer(event, this._area); + let type; + if (this._ruler.contains(event.target) && this.options.ruler && event.button === 0) type = 'ruler'; + else if ((event.shiftKey || event.button === 1) && this._zoomEnabled) type = 'pan'; + else if (brush.contains(event.target) && !event.shiftKey && event.button === 0 && this._brushEnabled) { + type = event.target.classList.contains('handle--w') ? 'west' : + event.target.classList.contains('handle--e') ? 'east' : + event.target.classList.contains('selection') ? 'move' : 'brush'; } - } - - const focus = (e) => { - if (this._data.length && (e.type != 'brush' /*|| e.sourceEvent*/)) { - let rect = this._chart.panes.brush.select('.overlay').node(); - let coords = d3.pointers(e, rect)[0]; - let xCoord = _.clamp(coords[0], [0, this._width()]); // Clamps cursor position to chart's bounds (see issues: #270, #301) - let item = this._data[this._findIndexForXCoord(xCoord)]; - - this.fire("mouse_move", { item: item, xCoord: xCoord }); + if (!type) return; + event.preventDefault(); + event.stopPropagation(); + svg.setPointerCapture(event.pointerId); + this._gesture = { type, id: event.pointerId, start: x, selection: this._selection?.slice(), transform: { ...this._transform } }; + if (type === 'ruler') rulerLabel(); + else if (type === 'pan') svg.style.cursor = 'grabbing'; + else { + this.fire('mouse_enter'); + if (type === 'brush') this._setSelection([x, x]); + focus(event); } - }; - - this._brush - .filter(({shiftKey, button}) => !shiftKey && !button && this._brushEnabled) - .on("end.update", brush) - .on("brush.update", focus); - - this._chart.panes.brush - .on("mouseenter.focus touchstart.focus", this.fire.bind(this, "mouse_enter")) - .on("mouseout.focus touchend.focus", this.fire.bind(this, "mouse_out") ) - .on("mousemove.focus touchmove.focus", focus ); - - }, - - /** - * Initialize "d3-zoom" - */ - _initClipper() { - let svg = this._container; - let margin = this.options.margins; - - const zoom = this._zoom; - - const onStart = ({transform, sourceEvent}) => { - if (sourceEvent && sourceEvent.type == "mousedown") svg.style('cursor', 'grabbing'); - if (transform.k == 1 && transform.x == 0) { - this._container.classed('zoomed', true); - // Apply d3-zoom and bind <mask> - if (this._mask) { - this._point.attr('mask', 'url(#' + this._mask.attr('id') + ')'); + }); + svg.addEventListener('pointermove', event => { + const gesture = this._gesture; + if (!gesture || gesture.id !== event.pointerId) return; + event.preventDefault(); + const [rawX, rawY] = _.pointer(event, this._area); + const x = _.clamp(rawX, [0, this._width()]); + if (gesture.type === 'pan') { + this._setZoom(gesture.transform.k, gesture.transform.x + rawX - gesture.start); + this._hideDiagramIndicator(); + } else if (gesture.type === 'ruler') { + const y = _.clamp(rawY, [0, this._height()]); + this._ruler.dataset.y = y; + this._ruler.setAttribute('transform', `translate(0,${y})`); + this._ruler.classList.toggle('active', y < this._height()); + this._ruler.querySelector('text').textContent = this._y.invert(y).toFixed(0) + ' ' + (this.options.imperial ? 'ft' : 'm'); + const groups = []; + if (rawY > 0 && rawY < this._height()) { + const altitude = this._y.invert(rawY); + let group; + for (const item of this._data) { + if (item[this.options.yAttr] >= altitude) { + if (!group) groups.push(group = []); + group.push(item.latlng); + } else group = null; + } } + this.fire('ruler_filter', { coords: groups }); + } else { + let selection; + if (gesture.type === 'move') { + const delta = _.clamp(x - gesture.start, [-gesture.selection[0], this._width() - gesture.selection[1]]); + selection = gesture.selection.map(value => value + delta); + } else if (gesture.type === 'west') selection = [x, gesture.selection[1]]; + else if (gesture.type === 'east') selection = [gesture.selection[0], x]; + else selection = [_.clamp(gesture.start, [0, this._width()]), x]; + this._setSelection(selection); } - this.zooming = true; - }; - - const onEnd = ({transform}) => { - if (transform.k ==1 && transform.x == 0) { - this._container.classed('zoomed', false); - // Reset d3-zoom and remove <mask> - if (this._mask) { - this._point.attr('mask', null); - } + }); + const end = event => { + const gesture = this._gesture; + if (!gesture || gesture.id !== event.pointerId) return; + this._gesture = null; + svg.style.cursor = ''; + if (svg.hasPointerCapture(event.pointerId)) svg.releasePointerCapture(event.pointerId); + if (gesture.type === 'ruler') rulerLabel(); + else if (gesture.type !== 'pan') { + if (event.type === 'pointercancel' || !this._selection || this._selection[1] - this._selection[0] < 1) this._resetDrag(); + else if (this._data.length) this.fire('dragged', { + dragstart: this._data[this._findIndexForXCoord(this._selection[0])], + dragend: this._data[this._findIndexForXCoord(this._selection[1])], + }); } - this.zooming = false; - svg.style('cursor', ''); + if (event.pointerType === 'touch') this.fire('mouse_out'); }; - - const onZoom = ({transform, sourceEvent}) => { - // TODO: find a faster way to redraw the chart. - this.zooming = false; - this._updateScale(); // hacky way for restoring x scale when zooming out - this.zooming = true; - this._scales.distance = this._x = transform.rescaleX(this._x); // calculate x scale at zoom level - if (this._scales.time) this._scales.time = transform.rescaleX(this._scales.time); // calculate x scale at zoom level - this._resetDrag(); - if (sourceEvent && sourceEvent.type == "mousemove") { - this._hideDiagramIndicator(); - } - this.fire('zoom'); + for (const name of ['pointerup', 'pointercancel', 'lostpointercapture']) svg.addEventListener(name, end); + const zoomAt = (event, factor) => { + if (!this._zoomEnabled || !event.shiftKey) return; + event.preventDefault(); + const x = _.pointer(event, this._area)[0]; + const k = _.clamp(this._transform.k * factor, [1, 10]); + this._setZoom(k, x - (x - this._transform.x) * k / this._transform.k); }; - - zoom - .scaleExtent([1, 10]) - .extent([ - [margin.left, 0], - [this._width() - margin.right, this._height()] - ]) - .translateExtent([ - [margin.left, -Infinity], - [this._width() - margin.right, Infinity] - ]) - .filter(({shiftKey, buttons}) => (shiftKey || buttons == 4) && this._zoomEnabled) - .on("start", onStart) - .on("end", onEnd) - .on("zoom", onZoom); - - svg.call(zoom); // add zoom functionality to "svg" group - - // d3.select("body").on("keydown.grabzoom keyup.grabzoom", (e) => svg.style('cursor', e.shiftKey ? 'move' : '')); - + svg.addEventListener('wheel', event => zoomAt(event, 2 ** (-event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002))), { passive: false }); + svg.addEventListener('dblclick', event => zoomAt(event, 2)); + svg.addEventListener('legend_clicked', ({ detail: { path, name, legend, enabled } }) => { + if (!path) return; + this._togglePath(name, !enabled); + this.fire('elepath_toggle', { path, name, legend, enabled }); + }); }, - _initInteractions() { - this._initBrush(); - this._initRuler(); - this._initClipper(); - this._initLegend(); + render() { + return container => container.appendChild(this._container); }, - /** - * Toggle chart data on legend click - */ - _initLegend() { - this._container.on('legend_clicked', ({detail}) => { - let { path, legend, name, enabled } = detail; - if (path) { - let label = _.select('text', legend); - let rect = _.select('rect', legend); - _.toggleStyle(label, 'text-decoration-line', 'line-through', enabled); - _.toggleStyle(rect, 'fill-opacity', '0', enabled); - _.toggleClass(path, 'leaflet-hidden', enabled); - this._updateArea(); - this.fire("elepath_toggle", { path, name, legend, enabled }) - } - }); + clear() { + this._resetDrag(); + this._hideDiagramIndicator(); + this._transform = { k: 1, x: 0 }; + this._container.classList.remove('zoomed'); + this._point.removeAttribute('mask'); + this._point.replaceChildren(); + for (const path of Object.values(this._paths)) path.setAttribute('d', 'M0 0'); + this._context.clearRect(0, 0, this._width(), this._height()); + this._chart._renderCanvas(); + this._mask.querySelectorAll('.gap').forEach(node => node.remove()); + this._maskGaps = []; }, - /** - * Initialize "ruler". - */ - _initRuler() { - if (!this.options.ruler) return; - - // const yMax = this._height(); - const formatNum = d3.format(".0f"); - const drag = this._drag; - - const label = (e, d) => { - let yMax = this._height(); - let y = this._ruler.data()[0].y; - if (y >= yMax || y <= 0) this._ruler.select(".horizontal-drag-label").text(''); - this._hideDiagramIndicator(); - }; - - const position = (e, d) => { - let yCoord = d3.pointers(e, this._area.node())[0][1]; - let yMax = this._height(); - let y = _.clamp(yCoord, [0, yMax]); - - this._ruler - .data([L.extend(this._ruler.data()[0], { y: y })]) - .attr("transform", d => "translate(" + d.x + "," + d.y + ")") - .classed('active', y < yMax); - - this._container - .select(".horizontal-drag-label") - .text(formatNum(this._y.invert(y)) + " " + (this.options.imperial ? 'ft' : 'm')); - - this.fire('ruler_filter', { coords: yCoord < yMax && yCoord > 0 ? this._findCoordsForY(yCoord) : [] }); - } - - drag - .on("start end", label) - .on("drag", position); - - this._ruler.call(drag); - + _hasActiveLayers() { + return Object.values(this._paths).some(path => !path.classList.contains('leaflet-hidden')); }, - /** - * Initialize x and y scales - */ - _initScale() { - let opts = this.options; - - this._registerAxisScale({ - axis : 'x', - position: 'bottom', - attr : opts.xAttr, - min : opts.xAxisMin, - max : opts.xAxisMax, - name : 'distance' + _setSelection(values) { + this._selection = values.map(x => _.clamp(x, [0, this._width()])).sort((a, b) => a - b); + const [start, end] = this._selection; + _.setAttributes(this._chart.panes.brush.querySelector('.selection'), { + x: start, y: 0, width: end - start, height: this._height(), display: 'inline', cursor: 'move', }); - - this._registerAxisScale({ - axis : 'y', - position : 'left', - attr : opts.yAttr, - min : opts.yAxisMin, - max : opts.yAxisMax, - name : 'altitude' + for (const edge of ['w', 'e']) _.setAttributes(this._chart.panes.brush.querySelector('.handle--' + edge), { + x: (edge === 'w' ? start : end) - 3, y: 0, width: 6, height: this._height(), display: 'inline', }); + }, - this._x = this._scales.distance; - this._y = this._scales.altitude; + _setZoom(k, x) { + if (!Number.isFinite(k) || !Number.isFinite(x) || k <= 0) throw new Error('Invalid chart zoom'); + k = _.clamp(k, [1, 10]); + this._transform = { k, x: _.clamp(x, [this._width() * (1 - k), 0]) }; + this._container.classList.toggle('zoomed', k !== 1); + if (k !== 1) this._point.setAttribute('mask', `url(#${this._mask.id})`); + else this._point.removeAttribute('mask'); + this._resetDrag(); + this._updateScale(); + this.fire('zoom'); }, _registerAreaPath(props) { - if (props.scale == 'y') props.scale = this._y; - else if (props.scale == 'x') props.scale = this._x; - - let opts = this.options; - - if (!props.xAttr) props.xAttr = opts.xAttr; - if (!props.yAttr) props.yAttr = opts.yAttr; - if (typeof props.preferCanvas === "undefined") props.preferCanvas = opts.preferCanvas; - - // Save paths in memory for latter usage - this._paths[props.name] = D3.Path(props); + props = { xAttr: this.options.xAttr, yAttr: this.options.yAttr, preferCanvas: this.options.preferCanvas, ...props }; + const { name, color, strokeColor, strokeOpacity, fillOpacity, className = '' } = props; + const path = this._paths[name] = _.create('svg:path', '', { + class: `${name || ''} ${className}`, + fill: color || '#3366CC', stroke: strokeColor || '#000', + 'stroke-opacity': strokeOpacity ?? 1, 'fill-opacity': fillOpacity ?? 0.8, + }); + path.style.pointerEvents = 'none'; this._props.areas[props.name] = props; - - if (opts.legend) { - this._props.legendItems[props.name] = { - name : props.name, - label : props.label, - color : props.color, - className: props.className, - path : this._paths[props.name] - }; - } - + if (this.options.legend) this._props.legendItems[props.name] = { ...props, path: this._paths[props.name] }; }, _registerAxisGrid(props) { - if (props.scale == 'y') props.scale = this._y; - else if (props.scale == 'x') props.scale = this._x; - - this._props.grids[props.name || props.axis] = props; + this._props.grids[props.name || props.axis] = { ...props }; }, _registerAxisScale(props) { - if (props.scale == 'y') props.scale = this._y; - else if (props.scale == 'x') props.scale = this._x; - - let opts = this.options; - let scale = props.scale; - - if (typeof this._scales[props.name] === 'function') { - props.scale = this._scales[props.name]; // retrieve cached scale - } else if (typeof scale !== 'function') { - scale = L.extend({ - data : this._data, - forceBounds: opts.forceAxisBounds - }, scale); - - scale.attr = scale.attr || props.name; - - let domain = this._domains[props.name] = D3.Domain(props); - let range = this._ranges[props.name] = D3.Range(props); - scale.range = scale.range || range(this._width(),this._height()); - scale.domain = scale.domain || domain(this._data); - + props = { ...props }; + const alias = props.scale; + if (alias === 'y') props.scale = this._y; + else if (alias === 'x') props.scale = this._x; + if (typeof this._scales[props.name] === 'function') props.scale = this._scales[props.name]; + else if (typeof props.scale !== 'function') { + const scale = { data: this._data, forceBounds: this.options.forceAxisBounds, ...props.scale }; + scale.attr = scale.attr || props.name; + const { min, max, attr, name, forceBounds, scale: domainScale } = { forceBounds: scale.forceBounds, ...props }; + const key = (domainScale && domainScale.attr) || attr || name; + this._domains[props.name] = data => { + let low = Infinity, high = -Infinity; + for (const point of data || []) { + const value = point[key]; + if (value == null || !Number.isFinite(+value)) continue; + low = Math.min(low, +value); + high = Math.max(high, +value); + } + if (low === Infinity) [low, high] = [0, 1]; + if (min !== undefined && (min < low || forceBounds)) low = +min; + if (max !== undefined && (max > high || forceBounds)) high = +max; + return [low, high]; + }; + this._ranges[props.name] = (width, height) => props.axis === 'x' ? [0, width] : [height, 0]; + scale.range = scale.range || this._ranges[props.name](this._width(), this._height()); + scale.domain = scale.domain || this._domains[props.name](this._data); this._props.scales[props.name] = scale; - - props.scale = this._scales[props.name] = D3.Scale(scale); - } - - if (!props.ticks) { - if (props.axis == 'x') props.ticks = this._xTicks.bind(this); - else if (props.axis == 'y') props.ticks = this._yTicks.bind(this); + const Scale = function({ domain, range }) { + let bounds = domain; + let pixels = range; + const interpolate = (value, from, to) => { + const fraction = from[1] === from[0] ? 0.5 : (value - from[0]) / (from[1] - from[0]); + return to[0] + fraction * (to[1] - to[0]); + }; + const scale = value => value == null ? undefined : interpolate(+value, bounds, pixels); + scale.invert = value => interpolate(+value, pixels, bounds); + scale.domain = function(value) { + if (!arguments.length) return bounds.slice(); + bounds = value.map(Number); + return scale; + }; + scale.range = function(value) { + if (!arguments.length) return pixels.slice(); + pixels = value.map(Number); + return scale; + }; + scale.copy = () => Scale({ domain: bounds.slice(), range: pixels.slice() }); + scale.ticks = (count = 10) => { + const [low, high] = [Math.min(...bounds), Math.max(...bounds)]; + if (!(count > 0) || !Number.isFinite(low + high)) return []; + if (low === high) return [low]; + const raw = (high - low) / count; + const power = 10 ** Math.floor(Math.log10(raw)); + const error = raw / power; + const step = power * (error >= Math.sqrt(50) ? 10 : error >= Math.sqrt(10) ? 5 : error >= Math.sqrt(2) ? 2 : 1); + const first = Math.ceil(low / step), last = Math.floor(high / step); + const values = Array.from({ length: Math.max(0, last - first + 1) }, (_, i) => +( (first + i) * step).toPrecision(14)); + return bounds[0] > bounds[1] ? values.reverse() : values; + }; + return scale; + }; + props.scale = this._scales[props.name] = Scale(scale); + } else if (alias === 'x' || alias === 'y') { + // Aliases share the original scale, including its zoomed domain. + this._scales[props.name] = props.scale; } - + if (!props.ticks) props.ticks = (props.axis === 'x' ? this._xTicks : this._yTicks).bind(this); this._props.axes[props.name] = props; - - if (props.name == this.options.yScale) this._y = scale; - if (props.name == this.options.xScale) this._x = scale; - - return scale; + if (props.name === this.options.yScale) this._y = props.scale; + if (props.name === this.options.xScale) this._x = props.scale; + return props.scale; }, - /** - * Add a point of interest over the chart - */ _registerCheckPoint(point) { if (!this._data.length) return; - - const {xAttr, yAttr} = this.options; - let item, x, y; - + const { xAttr, yAttr } = this.options; + let item, x; if (point.latlng) { item = this._data[this._findIndexForLatLng(point.latlng)]; - x = this._x(item[xAttr]); - y = this._y(item[yAttr]); + x = this._x(item[xAttr]); } else if (!isNaN(point[xAttr])) { - x = this._x(point[xAttr]); - item = this._data[this._findIndexForXCoord(x)] - y = this._y(item[yAttr]); - } - - this._point.call(D3.CheckPoint({ - point: point, - width: this._width(), - height: this._height(), - x: x, - y: y, - })); + x = this._x(point[xAttr]); + item = this._data[this._findIndexForXCoord(x)]; + } + if (!item) return; + const y = this._y(item[yAttr]); + if (!Number.isFinite(x) || !Number.isFinite(y)) return; + if (!point.item?.isConnected) { + point.position = point.position || 'bottom'; + point.item = _.create('svg:g', '', {}, this._point); + _.create('svg:line', '', { x1: 0, y1: 0, style: 'stroke: rgb(51, 51, 51); stroke-width: 0.5; stroke-dasharray: 2, 2;' }, point.item); + _.create('svg:circle', '', { class: 'height-focus circle-lower', r: 3 }, point.item); + if (point.label) _.create('svg:text', '', { dx: '4px', dy: '-4px' }, point.item); + } + _.setAttributes(point.item, { class: 'point ' + point.position, transform: `translate(${x},${y})`, 'data-y': y }); + _.setAttributes(point.item.querySelector('line'), { y2: ({ top: -y, bottom: this._height() - y })[point.position], + x2: ({ left: -x, right: this._width() - x })[point.position] || 0 }); + if (point.label) point.item.querySelector('text').textContent = point.label; }, _registerTooltip(props) { @@ -447,337 +364,254 @@ export var Chart = L.Control.Elevation.Chart = L.Class.extend({ }, _updateArea() { - // Reset and update chart profiles this._context.clearRect(0, 0, this._width(), this._height()); - _.each(this._paths, (path, i) => !path.classed('leaflet-hidden') && this._drawPath(i)); - }, - - _updateAxis() { - - let opts = this.options; - - const gridOpts = { - width : this._width(), - height : this._height(), - tickFormat: "", - }; - - const axesOpts = { - width : this._width(), - height : this._height(), - }; - - // Reset grids - this._grid.selectAll('g').remove(); - _.each(this._props.grids, (grid, i) => { - if (opts[i] !== false && opts[i] !== 'summary') { - this._grid.call(D3.Grid(L.extend({}, gridOpts, grid))) + for (const name in this._paths) { + const path = this._paths[name], area = this._props.areas[name]; + if (path.classList.contains('leaflet-hidden')) continue; + const { xAttr, yAttr, interpolation = 'curveLinear' } = { interpolation: this.options.interpolation, ...area }; + const scaleX = this._scales[area.scaleX], scaleY = this._scales[area.scaleY]; + if (!['curveLinear', 'curveStep', 'curveStepBefore', 'curveStepAfter'].includes(interpolation)) { + throw new Error(`Unsupported interpolation "${interpolation}". Use curveLinear, curveStep, curveStepBefore or curveStepAfter.`); } - }); - - // Rest axis - this._axis.selectAll('g').remove(); - _.each(this._props.axes, (axis, i) => { - if (opts[i] !== false && opts[i] !== 'summary') { - this._axis.call(D3.Axis(L.extend({}, axesOpts, axis))); - } - }); - - // Adjust axis scale positions - this._axis - .selectAll('.y.axis.right') - .each((d, i, n) => { - - let axis = d3.select(n[i]); - let transform = axis.attr('transform'); - let translate = transform.substring(transform.indexOf("(") + 1, transform.indexOf(")")).split(","); - - axis.attr('transform', 'translate(' + (+translate[0] + (i * 40)) + ',' + translate[1] + ')') - - if (i > 0) { - axis.select(':scope > path') .attr('opacity', 0.25); - axis.selectAll(':scope > .tick line').attr('opacity', 0.75); + let outline = ''; + if (this._data.length) { + const points = this._data.map(d => [d.xDiagCoord = scaleX(d[xAttr]), scaleY(d[yAttr])]); + outline = `M${points[0]}`; + for (let i = 1; i < points.length; i++) { + const [x, y] = points[i], [previousX] = points[i - 1]; + if (interpolation === 'curveStepBefore') outline += `V${y}H${x}`; + else if (interpolation === 'curveStepAfter') outline += `H${x}V${y}`; + else if (interpolation === 'curveStep') outline += `H${(previousX + x) / 2}V${y}H${x}`; + else outline += `L${x},${y}`; } - - }); - - }, - - _updateClipper() { - const { xAttr, margins } = this.options; - const data = this._data; - - this._zoom - .scaleExtent([1, 10]) - .extent([ - [margins.left, 0], - [this._width() - margins.right, this._height()] - ]) - .translateExtent([ - [margins.left, -Infinity], - [this._width() - margins.right, Infinity] - ]); - - // Apply svg mask on multi-track segments - this._mask.selectAll(".gap").remove() - this._maskGaps.forEach((d, i) => { - if (i >= this._maskGaps.length - 2) return; - let x1 = this._x(data[this._findIndexForLatLng(data[this._maskGaps[i]].latlng)][xAttr]); - let x2 = this._x(data[this._findIndexForLatLng(data[this._maskGaps[i + 1]].latlng)][xAttr]); - this._mask - .append("rect") - .attr("x", x1) - .attr("y", 0) - .attr("width", x2 - x1 ) - .attr("height", this._height()) - .attr('class', 'gap') - .attr('fill-opacity', '0.8') - .attr("fill", 'black'); // hide = black (mask) - }); - }, - - _updateLegend: function () { - let xAxesB = this._axis.selectAll('.x.axis.bottom').nodes().length; - - // Get legend items - let items = Object.keys(this._paths); - - // Calculate legend item positions - let n = items.length; - let v = Array(Math.floor(n / 2)).fill(null).map((d, i) => (i + 1) * 2 - (1 - Math.sign(n % 2))); - let rev = v.slice().reverse().map((d) => -(d)); - - // push a fake element to handle center alignment (odd numbers) - if (n % 2 !== 0) { - rev.push(0); - } - v = rev.concat(v); - - // Reset legend items - this._legend.selectAll('g').remove(); - - // Render legend items - _.each(this._props.legendItems, (legend) => { - this._legend.append("g").call( - D3.LegendItem(L.extend({ - width : this._width(), - height : this._height(), - margins: this.options.margins, - }, legend)) - ); - }); - - // Render legend item switcher - if (n > 1) { - this._legend.append("g").call( - D3.LegendSmall({ - width : this._width(), - height : this._height(), - items : items, - onClick: (selected) => { - _.each(items, name => this._togglePath(name, selected == name, true)); - this._updateArea(); - } - }) - ); + outline += `L${points.at(-1)[0]},${this._height()}L${points[0][0]},${this._height()}Z`; + } + path.setAttribute('d', outline); + if (this.options.preferCanvas) _.drawCanvas(this._context, path); + else this._area.appendChild(path); } - - _.each(items, (name, i) => { - // Adjust legend item positions - this._legend.select('[data-name=' + name + ']').attr("transform", "translate(" + (v[i] * 55) + ", " + (xAxesB * 2) + ")"); - // Set initial state (disabled controls) - this._togglePath(name, !(name in this.options && this.options[name] == 'disabled'), true); - }); - + this._chart._renderCanvas(); }, - _updateMargins() { - // Get chart margins - let xAxesB = this._axis.selectAll('.x.axis.bottom').nodes().length; - let xAxesL = this._axis.selectAll('.y.axis.left').nodes().length; - let xAxesR = this._axis.selectAll('.y.axis.right').nodes().length; - let marginB = 60 + (xAxesB * 2); - let marginL = 10 + (xAxesL * 30); - let marginR = 40 + (xAxesR * 30); - - let marginsUpdated = false - - // Adjust right margin - if (xAxesR && this.options.margins.right < marginR) { - this.options.margins.right = marginR; - marginsUpdated = true; + update(props) { + if (props?.data) this._data = props.data; + if (props?.options) this.options = props.options; + this.options.xTicks = this._xTicks(); + this.options.yTicks = this._yTicks(); + this._updateScale(); + this._grid.replaceChildren(); + this._axis.replaceChildren(); + const entries = [ + ...Object.entries(this._props.grids).map(([name, props]) => [name, { tickFormat: '', ...props, type: 'grid' }, this._grid]), + ...Object.entries(this._props.axes).map(([name, props]) => [name, props, this._axis]), + ]; + for (const [key, props, parent] of entries) { + if (this.options[key] === false || this.options[key] === 'summary') continue; + const { + type = 'axis', tickSize = 6, tickPadding = 3, position, height, width, + axis, ticks, tickFormat, label, labelX, labelY, name = '', onAxisMount, + } = { width: this._width(), height: this._height(), ...props }; + const scale = props.scale === 'x' ? this._x : props.scale === 'y' ? this._y : props.scale; + const horizontal = axis === 'x'; + const sign = position === 'top' || position === 'left' ? -1 : 1; + const size = type === 'grid' ? horizontal ? -height : -width : tickSize; + const group = _.create('svg:g', '', { + class: [axis, type, position, name].join(' '), + transform: `translate(${position === 'right' ? width : 0},${position === 'bottom' ? height : 0})`, + fill: 'none', 'font-size': 10, 'font-family': 'sans-serif', + 'text-anchor': horizontal ? 'middle' : sign < 0 ? 'end' : 'start', + }, parent); + const range = scale.range(); + _.create('svg:path', '', { class: 'domain', stroke: 'currentColor', + d: horizontal ? `M${range[0]},${sign * 6}V0.5H${range[1]}V${sign * 6}` : `M${sign * 6},${range[0]}H0.5V${range[1]}H${sign * 6}` }, group); + const values = scale.ticks(typeof ticks === 'function' ? ticks() : ticks); + const step = values.length > 1 ? Math.abs(values[1] - values[0]) : 1; + const format = new Intl.NumberFormat('en-US', { maximumFractionDigits: Math.min(20, Math.max(0, -Math.floor(Math.log10(step)))) }); + for (const value of values) { + const coordinate = scale(value) + 0.5; + const tick = _.create('svg:g', '', { class: 'tick', opacity: 1, transform: horizontal ? `translate(${coordinate},0)` : `translate(0,${coordinate})` }, group); + _.create('svg:line', '', { stroke: 'currentColor', [horizontal ? 'y2' : 'x2']: sign * size }, tick); + const text = _.create('svg:text', '', { fill: 'currentColor', [horizontal ? 'y' : 'x']: sign * (Math.max(0, size) + tickPadding), + dy: horizontal ? sign < 0 ? '0em' : '0.71em' : '0.32em' }, tick); + text.textContent = typeof tickFormat === 'function' ? tickFormat(value) : tickFormat ?? format.format(value); + } + if (label) _.create('svg:text', '', { + x: typeof labelX === 'function' ? labelX() : labelX, + y: typeof labelY === 'function' ? labelY() : labelY, + }, group).textContent = label; + if (onAxisMount) onAxisMount(group); } - - // Adjust left margin - if (xAxesL && this.options.margins.left < marginL) { - this.options.margins.left = marginL; - marginsUpdated = true; + this._axis.querySelectorAll('.y.axis.right').forEach((axis, i) => { + axis.setAttribute('transform', `translate(${this._width() + i * 40},0)`); + if (i > 0) { + axis.querySelector(':scope > path').setAttribute('opacity', 0.25); + axis.querySelectorAll(':scope > .tick line').forEach(line => line.setAttribute('opacity', 0.75)); + } + }); + const margins = { + bottom: 60 + this._axis.querySelectorAll('.x.axis.bottom').length * 2, + left: 10 + this._axis.querySelectorAll('.y.axis.left').length * 30, + right: 40 + this._axis.querySelectorAll('.y.axis.right').length * 30, + }; + let updated = false; + for (const side in margins) { + if (this._axis.querySelector(side === 'bottom' ? '.x.axis.bottom' : '.y.axis.' + side) && this.options.margins[side] < margins[side]) { + this.options.margins[side] = margins[side]; + updated = true; + } } + if (updated) this.fire('margins_updated'); - // Adjust bottom margin - if (xAxesB && this.options.margins.bottom < marginB) { - this.options.margins.bottom = marginB; - marginsUpdated = true; + const xAxesB = this._axis.querySelectorAll('.x.axis.bottom').length; + const items = Object.keys(this._paths), n = items.length; + let positions = Array.from({ length: Math.floor(n / 2) }, (_, i) => (i + 1) * 2 - (1 - Math.sign(n % 2))); + positions = positions.slice().reverse().map(value => -value).concat(n % 2 ? [0] : [], positions); + this._legend.replaceChildren(); + for (const legend of Object.values(this._props.legendItems)) { + const { name, label, width, height, margins = {}, color, path, className = '' } = { + width: this._width(), height: this._height(), margins: this.options.margins, ...legend, + }; + const group = _.create('svg:g', '', { class: 'legend-item legend-' + name.toLowerCase(), 'data-name': name, role: 'button', tabindex: 0 }, this._legend); + const toggle = () => group.ownerSVGElement.dispatchEvent(new CustomEvent('legend_clicked', { + detail: { path, name, legend: group, enabled: !path.classList.contains('leaflet-hidden') }, + })); + group.addEventListener('click', toggle); + group.addEventListener('keydown', event => { + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } + }); + _.create('svg:rect', '', { x: width / 2 - 50, y: height + margins.bottom / 2, width: 50, height: 10, + fill: color, stroke: '#000', 'stroke-opacity': 0.5, 'fill-opacity': 0.25, class: className }, group); + const text = _.create('svg:text', '', { x: width / 2 + 5, y: height + margins.bottom / 2, 'font-size': 10, 'font-weight': 700, dy: '0.75em' }, group); + text.textContent = L._(label || name); } - - if (marginsUpdated) { - this.fire('margins_updated'); + if (n > 1 && this.options.legend) { + let index = 0; + const group = _.create('svg:g', '', { class: 'legend-switcher', transform: `translate(${this._width()},${this._height() + 40})` }, this._legend); + const label = _.create('svg:text', '', { class: 'legend-switcher-label', 'text-anchor': 'end', x: -25, y: 5 }, group); + const select = delta => { + index = (index + delta + items.length) % items.length; + label.textContent = L._(items[index][0].toUpperCase() + items[index].slice(1)); + for (const name of items) this._togglePath(name, name === items[index], true); + this._updateArea(); + }; + label.addEventListener('click', () => select(1)); + for (const [x, y, angle, delta] of [[0, 3, 0, -1], [-13, 0, 180, 1]]) { + const symbol = _.create('svg:path', '', { class: 'legend-switcher-symbol', d: 'M0,-6L5,3L-5,3Z', + transform: `translate(${x},${y}) rotate(${angle})`, cursor: 'pointer', fill: '#000', + role: 'button', tabindex: 0, 'aria-label': L._(delta > 0 ? 'Next profile' : 'Previous profile') }, group); + symbol.addEventListener('click', () => select(delta)); + symbol.addEventListener('keydown', event => { + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); select(delta); } + }); + } + select(0); } + items.forEach((name, i) => { + const legend = this._legend.querySelector(`[data-name="${name}"]`); + if (legend) legend.setAttribute('transform', `translate(${positions[i] * 55},${xAxesB * 2})`); + this._togglePath(name, this.options[name] !== 'disabled', true); + }); + this._mask.querySelectorAll('.gap').forEach(node => node.remove()); + this._maskGaps.forEach((index, i) => { + if (i >= this._maskGaps.length - 2) return; + const x1 = this._x(this._data[index][this.options.xAttr]); + const x2 = this._x(this._data[this._maskGaps[i + 1]][this.options.xAttr]); + _.create('svg:rect', '', { x: x1, y: 0, width: x2 - x1, height: this._height(), class: 'gap', 'fill-opacity': 0.8, fill: 'black' }, this._mask); + }); + this._updateArea(); + return this; }, _updateScale() { - if (this.zooming) return { x: this._x, y: this._y }; - - for (let i in this._scales) { - this._scales[i] - .domain(this._domains[i](this._data)) - .range(this._ranges[i](this._width(), this._height())) + for (const name in this._domains) { + const scale = this._scales[name]; + scale.domain(this._domains[name](this._data)).range(this._ranges[name](this._width(), this._height())); + if (this._props.axes[name].axis === 'x') { + const { k, x } = this._transform; + scale.domain(scale.range().map(pixel => scale.invert((pixel - x) / k))); + } } - return { x: this._x, y: this._y }; }, - /** - * Calculates chart width. - */ _width() { - if (this._chart) this._chart._width; - const { width, margins } = this.options; - return width - margins.left - margins.right; + return this.options.width - this.options.margins.left - this.options.margins.right; }, - /** - * Calculates chart height. - */ _height() { - if (this._chart) return this._chart._height; - const { height, margins } = this.options; - return height - margins.top - margins.bottom; + return this.options.height - this.options.margins.top - this.options.margins.bottom; }, - /* - * Finds data entries above a given y-elevation value and returns geo-coordinates - */ - _findCoordsForY(y) { - let data = this._data; - let z = this._y.invert(y); - - // save indexes of elevation values above the horizontal line - const list = data.reduce((array, item, index) => { - if (item[this.options.yAttr] >= z) array.push(index); - return array; - }, []); - - let start = 0; - let next; - - // split index list into blocks of coordinates - const coords = list.reduce((array, _, curr) => { - next = curr + 1; - if (list[next] !== list[curr] + 1 || next === list.length) { - array.push( - list - .slice(start, next) - .map(i => data[i].latlng) - ); - start = next; - } - return array; - }, []); - - return coords; - }, - - /* - * Finds a data entry for a given x-coordinate of the diagram - */ _findIndexForXCoord(x) { - return d3 - .bisector(d => d[this.options.xAttr]) - .left(this._data || [0, 1], this._x.invert(x)); + return Math.min(this._data.length - 1, _.bisect(this._data, this._x.invert(x), this.options.xAttr)); }, - /* - * Finds a data entry for a given latlng of the map - */ _findIndexForLatLng(latlng) { - let result = null; - let d = Infinity; + let result = null, distance = Infinity; this._data.forEach((item, index) => { - let dist = latlng.distanceTo(item.latlng); - if (dist < d) { - d = dist; - result = index; - } + const current = latlng.distanceTo(item.latlng); + if (current < distance) { distance = current; result = index; } }); return result; }, - /* - * Removes the drag rectangle and zoms back to the total extent of the data. - */ _resetDrag() { - if (this._chart.panes.brush.select(".selection").attr('width')) { - this._chart.panes.brush.call(this._brush.clear); - this._hideDiagramIndicator(); - this.fire('reset_drag'); - } + if (!this._selection) return; + this._selection = null; + for (const node of this._chart.panes.brush.querySelectorAll('.selection, .handle')) node.setAttribute('display', 'none'); + this._hideDiagramIndicator(); + this.fire('reset_drag'); }, _resetZoom() { - if (this._zoom) { - this._zoom.transform(this._chart.svg, d3.zoomIdentity); - } + this._setZoom(1, 0); }, - /** - * Display distance and altitude level ("focus-rect"). - */ _showDiagramIndicator(item, xCoordinate) { - this._tooltip - .attr("display", null) - .call(D3.Tooltip({ - xCoord: xCoordinate, - yCoord: this._y(item[this.options.yAttr]), - height: this._height(), - width : this._width(), - labels: this._props.tooltipItems, - item: item - })); + this._tooltip.removeAttribute('display'); + const group = this._tooltip; + const xCoord = xCoordinate, yCoord = this._y(item[this.options.yAttr]); + group.replaceChildren(); + _.create('svg:line', '', { class: 'mouse-focus-line', x1: xCoord, x2: xCoord, y1: this._height(), y2: 0 }, group); + const box = _.create('svg:g', '', { class: 'mouse-focus-label' }, group); + const rect = _.create('svg:rect', '', { class: 'mouse-focus-label-rect', rx: 3, ry: 3 }, box); + const text = _.create('svg:text', '', { class: 'mouse-focus-label-text', 'font-weight': 700 }, box); + Object.values(this._props.tooltipItems).sort((a, b) => a.order - b.order).forEach(label => { + _.create('svg:tspan', '', { class: 'mouse-focus-label-' + label.name, dy: '1.5em' }, text).textContent = + typeof label.value === 'function' ? label.value(item) : label.value; + }); + if (text.firstChild) text.firstChild.setAttribute('dy', '1em'); + for (const span of text.children) span.setAttribute('x', 0); + const bounds = text.getBBox(); + const x = xCoord ? xCoord + (xCoord < this._width() / 2 ? 10 : -bounds.width - 10) : 0; + const y = yCoord ? Math.max(yCoord - bounds.height, (L.Browser.webkit || L.Browser.safari) ? 0 : -Infinity) : 0; + for (const span of text.children) span.setAttribute('x', x); + text.setAttribute('y', y); + _.setAttributes(rect, { x: x + bounds.x - 5, y: y + bounds.y - 5, width: bounds.width + 10, height: bounds.height + 10 }); }, _togglePath(name, enabled = true, lazy = false) { - let path = this._paths[name]; - let legend = this._container.select('.legend [data-name=' + name + ']'); - path.classed('leaflet-hidden', !enabled); - legend.select('text').style('text-decoration-line', enabled ? '' : 'line-through'); - legend.select('rect').style('fill-opacity', enabled ? '': '0'); - // Apply d3-zoom (bind <clipPath> mask) - if (this._mask) { - path.attr('mask', 'url(#' + this._mask.attr('id') + ')'); - } - if (!lazy) { - this._updateArea(); + const path = this._paths[name]; + const legend = this._legend.querySelector(`[data-name="${name}"]`); + path.classList.toggle('leaflet-hidden', !enabled); + if (legend) { + legend.querySelector('text').style.textDecorationLine = enabled ? '' : 'line-through'; + legend.querySelector('rect').style.fillOpacity = enabled ? '' : '0'; + legend.setAttribute('aria-pressed', enabled); } + path.setAttribute('mask', `url(#${this._mask.id})`); + if (!lazy) this._updateArea(); }, _hideDiagramIndicator() { - this._tooltip.attr("display", 'none'); + this._tooltip.setAttribute('display', 'none'); }, - /** - * Calculate chart xTicks - */ _xTicks() { - if (this.__xTicks) this.__xTicks = this.options.xTicks; - return this.__xTicks || Math.round(this._width() / 75); -}, + return this.__xTicks || Math.round(this._width() / 75); + }, - /** - * Calculate chart yTicks - */ _yTicks() { - if (this.__yTicks) this.__yTicks = this.options.yTicks; return this.__yTicks || Math.round(this._height() / 30); - } + }, }); diff --git a/assets/static/vendor/leaflet-elevation/src/components/marker.js b/assets/static/vendor/leaflet-elevation/src/components/marker.js index 6f1f6af..00a316d 100644 --- a/assets/static/vendor/leaflet-elevation/src/components/marker.js +++ b/assets/static/vendor/leaflet-elevation/src/components/marker.js @@ -1,5 +1,3 @@ -import * as D3 from './d3.js'; - const _ = L.Control.Elevation.Utils; export var Marker = L.Class.extend({ @@ -9,12 +7,8 @@ export var Marker = L.Class.extend({ this.control = control switch(this.options.marker) { - case 'elevation-line': - // this._container = d3.create("g").attr("class", "height-focus-group"); - break; case 'position-marker': - // this._marker = L.circleMarker([0, 0], { pane: 'overlayPane', radius: 6, fillColor: '#fff', fillOpacity:1, color: '#000', weight:1, interactive: false }); - this._marker = L.marker([0, 0], { icon: this.options.markerIcon, zIndexOffset: 1000000, interactive: false }); + this._marker = new L.Marker([0, 0], { icon: this.options.markerIcon, zIndexOffset: 1000000, interactive: false }); break; } @@ -26,7 +20,11 @@ export var Marker = L.Class.extend({ addTo(map) { this._map = map; switch(this.options.marker) { - case 'elevation-line': this._container = d3.select(map.getPane('elevationPane')).select("svg > g").call(D3.PositionMarker({})); break; + case 'elevation-line': + this._container = map.getPane('elevationPane').querySelector("svg > g"); + this._container.replaceChildren(); + this._container.setAttribute('class', 'height-focus-group'); + break; case 'position-marker': this._marker.addTo(map, { pane: 'overlayPane' }); break; } return this; @@ -50,21 +48,30 @@ export var Marker = L.Class.extend({ case 'elevation-line': if (this._container) { let point = this._map.latLngToLayerPoint(this._latlng); - point = L.extend({}, props.item, this._map._rotate ? this._map.rotatedPointToMapPanePoint(point) : point); + point = Object.assign({}, props.item, this._map._rotate ? this._map.rotatedPointToMapPanePoint(point) : point); - let yMax = (this.control._height() / props.yCoordMax * point[this.options.yAttr]); + // Keep the zero baseline unless the track extends below sea level. + let yMin = props.yCoordMin || 0; + let yMax = (this.control._height() / (props.yCoordMax - yMin) * (point[this.options.yAttr] - yMin)); if (!isFinite(yMax) || isNaN(yMax)) yMax = 0; - this._container.classed("leaflet-hidden", false); - this._container.call(D3.PositionMarker({ - theme : this.options.theme, - xCoord: point.x, - yCoord: point.y, - length: point.y - yMax, // normalized Y - labels: this._labels, - item: point, - })); + const { x: xCoord, y: yCoord } = point; + if (!Number.isFinite(xCoord) || !Number.isFinite(yCoord)) return; + const group = this._container; + const { theme } = this.options; + const length = point.y - yMax; + group.replaceChildren(); + group.setAttribute('class', 'height-focus-group'); + _.create('svg:circle', '', { class: `${theme} height-focus circle-lower`, transform: `translate(${xCoord},${yCoord})`, r: 6, cx: 0, cy: 0 }, group); + _.create('svg:line', '', { class: `${theme} height-focus line`, x1: xCoord, x2: xCoord, y1: yCoord, y2: length }, group); + const text = _.create('svg:text', '', { class: `${theme} height-focus-label`, x: xCoord + 5, y: length, 'pointer-events': 'none' }, group); + Object.values(this._labels).sort((a, b) => a.order - b.order).forEach(label => { + _.create('svg:tspan', '', { class: 'height-focus-' + label.name, dy: '1.5em' }, text).textContent = + typeof label.value === 'function' ? label.value(point) : label.value; + }); + if (text.firstChild) text.firstChild.setAttribute('dy', text.children.length > 1 ? '-1.5em' : '0em'); + for (const span of text.children) span.setAttribute('x', xCoord + 5); } break; case 'position-marker': @@ -80,7 +87,7 @@ export var Marker = L.Class.extend({ remove() { this._props = null; switch(this.options.marker) { - case 'elevation-line': this._container && this._container.classed("leaflet-hidden", true); break; + case 'elevation-line': this._container && this._container.classList.add("leaflet-hidden"); break; case 'position-marker': _.addClass(this._marker.getElement(), 'leaflet-hidden'); break; } }, diff --git a/assets/static/vendor/leaflet-elevation/src/components/summary.js b/assets/static/vendor/leaflet-elevation/src/components/summary.js index e8da57f..95de5d4 100644 --- a/assets/static/vendor/leaflet-elevation/src/components/summary.js +++ b/assets/static/vendor/leaflet-elevation/src/components/summary.js @@ -1,43 +1,43 @@ -const _ = L.Control.Elevation.Utils;
-
-export var Summary = L.Class.extend({
- initialize(opts, control) {
- this.options = opts;
- this.control = control;
- this.labels = {};
-
- let summary = this._container = _.create("div", "elevation-summary " + (opts.summary ? opts.summary + "-summary" : ''));
- _.style(summary, 'max-width', opts.width ? opts.width + 'px' : '');
- },
-
- render() {
- return container => container.append(() => this._container);
- },
-
- reset() {
- this._container.innerHTML = '';
- },
-
- append(className, label, value) {
- this._container.innerHTML += `<span class="${className}"><span class="summarylabel">${label}</span><span class="summaryvalue">${value}</span></span>`;
- return this;
- },
-
- update() {
- Object
- .keys(this.labels)
- .sort((a, b) => this.labels[a].order - this.labels[b].order) // TODO: any performance issues?
- .forEach((i)=> {
- let value = typeof this.labels[i].value !== "function" ? this.labels[i].value : this.labels[i].value(this.control.track_info, this.labels[i].unit || '');
- this.append(i /*+ " order-" + this.labels[i].order*/, L._(this.labels[i].label), value, this.labels[i].order);
- });
- },
-
- _registerSummary(data) {
- for (let i in data) {
- data[i].order = data[i].order ?? 1000;
- this.labels[i] = data[i];
- }
- }
-
-});
+const _ = L.Control.Elevation.Utils; + +export var Summary = L.Class.extend({ + initialize(opts, control) { + this.options = opts; + this.control = control; + this.labels = {}; + + let summary = this._container = _.create("div", "elevation-summary " + (opts.summary ? opts.summary + "-summary" : '')); + _.style(summary, 'max-width', opts.width ? opts.width + 'px' : ''); + }, + + render() { + return container => container.appendChild(this._container); + }, + + reset() { + this._container.innerHTML = ''; + }, + + append(className, label, value) { + this._container.innerHTML += `<span class="${className}"><span class="summarylabel">${label}</span><span class="summaryvalue">${value}</span></span>`; + return this; + }, + + update() { + Object + .keys(this.labels) + .sort((a, b) => this.labels[a].order - this.labels[b].order) // TODO: any performance issues? + .forEach((i)=> { + let value = typeof this.labels[i].value !== "function" ? this.labels[i].value : this.labels[i].value(this.control.track_info, this.labels[i].unit || ''); + this.append(i /*+ " order-" + this.labels[i].order*/, L._(this.labels[i].label), value, this.labels[i].order); + }); + }, + + _registerSummary(data) { + for (let i in data) { + data[i].order = data[i].order ?? 1000; + this.labels[i] = data[i]; + } + } + +}); diff --git a/assets/static/vendor/leaflet-elevation/src/control.js b/assets/static/vendor/leaflet-elevation/src/control.js index 27ecf77..cc0edd0 100644 --- a/assets/static/vendor/leaflet-elevation/src/control.js +++ b/assets/static/vendor/leaflet-elevation/src/control.js @@ -8,15 +8,10 @@ if (!L._ || !L.i18n) { export const Elevation = L.Control.Elevation = L.Control.extend({ - includes: L.Evented ? L.Evented.prototype : L.Mixin.Events, - options: Options, __mileFactor: 0.621371, // 1 km = (0.621371 mi) - __footFactor: 3.28084, // 1 m = (3.28084 ft) - __D3: 'https://unpkg.com/d3@7.8.4/dist/d3.min.js', + __footFactor: 3.28084, // 1 m = (3.28084 ft) __TOGEOJSON: 'https://unpkg.com/@tmcw/togeojson@5.6.2/dist/togeojson.umd.js', - __LGEOMUTIL: 'https://unpkg.com/leaflet-geometryutil@0.10.1/src/leaflet.geometryutil.js', - __LALMOSTOVER: 'https://unpkg.com/leaflet-almostover@1.0.1/src/leaflet.almostover.js', __LHOTLINE: '../libs/leaflet-hotline.min.js', __LDISTANCEM: '../libs/leaflet-distance-marker.min.js', __LEDGESCALE: '../libs/leaflet-edgescale.min.js', @@ -30,17 +25,16 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ * Add data to the diagram either from GPX or GeoJSON and update the axis domain and data */ addData(d, layer) { - this.import(this.__D3) - .then(() => { - if (this._modulesLoaded) { - layer = layer ?? (d.on && d); - this._addData(d); - this._addLayer(layer); - this._fireEvt("eledata_added", { data: d, layer: layer, track_info: this.track_info }); - } else { - this.once('modules_loaded', () => this.addData(d,layer)); - } - }); + return Promise.resolve().then(() => { + if (!this._modulesLoaded) { + return new Promise(resolve => this.once('modules_loaded', () => resolve(this.addData(d, layer)))); + } + layer = layer ?? (d.on && d); + this._addData(d); + this._addLayer(layer); + this._fireEvt("eledata_added", { data: d, layer: layer, track_info: this.track_info }); + }); + }, /** @@ -71,6 +65,8 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this._data = []; this.track_info = {}; + this._yCoordMin = 0; + this._yCoordMax = -Infinity; this._fireEvt("eledata_clear"); @@ -82,7 +78,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this._events.elechart_updated.forEach(({fn, ctx}) => this.off('elechart_updated', fn, ctx)); } if (this._chart && this._chart._container) { - this._chart._container.selectAll('g.point .point').remove(); + this._chart._container.querySelectorAll('g.point .point').forEach(node => node.remove()); this._chart.clear(); } }, @@ -100,7 +96,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ * * @link https://leafletjs.com/examples/extending/extending-3-controls.html#handlers */ - // addHandler: function (name, HandlerClass) { + // addHandler(name, HandlerClass) { // if (HandlerClass) { // let handler = this[name] = new HandlerClass(this); // this.handlers.push(handler); @@ -150,7 +146,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ }, getBounds(data) { - return L.latLngBounds((data || this._data).map((d) => d.latlng)); + return new L.LatLngBounds((data || this._data).map((d) => d.latlng)); }, /** @@ -172,20 +168,19 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ */ initialize(opts) { - // opts = L.setOptions(this, opts); - // Fixes: https://github.com/Raruto/leaflet-elevation/pull/240 - opts = L.setOptions(this, L.extend({}, _.cloneDeep(Options), opts)); // "deep copy" nested objects (multiple charts) + opts = L.Util.setOptions(this, Object.assign({}, _.cloneDeep(Options), opts)); // "deep copy" nested objects (multiple charts) this._data = []; - this._layers = L.featureGroup(); - this._markers = L.featureGroup(); - this._hotline = L.featureGroup(); - this._circleMarkers = L.featureGroup(); - this._markedSegments = L.polyline([]); - this._start = L.circleMarker([0,0], (opts.trkStart || Options.trkStart)); - this._end = L.circleMarker([0,0], (opts.trkEnd || Options.trkEnd)); + this._layers = new L.FeatureGroup(); + this._markers = new L.FeatureGroup(); + this._hotline = new L.FeatureGroup(); + this._circleMarkers = new L.FeatureGroup(); + this._markedSegments = new L.Polyline([]); + this._start = new L.CircleMarker([0,0], (opts.trkStart || Options.trkStart)); + this._end = new L.CircleMarker([0,0], (opts.trkEnd || Options.trkEnd)); this._chartEnabled = true; + this._yCoordMin = 0; this._yCoordMax = -Infinity; this.track_info = {}; // this.handlers = []; @@ -202,7 +197,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this._markedSegments.setStyle(opts.polylineSegments); // Leaflet canvas renderer colors - L.extend(_.Colors, opts.colors || {}); + Object.assign(_.Colors, opts.colors || {}); // Various stuff this._fixCanvasPaths(); @@ -218,10 +213,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ return Promise.all(src.map(m => this.import(m))); } switch(src) { - case this.__D3: condition = typeof d3 !== 'object'; break; case this.__TOGEOJSON: condition = typeof toGeoJSON !== 'object'; break; - case this.__LGEOMUTIL: condition = typeof L.GeometryUtil !== 'object'; break; - case this.__LALMOSTOVER: condition = typeof L.Handler.AlmostOver !== 'function'; break; case this.__LDISTANCEM: condition = typeof L.DistanceMarkers !== 'function'; break; case this.__LEDGESCALE: condition = typeof L.Control.EdgeScale !== 'function'; break; case this.__LHOTLINE: condition = typeof L.Hotline !== 'function'; break; @@ -245,7 +237,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ let container = this._container = _.create("div", "elevation-control " + this.options.theme + " " + (this.options.detached ? 'elevation-detached' : 'leaflet-control'), this.options.detached ? { id: 'elevation-' + _.randomId() } : {}); - if (!this.eleDiv) this.eleDiv = container; + this.eleDiv = container; this._loadModules(this.options.handlers).then(() => { // Inject here required modules (data handlers) this._initChart(container); @@ -257,6 +249,8 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this.fire('modules_loaded'); }); + + this.fire('add'); return container; @@ -362,6 +356,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this.fire("elepoint_added", { point: point, index: this._data.length - 1 }); + if (this._yCoordMin > this._data[this._data.length - 1][this.options.yAttr]) this._yCoordMin = this._data[this._data.length - 1][this.options.yAttr]; if (this._yCoordMax < this._data[this._data.length - 1][this.options.yAttr]) this._yCoordMax = this._data[this._data.length - 1][this.options.yAttr]; }); @@ -380,7 +375,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ x: x, y: y, z: z, - latlng: L.latLng(x, y, z) + latlng: new L.LatLng(x, y, z) }); this.fire("eledata_updated", { index: this._data.length - 1 }); @@ -402,31 +397,155 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ /** * Initialize "L.AlmostOver" integration + * + * Inspired by: https://github.com/makinacorpus/Leaflet.AlmostOver */ _initAlmostOverHandler(map, layer) { - return (map && this.options.almostOver && !L.Browser.mobile) ? this.import([this.__LGEOMUTIL, this.__LALMOSTOVER]) - .then(() => { - map.addHandler('almostOver', L.Handler.AlmostOver) - if (L.GeometryUtil && map.almostOver && map.almostOver.enabled()) { - map.almostOver.addLayer(layer); - map - .on('almost:move', this._onMouseMoveLayer, this) - .on('almost:out', this._onMouseOut, this); - this.once('eledata_clear', () => { - map.almostOver.removeLayer(layer); - map - .off('almost:move', this._onMouseMoveLayer, this) - .off('almost:out', this._onMouseOut, this); - }) + if (!map || !this.options.almostOver || L.Browser.mobile) return Promise.resolve(); + map.almostOver = map.almostOver || { + _map: map, + _projectedLayers: new WeakMap(), + _layers: [], + _previous: null, + _lastSample: 0, + enabled() { + return !!this._enabled; + }, + enable() { + if (this.enabled()) return; + this._enabled = true; + if (this._map.options.almostOnMouseMove !== false) this._map.on('mousemove', this._sampleMouseMove, this); + this._map.on('click dblclick', this._onMouseClick, this); + }, + disable() { + if (!this.enabled()) return; + this._map.off('mousemove', this._sampleMouseMove, this); + this._map.off('click dblclick', this._onMouseClick, this); + if (this._previous) this._map.fire('almost:out', { layer: this._previous.layer }); + this._previous = null; + this._enabled = false; + }, + addLayer(layer) { + if (layer.eachLayer) layer.eachLayer(child => this.addLayer(child)); + else if (!this._layers.includes(layer)) { + this._layers.push(layer); + this._projectedLayers.delete(layer); } - }) : Promise.resolve(); + }, + removeLayer(layer) { + if (layer.eachLayer) layer.eachLayer(child => this.removeLayer(child)); + else { + this._layers = this._layers.filter(item => item !== layer); + this._projectedLayers.delete(layer); + } + this._previous = null; + }, + getClosest(latlng) { + let closest; + const maxDistance = this._map.options.almostDistance ?? 25; + + const closestPointOnLayer = (map, layer, latlng, maxDistance, cache) => { + let closest; + const zoom = map.getZoom(); + const target = map.project(latlng, zoom); + + function checkPath(points) { + let closestSquared = closest ? closest.distance * closest.distance : maxDistance * maxDistance; + + for (let i = 1; i < points.length; i++) { + const start = points[i - 1]; + const end = points[i]; + const point = L.LineUtil.closestPointOnSegment(target, start, end); + const distanceSquared = (target.x - point.x) ** 2 + (target.y - point.y) ** 2; + + if (distanceSquared <= maxDistance * maxDistance && distanceSquared < closestSquared) { + closestSquared = distanceSquared; + closest = { + layer, + latlng: map.unproject(point, zoom), + distance: Math.sqrt(distanceSquared), + }; + } + } + } + if (layer.eachLayer) { + layer.eachLayer(child => { + const match = closestPointOnLayer(map, child, latlng, closest?.distance ?? maxDistance, cache); + if (match && (!closest || match.distance < closest.distance)) closest = match; + }); + } else if (layer.getLatLngs) { + const cached = cache.get(layer); + if (cached?.zoom === zoom) { + cached.paths.forEach(checkPath); + } else { + const paths = []; + const collectPaths = (coords) => { + if (!Array.isArray(coords)) return; + if (coords.length && Number.isFinite(coords[0]?.lat)) paths.push(coords.map(point => map.project(point, zoom))); + else coords.forEach(collectPaths); + } + collectPaths(layer.getLatLngs()); + cache.set(layer, { zoom, paths }); + paths.forEach(checkPath); + } + } + return closest; + } + + // ponytail: scans all route segments per sampled move; add a spatial index if large collections become slow. + for (const layer of this._layers) { + const match = closestPointOnLayer(this._map, layer, latlng, closest?.distance ?? maxDistance, this._projectedLayers); + if (match && (!closest || match.distance < closest.distance)) closest = match; + } + + return closest; + }, + _sampleMouseMove(event) { + const now = Date.now(); + if (this._map._animatingZoom || this._map._panAnim?._inProgress || + now - this._lastSample < (this._map.options.almostSamplingPeriod ?? 50) || !this._layers.length) return; + this._lastSample = now; + this._onMouseMove(event); + }, + _onMouseMove(event) { + const closest = this.getClosest(event.latlng); + if (closest) { + if (!this._previous || this._previous.layer !== closest.layer) { + if (this._previous) this._map.fire('almost:out', { layer: this._previous.layer }); + this._map.fire('almost:over', closest); + } + this._map.fire('almost:move', closest); + } else if (this._previous) { + this._map.fire('almost:out', { layer: this._previous.layer }); + } + this._previous = closest; + }, + _onMouseClick(event) { + const closest = this.getClosest(event.latlng); + if (closest) this._map.fire(`almost:${event.type}`, closest); + }, + }; + if (!map.almostOver.enabled() && map.options.almostOver !== false) map.almostOver.enable(); + if (map.almostOver.enabled()) { + map.almostOver.addLayer(layer); + map + .on('almost:move', this._onMouseMoveLayer, this) + .on('almost:out', this._onMouseOut, this); + this.once('eledata_clear', () => { + map.almostOver.removeLayer(layer); + map + .off('almost:move', this._onMouseMoveLayer, this) + .off('almost:out', this._onMouseOut, this); + }); + } + return Promise.resolve(); }, /** * Initialize "L.DistanceMarkers" integration */ _initDistanceMarkers() { - return this.options.distanceMarkers ? this.import([this.__LGEOMUTIL, this.__LDISTANCEM]) : Promise.resolve(); + return this.options.distanceMarkers ? this.import(this.__LDISTANCEM) : Promise.resolve(); }, /** @@ -445,7 +564,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ .then(() => { layer.eachLayer((trkseg) => { if (trkseg.feature.geometry.type != "Point") { - let geo = L.geoJson(trkseg.toGeoJSON(), { coordsToLatLng: (coords) => L.latLng(coords[0], coords[1], coords[2] * (this.options.altitudeFactor || 1))}); + let geo = new L.GeoJSON(trkseg.toGeoJSON(), { coordsToLatLng: (coords) => new L.LatLng(coords[0], coords[1], coords[2] * (this.options.altitudeFactor || 1))}); let line = L.hotline(geo.toGeoJSON().features[0].geometry.coordinates, { renderer: L.Hotline.renderer(), min: isFinite(this.track_info[prop + '_min']) ? this.track_info[prop + '_min'] : 0, @@ -532,7 +651,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ let options = layer.options; - options.color = color.line || color.area || theme; + options.color = control._chartEnabled ? (color.line || color.area || theme) : '#000'; options.stroke = !!options.color; oldProto.call(this, ctx, layer); @@ -596,7 +715,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ * Hides the position/height indicator marker drawn onto the map */ _hideMarker() { - if (this.options.autohideMarker) { + if (this.options.autohideMarker && this._marker) { this._marker.remove(); } }, @@ -620,17 +739,15 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ } this - .import([this.__D3, this.__LCHART]) + .import(this.__LCHART) .then((m) => { - let chart = this._chart = new (m[1] || Elevation).Chart(opts, this); + let chart = this._chart = new (m || Elevation).Chart(opts, this); this._x = this._chart._x; this._y = this._chart._y; - d3 - .select(container) - .call(chart.render()) + chart.render()(container); chart .on('reset_drag', this._hideMarker, this) @@ -663,6 +780,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this._updateChart(); this._updateSummary(); + map.invalidateSize(); }); @@ -687,11 +805,11 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ } if (this._renderer) this._renderer.remove() - this._renderer = L.svg({ pane: "elevationPane" }).addTo(this._map); // default leaflet svg renderer + this._renderer = new L.SVG({ pane: "elevationPane" }).addTo(this._map); // default leaflet svg renderer - this.import([this.__D3, this.__LMARKER]) + this.import(this.__LMARKER) .then((m) => { - this._marker = new (m[1] || Elevation).Marker(this.options, this); + this._marker = new (m || Elevation).Marker(this.options, this); this.fire("elechart_marker"); }); }, @@ -724,10 +842,12 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ _initSummary(container) { this.import(this.__LSUMMARY).then((m)=>{ this._summary = new (m || Elevation).Summary({ summary: this.options.summary }, this); - - this.on('elechart_init', () => { - d3.select(container).call(this._summary.render()); - }); + const render = () => { + this._summary.render()(container); + this._updateSummary(); + }; + if (this._chart && container.contains(this._chart._container)) render(); + else this.once('elechart_init', render); }); }, @@ -768,7 +888,8 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ */ _loadLayer(geojson) { let { polyline, theme, waypoints, wptIcons, wptLabels, distanceMarkers } = this.options; - let style = L.extend({}, polyline); + let style = Object.assign({}, polyline); + let dataAdded = []; if (theme) { style.className += ' ' + theme; @@ -778,7 +899,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this.track_info.name = geojson.name; } - let layer = L.geoJson(geojson, { + let layer = new L.GeoJSON(geojson, { distanceMarkers: distanceMarkers, style: style, pointToLayer: (feature, latlng) => { @@ -797,16 +918,16 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ if ([true, 'markers'].includes(waypoints) && wptIcons != false) { return this._registerMarker({ latlng : latlng, - sym : (sym ?? name).replace(' ', '-').replace('"', '').replace("'", '').toLowerCase(), + sym : (sym ?? name).replace(/["']/g, '').replace(/ /g, '-').toLowerCase(), content: [true, 'markers'].includes(wptLabels) && (name || desc) && decodeURI("<b>" + name + "</b>" + (desc.length > 0 ? '<br>' + desc : '')) }); } } }, - onEachFeature: (feature, layer) => feature.geometry && feature.geometry.type != 'Point' && this.addData(feature, layer), + onEachFeature: (feature, layer) => feature.geometry && feature.geometry.type != 'Point' && dataAdded.push(this.addData(feature, layer)), }); - this.import(this.__D3).then(() => { + Promise.all(dataAdded).then(() => { this._initMapIntegrations(layer); const event_data = { data: geojson, layer: layer, name: this.track_info.name, track_info: this.track_info }; if (this._modulesLoaded) { @@ -821,7 +942,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ _onDragEnd({ dragstart, dragend}) { this._hideMarker(); - this.fitBounds(L.latLngBounds([dragstart.latlng, dragend.latlng])); + this.fitBounds(new L.LatLngBounds([dragstart.latlng, dragend.latlng])); this.fire("elechart_dragged"); }, @@ -910,7 +1031,10 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this._chartEnabled = this._chart._hasActiveLayers(); // toggle layer visibility on empty chart - this._layers.eachLayer(layer => _.toggleClass(layer.getElement && layer.getElement(), this.options.polyline.className + ' ' + this.options.theme, this._chartEnabled)); + this._layers.eachLayer(layer => { + _.toggleClass(layer.getElement && layer.getElement(), this.options.polyline.className + ' ' + this.options.theme, this._chartEnabled); + if (layer._renderer instanceof L.Canvas) layer.redraw(); + }); // toggle option value (eg. altitude = { 'disabled' || 'enabled' }) this.options[name] = !enabled && this.options[name] == 'disabled' ? 'enabled' : 'disabled'; @@ -1130,20 +1254,20 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ }); if (grid) { - this._registerAxisGrid(L.extend({ name }, grid)); + this._registerAxisGrid(Object.assign({ name }, grid)); } if (this.options[name] !== "summary") { - if (scale) this._registerAxisScale(L.extend({ name, label: unit }, scale)); - if (path) this._registerAreaPath(L.extend({ name }, path)); + if (scale) this._registerAxisScale(Object.assign({ name, label: unit }, scale)); + if (path) this._registerAreaPath(Object.assign({ name }, path)); } if (tooltip || props.tooltips) { - _.each([tooltip, ...(props.tooltips || [])], t => t && this._registerTooltip(L.extend({ name }, t))); + _.each([tooltip, ...(props.tooltips || [])], t => t && this._registerTooltip(Object.assign({ name }, t))); } if (summary) { - _.each(summary, (s, k) => summary[k] = L.extend({ unit }, s)); + _.each(summary, (s, k) => summary[k] = Object.assign({ unit }, s)); this._registerSummary(summary); } } @@ -1153,9 +1277,9 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ let { wptIcons } = this.options; // generate and cache appropriate icon symbol if (!wptIcons.hasOwnProperty(sym)) { - wptIcons[sym] = L.divIcon(L.extend({}, wptIcons[""].options, { html: '<i class="elevation-waypoint-icon ' + sym + '"></i>' } )); + wptIcons[sym] = new L.DivIcon(Object.assign({}, wptIcons[""].options, { html: '<i class="elevation-waypoint-icon ' + sym + '"></i>' } )); } - let marker = L.marker(latlng, { icon: wptIcons[sym] }); + let marker = new L.Marker(latlng, { icon: wptIcons[sym] }); if (content) { marker.bindPopup(content, { className: 'elevation-popup', keepInView: true }).openPopup(); marker.bindTooltip(content, { className: 'elevation-tooltip', direction: 'auto', sticky: true, opacity: 1 }).openTooltip(); @@ -1167,8 +1291,8 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ * Add chart or marker tooltip info */ _registerTooltip(props) { - props.chart && this.on("elechart_init", () => this._chart._registerTooltip(L.extend({}, props, { value: props.chart }))); - props.marker && this.on("elechart_marker", () => this._marker._registerTooltip(L.extend({}, props, { value: props.marker }))); + props.chart && this.on("elechart_init", () => this._chart._registerTooltip(Object.assign({}, props, { value: props.chart }))); + props.marker && this.on("elechart_marker", () => this._marker._registerTooltip(Object.assign({}, props, { value: props.marker }))); }, /** @@ -1262,6 +1386,7 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ this._marker.update({ map : this._map, item : item, + yCoordMin : this._yCoordMin, yCoordMax : this._yCoordMax || 0, options : this.options }); @@ -1333,3 +1458,12 @@ export const Elevation = L.Control.Elevation = L.Control.extend({ }, }); + +// backcomp for leaflet v1 +if (!('on' in Elevation.prototype)) { + for (const name of Object.getOwnPropertyNames(L.Evented.prototype)) { + if (name !== 'constructor') { + Object.defineProperty(Elevation.prototype, name, Object.getOwnPropertyDescriptor(L.Evented.prototype, name)); + } + } +} diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/acceleration.js b/assets/static/vendor/leaflet-elevation/src/handlers/acceleration.js index 9b31b5c..dfb775d 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/acceleration.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/acceleration.js @@ -1,64 +1,64 @@ -export function Acceleration() {
-
- const _ = L.Control.Elevation.Utils;
-
- let opts = this.options;
- let acceleration = {};
-
- acceleration.label = opts.accelerationLabel || L._(opts.imperial ? 'ft/s²' : 'm/s²');
- opts.accelerationFactor = opts.accelerationFactor || 1;
-
- return {
- name: 'acceleration',
- unit: acceleration.label,
- deltaMax: this.options.accelerationDeltaMax,
- clampRange: this.options.accelerationRange,
- decimals: 2,
- pointToAttr: (_, i) => {
- let dv = (this._data[i].speed - this._data[i > 0 ? i - 1 : i].speed) * (1000 / opts.timeFactor);
- let dt = (this._data[i].time - this._data[i > 0 ? i - 1 : i].time) / 1000;
- return dt > 0 ? Math.abs((dv / dt)) * opts.accelerationFactor : NaN;
- },
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg },
- scale: {
- axis : "y",
- position : "right",
- scale : { min: 0, max: +1 },
- tickPadding: 16,
- labelX : 25,
- labelY : -8,
- },
- path: {
- label : 'Acceleration',
- yAttr : 'acceleration',
- scaleX : 'distance',
- scaleY : 'acceleration',
- color : '#050402',
- strokeColor : '#000',
- strokeOpacity: "0.5",
- fillOpacity : "0.25",
- },
- tooltip: {
- chart: (item) => L._("a: ") + item.acceleration + " " + acceleration.label,
- marker: (item) => Math.round(item.acceleration) + " " + acceleration.label,
- order: 60,
- },
- summary: {
- "minacceleration" : {
- label: "Min Acceleration: ",
- value: (track, unit) => Math.round(track.acceleration_min || 0) + ' ' + unit,
- order: 60
- },
- "maxacceleration" : {
- label: "Max Acceleration: ",
- value: (track, unit) => Math.round(track.acceleration_max || 0) + ' ' + unit,
- order: 61
- },
- "avgacceleration": {
- label: "Avg Acceleration: ",
- value: (track, unit) => Math.round(track.acceleration_avg || 0) + ' ' + unit,
- order: 62
- },
- }
- };
-}
+export function Acceleration() { + + const _ = L.Control.Elevation.Utils; + + let opts = this.options; + let acceleration = {}; + + acceleration.label = opts.accelerationLabel || L._(opts.imperial ? 'ft/s²' : 'm/s²'); + opts.accelerationFactor = opts.accelerationFactor || 1; + + return { + name: 'acceleration', + unit: acceleration.label, + deltaMax: this.options.accelerationDeltaMax, + clampRange: this.options.accelerationRange, + decimals: 2, + pointToAttr: (_, i) => { + let dv = (this._data[i].speed - this._data[i > 0 ? i - 1 : i].speed) * (1000 / opts.timeFactor); + let dt = (this._data[i].time - this._data[i > 0 ? i - 1 : i].time) / 1000; + return dt > 0 ? Math.abs((dv / dt)) * opts.accelerationFactor : NaN; + }, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg }, + scale: { + axis : "y", + position : "right", + scale : { min: 0, max: +1 }, + tickPadding: 16, + labelX : 25, + labelY : -8, + }, + path: { + label : 'Acceleration', + yAttr : 'acceleration', + scaleX : 'distance', + scaleY : 'acceleration', + color : '#050402', + strokeColor : '#000', + strokeOpacity: "0.5", + fillOpacity : "0.25", + }, + tooltip: { + chart: (item) => L._("a: ") + item.acceleration + " " + acceleration.label, + marker: (item) => Math.round(item.acceleration) + " " + acceleration.label, + order: 60, + }, + summary: { + "minacceleration" : { + label: "Min Acceleration: ", + value: (track, unit) => Math.round(track.acceleration_min || 0) + ' ' + unit, + order: 60 + }, + "maxacceleration" : { + label: "Max Acceleration: ", + value: (track, unit) => Math.round(track.acceleration_max || 0) + ' ' + unit, + order: 61 + }, + "avgacceleration": { + label: "Avg Acceleration: ", + value: (track, unit) => Math.round(track.acceleration_avg || 0) + ' ' + unit, + order: 62 + }, + } + }; +} diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/altitude.js b/assets/static/vendor/leaflet-elevation/src/handlers/altitude.js index b7fe6e3..5f6d6c8 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/altitude.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/altitude.js @@ -1,78 +1,78 @@ -export function Altitude() {
-
- const _ = L.Control.Elevation.Utils;
-
- let opts = this.options;
- let altitude = {};
-
- let theme = opts.theme.split(' ')[0].replace('-theme', '');
- let color = _.Colors[theme] || {};
-
- opts.altitudeFactor = opts.imperial ? this.__footFactor : (opts.altitudeFactor || 1); // 1 m = (1 m)
- altitude.label = opts.imperial ? "ft" : opts.yLabel;
-
- return {
- name: 'altitude',
- required: this.options.slope,
- meta: 'z',
- unit: altitude.label,
- statsName: 'elevation',
- deltaMax: this.options.altitudeDeltaMax,
- clampRange: this.options.altitudeRange,
- // init: ({point}) => {
- // // "alt" property is generated inside "leaflet"
- // if ("alt" in point) point.meta.ele = point.alt;
- // },
- pointToAttr: (point, i) => {
- if ("alt" in point) point.meta.ele = point.alt; // "alt" property is generated inside "leaflet"
- return this._data[i].z *= opts.altitudeFactor;
- },
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg },
- grid: {
- axis : "y",
- position : "left",
- scale : "y" // this._chart._y,
- },
- scale: {
- axis : "y",
- position: "left",
- scale : "y", // this._chart._y,
- labelX : -3,
- labelY : -8,
- },
- path: {
- label : 'Altitude',
- scaleX : 'distance',
- scaleY : 'altitude',
- className : 'area',
- color : color.area || theme,
- strokeColor : opts.detached ? color.stroke : '#000',
- strokeOpacity: "1",
- fillOpacity : opts.detached ? (color.alpha || '0.8') : 1,
- preferCanvas : opts.preferCanvas,
- },
- tooltip: {
- name: 'y',
- chart: (item) => L._("y: ") + _.round(item[opts.yAttr], opts.decimalsY) + " " + altitude.label,
- marker: (item) => _.round(item[opts.yAttr], opts.decimalsY) + " " + altitude.label,
- order: 10,
- },
- summary: {
- "minele" : {
- label: "Min Elevation: ",
- value: (track, unit) => (track.elevation_min || 0).toFixed(2) + ' ' + unit,
- order: 30,
- },
- "maxele" : {
- label: "Max Elevation: ",
- value: (track, unit) => (track.elevation_max || 0).toFixed(2) + ' ' + unit,
- order: 31,
- },
- "avgele" : {
- label: "Avg Elevation: ",
- value: (track, unit) => (track.elevation_avg || 0).toFixed(2) + ' ' + unit,
- order: 32,
- },
- }
- };
-}
+export function Altitude() { + + const _ = L.Control.Elevation.Utils; + + let opts = this.options; + let altitude = {}; + + let theme = opts.theme.split(' ')[0].replace('-theme', ''); + let color = _.Colors[theme] || {}; + + opts.altitudeFactor = opts.imperial ? this.__footFactor : (opts.altitudeFactor || 1); // 1 m = (1 m) + altitude.label = opts.imperial ? "ft" : opts.yLabel; + + return { + name: 'altitude', + required: this.options.slope, + meta: 'z', + unit: altitude.label, + statsName: 'elevation', + deltaMax: this.options.altitudeDeltaMax, + clampRange: this.options.altitudeRange, + // init: ({point}) => { + // // "alt" property is generated inside "leaflet" + // if ("alt" in point) point.meta.ele = point.alt; + // }, + pointToAttr: (point, i) => { + if ("alt" in point) point.meta.ele = point.alt; // "alt" property is generated inside "leaflet" + return this._data[i].z *= opts.altitudeFactor; + }, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg }, + grid: { + axis : "y", + position : "left", + scale : "y" // this._chart._y, + }, + scale: { + axis : "y", + position: "left", + scale : "y", // this._chart._y, + labelX : -3, + labelY : -8, + }, + path: { + label : 'Altitude', + scaleX : 'distance', + scaleY : 'altitude', + className : 'area', + color : color.area || theme, + strokeColor : opts.detached ? color.stroke : '#000', + strokeOpacity: "1", + fillOpacity : opts.detached ? (color.alpha || '0.8') : 1, + preferCanvas : opts.preferCanvas, + }, + tooltip: { + name: 'y', + chart: (item) => L._("y: ") + _.round(item[opts.yAttr], opts.decimalsY) + " " + altitude.label, + marker: (item) => _.round(item[opts.yAttr], opts.decimalsY) + " " + altitude.label, + order: 10, + }, + summary: { + "minele" : { + label: "Min Elevation: ", + value: (track, unit) => (track.elevation_min || 0).toFixed(2) + ' ' + unit, + order: 30, + }, + "maxele" : { + label: "Max Elevation: ", + value: (track, unit) => (track.elevation_max || 0).toFixed(2) + ' ' + unit, + order: 31, + }, + "avgele" : { + label: "Avg Elevation: ", + value: (track, unit) => (track.elevation_avg || 0).toFixed(2) + ' ' + unit, + order: 32, + }, + } + }; +} diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/cadence.js b/assets/static/vendor/leaflet-elevation/src/handlers/cadence.js index 0ad7704..db1a6d7 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/cadence.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/cadence.js @@ -1,54 +1,54 @@ -export function Cadence() {
-
- const _ = L.Control.Elevation.Utils;
-
- return {
- name: 'cadence', // <-- Your custom option name (eg. "cadence: true")
- unit: 'rpm',
- meta: 'cad', // <-- point.meta.cad
- coordinateProperties: ["cads", "cadences", "cad", "cadence"], // List of GPX Extensions ("coordinateProperties") to be handled by "@tmcw/toGeoJSON"
- pointToAttr: (point, i) => (point.cad ?? point.meta.cad ?? point.prev('cadence')) || 0,
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg },
- scale: {
- axis : "y",
- position : "right",
- scale : { min: -1, max: +1 },
- tickPadding: 16,
- labelX : 25,
- labelY : -8,
- },
- path: {
- label : 'RPM',
- yAttr : 'cadence',
- scaleX : 'distance',
- scaleY : 'cadence',
- color : '#FFF',
- strokeColor : 'blue',
- strokeOpacity: "0.85",
- fillOpacity : "0.1",
- },
- tooltip: {
- name: 'cadence',
- chart: (item) => L._("cad: ") + item.cadence + " " + 'rpm',
- marker: (item) => Math.round(item.cadence) + " " + 'rpm',
- order: 1
- },
- summary: {
- "minrpm": {
- label: "Min RPM: ",
- value: (track, unit) => Math.round(track.cadence_min || 0) + ' ' + unit,
- // order: 30
- },
- "maxrpm": {
- label: "Max RPM: ",
- value: (track, unit) => Math.round(track.cadence_max || 0) + ' ' + unit,
- // order: 30
- },
- "avgrpm": {
- label: "Avg RPM: ",
- value: (track, unit) => Math.round(track.cadence_avg || 0) + ' ' + unit,
- // order: 20
- },
- }
- };
+export function Cadence() { + + const _ = L.Control.Elevation.Utils; + + return { + name: 'cadence', // <-- Your custom option name (eg. "cadence: true") + unit: 'rpm', + meta: 'cad', // <-- point.meta.cad + coordinateProperties: ["cads", "cadences", "cad", "cadence"], // List of GPX Extensions ("coordinateProperties") to be handled by "@tmcw/toGeoJSON" + pointToAttr: (point, i) => (point.cad ?? point.meta.cad ?? point.prev('cadence')) || 0, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg }, + scale: { + axis : "y", + position : "right", + scale : { min: -1, max: +1 }, + tickPadding: 16, + labelX : 25, + labelY : -8, + }, + path: { + label : 'RPM', + yAttr : 'cadence', + scaleX : 'distance', + scaleY : 'cadence', + color : '#FFF', + strokeColor : 'blue', + strokeOpacity: "0.85", + fillOpacity : "0.1", + }, + tooltip: { + name: 'cadence', + chart: (item) => L._("cad: ") + item.cadence + " " + 'rpm', + marker: (item) => Math.round(item.cadence) + " " + 'rpm', + order: 1 + }, + summary: { + "minrpm": { + label: "Min RPM: ", + value: (track, unit) => Math.round(track.cadence_min || 0) + ' ' + unit, + // order: 30 + }, + "maxrpm": { + label: "Max RPM: ", + value: (track, unit) => Math.round(track.cadence_max || 0) + ' ' + unit, + // order: 30 + }, + "avgrpm": { + label: "Avg RPM: ", + value: (track, unit) => Math.round(track.cadence_avg || 0) + ' ' + unit, + // order: 20 + }, + } + }; }
\ No newline at end of file diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/heart.js b/assets/static/vendor/leaflet-elevation/src/handlers/heart.js index 1930f60..1e81b3a 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/heart.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/heart.js @@ -1,53 +1,53 @@ -export function Heart() {
-
- const _ = L.Control.Elevation.Utils;
-
- return {
- name: 'heart', // <-- Your custom option name (eg. "heart: true")
- unit: 'bpm',
- meta: 'hr', // <-- point.meta.hr
- coordinateProperties: ["heart", "heartRates", "heartRate"], // List of GPX Extensions ("coordinateProperties") to be handled by "@tmcw/toGeoJSON"
- pointToAttr: (point, i) => (point.hr ?? point.meta.hr ?? point.prev('heart')) || 0,
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg },
- scale: {
- axis : "y",
- position : "left",
- scale : { min: -1, max: +1 },
- tickPadding: 25,
- labelX : -30,
- labelY : -8,
- },
- path: {
- label : 'ECG',
- yAttr : 'heart',
- scaleX : 'distance',
- scaleY : 'heart',
- color : 'white',
- strokeColor : 'red',
- strokeOpacity: "0.85",
- fillOpacity : "0.1",
- },
- tooltip: {
- chart: (item) => L._("hr: ") + item.heart + " " + 'bpm',
- marker: (item) => Math.round(item.heart) + " " + 'bpm',
- order: 1
- },
- summary: {
- "minbpm": {
- label: "Min BPM: ",
- value: (track, unit) => Math.round(track.heart_min || 0) + ' ' + unit,
- // order: 30
- },
- "maxbpm": {
- label: "Max BPM: ",
- value: (track, unit) => Math.round(track.heart_max || 0) + ' ' + unit,
- // order: 30
- },
- "avgbpm": {
- label: "Avg BPM: ",
- value: (track, unit) => Math.round(track.heart_avg || 0) + ' ' + unit,
- // order: 20
- },
- }
- };
+export function Heart() { + + const _ = L.Control.Elevation.Utils; + + return { + name: 'heart', // <-- Your custom option name (eg. "heart: true") + unit: 'bpm', + meta: 'hr', // <-- point.meta.hr + coordinateProperties: ["heart", "heartRates", "heartRate"], // List of GPX Extensions ("coordinateProperties") to be handled by "@tmcw/toGeoJSON" + pointToAttr: (point, i) => (point.hr ?? point.meta.hr ?? point.prev('heart')) || 0, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg }, + scale: { + axis : "y", + position : "left", + scale : { min: -1, max: +1 }, + tickPadding: 25, + labelX : -30, + labelY : -8, + }, + path: { + label : 'ECG', + yAttr : 'heart', + scaleX : 'distance', + scaleY : 'heart', + color : 'white', + strokeColor : 'red', + strokeOpacity: "0.85", + fillOpacity : "0.1", + }, + tooltip: { + chart: (item) => L._("hr: ") + item.heart + " " + 'bpm', + marker: (item) => Math.round(item.heart) + " " + 'bpm', + order: 1 + }, + summary: { + "minbpm": { + label: "Min BPM: ", + value: (track, unit) => Math.round(track.heart_min || 0) + ' ' + unit, + // order: 30 + }, + "maxbpm": { + label: "Max BPM: ", + value: (track, unit) => Math.round(track.heart_max || 0) + ' ' + unit, + // order: 30 + }, + "avgbpm": { + label: "Avg BPM: ", + value: (track, unit) => Math.round(track.heart_avg || 0) + ' ' + unit, + // order: 20 + }, + } + }; };
\ No newline at end of file diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/labels.js b/assets/static/vendor/leaflet-elevation/src/handlers/labels.js index 31b3cd6..4deb0c7 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/labels.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/labels.js @@ -17,25 +17,24 @@ export function Labels() { if (90 == Math.abs(textRotation)) { - pointG.selectAll('text') - .attr('dy', '4px') - .attr("dx", (d, i, el) => Math.sign(textRotation) * (this._height() - d3.select(el[i].parentElement).datum().y - 8) + 'px') - .attr('text-anchor', textRotation > 0 ? 'end' : 'start') - .attr('transform', 'rotate(' + textRotation + ')') + pointG.querySelectorAll('text').forEach(text => L.Control.Elevation.Utils.setAttributes(text, { + dy: '4px', + dx: Math.sign(textRotation) * (this._height() - Number(text.parentElement.dataset.y) - 8) + 'px', + 'text-anchor': textRotation > 0 ? 'end' : 'start', + transform: 'rotate(' + textRotation + ')', + })); - pointG.selectAll('circle') - .attr('r', '2.5') - .attr('fill', '#fff') - .attr("stroke", '#000') - .attr("stroke-width", '1.1'); + pointG.querySelectorAll('circle').forEach(circle => L.Control.Elevation.Utils.setAttributes(circle, { + r: 2.5, fill: '#fff', stroke: '#000', 'stroke-width': 1.1, + })); } else if (!isNaN(textRotation)) { - pointG.selectAll('text') - .attr("dx", "4px") - .attr("dy", "-9px") - .attr('text-anchor', textAnchor ?? (0 == textRotation ? 'start' : 'middle')) - .attr('transform', 'rotate('+ -textRotation +')') + pointG.querySelectorAll('text').forEach(text => L.Control.Elevation.Utils.setAttributes(text, { + dx: '4px', dy: '-9px', + 'text-anchor': textAnchor ?? (0 == textRotation ? 'start' : 'middle'), + transform: 'rotate(' + -textRotation + ')', + })); } diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/lineargradient.js b/assets/static/vendor/leaflet-elevation/src/handlers/lineargradient.js index 90e33ce..ccf5d73 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/lineargradient.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/lineargradient.js @@ -16,6 +16,7 @@ * }, * }) * ``` + * `min` and `max` can also be numeric bounds. */ export function LinearGradient() { @@ -60,7 +61,7 @@ export function LinearGradient() { }; const { preferCanvas } = this.options; - const { attr, path: path_name, range, min, max } = L.extend({ + const { attr, path: path_name, range, min, max } = Object.assign({ attr: 'z', path: 'altitude', range: { 0.0: '#008800', 0.5: '#ffff00', 1.0: '#ff0000' }, @@ -80,8 +81,8 @@ export function LinearGradient() { const { defs } = chart._chart.utils; const palette = get_palette({ - min: isFinite(this.track_info[min]) ? this.track_info[min] : 0, - max: isFinite(this.track_info[max]) ? this.track_info[max] : 1, + min: isFinite(min) ? Number(min) : (isFinite(this.track_info[min]) ? this.track_info[min] : 0), + max: isFinite(max) ? Number(max) : (isFinite(this.track_info[max]) ? this.track_info[max] : 1), range, }); @@ -91,15 +92,22 @@ export function LinearGradient() { /** ref: `path.__fillStyle` within L.Control.Elevation.Utils::drawCanvas(ctx, path) */ path.__fillStyle = gradient = chart._context.createLinearGradient(0, 0, chart._width(), 0); } else { - defs.select('#' + gradient_id).remove(); - gradient = defs.append('svg:linearGradient').attr('id', gradient_id); - gradient.addColorStop = function(offset, color) { gradient.append('svg:stop').attr('offset', offset).attr('stop-color', color) }; - path.attr('fill', 'url(#' + gradient_id + ')').classed('area', false); + defs.querySelector('#' + gradient_id)?.remove(); + gradient = _.create('svg:linearGradient', '', { id: gradient_id }, defs); + gradient.addColorStop = (offset, color) => _.create('svg:stop', '', { offset, 'stop-color': color }, gradient); + path.setAttribute('fill', 'url(#' + gradient_id + ')'); + path.classList.remove('area'); } // Generate gradient for each segment picking colors from palette - for (let i = 0, data = this._data; i < data.length; i++) { - gradient.addColorStop((i) / data.length, palette.getRGBColor(data[i][attr])); + const data = this._data; + const xAttr = chart._props.areas[path_name].xAttr; + const minX = data[0][xAttr]; + const xRange = data[data.length - 1][xAttr] - minX; + + for (let i = 0; i < data.length; i++) { + const offset = xRange ? (data[i][xAttr] - minX) / xRange : 0; + gradient.addColorStop(offset, palette.getRGBColor(data[i][attr])); } }); @@ -108,14 +116,15 @@ export function LinearGradient() { this.on('elechart_updated', () => { const chart = this._chart; const { defs } = chart._chart.utils; - defs.select('#' + legend_id).remove(); - const legendGradient = defs.append('svg:linearGradient').attr('id', legend_id); - Object.keys(range).sort().forEach(i => legendGradient.append('svg:stop').attr('offset', i).attr('stop-color', range[i])); + defs.querySelector('#' + legend_id)?.remove(); + const legendGradient = _.create('svg:linearGradient', '', { id: legend_id }, defs); + Object.keys(range).sort().forEach(i => _.create('svg:stop', '', { offset: i, 'stop-color': range[i] }, legendGradient)); - chart._container - .select('.legend-' + path_name + ' > rect') - .attr('fill', 'url(#' + legend_id + ')') - .classed('area', false); + const rect = chart._container.querySelector('.legend-' + path_name + ' > rect'); + if (rect) { + rect.setAttribute('fill', 'url(#' + legend_id + ')'); + rect.classList.remove('area'); + } }); return { }; diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/pace.js b/assets/static/vendor/leaflet-elevation/src/handlers/pace.js index 9017f39..7f0c260 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/pace.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/pace.js @@ -1,65 +1,65 @@ -export function Pace() {
-
- const _ = L.Control.Elevation.Utils;
-
- let opts = this.options;
- let pace = {};
-
- pace.label = opts.paceLabel || L._(opts.imperial ? 'min/mi' : 'min/km');
- opts.paceFactor = opts.paceFactor || 60; // 1 min = 60 sec
-
- return {
- name: 'pace',
- unit: pace.label,
- deltaMax: this.options.paceDeltaMax,
- clampRange: this.options.paceRange,
- decimals: 2,
- pointToAttr: (_, i) => {
- let dx = (this._data[i].dist - this._data[i > 0 ? i - 1 : i].dist) * 1000;
- let dt = this._data[i].time - this._data[ i > 0 ? i - 1 : i].time;
- return dx > 0 ? Math.abs((dt / dx) / opts.paceFactor) : NaN;
- },
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg },
- scale : (this.options.pace && this.options.pace != "summary") && {
- axis : "y",
- position : "right",
- scale : { min : 0, max : +1 },
- tickPadding: 16,
- labelX : 25,
- labelY : -8,
- },
- path: (this.options.pace && this.options.pace != "summary") && {
- // name : 'pace',
- label : 'Pace',
- yAttr : "pace",
- scaleX : 'distance',
- scaleY : 'pace',
- color : '#03ffff',
- strokeColor : '#000',
- strokeOpacity: "0.5",
- fillOpacity : "0.25",
- },
- tooltip: (this.options.pace) && {
- chart: (item) => L._('pace: ') + item.pace + " " + pace.label,
- marker: (item) => Math.round(item.pace) + " " + pace.label,
- order: 50,
- },
- summary: (this.options.pace) && {
- "minpace" : {
- label: "Min Pace: ",
- value: (track, unit) => Math.round(track.pace_min || 0) + ' ' + unit,
- order: 51
- },
- "maxpace" : {
- label: "Max Pace: ",
- value: (track, unit) => Math.round(track.pace_max || 0) + ' ' + unit,
- order: 51
- },
- "avgpace": {
- label: "Avg Pace: ",
- value: (track, unit) => Math.round(track.pace_avg || 0) + ' ' + unit,
- order: 52
- },
- }
- };
-}
+export function Pace() { + + const _ = L.Control.Elevation.Utils; + + let opts = this.options; + let pace = {}; + + pace.label = opts.paceLabel || L._(opts.imperial ? 'min/mi' : 'min/km'); + opts.paceFactor = opts.paceFactor || 60; // 1 min = 60 sec + + return { + name: 'pace', + unit: pace.label, + deltaMax: this.options.paceDeltaMax, + clampRange: this.options.paceRange, + decimals: 2, + pointToAttr: (_, i) => { + let dx = (this._data[i].dist - this._data[i > 0 ? i - 1 : i].dist) * 1000; + let dt = this._data[i].time - this._data[ i > 0 ? i - 1 : i].time; + return dx > 0 ? Math.abs((dt / dx) / opts.paceFactor) : NaN; + }, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg }, + scale : (this.options.pace && this.options.pace != "summary") && { + axis : "y", + position : "right", + scale : { min : 0, max : +1 }, + tickPadding: 16, + labelX : 25, + labelY : -8, + }, + path: (this.options.pace && this.options.pace != "summary") && { + // name : 'pace', + label : 'Pace', + yAttr : "pace", + scaleX : 'distance', + scaleY : 'pace', + color : '#03ffff', + strokeColor : '#000', + strokeOpacity: "0.5", + fillOpacity : "0.25", + }, + tooltip: (this.options.pace) && { + chart: (item) => L._('pace: ') + item.pace + " " + pace.label, + marker: (item) => Math.round(item.pace) + " " + pace.label, + order: 50, + }, + summary: (this.options.pace) && { + "minpace" : { + label: "Min Pace: ", + value: (track, unit) => Math.round(track.pace_min || 0) + ' ' + unit, + order: 51 + }, + "maxpace" : { + label: "Max Pace: ", + value: (track, unit) => Math.round(track.pace_max || 0) + ' ' + unit, + order: 51 + }, + "avgpace": { + label: "Avg Pace: ", + value: (track, unit) => Math.round(track.pace_avg || 0) + ' ' + unit, + order: 52 + }, + } + }; +} diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/runner.js b/assets/static/vendor/leaflet-elevation/src/handlers/runner.js index 30dd80a..8135edd 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/runner.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/runner.js @@ -1,18 +1,20 @@ /** - * @see https://github.com/Igor-Vladyka/leaflet.motion + * Animate a track with requestAnimationFrame; motion speed is in km/h and duration in ms. * + * Inspired by: https://github.com/Igor-Vladyka/leaflet.motion + * * @example * ```js * L.control.Elevation({ handlers: [ 'Runner' ], runnerOptions: { polyline: {..}, motion: {..}, marker {..} } }) * ``` */ -export async function Runner() { +export function Runner() { - await this.import(this.__LMOTION || 'https://unpkg.com/leaflet.motion@0.3.2/dist/leaflet.motion.min.js', typeof L.Motion !== 'object') + const _ = L.Control.Elevation.Utils; let { runnerOptions } = this.options; - runnerOptions = L.extend( + runnerOptions = Object.assign( { polyline: {}, motion: {}, marker: undefined }, 'object' === typeof runnerOptions ? runnerOptions : {} ); @@ -40,13 +42,10 @@ export async function Runner() { this.addRunner = function (runner) { let x = this._x(runner.dist); let y = this._y(this._findItemForX(x).z) - let g = d3.select(this._container) - .select('svg > g') - .append("svg:circle") - .attr("class", "runner " + this.options.theme + " height-focus circle-lower") - .attr("r", 6) - .attr("cx", x) - .attr("cy", y); + let g = _.create('svg:circle', '', { + class: "runner " + this.options.theme + " height-focus circle-lower", + r: 6, cx: x, cy: y, + }, this._container.querySelector('svg > g')); return g; } @@ -71,13 +70,36 @@ export async function Runner() { curr = this._findItemForX(x); } - runner - .attr("cx", x) - .attr("cy", this._y(curr.z)); + runner.setAttribute("cx", x); + runner.setAttribute("cy", this._y(curr.z)); this.setPositionFromLatLng(curr.latlng); }; this.animate = function (layer, speed = 1500) { + const latlngs = []; + const collect = segment => { + if (segment instanceof L.Polyline) { + const append = points => { + if (L.LineUtil.isFlat(points)) latlngs.push(...points); + else points.forEach(append); + }; + append(segment.getLatLngs()); + } else if (segment.eachLayer) segment.eachLayer(collect); + }; + collect(layer); + if (!latlngs.length) throw new Error('The runner requires a track with coordinates.'); + + const distances = [0]; + for (let i = 1; i < latlngs.length; i++) { + distances.push(distances[i - 1] + latlngs[i - 1].distanceTo(latlngs[i])); + } + const length = distances[distances.length - 1]; + const motion = Object.assign({ auto: true, speed, easing: value => value }, runnerOptions.motion); + const duration = motion.duration || (motion.speed ? length / motion.speed * 3600 : 0); + if (!Number.isFinite(duration) || duration < 0 || !Number.isFinite(motion.speed) || motion.speed < 0) { + throw new Error('Runner speed and duration must be finite, non-negative numbers.'); + } + if (typeof motion.easing !== 'function') throw new Error('Runner easing must be a function.'); if (this._runner) { this._runner.remove(); @@ -85,24 +107,75 @@ export async function Runner() { layer.setStyle({ opacity: 0.5 }); - const geo = L.geoJson(layer.toGeoJSON(), { coordsToLatLng: (coords) => L.latLng(coords[0], coords[1], coords[2] * (this.options.altitudeFactor || 1)) }); - this._runner = L.motion.polyline( - geo.toGeoJSON().features[0].geometry.coordinates, - L.extend({}, { color: 'red', pane: 'elevationPane', attribution: '' }, runnerOptions.polyline), - L.extend({}, { auto: true, speed: speed, }, runnerOptions.motion), - runnerOptions.marker || undefined - ); + const runner = this._runner = new L.Polyline([], Object.assign( + { color: 'red', pane: 'elevationPane', attribution: '' }, runnerOptions.polyline + )); + const marker = runnerOptions.marker ? new L.Marker(latlngs[0], runnerOptions.marker) : null; + let circle; + let frame; + let started; + let elapsed = 0; + let running = false; - // Override default function behavior: `L.Motion.Polyline::_drawMarker()` - this._runner._drawMarker = new Proxy(this._runner._drawMarker, { - apply: (target, thisArg, argArray) => { - thisArg._runner = thisArg._runner || this.addRunner({ dist: 0 }); - this.updateRunnerPos(thisArg._runner, argArray[0]); - return target.apply(thisArg, argArray); + const draw = progress => { + const distance = length * progress; + let index = 1; + while (index < distances.length - 1 && distances[index] < distance) index++; + index = Math.min(index, latlngs.length - 1); + const previous = Math.max(0, index - 1); + const segmentLength = distances[index] - distances[previous]; + const ratio = segmentLength ? (distance - distances[previous]) / segmentLength : 0; + const from = this._map.project(latlngs[previous]); + const to = this._map.project(latlngs[index]); + const position = this._map.unproject(from.add(to.subtract(from).multiplyBy(ratio))); + runner.setLatLngs([...latlngs.slice(0, index), position]); + circle = circle || this.addRunner({ dist: 0 }); + this.updateRunnerPos(circle, position); + if (marker) marker.setLatLng(position).addTo(this._map); + }; + const advance = timestamp => { + started = started ?? timestamp - elapsed; + elapsed = timestamp - started; + const progress = duration ? Math.min(1, elapsed / duration) : 1; + draw(progress === 1 ? 1 : Math.max(0, Math.min(1, motion.easing(progress, elapsed, 0, 1, duration)))); + if (progress < 1) frame = requestAnimationFrame(advance); + else { + running = false; + if (runnerOptions.marker?.removeOnEnd) marker.remove(); + runner.fire('motion-ended', { layer: runner }); } + }; + runner.motionPause = () => { + cancelAnimationFrame(frame); + running = false; + started = undefined; + return runner; + }; + runner.motionResume = () => { + if (!running && runner._map) { + running = true; + frame = requestAnimationFrame(advance); + } + return runner; + }; + runner.motionStart = () => { + runner.motionPause(); + elapsed = 0; + return runner.motionResume(); + }; + runner.getMarker = () => marker; + runner.on('remove', () => { + runner.motionPause(); + circle?.remove(); + marker?.remove(); + this.off('eledata_clear', remove); + this.off('remove', remove); }); - - this._runner.addTo(this._map); + const remove = () => runner.remove(); + this.on('eledata_clear', remove); + this.on('remove', remove); + runner.addTo(this._map); + if (motion.auto) runner.motionStart(); }; return {}; diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/slope.js b/assets/static/vendor/leaflet-elevation/src/handlers/slope.js index 37291b3..1ed65af 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/slope.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/slope.js @@ -1,79 +1,79 @@ -export function Slope() {
-
- const _ = L.Control.Elevation.Utils;
-
- let opts = this.options;
- let slope = {};
-
- slope.label = opts.slopeLabel || '%';
-
- return {
- name: 'slope',
- meta: 'slope',
- unit: slope.label,
- deltaMax: this.options.slopedDeltaMax,
- clampRange: this.options.slopeRange,
- decimals: 2,
- pointToAttr: (_, i) => { // slope in % = ( dy / dx ) * 100;
- let dx = (this._data[i].dist - this._data[i > 0 ? i - 1 : i].dist) * 1000;
- let dy = this._data[i][this.options.yAttr] - this._data[i > 0 ? i - 1 : i][this.options.yAttr];
- return dx !== 0 ? (dy / dx) * 100 : NaN;
- },
- onPointAdded: (_, i) => {
- let dz = this._data[i][this.options.yAttr] - this._data[i > 0 ? i - 1 : i][this.options.yAttr];
- if (dz > 0) this.track_info.ascent = (this.track_info.ascent || 0) + dz; // Total Ascent
- else if (dz < 0) this.track_info.descent = (this.track_info.descent || 0) - dz; // Total Descent
- },
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg, },
- scale: {
- axis : "y",
- position : "right",
- scale : { min: -1, max: +1 },
- tickPadding: 16,
- labelX : 25,
- labelY : -8,
- },
- path: {
- label : 'Slope',
- yAttr : 'slope',
- scaleX : 'distance',
- scaleY : 'slope',
- color : '#F00',
- strokeColor : '#000',
- strokeOpacity: "0.5",
- fillOpacity : "0.25",
- },
- tooltip: {
- chart: (item) => L._("m: ") + item.slope + slope.label,
- marker: (item) => Math.round(item.slope) + slope.label,
- order: 40,
- },
- summary: {
- "minslope": {
- label: "Min Slope: ",
- value: (track, unit) => Math.round(track.slope_min || 0) + ' ' + unit,
- order: 40
- },
- "maxslope": {
- label: "Max Slope: ",
- value: (track, unit) => Math.round(track.slope_max || 0) + ' ' + unit,
- order: 41
- },
- "avgslope": {
- label: "Avg Slope: ",
- value: (track, unit) => Math.round(track.slope_avg || 0) + ' ' + unit,
- order: 42
- },
- "ascent" : {
- label: "Total Ascent: ",
- value: (track, unit) => Math.round(track.ascent || 0) + ' ' + (this.options.imperial ? 'ft' : 'm'),
- order: 43
- },
- "descent" : {
- label: "Total Descent: ",
- value: (track, unit) => Math.round(track.descent || 0) + ' ' + (this.options.imperial ? 'ft' : 'm'),
- order: 45
- },
- }
- };
-}
+export function Slope() { + + const _ = L.Control.Elevation.Utils; + + let opts = this.options; + let slope = {}; + + slope.label = opts.slopeLabel || '%'; + + return { + name: 'slope', + meta: 'slope', + unit: slope.label, + deltaMax: this.options.slopedDeltaMax, + clampRange: this.options.slopeRange, + decimals: 2, + pointToAttr: (_, i) => { // slope in % = ( dy / dx ) * 100; + let dx = (this._data[i].dist - this._data[i > 0 ? i - 1 : i].dist) * 1000; + let dy = this._data[i][this.options.yAttr] - this._data[i > 0 ? i - 1 : i][this.options.yAttr]; + return dx !== 0 ? (dy / dx) * 100 : NaN; + }, + onPointAdded: (_, i) => { + let dz = this._data[i][this.options.yAttr] - this._data[i > 0 ? i - 1 : i][this.options.yAttr]; + if (dz > 0) this.track_info.ascent = (this.track_info.ascent || 0) + dz; // Total Ascent + else if (dz < 0) this.track_info.descent = (this.track_info.descent || 0) - dz; // Total Descent + }, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg, }, + scale: { + axis : "y", + position : "right", + scale : { min: -1, max: +1 }, + tickPadding: 16, + labelX : 25, + labelY : -8, + }, + path: { + label : 'Slope', + yAttr : 'slope', + scaleX : 'distance', + scaleY : 'slope', + color : '#F00', + strokeColor : '#000', + strokeOpacity: "0.5", + fillOpacity : "0.25", + }, + tooltip: { + chart: (item) => L._("m: ") + item.slope + slope.label, + marker: (item) => Math.round(item.slope) + slope.label, + order: 40, + }, + summary: { + "minslope": { + label: "Min Slope: ", + value: (track, unit) => Math.round(track.slope_min || 0) + ' ' + unit, + order: 40 + }, + "maxslope": { + label: "Max Slope: ", + value: (track, unit) => Math.round(track.slope_max || 0) + ' ' + unit, + order: 41 + }, + "avgslope": { + label: "Avg Slope: ", + value: (track, unit) => Math.round(track.slope_avg || 0) + ' ' + unit, + order: 42 + }, + "ascent" : { + label: "Total Ascent: ", + value: (track, unit) => Math.round(track.ascent || 0) + ' ' + (this.options.imperial ? 'ft' : 'm'), + order: 43 + }, + "descent" : { + label: "Total Descent: ", + value: (track, unit) => Math.round(track.descent || 0) + ' ' + (this.options.imperial ? 'ft' : 'm'), + order: 45 + }, + } + }; +} diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/speed.js b/assets/static/vendor/leaflet-elevation/src/handlers/speed.js index 534b340..52068e8 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/speed.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/speed.js @@ -1,66 +1,66 @@ -export function Speed() {
-
- const _ = L.Control.Elevation.Utils;
-
- let opts = this.options;
- let speed = {};
-
- speed.label = opts.speedLabel || L._(opts.imperial ? 'mph' : 'km/h');
- opts.speedFactor = opts.speedFactor || 1;
-
- return {
- name: 'speed',
- required: (this.options.acceleration),
- unit: speed.label,
- deltaMax: this.options.speedDeltaMax,
- clampRange: this.options.speedRange,
- decimals: 2,
- pointToAttr: (_, i) => {
- let dx = (this._data[i].dist - this._data[i > 0 ? i - 1 : i].dist) * 1000;
- let dt = this._data[i].time - this._data[ i > 0 ? i - 1 : i].time;
- return dt > 0 ? Math.abs((dx / dt) * opts.timeFactor) * opts.speedFactor : NaN;
- },
- stats: { max: _.iMax, min: _.iMin, avg: _.iAvg },
- scale : (this.options.speed && this.options.speed != "summary") && {
- axis : "y",
- position : "right",
- scale : { min : 0, max : +1 },
- tickPadding: 16,
- labelX : 25,
- labelY : -8,
- },
- path: (this.options.speed && this.options.speed != "summary") && {
- // name : 'speed',
- label : 'Speed',
- yAttr : "speed",
- scaleX : 'distance',
- scaleY : 'speed',
- color : '#03ffff',
- strokeColor : '#000',
- strokeOpacity: "0.5",
- fillOpacity : "0.25",
- },
- tooltip: (this.options.speed) && {
- chart: (item) => L._('v: ') + item.speed + " " + speed.label,
- marker: (item) => Math.round(item.speed) + " " + speed.label,
- order: 50,
- },
- summary: (this.options.speed) && {
- "minspeed" : {
- label: "Min Speed: ",
- value: (track, unit) => Math.round(track.speed_min || 0) + ' ' + unit,
- order: 51
- },
- "maxspeed" : {
- label: "Max Speed: ",
- value: (track, unit) => Math.round(track.speed_max || 0) + ' ' + unit,
- order: 51
- },
- "avgspeed": {
- label: "Avg Speed: ",
- value: (track, unit) => Math.round(track.speed_avg || 0) + ' ' + unit,
- order: 52
- },
- }
- };
-}
+export function Speed() { + + const _ = L.Control.Elevation.Utils; + + let opts = this.options; + let speed = {}; + + speed.label = opts.speedLabel || L._(opts.imperial ? 'mph' : 'km/h'); + opts.speedFactor = opts.speedFactor || 1; + + return { + name: 'speed', + required: (this.options.acceleration), + unit: speed.label, + deltaMax: this.options.speedDeltaMax, + clampRange: this.options.speedRange, + decimals: 2, + pointToAttr: (_, i) => { + let dx = (this._data[i].dist - this._data[i > 0 ? i - 1 : i].dist) * 1000; + let dt = this._data[i].time - this._data[ i > 0 ? i - 1 : i].time; + return dt > 0 ? Math.abs((dx / dt) * opts.timeFactor) * opts.speedFactor : NaN; + }, + stats: { max: _.iMax, min: _.iMin, avg: _.iAvg }, + scale : (this.options.speed && this.options.speed != "summary") && { + axis : "y", + position : "right", + scale : { min : 0, max : +1 }, + tickPadding: 16, + labelX : 25, + labelY : -8, + }, + path: (this.options.speed && this.options.speed != "summary") && { + // name : 'speed', + label : 'Speed', + yAttr : "speed", + scaleX : 'distance', + scaleY : 'speed', + color : '#03ffff', + strokeColor : '#000', + strokeOpacity: "0.5", + fillOpacity : "0.25", + }, + tooltip: (this.options.speed) && { + chart: (item) => L._('v: ') + item.speed + " " + speed.label, + marker: (item) => Math.round(item.speed) + " " + speed.label, + order: 50, + }, + summary: (this.options.speed) && { + "minspeed" : { + label: "Min Speed: ", + value: (track, unit) => Math.round(track.speed_min || 0) + ' ' + unit, + order: 51 + }, + "maxspeed" : { + label: "Max Speed: ", + value: (track, unit) => Math.round(track.speed_max || 0) + ' ' + unit, + order: 51 + }, + "avgspeed": { + label: "Avg Speed: ", + value: (track, unit) => Math.round(track.speed_avg || 0) + ' ' + unit, + order: 52 + }, + } + }; +} diff --git a/assets/static/vendor/leaflet-elevation/src/handlers/time.js b/assets/static/vendor/leaflet-elevation/src/handlers/time.js index d94b136..b1f08b8 100644 --- a/assets/static/vendor/leaflet-elevation/src/handlers/time.js +++ b/assets/static/vendor/leaflet-elevation/src/handlers/time.js @@ -40,7 +40,7 @@ export function Time() { if (!point.meta || !point.meta.time) { point.meta = point.meta || {}; if (i > 0) { - let dx = (this._data[i].dist - this._data[i - 1].dist); + let dx = this._data[i].latlng.distanceTo(this._data[i - 1].latlng) / 1000; let t0 = this._data[i - 1].time.getTime(); point.meta.time = new Date(t0 + ( dx / this._timeAVGSpeed) * this.options.timeFactor * 1000); } else { @@ -57,27 +57,34 @@ export function Time() { scale: (opts.time && opts.time != "summary" && !L.Browser.mobile) && { axis : "x", position : "top", - scale : { - attr : "duration", - min : 0, - }, + scale : "x", label : time.label, labelY : -10, labelX : () => this._width(), name : "time", ticks : () => _.clamp(this._chart._xTicks() / 2, [4, +Infinity]), - tickFormat : (d) => (d == 0 ? '' : opts.xTimeFormat(d)), + tickFormat : (distance) => { + const data = this._data; + if (!data.length) return ''; + const i = _.bisect(data, distance, opts.xAttr, true); + const start = data[Math.max(0, i - 1)]; + const end = data[Math.min(i, data.length - 1)]; + const span = end[opts.xAttr] - start[opts.xAttr]; + // Time is only linear between consecutive recorded points, not across the whole track. + const fraction = span ? _.clamp((distance - start[opts.xAttr]) / span, [0, 1]) : 0; + const duration = start.duration + fraction * (end.duration - start.duration); + return duration == 0 ? '' : opts.xTimeFormat(duration); + }, onAxisMount: axis => { - axis.select(".domain") - .remove(); - axis.selectAll("text") - .attr('opacity', 0.65) - .style('font-family', 'Monospace') - .style('font-size', '110%'); - axis.selectAll(".tick line") - .attr('y2', this._height()) - .attr('stroke-dasharray', 2) - .attr('opacity', 0.75); + axis.querySelector(".domain").remove(); + axis.querySelectorAll("text").forEach(text => { + text.setAttribute('opacity', 0.65); + text.style.fontFamily = 'Monospace'; + text.style.fontSize = '110%'; + }); + axis.querySelectorAll(".tick line").forEach(line => _.setAttributes(line, { + y2: this._height(), 'stroke-dasharray': 2, opacity: 0.75, + })); } }, tooltips: [ diff --git a/assets/static/vendor/leaflet-elevation/src/index.css b/assets/static/vendor/leaflet-elevation/src/index.css index 9b29174..d2405bd 100644 --- a/assets/static/vendor/leaflet-elevation/src/index.css +++ b/assets/static/vendor/leaflet-elevation/src/index.css @@ -1,329 +1,329 @@ -.leaflet-hidden {
- visibility: hidden;
-}
-
-.legend {
- cursor: pointer;
-}
-
-.leaflet-container {
- z-index: 0;
- /* prevent overlapping the .elevation-detached chart */
-}
-
-.elevation-control .background {
- background-color: var(--ele-bg, rgba(70, 130, 180, 0.2));
- border-radius: 5px;
- overflow: visible;
- display: block;
- touch-action: none;
- user-select: none;
- max-width: 100%;
-}
-
-.elevation-control .grid,
-.elevation-control .area > foreignObject,
-.elevation-control .axis,
-.elevation-control .tooltip,
-.height-focus.line {
- pointer-events: none;
-}
-
-.elevation-control .axis line,
-.elevation-control .axis path {
- stroke: var(--ele-axis, #2D1130);
- stroke-width: 1;
- fill: none;
-}
-
-.elevation-control .grid .tick line {
- stroke: var(--ele-grid, #EEE);
- stroke-width: 1px;
- shape-rendering: crispEdges;
-}
-
-.elevation-control .grid path {
- stroke-width: 0;
-}
-
-.elevation-control .axis text,
-.elevation-control .legend text,
-.elevation-control .point text {
- fill: #000;
- font-weight: 700;
- paint-order: stroke fill;
- stroke: #fff;
- stroke-width: 2px
-}
-
-.elevation-control .y.axis text {
- text-anchor: end;
-}
-
-.elevation-control .area {
- fill: var(--ele-area, #4682B4);
- stroke: var(--ele-stroke, #000);
- stroke-width: 1.2;
- paint-order: stroke fill;
-}
-
-.elevation-control .horizontal-drag-line {
- cursor: row-resize;
- stroke: transparent;
- stroke-dasharray: 5;
- stroke-width: 1.1;
-}
-
-.elevation-control .active .horizontal-drag-line {
- stroke: #000;
-}
-
-.elevation-control .horizontal-drag-label {
- fill: #000;
- font-weight: 700;
- paint-order: stroke;
- stroke: #FFF;
- stroke-width: 2px;
-}
-
-.elevation-control .ruler {
- color: #000;
- cursor: row-resize;
-}
-
-.elevation-control .mouse-focus-line {
- stroke: #000;
- stroke-width: 1;
-}
-
-.elevation-control .mouse-focus-label-rect {
- fill: #000;
- fill-opacity: 0.75;
- stroke-width: 1;
- stroke: #444;
-}
-
-.elevation-control .mouse-focus-label-text {
- fill: #FFF;
- font-size: 10px;
-}
-
-.elevation-control .brush .overlay {
- cursor: unset;
-}
-
-.elevation-control .brush .selection {
- fill: var(--ele-brush, rgba(23, 74, 117, 0.4));
- stroke: none;
- fill-opacity: unset;
-}
-
-.elevation-summary {
- font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
- font-size: 12px;
- margin: var(--ele-sum-margin, 0 auto);
- text-shadow: var(--ele-sum-shadow, 1px 0 0 #FFF, -1px 0 0 #FFF, 0 1px 0 #FFF, 0 -1px 0 #FFF, 1px 1px #FFF, -1px -1px 0 #FFF, 1px -1px 0 #FFF, -1px 1px 0 #FFF);
-}
-
-.elevation-summary>span:not(:last-child):after {
- content: var(--ele-sum-sep, '');
-}
-
-.multiline-summary>span {
- display: block;
-}
-
-.multiline-summary .download {
- float: right;
- margin-top: -3em;
- margin-right: 2em;
- font-weight: bold;
- font-size: 1.2em;
-}
-
-.elevation-summary .summaryvalue {
- font-weight: bold;
-}
-
-.elevation-toggle-icon {
- background-color: #fff;
- right: 5px;
- top: 5px;
- height: var(--ele-toggle-size, 36px);
- width: var(--ele-toggle-size, 36px);
- cursor: pointer;
- box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
- border-radius: 5px;
- display: inline-block;
- position: var(--ele-toggle-pos, relative);
-}
-
-.elevation-toggle-icon:before {
- content: '\2716';
- display: var(--ele-close-btn, none);
- color: #000;
- width: 100%;
- line-height: 20px;
- text-align: center;
- font-weight: bold;
- font-size: 15px;
-}
-
-.leaflet-elevation-pane .height-focus,
-.leaflet-overlay-pane .height-focus {
- stroke: #000;
- fill: var(--ele-circle, var(--ele-area, #FFF));
-}
-
-.leaflet-elevation-pane .height-focus.line,
-.leaflet-overlay-pane .height-focus.line {
- stroke-width: 2;
-}
-
-.leaflet-elevation-pane .height-focus-label,
-.leaflet-overlay-pane .height-focus-label {
- font-size: 12px;
- font-weight: 600;
- fill: #000;
- paint-order: stroke;
- stroke: #FFF;
- stroke-width: 2px;
-}
-
-.elevation-waypoint-icon:before,
-.elevation-position-icon:before {
- content: "";
- width: 100%;
- height: 100%;
- display: inline-block;
- background: var(--ele-marker) no-repeat center center / contain;
-}
-
-.elevation-polyline {
- stroke: var(--ele-poly, var(--ele-area, #000));
- filter: drop-shadow(1px 1px 0 #FFF) drop-shadow(-1px -1px 0 #FFF) drop-shadow(1px -1px 0 #FFF) drop-shadow(-1px 1px 0 #FFF);
-}
-
-/* CHART STATES /////////////////////////////////////////////////// */
-
-.elevation-detached {
- font: 12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif;
- height: auto;
- width: 100%;
- position: relative;
- z-index: 0;
-}
-
-.elevation-detached .area {
- fill-opacity: var(--ele-alpha, 0.8);
-}
-
-.elevation-detached.elevation-collapsed .elevation-summary {
- display: block;
-}
-
-.elevation-detached.elevation-collapsed .elevation-toggle-icon {
- top: 5px;
- right: 9px;
- bottom: 5px;
- margin: auto;
-}
-
-.elevation-control.elevation-collapsed > * {
- display: none;
-}
-
-.elevation-control.elevation-collapsed > .elevation-toggle-icon {
- display: inline-block;
-}
-
-.elevation-detached {
- --ele-sum-margin: 12px 35px;
- --ele-sum-shadow: none;
- --ele-toggle-pos: absolute;
-}
-
-.elevation-expanded {
- --ele-close-btn: inline-block;
- --ele-toggle-bg: none;
- --ele-toggle-pos: absolute;
- --ele-toggle-size: 20px;
-}
-
-.inline-summary {
- --ele-sum-sep: "\0020\2014\0020";
-}
-
-.elevation-waypoint-icon {
- --ele-marker: url(../images/elevation-pushpin.svg);
-}
-
-.elevation-position-icon {
- --ele-marker: url(../images/elevation-position.svg);
-}
-
-/* LIME THEME ///////////////////////////////////////////////////// */
-.lime-theme {
- --ele-bg: rgba(156, 194, 34, 0.2);
- --ele-axis: #566B13;
- --ele-area: #9CC222;
- --ele-grid: #CCC;
- --ele-brush: rgba(99, 126, 11, 0.4);
- --ele-poly: #566B13;
- --ele-line: #70ab00;
-}
-
-/* STEELBLUE THEME //////////////////////////////////////////////// */
-.steelblue-theme {
- --ele-axis: #0D1821;
- --ele-area: #4682B4;
- --ele-brush: rgba(23, 74, 117, 0.4);
- --ele-line: #174A75;
-}
-
-/* PURPLE THEME /////////////////////////////////////////////////// */
-.purple-theme {
- --ele-bg: rgba(115, 44, 123, 0.2);
- --ele-area: #732C7B;
- --ele-brush: rgba(74, 14, 80, 0.4);
- --ele-line: #732c7b;
-}
-
-/* YELLOW THEME /////////////////////////////////////////////////// */
-.yellow-theme {
- --ele-area: #FF0;
-}
-
-/* RED THEME ////////////////////////////////////////////////////// */
-.red-theme {
- --ele-area: #F00;
-}
-
-/* MAGENTA THEME ////////////////////////////////////////////////// */
-.magenta-theme {
- --ele-bg: rgba(255, 255, 255, 0.47);
- --ele-area: #FF005E;
-}
-
-/* LIGHTBLUE THEME //////////////////////////////////////////////// */
-.lightblue-theme {
- --ele-area: #3366CC;
- --ele-alpha: 0.45;
- --ele-stroke: #4682B4;
- --ele-circle: #fff;
- --ele-line: #000;
-}
-
-.elevation-detached.lightblue-theme .area {
- stroke: #3366CC;
-}
-
-/* leaflet-distance-markers */
-.dist-marker {
- font-size: 0.5rem;
- border: 1px solid #777;
- border-radius: 10px;
- text-align: center;
- color: #000;
- background: #fff;
-}
+.leaflet-hidden { + visibility: hidden; +} + +.legend { + cursor: pointer; +} + +.leaflet-container { + z-index: 0; + /* prevent overlapping the .elevation-detached chart */ +} + +.elevation-control .background { + background-color: var(--ele-bg, rgba(70, 130, 180, 0.2)); + border-radius: 5px; + overflow: visible; + display: block; + touch-action: none; + user-select: none; + max-width: 100%; +} + +.elevation-control .grid, +.elevation-control .area > foreignObject, +.elevation-control .axis, +.elevation-control .tooltip, +.height-focus.line { + pointer-events: none; +} + +.elevation-control .axis line, +.elevation-control .axis path { + stroke: var(--ele-axis, #2D1130); + stroke-width: 1; + fill: none; +} + +.elevation-control .grid .tick line { + stroke: var(--ele-grid, #EEE); + stroke-width: 1px; + shape-rendering: crispEdges; +} + +.elevation-control .grid path { + stroke-width: 0; +} + +.elevation-control .axis text, +.elevation-control .legend text, +.elevation-control .point text { + fill: #000; + font-weight: 700; + paint-order: stroke fill; + stroke: #fff; + stroke-width: 2px +} + +.elevation-control .y.axis text { + text-anchor: end; +} + +.elevation-control .area { + fill: var(--ele-area, #4682B4); + stroke: var(--ele-stroke, #000); + stroke-width: 1.2; + paint-order: stroke fill; +} + +.elevation-control .horizontal-drag-line { + cursor: row-resize; + stroke: transparent; + stroke-dasharray: 5; + stroke-width: 1.1; +} + +.elevation-control .active .horizontal-drag-line { + stroke: #000; +} + +.elevation-control .horizontal-drag-label { + fill: #000; + font-weight: 700; + paint-order: stroke; + stroke: #FFF; + stroke-width: 2px; +} + +.elevation-control .ruler { + color: #000; + cursor: row-resize; +} + +.elevation-control .mouse-focus-line { + stroke: #000; + stroke-width: 1; +} + +.elevation-control .mouse-focus-label-rect { + fill: #000; + fill-opacity: 0.75; + stroke-width: 1; + stroke: #444; +} + +.elevation-control .mouse-focus-label-text { + fill: #FFF; + font-size: 10px; +} + +.elevation-control .brush .overlay { + cursor: unset; +} + +.elevation-control .brush .selection { + fill: var(--ele-brush, rgba(23, 74, 117, 0.4)); + stroke: none; + fill-opacity: unset; +} + +.elevation-summary { + font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; + font-size: 12px; + margin: var(--ele-sum-margin, 0 auto); + text-shadow: var(--ele-sum-shadow, 1px 0 0 #FFF, -1px 0 0 #FFF, 0 1px 0 #FFF, 0 -1px 0 #FFF, 1px 1px #FFF, -1px -1px 0 #FFF, 1px -1px 0 #FFF, -1px 1px 0 #FFF); +} + +.elevation-summary>span:not(:last-child):after { + content: var(--ele-sum-sep, ''); +} + +.multiline-summary>span { + display: block; +} + +.multiline-summary .download { + float: right; + margin-top: -3em; + margin-right: 2em; + font-weight: bold; + font-size: 1.2em; +} + +.elevation-summary .summaryvalue { + font-weight: bold; +} + +.elevation-toggle-icon { + background-color: #fff; + right: 5px; + top: 5px; + height: var(--ele-toggle-size, 36px); + width: var(--ele-toggle-size, 36px); + cursor: pointer; + box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4); + border-radius: 5px; + display: inline-block; + position: var(--ele-toggle-pos, relative); +} + +.elevation-toggle-icon:before { + content: '\2716'; + display: var(--ele-close-btn, none); + color: #000; + width: 100%; + line-height: 20px; + text-align: center; + font-weight: bold; + font-size: 15px; +} + +.leaflet-elevation-pane .height-focus, +.leaflet-overlay-pane .height-focus { + stroke: #000; + fill: var(--ele-circle, var(--ele-area, #FFF)); +} + +.leaflet-elevation-pane .height-focus.line, +.leaflet-overlay-pane .height-focus.line { + stroke-width: 2; +} + +.leaflet-elevation-pane .height-focus-label, +.leaflet-overlay-pane .height-focus-label { + font-size: 12px; + font-weight: 600; + fill: #000; + paint-order: stroke; + stroke: #FFF; + stroke-width: 2px; +} + +.elevation-waypoint-icon:before, +.elevation-position-icon:before { + content: ""; + width: 100%; + height: 100%; + display: inline-block; + background: var(--ele-marker) no-repeat center center / contain; +} + +.elevation-polyline { + stroke: var(--ele-poly, var(--ele-area, #000)); + filter: drop-shadow(1px 1px 0 #FFF) drop-shadow(-1px -1px 0 #FFF) drop-shadow(1px -1px 0 #FFF) drop-shadow(-1px 1px 0 #FFF); +} + +/* CHART STATES /////////////////////////////////////////////////// */ + +.elevation-detached { + font: 12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif; + height: auto; + width: 100%; + position: relative; + z-index: 0; +} + +.elevation-detached .area { + fill-opacity: var(--ele-alpha, 0.8); +} + +.elevation-detached.elevation-collapsed .elevation-summary { + display: block; +} + +.elevation-detached.elevation-collapsed .elevation-toggle-icon { + top: 5px; + right: 9px; + bottom: 5px; + margin: auto; +} + +.elevation-control.elevation-collapsed > * { + display: none; +} + +.elevation-control.elevation-collapsed > .elevation-toggle-icon { + display: inline-block; +} + +.elevation-detached { + --ele-sum-margin: 12px 35px; + --ele-sum-shadow: none; + --ele-toggle-pos: absolute; +} + +.elevation-expanded { + --ele-close-btn: inline-block; + --ele-toggle-bg: none; + --ele-toggle-pos: absolute; + --ele-toggle-size: 20px; +} + +.inline-summary { + --ele-sum-sep: "\0020\2014\0020"; +} + +.elevation-waypoint-icon { + --ele-marker: url(../images/elevation-pushpin.svg); +} + +.elevation-position-icon { + --ele-marker: url(../images/elevation-position.svg); +} + +/* LIME THEME ///////////////////////////////////////////////////// */ +.lime-theme { + --ele-bg: rgba(156, 194, 34, 0.2); + --ele-axis: #566B13; + --ele-area: #9CC222; + --ele-grid: #CCC; + --ele-brush: rgba(99, 126, 11, 0.4); + --ele-poly: #566B13; + --ele-line: #70ab00; +} + +/* STEELBLUE THEME //////////////////////////////////////////////// */ +.steelblue-theme { + --ele-axis: #0D1821; + --ele-area: #4682B4; + --ele-brush: rgba(23, 74, 117, 0.4); + --ele-line: #174A75; +} + +/* PURPLE THEME /////////////////////////////////////////////////// */ +.purple-theme { + --ele-bg: rgba(115, 44, 123, 0.2); + --ele-area: #732C7B; + --ele-brush: rgba(74, 14, 80, 0.4); + --ele-line: #732c7b; +} + +/* YELLOW THEME /////////////////////////////////////////////////// */ +.yellow-theme { + --ele-area: #FF0; +} + +/* RED THEME ////////////////////////////////////////////////////// */ +.red-theme { + --ele-area: #F00; +} + +/* MAGENTA THEME ////////////////////////////////////////////////// */ +.magenta-theme { + --ele-bg: rgba(255, 255, 255, 0.47); + --ele-area: #FF005E; +} + +/* LIGHTBLUE THEME //////////////////////////////////////////////// */ +.lightblue-theme { + --ele-area: #3366CC; + --ele-alpha: 0.45; + --ele-stroke: #4682B4; + --ele-circle: #fff; + --ele-line: #000; +} + +.elevation-detached.lightblue-theme .area { + stroke: #3366CC; +} + +/* leaflet-distance-markers */ +.dist-marker { + font-size: 0.5rem; + border: 1px solid #777; + border-radius: 10px; + text-align: center; + color: #000; + background: #fff; +} diff --git a/assets/static/vendor/leaflet-elevation/src/index.js b/assets/static/vendor/leaflet-elevation/src/index.js index 4e094ff..4263cef 100644 --- a/assets/static/vendor/leaflet-elevation/src/index.js +++ b/assets/static/vendor/leaflet-elevation/src/index.js @@ -1,42 +1,44 @@ -/*
- * Copyright (c) 2019, GPL-3.0+ Project, Raruto
- *
- * This file is free software: you may copy, redistribute and/or modify it
- * under the terms of the GNU General Public License as published by the
- * Free Software Foundation, either version 2 of the License, or (at your
- * option) any later version.
- *
- * This file is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- *
- * This file incorporates work covered by the following copyright and
- * permission notice:
- *
- * Copyright (c) 2013-2016, MIT License, Felix “MrMufflon” Bache
- *
- * Permission to use, copy, modify, and/or distribute this software
- * for any purpose with or without fee is hereby granted, provided
- * that the above copyright notice and this permission notice appear
- * in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
- * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
- * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
- * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
- * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
- * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-import * as _ from './utils';
-import { Elevation } from './control';
-
-Elevation.Utils = _;
-
-L.control.elevation = (options) => new Elevation(options);
+/* + * Copyright (c) 2019, GPL-3.0+ Project, Raruto + * + * This file is free software: you may copy, redistribute and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 2 of the License, or (at your + * option) any later version. + * + * This file is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * Copyright (c) 2013-2016, MIT License, Felix “MrMufflon” Bache + * + * Permission to use, copy, modify, and/or distribute this software + * for any purpose with or without fee is hereby granted, provided + * that the above copyright notice and this permission notice appear + * in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +import * as _ from './utils'; +import { Elevation } from './control'; + +Elevation.Utils = _; + +// backcomps for leaflet v1 +L.control = L.control || {}; +L.control.elevation = (options) => new Elevation(options); diff --git a/assets/static/vendor/leaflet-elevation/src/options.js b/assets/static/vendor/leaflet-elevation/src/options.js index 5923163..1efcf29 100644 --- a/assets/static/vendor/leaflet-elevation/src/options.js +++ b/assets/static/vendor/leaflet-elevation/src/options.js @@ -4,7 +4,7 @@ export var Options = { autofitBounds: true, autohide: false, autohideMarker: true, - almostover: true, + almostOver: true, altitude: true, closeBtn: true, collapsed: false, @@ -21,7 +21,7 @@ export var Options = { handlers: ["Distance", "Time", "Altitude", "Slope", "Speed", "Acceleration"], hotline: 'elevation', marker: 'elevation-line', - markerIcon: L.divIcon({ + markerIcon: new L.DivIcon({ className: 'elevation-position-marker', html: '<i class="elevation-position-icon"></i>', iconSize: [32, 32], @@ -54,7 +54,7 @@ export var Options = { trkEnd: { className: 'end-marker', radius: 6, weight: 2, color: '#fff', fillColor: '#ff0606', fillOpacity: 1, interactive: false }, waypoints: true, wptIcons: { - '': L.divIcon({ + '': new L.DivIcon({ className: 'elevation-waypoint-marker', html: '<i class="elevation-waypoint-icon default"></i>', iconSize: [30, 30], @@ -67,7 +67,7 @@ export var Options = { yAttr: "z", yLabel: "m", zFollow: false, - zooming: !L.Browser.Mobile, + zooming: !L.Browser.mobile, // Quite uncommon and undocumented options margins: { top: 30, right: 30, bottom: 30, left: 40 }, @@ -84,5 +84,5 @@ export var Options = { yAxisMin: undefined, // Prevent CORS issues for relative locations (dynamic import) - srcFolder: ((document.currentScript && document.currentScript.src) || (import.meta && import.meta.url)).split("/").slice(0,-1).join("/") + '/', + srcFolder: ((document.currentScript && document.currentScript.src) || (import.meta && import.meta.url) || document.baseURI).split("/").slice(0,-1).join("/") + '/', }; diff --git a/assets/static/vendor/leaflet-elevation/src/utils.js b/assets/static/vendor/leaflet-elevation/src/utils.js index 90035f7..261ced2 100644 --- a/assets/static/vendor/leaflet-elevation/src/utils.js +++ b/assets/static/vendor/leaflet-elevation/src/utils.js @@ -64,23 +64,23 @@ export function formatTime(t) { * Convert SVG Path into Path2D and then update canvas */ export function drawCanvas(ctx, path) { - path.classed('canvas-path', true); + path.classList.add('canvas-path'); ctx.beginPath(); ctx.moveTo(0, 0); - let p = new Path2D(path.attr('d')); + let p = new Path2D(path.getAttribute('d')); - ctx.strokeStyle = path.__strokeStyle || path.attr('stroke'); - ctx.fillStyle = path.__fillStyle || path.attr('fill'); + ctx.strokeStyle = path.__strokeStyle || path.getAttribute('stroke'); + ctx.fillStyle = path.__fillStyle || path.getAttribute('fill'); ctx.lineWidth = 1.25; ctx.globalCompositeOperation = 'source-over'; // stroke opacity - ctx.globalAlpha = path.attr('stroke-opacity') || 0.3; + ctx.globalAlpha = path.getAttribute('stroke-opacity') || 0.3; ctx.stroke(p); // fill opacity - ctx.globalAlpha = path.attr('fill-opacity') || 0.45; + ctx.globalAlpha = path.getAttribute('fill-opacity') || 0.45; ctx.fill(p); ctx.globalAlpha = 1; @@ -117,15 +117,22 @@ export const parseDate = (property, id) => new Date(Date.parse((typeof property /** * A little bit shorter than L.DomUtil */ -export const addClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.addClass(n, s)); -export const removeClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.removeClass(n, s)); +export const addClass = (n, str) => n && str.split(" ").every(s => s && n.classList.add(s)); +export const removeClass = (n, str) => n && str.split(" ").every(s => s && n.classList.remove(s)); export const toggleClass = (n, str, cond) => (cond ? addClass : removeClass)(n, str); export const replaceClass = (n, rem, add) => (rem && removeClass(n, rem)) || (add && addClass(n, add)); -export const style = (n, k, v) => (typeof v === "undefined" && L.DomUtil.getStyle(n, k)) || n.style.setProperty(k, v); +export const style = (n, k, v) => (typeof v === "undefined" && getComputedStyle(n)[k]) || n.style.setProperty(k, v); export const toggleStyle = (n, k, v, cond) => style(n, k, cond ? v : ''); -export const setAttributes = (n, attrs) => { for (let k in attrs) { n.setAttribute(k, attrs[k]); } }; +export const setAttributes = (n, attrs) => { for (let k in attrs) { if (attrs[k] != null) n.setAttribute(k, attrs[k]); else n.removeAttribute(k); } }; export const toggleEvent = (el, e, fn, cond) => el[cond ? 'on' : 'off'](e, fn); -export const create = (tag, str, attrs, n) => { let elem = L.DomUtil.create(tag, str || ""); if (attrs) setAttributes(elem, attrs); if (n) append(n, elem); return elem; }; +export const create = (tag, str, attrs, n) => { + const svg = tag.startsWith('svg:'); + const elem = svg ? document.createElementNS('http://www.w3.org/2000/svg', tag.slice(4)) : L.DomUtil.create(tag, str || ""); + if (svg && str) elem.setAttribute('class', str); + if (attrs) setAttributes(elem, attrs); + if (n) append(n, elem); + return elem; +} export const append = (n, c) => n.appendChild(c); export const insert = (n, c, pos) => n.insertAdjacentElement(pos, c); export const select = (str, n) => (n || document).querySelector(str); @@ -133,6 +140,18 @@ export const each = (obj, fn) => { for (let i in obj) fn(obj export const randomId = () => Math.random().toString(36).substr(2, 9); /** + * Convert pointer client coordinates to local SVG coordinates, accounting for transforms. + */ +export function pointer(event, element) { + const svg = element.ownerSVGElement || element; + const point = svg.createSVGPoint(); + point.x = event.clientX; + point.y = event.clientY; + const local = point.matrixTransform(element.getScreenCTM().inverse()); + return [local.x, local.y]; +} + +/** * TODO: use generators instead? (ie. "yield") */ export const iMax = (iVal, max = -Infinity) => (iVal > max ? iVal : max); @@ -145,7 +164,7 @@ export const iSum = (iVal, sum = 0) => iVal + sum; */ export const { on, off } = L.DomEvent; export const { throttle, wrapNum } = L.Util; -export const { hasClass } = L.DomUtil; +export const hasClass = (n, str) => n && str.split(" ").every(s => s && n.classList.contains(s)); /** * Limit floating point precision @@ -158,6 +177,19 @@ export const round = L.Util.formatNum; export const clamp = (val, range) => range ? (val < range[0] ? range[0] : val > range[1] ? range[1] : val) : val; /** + * Find the insertion index in data sorted by attr, before equal values (or after if right). + */ +export function bisect(data, value, attr, right = false) { + let low = 0, high = data.length; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (data[middle][attr] < value || (right && data[middle][attr] === value)) low = middle + 1; + else high = middle; + } + return low; +} + +/** * Limit a delta difference between two values */ export const wrapDelta = (curr, prev, deltaMax) => Math.abs(curr - prev) > deltaMax ? prev + deltaMax * Math.sign(curr - prev) : curr; |
