goodmap 2.0.0a6__tar.gz → 2.0.0a8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/PKG-INFO +2 -3
  2. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/README.md +0 -1
  3. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/api/api_models.py +57 -5
  4. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/api/core_api.py +18 -7
  5. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/clustering.py +17 -8
  6. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/data_models/location.py +2 -4
  7. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/db.py +138 -8
  8. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/feature_flags.py +0 -5
  9. goodmap-2.0.0a8/goodmap/field_types.py +95 -0
  10. goodmap-2.0.0a8/goodmap/formatter.py +116 -0
  11. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/goodmap.py +60 -50
  12. goodmap-2.0.0a8/goodmap/initial_view.py +61 -0
  13. goodmap-2.0.0a8/goodmap/marker_styles.py +91 -0
  14. goodmap-2.0.0a8/goodmap/static/frontend/index.min.js +273 -0
  15. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/templates/goodmap-admin.html +0 -1
  16. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/templates/map.html +2 -1
  17. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/pyproject.toml +2 -2
  18. goodmap-2.0.0a6/goodmap/formatter.py +0 -59
  19. goodmap-2.0.0a6/goodmap/static/frontend/index.min.js +0 -273
  20. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/LICENSE.md +0 -0
  21. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/__init__.py +0 -0
  22. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/api/admin_api.py +0 -0
  23. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/config.py +0 -0
  24. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/core.py +0 -0
  25. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/exceptions.py +0 -0
  26. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/filtering.py +0 -0
  27. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/json_security.py +0 -0
  28. {goodmap-2.0.0a6 → goodmap-2.0.0a8}/goodmap/plugin.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: goodmap
3
- Version: 2.0.0a6
3
+ Version: 2.0.0a8
4
4
  Summary: Map engine to serve all the people :)
5
5
  Author: Krzysztof Kolodzinski
6
6
  Author-email: krzysztof.kolodzinski@problematy.pl
@@ -23,7 +23,7 @@ Requires-Dist: gunicorn (>=20.1,<26.0)
23
23
  Requires-Dist: humanize (>=4.6.0,<5.0.0)
24
24
  Requires-Dist: myst-parser (>=4.0.0,<5.0.0) ; extra == "docs"
25
25
  Requires-Dist: numpy (>=2.2.0,<3.0.0)
26
- Requires-Dist: platzky (==2.0.0a12)
26
+ Requires-Dist: platzky (==2.0.0a14)
27
27
  Requires-Dist: pydantic (>=2.12.0,<3.0.0)
28
28
  Requires-Dist: pysupercluster-problematy (>=0.7.8,<0.8.0)
29
29
  Requires-Dist: scipy (>=1.15.1,<2.0.0)
@@ -96,7 +96,6 @@ Afterwards run it with:
96
96
 
97
97
  | Option | Description |
98
98
  |--------------------------|------------------------------------------------------------------------------------------------------------------------------------|
99
- | USE_LAZY_LOADING | Loads point data only after the user clicks a point. If set to false, point data is loaded together with the initial map. |
100
99
  | FAKE_LOGIN | If set to true, allows access to the admin panel by simply selecting the role instead of logging in. **DO NOT USE IN PRODUCTION!** |
101
100
  | SHOW_ACCESSIBILITY_TABLE | If set as true it shows special view to help with accessing application. |
102
101
 
@@ -62,7 +62,6 @@ Afterwards run it with:
62
62
 
63
63
  | Option | Description |
64
64
  |--------------------------|------------------------------------------------------------------------------------------------------------------------------------|
65
- | USE_LAZY_LOADING | Loads point data only after the user clicks a point. If set to false, point data is loaded together with the initial map. |
66
65
  | FAKE_LOGIN | If set to true, allows access to the admin panel by simply selecting the role instead of logging in. **DO NOT USE IN PRODUCTION!** |
67
66
  | SHOW_ACCESSIBILITY_TABLE | If set as true it shows special view to help with accessing application. |
68
67
 
@@ -5,7 +5,7 @@ These models are used by Spectree for automatic OpenAPI schema generation
5
5
  and request/response validation.
6
6
  """
7
7
 
8
- from typing import Any, Literal
8
+ from typing import Any, Literal, NamedTuple
9
9
 
10
10
  from pydantic import BaseModel, Field, RootModel
11
11
 
@@ -68,18 +68,67 @@ class SuccessResponse(BaseModel):
68
68
  message: str = Field(..., description="Success message")
69
69
 
70
70
 
71
+ class PinMarkerFields(NamedTuple):
72
+ """Which of this deployment's fields drive pin icon/color, threaded through to
73
+ marker_style_values() by name, keeping the two roles distinct (a frozenset of
74
+ both would lose which is which)."""
75
+
76
+ icon_field: str | None = None
77
+ color_field: str | None = None
78
+
79
+
80
+ class MarkerInfo(BaseModel):
81
+ """Pin styling for one point: keys into the deployment's MARKER_STYLES lookup
82
+ tables, not resolved server-side to a URL/hex value."""
83
+
84
+ icon: str | int | float | bool | None = Field(
85
+ None, description="Raw icon_field value; key into MARKER_STYLES.icons"
86
+ )
87
+ color: str | int | float | bool | None = Field(
88
+ None, description="Raw color_field value; key into MARKER_STYLES.colors"
89
+ )
90
+ badge: bool | None = Field(
91
+ None, description="Present and true only when the point has a remark"
92
+ )
93
+
94
+
71
95
  class LocationBasicInfo(BaseModel):
72
- """One point as returned by the list endpoint: identity and position only."""
96
+ """One point as returned by the list endpoint: identity, position, and pin styling."""
73
97
 
74
98
  uuid: str = Field(..., description="Location UUID")
75
99
  position: tuple[Latitude, Longitude] = Field(..., description=_POSITION_DESCRIPTION)
76
- has_remark: bool = Field(
77
- ..., description="Whether the point has a remark, not the remark itself"
100
+ marker: MarkerInfo | None = Field(
101
+ None,
102
+ description="Pin styling for this point; absent when nothing applies "
103
+ "(no icon/color match and no remark)",
78
104
  )
79
105
 
80
106
 
81
107
  class LocationList(RootModel[list[LocationBasicInfo]]):
82
- """List of points, each with identity and position only."""
108
+ """List of points, each with identity, position, and pin styling."""
109
+
110
+
111
+ def marker_style_values(location: BaseModel, pin_marker_fields: PinMarkerFields) -> dict[str, Any]:
112
+ """Pin styling data for `location`, as /api/locations includes it for every point.
113
+
114
+ Returns {"marker": {...}} with icon/color (this location's value of the field
115
+ pin_marker_fields names, if it has one) and badge (present and true only when the
116
+ point has a remark), or {} when none of those apply. This is API response shaping,
117
+ not something the location domain model needs to know how to do itself - it
118
+ belongs alongside the models it fills, not on LocationBase.
119
+ """
120
+ marker: dict[str, Any] = {}
121
+ if pin_marker_fields.icon_field is not None:
122
+ value = getattr(location, pin_marker_fields.icon_field, None)
123
+ if value is not None:
124
+ marker["icon"] = value
125
+ if pin_marker_fields.color_field is not None:
126
+ value = getattr(location, pin_marker_fields.color_field, None)
127
+ if value is not None:
128
+ marker["color"] = value
129
+ if getattr(location, "remark", None):
130
+ marker["badge"] = True
131
+ return {"marker": marker} if marker else {}
83
132
 
84
133
 
85
134
  class ClusterInfo(BaseModel):
@@ -95,6 +144,9 @@ class ClusterInfo(BaseModel):
95
144
  cluster_count: int | None = Field(
96
145
  None, description="Number of points the cluster stands for; null for a point"
97
146
  )
147
+ marker: MarkerInfo | None = Field(
148
+ None, description="Pin styling for a point; null for a cluster or unstyled point"
149
+ )
98
150
 
99
151
 
100
152
  class ClusterList(RootModel[list[ClusterInfo]]):
@@ -29,8 +29,10 @@ from goodmap.api.api_models import (
29
29
  LocationReportRequest,
30
30
  LocationReportResponse,
31
31
  LocationSchemaResponse,
32
+ PinMarkerFields,
32
33
  SuccessResponse,
33
34
  VersionResponse,
35
+ marker_style_values,
34
36
  )
35
37
  from goodmap.clustering import (
36
38
  MAX_ZOOM,
@@ -118,20 +120,27 @@ def make_tuple_translation(keys_to_translate):
118
120
  return [(x, gettext(x)) for x in keys_to_translate]
119
121
 
120
122
 
121
- def get_locations_from_request(database, request_args):
123
+ def get_locations_from_request(database, request_args, pin_marker_fields):
122
124
  """
123
125
  Shared helper to fetch locations from database based on request arguments.
124
126
 
125
127
  Args:
126
128
  database: Database instance
127
129
  request_args: Request arguments (flask.request.args)
130
+ pin_marker_fields: This deployment's marker_styles icon_field/color_field
131
+ names - merged into each location's basic_info as a nested `marker`
132
+ object so the frontend can style pins without a further per-location
133
+ request.
128
134
 
129
135
  Returns:
130
- List of locations as basic_info dicts
136
+ List of locations as basic_info dicts, each merged with marker_style_values.
131
137
  """
132
138
  query_params = request_args.to_dict(flat=False)
133
139
  all_locations = database.get_locations(query_params)
134
- return [x.basic_info() for x in all_locations]
140
+ return [
141
+ {**location.basic_info(), **marker_style_values(location, pin_marker_fields)}
142
+ for location in all_locations
143
+ ]
135
144
 
136
145
 
137
146
  def photo_attachment_from_request(photo_attachment_config: AttachmentConfig):
@@ -195,6 +204,7 @@ def core_pages(
195
204
  photo_attachment_config: AttachmentConfig,
196
205
  feature_flags: FeatureFlagSet,
197
206
  shortcodes: dict[str, Shortcode],
207
+ pin_marker_fields: PinMarkerFields,
198
208
  ) -> Blueprint:
199
209
  core_api_blueprint = Blueprint("api", __name__, url_prefix="/api")
200
210
 
@@ -341,10 +351,11 @@ def core_pages(
341
351
  def get_locations():
342
352
  """Get list of locations with basic info.
343
353
 
344
- Returns locations filtered by query parameters,
345
- showing only uuid, position, and whether each has a remark.
354
+ Returns locations filtered by query parameters: uuid, position, and a
355
+ `marker` object (icon/color/badge) with everything needed to render a
356
+ styled pin.
346
357
  """
347
- locations = get_locations_from_request(database, request.args)
358
+ locations = get_locations_from_request(database, request.args, pin_marker_fields)
348
359
  return jsonify(locations)
349
360
 
350
361
  @core_api_blueprint.route("/locations-clustered", methods=["GET"])
@@ -363,7 +374,7 @@ def core_pages(
363
374
  query_params = request.args.to_dict(flat=False)
364
375
  zoom = int(query_params.get("zoom", [7])[0])
365
376
 
366
- points = get_locations_from_request(database, request.args)
377
+ points = get_locations_from_request(database, request.args, pin_marker_fields)
367
378
  if not points:
368
379
  return jsonify([])
369
380
 
@@ -25,11 +25,12 @@ def map_clustering_data_to_proper_lazy_loading_object(input_array):
25
25
 
26
26
  Args:
27
27
  input_array: List of cluster dicts with 'count', 'longitude', 'latitude',
28
- and 'uuid' keys.
28
+ 'uuid' and 'marker' keys.
29
29
 
30
30
  Returns:
31
31
  List of response dicts with 'position', 'uuid', 'cluster_uuid',
32
- 'cluster_count', and 'type' keys.
32
+ 'cluster_count' and 'type' keys, plus 'marker' for points that have
33
+ any pin styling.
33
34
  """
34
35
  response_array = []
35
36
  for item in input_array:
@@ -41,6 +42,10 @@ def map_clustering_data_to_proper_lazy_loading_object(input_array):
41
42
  "cluster_count": None,
42
43
  "type": "point",
43
44
  }
45
+ # Left out entirely rather than sent as null for an unstyled point, so a
46
+ # point here looks exactly like the same point from /api/locations.
47
+ if item.get("marker") is not None:
48
+ response_object["marker"] = item["marker"]
44
49
  response_array.append(response_object)
45
50
  continue
46
51
  response_object = {
@@ -61,17 +66,19 @@ def match_clusters_uuids(points, clusters):
61
66
  Match single-point clusters to their original point UUIDs.
62
67
 
63
68
  For clusters containing exactly one point, this function attempts to match the cluster
64
- coordinates back to the original point to retrieve its UUID. The 'uuid' key is optional
65
- and will only be present in single-point clusters where a matching point is found.
69
+ coordinates back to the original point to retrieve its UUID and marker styling. The
70
+ 'uuid'/'marker' keys are optional and will only be present in single-point clusters
71
+ where a matching point is found.
66
72
 
67
73
  Args:
68
- points: List of point dicts with 'position' and 'uuid' keys
74
+ points: List of point dicts with 'position', 'uuid' and 'marker' keys
69
75
  clusters: List of cluster dicts with 'longitude', 'latitude', and 'count' keys.
70
- For single-point clusters (count=1), a 'uuid' key will be added if a
71
- matching point is found (modified in place)
76
+ For single-point clusters (count=1), 'uuid' and 'marker' keys will be
77
+ added, from the matching point if found or None otherwise (modified
78
+ in place)
72
79
 
73
80
  Returns:
74
- The modified clusters list with 'uuid' keys added to matched single-point clusters
81
+ The modified clusters list with 'uuid'/'marker' keys added to single-point clusters
75
82
  """
76
83
  points_coords = [(point["position"][0], point["position"][1]) for point in points]
77
84
  tree = KDTree(points_coords)
@@ -82,6 +89,7 @@ def match_clusters_uuids(points, clusters):
82
89
  if dist < DISTANCE_THRESHOLD:
83
90
  closest_point = points[idx]
84
91
  cluster["uuid"] = closest_point["uuid"]
92
+ cluster["marker"] = closest_point.get("marker")
85
93
  else:
86
94
  # Log warning when no match is found - indicates data inconsistency
87
95
  logger.warning(
@@ -93,4 +101,5 @@ def match_clusters_uuids(points, clusters):
93
101
  DISTANCE_THRESHOLD,
94
102
  )
95
103
  cluster["uuid"] = None
104
+ cluster["marker"] = None
96
105
  return clusters
@@ -85,10 +85,8 @@ class LocationBase(BaseModel, extra="allow"):
85
85
  return super().model_dump(**kwargs)
86
86
 
87
87
  def basic_info(self) -> dict[str, Any]:
88
- """Get basic location information summary."""
89
- data = self.model_dump(include={"uuid", "position"})
90
- data["has_remark"] = bool(self.remark)
91
- return data
88
+ """Get basic location information summary: identity and position only."""
89
+ return self.model_dump(include={"uuid", "position"})
92
90
 
93
91
 
94
92
  _TYPE_MAPPING: dict[str, type] = {
@@ -562,19 +562,147 @@ def get_meta_data(db):
562
562
  return globals()[f"{db.module_name}_get_meta_data"]
563
563
 
564
564
 
565
+ # ------------------------------------------------
566
+ # get_marker_styles
567
+
568
+
569
+ def google_json_db_get_marker_styles(self) -> dict[str, Any]:
570
+ """
571
+ Retrieve marker icon/color styling configuration from Google Cloud Storage JSON blob.
572
+
573
+ Returns:
574
+ dict: Pin styling lookup table (icon_field, color_field, icons, colors).
575
+ Returns empty dict if not found.
576
+ """
577
+ return self.data.get("map", {}).get("marker_styles", {})
578
+
579
+
580
+ def json_file_db_get_marker_styles(self) -> dict[str, Any]:
581
+ """
582
+ Retrieve marker icon/color styling configuration from JSON file database.
583
+
584
+ Returns:
585
+ dict: Pin styling lookup table (icon_field, color_field, icons, colors).
586
+ Returns empty dict if not found.
587
+ """
588
+ return self.data.get("map", {}).get("marker_styles", {})
589
+
590
+
591
+ def json_db_get_marker_styles(self) -> dict[str, Any]:
592
+ """
593
+ Retrieve marker icon/color styling configuration from in-memory JSON database.
594
+
595
+ Returns:
596
+ dict: Pin styling lookup table (icon_field, color_field, icons, colors).
597
+ Returns empty dict if not found.
598
+ """
599
+ return self.data.get("marker_styles", {})
600
+
601
+
602
+ def mongodb_db_get_marker_styles(self) -> dict[str, Any]:
603
+ """
604
+ Retrieve marker icon/color styling configuration from MongoDB.
605
+
606
+ Returns:
607
+ dict: Pin styling lookup table (icon_field, color_field, icons, colors).
608
+ Returns empty dict if config document not found or field missing.
609
+ """
610
+ config_doc = self.db.config.find_one({"_id": "map_config"})
611
+ if config_doc:
612
+ return config_doc.get("marker_styles", {})
613
+ return {}
614
+
615
+
616
+ def get_marker_styles(db):
617
+ """
618
+ Get the appropriate get_marker_styles function for the given database backend.
619
+
620
+ Args:
621
+ db: Database instance (must have module_name attribute).
622
+
623
+ Returns:
624
+ callable: Backend-specific get_marker_styles function.
625
+ """
626
+ return globals()[f"{db.module_name}_get_marker_styles"]
627
+
628
+
629
+ # ------------------------------------------------
630
+ # get_initial_view
631
+
632
+
633
+ def google_json_db_get_initial_view(self) -> dict[str, Any]:
634
+ """
635
+ Retrieve the map's opening view from Google Cloud Storage JSON blob.
636
+
637
+ Returns:
638
+ dict: Raw ``initial_view`` config (center, zoom). Returns empty dict if
639
+ not found - declaring a view is optional.
640
+ """
641
+ return self.data.get("map", {}).get("initial_view", {})
642
+
643
+
644
+ def json_file_db_get_initial_view(self) -> dict[str, Any]:
645
+ """
646
+ Retrieve the map's opening view from JSON file database.
647
+
648
+ Returns:
649
+ dict: Raw ``initial_view`` config (center, zoom). Returns empty dict if
650
+ not found - declaring a view is optional.
651
+ """
652
+ return self.data.get("map", {}).get("initial_view", {})
653
+
654
+
655
+ def json_db_get_initial_view(self) -> dict[str, Any]:
656
+ """
657
+ Retrieve the map's opening view from in-memory JSON database.
658
+
659
+ Returns:
660
+ dict: Raw ``initial_view`` config (center, zoom). Returns empty dict if
661
+ not found - declaring a view is optional.
662
+ """
663
+ return self.data.get("initial_view", {})
664
+
665
+
666
+ def mongodb_db_get_initial_view(self) -> dict[str, Any]:
667
+ """
668
+ Retrieve the map's opening view from MongoDB.
669
+
670
+ Returns:
671
+ dict: Raw ``initial_view`` config (center, zoom). Returns empty dict if
672
+ the config document is missing or does not declare one.
673
+ """
674
+ config_doc = self.db.config.find_one({"_id": "map_config"})
675
+ if config_doc:
676
+ return config_doc.get("initial_view", {})
677
+ return {}
678
+
679
+
680
+ def get_initial_view(db):
681
+ """
682
+ Get the appropriate get_initial_view function for the given database backend.
683
+
684
+ Args:
685
+ db: Database instance (must have module_name attribute).
686
+
687
+ Returns:
688
+ callable: Backend-specific get_initial_view function.
689
+ """
690
+ return globals()[f"{db.module_name}_get_initial_view"]
691
+
692
+
565
693
  # ------------------------------------------------
566
694
  # get_categories
567
695
 
568
696
 
569
697
  def json_db_get_categories(self):
570
698
  """Return category keys from in-memory JSON database."""
571
- return self.data["categories"].keys()
699
+ return self.data.get("categories", {}).keys()
572
700
 
573
701
 
574
702
  def json_file_db_get_categories(self):
575
703
  """Return category keys from JSON file database."""
576
704
  with open(self.data_file_path, "r") as file:
577
- return json.load(file)["map"]["categories"].keys()
705
+ return json.load(file)["map"].get("categories", {}).keys()
578
706
 
579
707
 
580
708
  def google_json_db_get_categories(self):
@@ -603,7 +731,7 @@ def json_db_get_category_data(self, category_type=None):
603
731
  """Return category data from in-memory JSON database, optionally filtered by type."""
604
732
  if category_type:
605
733
  return {
606
- "categories": {category_type: self.data["categories"].get(category_type, [])},
734
+ "categories": {category_type: self.data.get("categories", {}).get(category_type, [])},
607
735
  "categories_help": self.data.get("categories_help", []),
608
736
  "categories_options_help": {
609
737
  category_type: self.data.get("categories_options_help", {}).get(category_type, [])
@@ -618,7 +746,7 @@ def json_db_get_category_data(self, category_type=None):
618
746
  },
619
747
  }
620
748
  return {
621
- "categories": self.data["categories"],
749
+ "categories": self.data.get("categories", {}),
622
750
  "categories_help": self.data.get("categories_help", []),
623
751
  "categories_options_help": self.data.get("categories_options_help", {}),
624
752
  "categories_default_checked": self.data.get("categories_default_checked", {}),
@@ -632,7 +760,7 @@ def json_file_db_get_category_data(self, category_type=None):
632
760
  data = json.load(file)["map"]
633
761
  if category_type:
634
762
  return {
635
- "categories": {category_type: data["categories"].get(category_type, [])},
763
+ "categories": {category_type: data.get("categories", {}).get(category_type, [])},
636
764
  "categories_help": data.get("categories_help", []),
637
765
  "categories_options_help": {
638
766
  category_type: data.get("categories_options_help", {}).get(category_type, [])
@@ -645,7 +773,7 @@ def json_file_db_get_category_data(self, category_type=None):
645
773
  },
646
774
  }
647
775
  return {
648
- "categories": data["categories"],
776
+ "categories": data.get("categories", {}),
649
777
  "categories_help": data.get("categories_help", []),
650
778
  "categories_options_help": data.get("categories_options_help", {}),
651
779
  "categories_default_checked": data.get("categories_default_checked", {}),
@@ -781,7 +909,7 @@ def get_locations_list_from_raw_data(map_data, query, location_model):
781
909
  """Filter and validate locations from raw map data based on query parameters.
782
910
 
783
911
  Args:
784
- map_data: Dict containing 'data' and 'categories' keys.
912
+ map_data: Dict containing a 'data' key, and optionally 'categories'.
785
913
  query: Dict of query parameters for filtering.
786
914
  location_model: Pydantic model class to validate each location.
787
915
 
@@ -790,7 +918,7 @@ def get_locations_list_from_raw_data(map_data, query, location_model):
790
918
  """
791
919
  filtered_locations = get_queried_data(
792
920
  map_data["data"],
793
- map_data["categories"],
921
+ map_data.get("categories", {}),
794
922
  query,
795
923
  map_data.get("categories_filter_mode", {}),
796
924
  )
@@ -1777,6 +1905,8 @@ def extend_db_with_goodmap_queries(db, location_model):
1777
1905
  db.extend("get_data", get_data(db))
1778
1906
  db.extend("get_visible_data", get_visible_data(db))
1779
1907
  db.extend("get_meta_data", get_meta_data(db))
1908
+ db.extend("get_marker_styles", get_marker_styles(db))
1909
+ db.extend("get_initial_view", get_initial_view(db))
1780
1910
  db.extend("get_locations", get_locations(db, location_model))
1781
1911
  db.extend("get_locations_paginated", get_locations_paginated(db, location_model))
1782
1912
  db.extend("get_location", get_location(db, location_model))
@@ -5,15 +5,10 @@ disable the corresponding feature at runtime.
5
5
 
6
6
  Flags:
7
7
  CategoriesHelp: Display help text alongside map categories to guide users.
8
- UseLazyLoading: Defer loading of location fields until they are needed,
9
- improving initial page load performance.
10
8
  EnableAdminPanel: Expose the admin panel for managing map data.
11
9
  """
12
10
 
13
11
  from platzky import FeatureFlag
14
12
 
15
13
  CategoriesHelp = FeatureFlag(alias="CATEGORIES_HELP", description="Show category help text")
16
- UseLazyLoading = FeatureFlag(
17
- alias="USE_LAZY_LOADING", default=True, description="Enable lazy loading of location fields"
18
- )
19
14
  EnableAdminPanel = FeatureFlag(alias="ENABLE_ADMIN_PANEL", description="Enable admin panel")
@@ -0,0 +1,95 @@
1
+ """Goodmap's built-in marker field types.
2
+
3
+ A location entry names a field's ``type`` in the data - ``{"type": "hyperlink", "value": …}``
4
+ - and this module is the catalogue of the types goodmap ships. Each is an ordinary platzky
5
+ ``Shortcode``, the same thing a plugin contributes, so ``prepare_pin`` renders every field
6
+ through one interface and the popup gets ``html`` either way.
7
+
8
+ What differs is how a renderer is found. A plugin's shortcode is bound to a field by *name*,
9
+ which is what makes the field its own. Goodmap's own are looked up by the ``type`` the entry
10
+ declares, so any field can ask to be a ``hyperlink`` whatever it is called. That lookup is
11
+ safe only because this catalogue is closed: an entry may name a type in here and nothing
12
+ else, and so can never point itself at a plugin's renderer.
13
+ """
14
+
15
+ from urllib.parse import urlparse
16
+
17
+ from markupsafe import escape
18
+ from platzky.shortcodes import Shortcode, ShortcodeAttr, ShortcodeAttrs, UrlNotPermitted
19
+ from platzky.shortcodes.link import LinkShortcode
20
+
21
+ #: Schemes that navigate the browser somewhere, and so are worth a new tab.
22
+ _NEW_TAB_SCHEMES = frozenset({"http", "https"})
23
+
24
+
25
+ class HyperlinkFieldShortcode(LinkShortcode):
26
+ """A marker field holding a URL, rendered as a link.
27
+
28
+ Subclasses platzky's ``[link]`` rather than restating it, so a link in a post and a link
29
+ on a marker agree on what may be linked to - ``mailto:`` and ``tel:`` included, which is
30
+ how a place's contact details are routinely written - and produce the same anchor.
31
+
32
+ The field's own shape is declared rather than adapted to: ``value`` is where the link
33
+ goes, ``displayValue`` what it reads, and ``content_key`` makes the latter the inner
34
+ content so an absent one falls back to the URL, which ``render_value`` already does.
35
+ """
36
+
37
+ name = "hyperlink"
38
+ description = "A marker field holding a URL, shown as a link."
39
+ content_key = "displayValue"
40
+ attributes = ShortcodeAttrs(
41
+ [
42
+ ShortcodeAttr("value", "Where the link goes", required=True),
43
+ ShortcodeAttr("displayValue", "Text to show for it", required=False),
44
+ ]
45
+ )
46
+
47
+ def render(self, attrs: ShortcodeAttrs, content: str) -> str:
48
+ """Render the anchor, keeping the text when the URL is refused.
49
+
50
+ A refusal reaches ``render_value`` as a dropped element, which suits a link written
51
+ in prose but not a field: the label would be left sitting above a blank, the text is
52
+ usually the part a reader wanted, and a wrapper plugin attached to this type would
53
+ receive nothing to wrap. So it is caught here and the text kept, escaped and
54
+ unlinked.
55
+
56
+ Args:
57
+ attrs: The field's stored keys, ``value`` among them.
58
+ content: The link text, already escaped.
59
+
60
+ Returns:
61
+ An anchor, or just the link text when the URL is not one we may emit.
62
+ """
63
+ url = str(attrs.value or "")
64
+ # ``render_value`` falls back to ``value`` only when ``displayValue`` is absent; a
65
+ # present-but-empty one would otherwise render an anchor with nothing to click.
66
+ content = content or escape(url)
67
+ link_attrs = ShortcodeAttrs(list(LinkShortcode.attributes))
68
+ link_attrs.values = {"url": url}
69
+ # A new tab is for leaving the site; handing a mailto: or tel: to the mail client or
70
+ # dialer navigates nowhere, and asking for one anyway leaves a blank tab behind.
71
+ if urlparse(url).scheme in _NEW_TAB_SCHEMES:
72
+ link_attrs.values["target"] = "_blank"
73
+ try:
74
+ return super().render(link_attrs, content)
75
+ except UrlNotPermitted:
76
+ return str(content)
77
+
78
+
79
+ class CTAFieldShortcode(HyperlinkFieldShortcode):
80
+ """The same link, shown as a button below the details rather than among them.
81
+
82
+ ``hyperlink`` and ``CTA`` only ever differed in presentation - both are a URL and the
83
+ text to show for it - and where the popup puts one is ``LocationDetails``' business,
84
+ decided from the field name it already groups on. The ``type`` travels on the payload
85
+ either way, so a field plugin can still attach to just one of them.
86
+ """
87
+
88
+ name = "CTA"
89
+ description = "A marker field holding a URL, shown as a call-to-action button."
90
+
91
+
92
+ #: Field ``type`` -> the shortcode rendering it, keyed by the name written in the data.
93
+ BUILTIN_FIELD_TYPES: dict[str, Shortcode] = {
94
+ shortcode.name: shortcode for shortcode in (HyperlinkFieldShortcode(), CTAFieldShortcode())
95
+ }