Skip to content

First pass / rough draft of HTMLMapmlViewerElement.matchMedia API, #1008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,22 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

MIT License

Copyright (c) 2023 Tom Golden <oss@tom.bio>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 changes: 28 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@maps4html/mapml",
"version": "0.14.1",
"version": "0.15.0",
"description": "Custom <mapml-viewer> element suite",
"keywords": [
"mapml-viewer",
Expand Down Expand Up @@ -56,6 +56,9 @@
"grunt-prettier": "^2.2.0",
"leaflet": "^1.9.4",
"leaflet.locatecontrol": "^0.81.1",
"mapml-extension": "git+https://github.com/Maps4HTML/mapml-extension",
"media-query-parser": "^3.0.2",
"media-query-solver": "^0.1.3",
"path": "^0.12.7",
"playwright": "^1.39.0",
"proj4": "^2.6.2",
Expand Down
14 changes: 10 additions & 4 deletions src/mapml-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import Proj from 'proj4leaflet/src/proj4leaflet.js';
import { Util } from './mapml/utils/Util.js';
import { DOMTokenList } from './mapml/utils/DOMTokenList.js';

import { matchMedia } from './mapml/elementSupport/viewers/matchMedia.js';
import { HTMLLayerElement } from './map-layer.js';
import { LayerDashElement } from './layer-.js';
import { HTMLMapCaptionElement } from './map-caption.js';
Expand Down Expand Up @@ -240,7 +240,8 @@ export class HTMLMapmlViewerElement extends HTMLElement {
}
})
.catch((e) => {
throw new Error('Projection not defined: ' + e);
console.log(e);
throw new Error('Error: ' + e);
});
}
_setLocale() {
Expand Down Expand Up @@ -411,7 +412,7 @@ export class HTMLMapmlViewerElement extends HTMLElement {
this._map.options.projection = newValue;
let layersReady = [];
this._map.announceMovement.disable();
for (let layer of this.querySelectorAll('map-layer')) {
for (let layer of this.querySelectorAll('map-layer,layer-')) {
layer.removeAttribute('disabled');
let reAttach = this.removeChild(layer);
this.appendChild(reAttach);
Expand Down Expand Up @@ -986,7 +987,6 @@ export class HTMLMapmlViewerElement extends HTMLElement {
}
});
}

locate(options) {
//options: https://leafletjs.com/reference.html#locate-options
if (this._geolocationButton) {
Expand Down Expand Up @@ -1468,6 +1468,12 @@ export class HTMLMapmlViewerElement extends HTMLElement {
return geojsonLayer;
}
}

// ensure that 'this' always refers the the map on which the function runs
HTMLMapmlViewerElement.prototype.matchMedia = function (...args) {
return matchMedia.apply(this, args);
};

window.customElements.define('mapml-viewer', HTMLMapmlViewerElement);
try {
window.customElements.define('web-map', HTMLWebMapElement, {
Expand Down
251 changes: 251 additions & 0 deletions src/mapml/elementSupport/viewers/matchMedia.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
import { parseMediaQueryList } from 'media-query-parser';
import { solveMediaQueryList } from 'media-query-solver';

export const matchMedia = function (query) {
// useful features for maps: prefers-color-scheme, prefers-lang, projection, zoom, extent
const parsedQuery = parseMediaQueryList(query);

// less obviously useful: aspect-ratio, orientation, (device) resolution, overflow-block, overflow-inline

const map = this;
const features = {
'prefers-lang': {
type: 'discrete',
get values() {
return [navigator.language.substring(0, 2)];
}
},
'map-projection': {
type: 'discrete',
get values() {
return [map.projection.toLowerCase()];
}
},
'map-zoom': {
type: 'range',
valueType: 'integer',
canBeNegative: false,
canBeZero: true,
get extraValues() {
return {
min: 0,
max: map.zoom
};
}
},
'map-top-left-easting': {
type: 'range',
valueType: 'integer',
canBeNegative: true,
canBeZero: true,
get values() {
return [Math.trunc(map.extent.topLeft.pcrs.horizontal)];
}
},
'map-top-left-northing': {
type: 'range',
valueType: 'integer',
canBeNegative: true,
canBeZero: true,
get values() {
return [Math.trunc(map.extent.topLeft.pcrs.vertical)];
}
},
'map-bottom-right-easting': {
type: 'range',
valueType: 'integer',
canBeNegative: true,
canBeZero: true,
get values() {
return [Math.trunc(map.extent.bottomRight.pcrs.horizontal)];
}
},
'map-bottom-right-northing': {
type: 'range',
valueType: 'integer',
canBeNegative: true,
canBeZero: true,
get values() {
return [Math.trunc(map.extent.bottomRight.pcrs.vertical)];
}
},
'prefers-color-scheme': {
type: 'discrete',
get values() {
return [
window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
];
}
},
'prefers-map-content': {
type: 'discrete',
get values() {
return M.options.contentPreference;
}
}
};

const solveUnknownFeature = (featureNode) => {
let feature = featureNode.feature;
let queryValue = featureNode.value.value;

if (feature === 'prefers-lang') {
return features['prefers-lang'].values.includes(queryValue).toString();
} else if (
feature === 'map-zoom' ||
feature === 'map-top-left-easting' ||
feature === 'map-top-left-northing' ||
feature === 'map-bottom-right-easting' ||
feature === 'map-bottom-right-northing'
) {
return solveRangeFeature(featureNode);
} else if (feature === 'map-projection') {
return features['map-projection'].values
.some((p) => p === queryValue)
.toString();
} else if (feature === 'prefers-color-scheme') {
return features['prefers-color-scheme'].values
.some((s) => s === queryValue)
.toString();
} else if (feature === 'prefers-map-content') {
return features[feature].values
.some((pref) => pref === queryValue)
.toString();
}
return 'false';
};
let matches =
solveMediaQueryList(parsedQuery, {
features,
solveUnknownFeature
}) === 'true'
? true
: false;

function solveRangeFeature(featureNode) {
const { context, feature, value, op } = featureNode;

if (!feature.startsWith('map-')) {
return 'unknown';
}

const currentValue = getMapFeatureValue(feature);

if (currentValue === undefined) {
return 'unknown';
}

if (context === 'value') {
// Plain case: <mf-name>: <mf-value>
// Example: (map-zoom: 15)
return currentValue === value.value ? 'true' : 'false';
}

if (context === 'range') {
// Range case: <mf-name> <mf-comparison> <mf-value>
// Example: (0 <= map-zoom < 15)
switch (op) {
case '<':
return currentValue < value.value ? 'true' : 'false';
case '<=':
return currentValue <= value.value ? 'true' : 'false';
case '>':
return currentValue > value.value ? 'true' : 'false';
case '>=':
return currentValue >= value.value ? 'true' : 'false';
case '=':
return currentValue === value.value ? 'true' : 'false';
default:
return 'unknown';
}
}

return 'unknown'; // If the context is neither "value" nor "range"
}

function getMapFeatureValue(feature) {
switch (feature) {
case 'map-zoom':
return map.zoom;
case 'map-top-left-easting':
return Math.trunc(map.extent.topLeft.pcrs.horizontal);
case 'map-top-left-northing':
return Math.trunc(map.extent.topLeft.pcrs.vertical);
case 'map-bottom-right-easting':
return Math.trunc(map.extent.bottomRight.pcrs.horizontal);
case 'map-bottom-right-northing':
return Math.trunc(map.extent.bottomRight.pcrs.vertical);
default:
return undefined; // Unsupported or unknown feature
}
}

// Make mediaQueryList an EventTarget for dispatching events
const mediaQueryList = Object.assign(new EventTarget(), {
matches,
media: query,
listeners: [],
// this is a client facing api
addEventListener(event, listener) {
if (event === 'change') {
this.listeners.push(listener);

// Start observing properties only if there is at least one listener
if (this.listeners.length !== 0) {
observeProperties();
}
EventTarget.prototype.addEventListener.call(this, event, listener);
}
},

// this is a client facing api
removeEventListener(event, listener) {
if (event === 'change') {
this.listeners = this.listeners.filter((l) => l !== listener);

// Stop observing if there are no more listeners
if (this.listeners.length === 0) {
stopObserving();
}
EventTarget.prototype.removeEventListener.call(this, event, listener);
}
}
});

const observeProperties = () => {
const notifyIfChanged = () => {
const newMatches =
solveMediaQueryList(parsedQuery, {
features,
solveUnknownFeature
}) === 'true'
? true
: false;
if (newMatches !== mediaQueryList.matches) {
mediaQueryList.matches = newMatches;

// Dispatch a "change" event to notify listeners of the update
mediaQueryList.dispatchEvent(new Event('change'));
}
};
notifyIfChanged.bind(this);
// Subscribe to internal events for changes in projection, zoom, and extent
this.addEventListener('map-projectionchange', notifyIfChanged);
this.addEventListener('map-moveend', notifyIfChanged);
const colorSchemeQuery = window.matchMedia('(prefers-color-scheme: dark)');
colorSchemeQuery.addEventListener('change', notifyIfChanged);

// Stop observing function
stopObserving = () => {
this.removeEventListener('map-projectionchange', notifyIfChanged);
this.removeEventListener('map-moveend', notifyIfChanged);
colorSchemeQuery.removeEventListener('change', notifyIfChanged);
};
};

let stopObserving; // Declare here so it can be assigned within observeProperties

return mediaQueryList;
};
Loading
Loading