|
4 | 4 | """ |
5 | 5 |
|
6 | 6 | import warnings |
7 | | -from collections import OrderedDict |
8 | | -from typing import TYPE_CHECKING, Optional, Sequence, Union, cast |
| 7 | +from collections import OrderedDict, defaultdict |
| 8 | +from typing import TYPE_CHECKING, DefaultDict, Optional, Sequence, Union, cast |
9 | 9 |
|
10 | 10 | from branca.element import Element, Figure, Html, MacroElement |
11 | 11 |
|
12 | | -from folium.elements import ElementAddToElement, EventHandler |
| 12 | +from folium.elements import ElementAddToElement, EventHandler, IncludeStatement |
13 | 13 | from folium.template import Template |
14 | 14 | from folium.utilities import ( |
15 | 15 | JsCode, |
|
22 | 22 | validate_location, |
23 | 23 | ) |
24 | 24 |
|
| 25 | + |
| 26 | +class classproperty: |
| 27 | + def __init__(self, f): |
| 28 | + self.f = f |
| 29 | + |
| 30 | + def __get__(self, obj, owner): |
| 31 | + return self.f(owner) |
| 32 | + |
| 33 | + |
25 | 34 | if TYPE_CHECKING: |
26 | 35 | from folium.features import CustomIcon, DivIcon |
27 | 36 |
|
28 | 37 |
|
29 | | -class Evented(MacroElement): |
| 38 | +class Class(MacroElement): |
| 39 | + """The root class of the leaflet class hierarchy""" |
| 40 | + |
| 41 | + _includes: DefaultDict[str, dict] = defaultdict(dict) |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def include(cls, **kwargs): |
| 45 | + cls._includes[cls].update(**kwargs) |
| 46 | + |
| 47 | + @classproperty |
| 48 | + def includes(cls): |
| 49 | + return cls._includes[cls] |
| 50 | + |
| 51 | + @property |
| 52 | + def leaflet_class_name(self): |
| 53 | + # TODO: I did not check all Folium classes to see if |
| 54 | + # this holds up. This breaks at least for CustomIcon. |
| 55 | + return f"L.{self._name}" |
| 56 | + |
| 57 | + def render(self, **kwargs): |
| 58 | + figure = self.get_root() |
| 59 | + assert isinstance( |
| 60 | + figure, Figure |
| 61 | + ), "You cannot render this Element if it is not in a Figure." |
| 62 | + if self.includes: |
| 63 | + stmt = IncludeStatement(self.leaflet_class_name, **self.includes) |
| 64 | + # A bit weird. I tried adding IncludeStatement directly to both |
| 65 | + # figure and script, but failed. So we render this ourself. |
| 66 | + figure.script.add_child( |
| 67 | + Element(stmt._template.render(this=stmt, kwargs=self.includes)), |
| 68 | + # make sure each class include gets rendered only once |
| 69 | + name=self._name + "_includes", |
| 70 | + # make sure this renders before the element itself |
| 71 | + index=-1, |
| 72 | + ) |
| 73 | + super().render(**kwargs) |
| 74 | + |
| 75 | + |
| 76 | +class Evented(Class): |
30 | 77 | """The base class for Layer and Map |
31 | 78 |
|
32 | 79 | Adds the `on` and `once` methods for event handling capabilities. |
|
0 commit comments