diff --git a/docs/user_guide/plugins.rst b/docs/user_guide/plugins.rst index 68447bc3bd..e788923e4f 100644 --- a/docs/user_guide/plugins.rst +++ b/docs/user_guide/plugins.rst @@ -36,6 +36,7 @@ Plugins plugins/side_by_side_layers plugins/tag_filter_button plugins/terminator + plugins/tile_layer_color_filter plugins/timeline plugins/timeslider_choropleth plugins/timestamped_geojson @@ -115,6 +116,8 @@ Plugins - Creates a Tag Filter Button to filter elements based on different criteria. * - :doc:`Terminator ` - Overlay day and night regions on a map. + * - :doc:`Tile Layer Color Filter ` + - Apply CSS color filters to the tiles of a map, for example for a dark or grayscale basemap. * - :doc:`Timeline ` - Create a timeline with a time slider for geojson data with start and end times. * - :doc:`Timeslider Choropleth ` diff --git a/docs/user_guide/plugins/tile_layer_color_filter.md b/docs/user_guide/plugins/tile_layer_color_filter.md new file mode 100644 index 0000000000..c6945383ab --- /dev/null +++ b/docs/user_guide/plugins/tile_layer_color_filter.md @@ -0,0 +1,48 @@ +```{code-cell} ipython3 +--- +nbsphinx: hidden +--- +import folium +import folium.plugins +``` + +## Tile Layer Color Filter + +Apply a [CSS filter](https://developer.mozilla.org/en-US/docs/Web/CSS/filter) to the tiles of a map, for example to turn a light basemap into a dark or grayscale background. This wraps the [Leaflet.TileLayer.ColorFilter](https://github.com/xtk93x/Leaflet.TileLayer.ColorFilter) plugin. + +Filters are written as `":"`. The supported filters are `blur` (px), `brightness` (%), `contrast` (%), `grayscale` (%), `hue-rotate` (deg), `invert` (%), `opacity` (%), `saturate` (%) and `sepia` (%). The unit can be left out; the ones above are added for you. + +### Dark basemap + +Inverting the tiles and rotating the hue turns the light OpenStreetMap tiles into a dark basemap: + +```{code-cell} ipython3 +m = folium.Map([52.1, 5.1], zoom_start=6, tiles=None) + +folium.plugins.TileLayerColorFilter( + ["invert:100%", "hue-rotate:180deg", "brightness:95%", "contrast:90%"], + name="dark", + control=False, +).add_to(m) + +m +``` + +### Grayscale background + +A grayscale basemap keeps the attention on the data drawn on top of it. The filter applies to the tiles only, not to markers or other layers: + +```{code-cell} ipython3 +m = folium.Map([52.1, 5.1], zoom_start=6, tiles=None) + +folium.plugins.TileLayerColorFilter( + "grayscale:100%", name="grayscale", control=False +).add_to(m) + +for lat, lon in [(52.37, 4.89), (51.92, 4.48), (52.09, 5.12)]: + folium.CircleMarker([lat, lon], radius=8, color="red", fill=True).add_to(m) + +m +``` + +Multiple filtered layers can be combined with a `LayerControl` to let the user switch between them. diff --git a/folium/plugins/__init__.py b/folium/plugins/__init__.py index f68b9b17a9..ea60a2f50e 100644 --- a/folium/plugins/__init__.py +++ b/folium/plugins/__init__.py @@ -32,6 +32,7 @@ from folium.plugins.side_by_side import SideBySideLayers from folium.plugins.tag_filter_button import TagFilterButton from folium.plugins.terminator import Terminator +from folium.plugins.tile_layer_color_filter import TileLayerColorFilter from folium.plugins.time_slider_choropleth import TimeSliderChoropleth from folium.plugins.timeline import Timeline, TimelineSlider from folium.plugins.timestamped_geo_json import TimestampedGeoJson @@ -80,6 +81,7 @@ "StripePattern", "TagFilterButton", "Terminator", + "TileLayerColorFilter", "TimeSliderChoropleth", "Timeline", "TimelineSlider", diff --git a/folium/plugins/tile_layer_color_filter.py b/folium/plugins/tile_layer_color_filter.py new file mode 100644 index 0000000000..876c3c124b --- /dev/null +++ b/folium/plugins/tile_layer_color_filter.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import re +from collections.abc import Sequence + +from folium.elements import JSCSSMixin +from folium.raster_layers import TileLayer + +# CSS filter functions supported by Leaflet.TileLayer.ColorFilter, with the unit +# the plugin appends to a bare number and the short names the plugin also +# accepts. +_FILTERS = { + "blur": ("px", ()), + "brightness": ("%", ("bright", "bri")), + "contrast": ("%", ("con",)), + "grayscale": ("%", ("gray",)), + "hue-rotate": ("deg", ("hue", "hue-rotation")), + "invert": ("%", ("inv",)), + "opacity": ("%", ("op",)), + "saturate": ("%", ("sat", "saturation")), + "sepia": ("%", ("sep",)), +} + +_ALIASES = {alias: name for name, (_, aliases) in _FILTERS.items() for alias in aliases} + +_VALUE = re.compile(r"(?P\d+)(?P%|deg|px)?") + + +def _normalize_color_filter(color_filter: str | Sequence[str]) -> list[str]: + """Validate color filter definitions and return them in canonical form. + + Each filter is written as ``":"``. The plugin silently + drops a filter it does not understand, which leaves the map looking as if + nothing was configured, so the definitions are checked here instead. + """ + if isinstance(color_filter, str): + color_filter = [color_filter] + filters = [] + for item in color_filter: + if not isinstance(item, str): + raise ValueError( + f"Filters must be strings like 'invert:100%', got {item!r}." + ) + name, _, value = item.partition(":") + name = _ALIASES.get(name.strip().lower(), name.strip().lower()) + value = value.strip().lower() + if name not in _FILTERS: + valid = ", ".join(sorted(_FILTERS)) + aliases = ", ".join(sorted(_ALIASES)) + raise ValueError( + f"Unknown color filter {name!r}. Valid filters are: {valid}. " + f"Short names: {aliases}." + ) + unit, _ = _FILTERS[name] + match = _VALUE.fullmatch(value) + if match is None: + raise ValueError( + f"Invalid value in filter {item!r}: expected a whole number, " + f"optionally followed by {unit!r}, for example " + f"'{name}:100{unit}'." + ) + if match["unit"] and match["unit"] != unit: + raise ValueError( + f"Wrong unit in filter {item!r}: {name!r} takes {unit!r}, " + f"not {match['unit']!r}." + ) + filters.append(f"{name}:{match['number']}{unit}") + return filters + + +class TileLayerColorFilter(JSCSSMixin, TileLayer): + """ + Add a tile layer and apply CSS color filters to its tiles. + + This wraps the `Leaflet.TileLayer.ColorFilter plugin + `_. A CSS filter + changes how the tiles are painted, so a single light basemap can serve as a + dark or grayscale background, which avoids a separate dark tile provider. + The filter is purely presentational: it applies to the tile images, not to + markers, vector layers or the controls on top of them. + + Parameters + ---------- + color_filter: str or list of str + One or more CSS filters, written as ``":"``, for + example ``"invert:100%"`` or ``["grayscale:100%", "contrast:110%"]``. + Supported filters are blur (px), brightness (%), contrast (%), + grayscale (%), hue-rotate (deg), invert (%), opacity (%), saturate (%) + and sepia (%), plus the plugin's short names such as ``"inv"`` or + ``"gray"``. The unit may be left out, it is added for you. + tiles: str or :class:`xyzservices.TileProvider`, default 'OpenStreetMap' + Map tileset to use. See :class:`folium.raster_layers.TileLayer`. + **kwargs + Other keyword arguments are passed to + :class:`folium.raster_layers.TileLayer`. + + Examples + -------- + A dark basemap from the default tiles: + + >>> m = folium.Map() + >>> folium.plugins.TileLayerColorFilter( + ... ["invert:100%", "hue-rotate:180deg", "brightness:95%", "contrast:90%"], + ... name="dark", + ... ).add_to(m) + + See https://github.com/xtk93x/Leaflet.TileLayer.ColorFilter for the plugin. + + """ + + default_js = [ + ( + "leaflet_tilelayer_colorfilter", + "https://cdn.jsdelivr.net/npm/leaflet.tilelayer.colorfilter@2.0.0/dist/leaflet-tilelayer-colorfilter-global.min.js", + ) + ] + + def __init__( + self, + color_filter: str | Sequence[str], + tiles: str = "OpenStreetMap", + **kwargs, + ): + super().__init__(tiles=tiles, **kwargs) + self._name = "TileLayerColorFilter" + self.color_filter = _normalize_color_filter(color_filter) + self.options["colorFilter"] = self.color_filter diff --git a/tests/plugins/test_tile_layer_color_filter.py b/tests/plugins/test_tile_layer_color_filter.py new file mode 100644 index 0000000000..7fc27e1e82 --- /dev/null +++ b/tests/plugins/test_tile_layer_color_filter.py @@ -0,0 +1,103 @@ +""" +Test TileLayerColorFilter +------------------------- +""" + +import json +import re + +import pytest + +import folium +from folium import plugins +from folium.raster_layers import TileLayer + +PLUGIN_SCRIPT = ( + '' +) + + +def layer_options(rendered: str, name: str) -> dict: + """Return the options dict folium rendered for a tile layer.""" + pattern = rf'var {name} = L\.tileLayer\(\s*"[^"]*",\s*(\{{.*?\}})\s*\);' + match = re.search(pattern, rendered, re.S) + assert match is not None, f"no L.tileLayer call found for {name}" + # the options are rendered as a JavaScript object, which allows trailing + # commas that json does not accept. + return json.loads(re.sub(r",(\s*[}\]])", r"\1", match.group(1))) + + +def test_tile_layer_color_filter(): + m = folium.Map([52.1, 5.1], zoom_start=5, tiles=None) + layer = plugins.TileLayerColorFilter( + ["invert:100%", "hue-rotate:180deg"], name="dark" + ).add_to(m) + + rendered = m.get_root().render() + + assert PLUGIN_SCRIPT in rendered + # the plugin patches L.TileLayer, so it has to load after Leaflet itself. + assert rendered.index("leaflet@1.9.4/dist/leaflet.js") < rendered.index( + "leaflet.tilelayer.colorfilter@2.0.0" + ) + assert layer_options(rendered, layer.get_name())["colorFilter"] == [ + "invert:100%", + "hue-rotate:180deg", + ] + + +def test_tile_layer_color_filter_keeps_tile_layer_arguments(): + m = folium.Map([52.1, 5.1], zoom_start=5, tiles=None) + layer = plugins.TileLayerColorFilter( + "grayscale:100%", + tiles="OpenStreetMap", + min_zoom=3, + max_zoom=12, + name="gray", + ).add_to(m) + + options = layer_options(m.get_root().render(), layer.get_name()) + assert options["minZoom"] == 3 + assert options["maxZoom"] == 12 + assert options["colorFilter"] == ["grayscale:100%"] + + +def test_tile_layer_color_filter_normalizes_filters(): + layer = plugins.TileLayerColorFilter(["inv:100", "gray:80", "hue:180deg"]) + assert layer.options["colorFilter"] == [ + "invert:100%", + "grayscale:80%", + "hue-rotate:180deg", + ] + + +def test_plain_tile_layer_gets_no_color_filter(): + m = folium.Map([52.1, 5.1], zoom_start=5, tiles=None) + layer = TileLayer().add_to(m) + + rendered = m.get_root().render() + + assert PLUGIN_SCRIPT not in rendered + assert "colorFilter" not in layer_options(rendered, layer.get_name()) + + +@pytest.mark.parametrize( + "filter,message", + [ + ("notafilter:1", "Unknown color filter"), + ("invert:abc", "Invalid value"), + ("invert:-10", "Invalid value"), + ("invert:10.5%", "Invalid value"), + ("invert:100deg", "Wrong unit"), + ("blur:10%", "Wrong unit"), + ], +) +def test_tile_layer_color_filter_invalid(filter, message): + with pytest.raises(ValueError, match=message): + plugins.TileLayerColorFilter(filter) + + +def test_tile_layer_color_filter_requires_strings(): + with pytest.raises(ValueError, match="Filters must be strings"): + plugins.TileLayerColorFilter([100]) # type: ignore[list-item]