diff --git a/leafmap/maplibregl.py b/leafmap/maplibregl.py index dbb0981955..c1971b72db 100644 --- a/leafmap/maplibregl.py +++ b/leafmap/maplibregl.py @@ -110,9 +110,49 @@ def _panel_header_chevron(color: str) -> List[Dict[str, Any]]: ] +MAP_CSS_CLASS = "leafmap-maplibre" + + +def _map_widget_css() -> Any: + """Builds the map widget CSS with a readable popup text color. + + MapLibre popups have a white background but no text color, so in a dark + notebook theme the popup text inherits the light theme color and is + unreadable. The upstream widget CSS is kept and a dark text color is + appended for popups. The rule is scoped to leafmap maps because anywidget + loads the CSS for the whole page. + + Returns: + The CSS for the map widget, or the upstream CSS unchanged if it cannot + be read. + """ + # anywidget may wrap the upstream CSS file in a FileContents object, whose + # str() is the file contents. + original = getattr(MapWidget, "_css", None) + try: + if isinstance(original, os.PathLike) or ( + isinstance(original, str) and os.path.isfile(original) + ): + with open(original, encoding="utf-8") as f: + css = f.read() + else: + css = str(original) if original is not None else "" + except Exception: + css = "" + if not css.strip(): + # Never replace the upstream map CSS with only the popup rule. + return original + return ( + css + f"\n.{MAP_CSS_CLASS} .maplibregl-popup-content {{" + f" color: {SIDEBAR_PANEL_TEXT_COLOR}; }}\n" + ) + + class Map(MapWidget): """The Map class inherits from the MapWidget class of the maplibre.ipywidget module.""" + _css = _map_widget_css() + def __init__( self, center: Tuple[float, float] = (0, 20), @@ -254,6 +294,7 @@ def __init__( ) super().__init__(map_options, height=height) + self.add_class(MAP_CSS_CLASS) if use_message_queue is None: use_message_queue = os.environ.get( "USE_MESSAGE_QUEUE", ""