Skip to content
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

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

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
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.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
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
294 changes: 294 additions & 0 deletions src/mapml-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import Proj from 'proj4leaflet/src/proj4leaflet.js';
import { Util } from './mapml/utils/Util.js';
import { DOMTokenList } from './mapml/utils/DOMTokenList.js';

import { parseMediaQueryList } from 'media-query-parser';
import { solveMediaQueryList } from 'media-query-solver';

import { HTMLLayerElement } from './map-layer.js';
import { LayerDashElement } from './layer-.js';
import { HTMLMapCaptionElement } from './map-caption.js';
Expand Down Expand Up @@ -986,7 +989,298 @@ export class HTMLMapmlViewerElement extends HTMLElement {
}
});
}
getTestQuery() {
// Retrieve the map extent
const extent = this.extent;

// Extract the PCRS values for the bounding box
const topLeftEasting = Math.trunc(extent.topLeft.pcrs.horizontal);
const topLeftNorthing = Math.trunc(extent.topLeft.pcrs.vertical);
const bottomRightEasting = Math.trunc(extent.bottomRight.pcrs.horizontal);
const bottomRightNorthing = Math.trunc(extent.bottomRight.pcrs.vertical);

// Format the media query string to detect overlap:
// (xminm < xmaxq) and (xmaxm > xminq) and (yminm < ymaxq) and (ymaxm > yminq)
const query = `(map-projection: OSMTILE) and (map-zoom < 14) and (map-top-left-easting < ${bottomRightEasting}) and (map-bottom-right-easting > ${topLeftEasting}) and (map-bottom-right-northing < ${topLeftNorthing}) and (map-top-left-northing > ${bottomRightNorthing})`;

console.log(query);
let matcher = this.matchMedia(query);
const logResults = (e) => {
if (e.target.matches) {
layer.checked = true;
layer.removeAttribute('hidden');
} else {
layer.checked = false;
layer.hidden = true;
}
console.log('The query matches the map extent: ' + e.target.matches);
};
matcher.addEventListener('change', logResults);

// create a layer to visually represent the query as the map moves
let f = `<map-layer checked label="test media query"><map-meta name="projection" content="OSMTILE"></map-meta>
<map-meta name="cs" content="pcrs"></map-meta><map-feature><map-properties>${query}</map-properties>
<map-geometry><map-polygon><map-coordinates>${topLeftEasting} ${topLeftNorthing}
${bottomRightEasting} ${topLeftNorthing} ${bottomRightEasting} ${bottomRightNorthing} ${topLeftEasting} ${bottomRightNorthing}
${topLeftEasting} ${topLeftNorthing}</map-coordinates</map-polygon></map-geometry></map-feature></map-layer>`;

const parser = new DOMParser();
const layer = parser
.parseFromString(f, 'text/html')
.querySelector('map-layer');
this.appendChild(layer);
return { matcher, logResults };
}
matchMedia(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;
}
locate(options) {
//options: https://leafletjs.com/reference.html#locate-options
if (this._geolocationButton) {
Expand Down