shinymap 0.2.1__tar.gz → 0.3.0__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 (85) hide show
  1. {shinymap-0.2.1 → shinymap-0.3.0}/.gitignore +9 -0
  2. shinymap-0.3.0/PKG-INFO +152 -0
  3. shinymap-0.3.0/README.md +131 -0
  4. {shinymap-0.2.1 → shinymap-0.3.0}/pyproject.toml +5 -2
  5. shinymap-0.3.0/src/shinymap/__init__.py +60 -0
  6. shinymap-0.3.0/src/shinymap/_map.py +236 -0
  7. shinymap-0.3.0/src/shinymap/_stilllife.py +404 -0
  8. shinymap-0.3.0/src/shinymap/aes/__init__.py +56 -0
  9. shinymap-0.3.0/src/shinymap/aes/_core.py +981 -0
  10. shinymap-0.3.0/src/shinymap/aes/_defaults.py +43 -0
  11. shinymap-0.2.1/src/shinymap/aes.py → shinymap-0.3.0/src/shinymap/aes/_factory.py +30 -20
  12. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/__init__.py +2 -2
  13. shinymap-0.3.0/src/shinymap/aes/line/__init__.py +13 -0
  14. shinymap-0.2.1/src/shinymap/linestyle.py → shinymap-0.3.0/src/shinymap/aes/line/style.py +9 -8
  15. shinymap-0.3.0/src/shinymap/geometry/__init__.py +18 -0
  16. shinymap-0.3.0/src/shinymap/kit/__init__.py +44 -0
  17. shinymap-0.3.0/src/shinymap/kit/_caption.py +169 -0
  18. shinymap-0.3.0/src/shinymap/kit/_code_gen.py +238 -0
  19. shinymap-0.3.0/src/shinymap/kit/caption/__init__.py +1 -0
  20. shinymap-0.3.0/src/shinymap/kit/caption/__main__.py +120 -0
  21. shinymap-0.3.0/src/shinymap/kit/sketch/__init__.py +0 -0
  22. {shinymap-0.2.1/src/shinymap/geometry/converter → shinymap-0.3.0/src/shinymap/kit/sketch}/__main__.py +13 -15
  23. shinymap-0.3.0/src/shinymap/kit/sketch/_tab_finish.py +136 -0
  24. shinymap-0.3.0/src/shinymap/kit/sketch/_tab_infer.py +263 -0
  25. shinymap-0.3.0/src/shinymap/kit/sketch/_tab_original.py +213 -0
  26. shinymap-0.3.0/src/shinymap/kit/sketch/_tab_relabel.py +795 -0
  27. shinymap-0.3.0/src/shinymap/kit/sketch/app.py +206 -0
  28. {shinymap-0.2.1 → shinymap-0.3.0}/src/shinymap/mode.py +246 -41
  29. shinymap-0.3.0/src/shinymap/outline/__init__.py +107 -0
  30. shinymap-0.3.0/src/shinymap/outline/_core.py +55 -0
  31. {shinymap-0.2.1/src/shinymap/geometry → shinymap-0.3.0/src/shinymap/outline}/_export.py +32 -28
  32. shinymap-0.2.1/src/shinymap/geometry/_geometry.py → shinymap-0.3.0/src/shinymap/outline/_outline.py +549 -115
  33. {shinymap-0.2.1/src/shinymap/geometry → shinymap-0.3.0/src/shinymap/outline}/_regions.py +6 -4
  34. {shinymap-0.2.1/src/shinymap/geometry → shinymap-0.3.0/src/shinymap/outline}/_repr_config.py +21 -34
  35. shinymap-0.3.0/src/shinymap/outline/converter/__init__.py +11 -0
  36. shinymap-0.3.0/src/shinymap/payload/__init__.py +15 -0
  37. shinymap-0.3.0/src/shinymap/payload/_aes.py +127 -0
  38. {shinymap-0.2.1 → shinymap-0.3.0}/src/shinymap/relative.py +40 -57
  39. shinymap-0.3.0/src/shinymap/svg/__init__.py +45 -0
  40. {shinymap-0.2.1/src/shinymap/geometry → shinymap-0.3.0/src/shinymap/svg}/_elements.py +86 -11
  41. shinymap-0.2.1/src/shinymap/geometry/_element_mixins.py → shinymap-0.3.0/src/shinymap/svg/_mixins.py +11 -5
  42. shinymap-0.3.0/src/shinymap/types.py +115 -0
  43. shinymap-0.3.0/src/shinymap/ui/__init__.py +41 -0
  44. shinymap-0.3.0/src/shinymap/ui/_ui.py +210 -0
  45. shinymap-0.3.0/src/shinymap/uicore/__init__.py +21 -0
  46. shinymap-0.3.0/src/shinymap/uicore/_input_map.py +111 -0
  47. shinymap-0.3.0/src/shinymap/uicore/_output_map.py +128 -0
  48. shinymap-0.3.0/src/shinymap/uicore/_registry.py +12 -0
  49. shinymap-0.3.0/src/shinymap/uicore/_render_map.py +200 -0
  50. shinymap-0.3.0/src/shinymap/uicore/_update_map.py +101 -0
  51. shinymap-0.3.0/src/shinymap/uicore/_util.py +96 -0
  52. shinymap-0.3.0/src/shinymap/uicore/_wash.py +680 -0
  53. shinymap-0.3.0/src/shinymap/utils/__init__.py +12 -0
  54. shinymap-0.3.0/src/shinymap/utils/_dict.py +17 -0
  55. shinymap-0.2.1/src/shinymap/utils/__init__.py → shinymap-0.3.0/src/shinymap/utils/_linspace.py +11 -14
  56. shinymap-0.3.0/src/shinymap/utils/_svg.py +75 -0
  57. shinymap-0.3.0/src/shinymap/www/shinymap-shiny.js +1 -0
  58. {shinymap-0.2.1 → shinymap-0.3.0}/src/shinymap/www/shinymap.global.js +295 -176
  59. shinymap-0.2.1/PKG-INFO +0 -143
  60. shinymap-0.2.1/README.md +0 -122
  61. shinymap-0.2.1/src/shinymap/__init__.py +0 -73
  62. shinymap-0.2.1/src/shinymap/_aesthetics.py +0 -472
  63. shinymap-0.2.1/src/shinymap/_base.py +0 -520
  64. shinymap-0.2.1/src/shinymap/_sentinel.py +0 -42
  65. shinymap-0.2.1/src/shinymap/_theme.py +0 -64
  66. shinymap-0.2.1/src/shinymap/_ui.py +0 -575
  67. shinymap-0.2.1/src/shinymap/_validation.py +0 -160
  68. shinymap-0.2.1/src/shinymap/_wash.py +0 -509
  69. shinymap-0.2.1/src/shinymap/geometry/__init__.py +0 -139
  70. shinymap-0.2.1/src/shinymap/geometry/_bounds.py +0 -374
  71. shinymap-0.2.1/src/shinymap/geometry/_conversion.py +0 -336
  72. shinymap-0.2.1/src/shinymap/geometry/_core.py +0 -96
  73. shinymap-0.2.1/src/shinymap/geometry/_loader.py +0 -156
  74. shinymap-0.2.1/src/shinymap/geometry/converter/README.md +0 -104
  75. shinymap-0.2.1/src/shinymap/geometry/converter/__init__.py +0 -28
  76. shinymap-0.2.1/src/shinymap/geometry/converter/_app.py +0 -568
  77. shinymap-0.2.1/src/shinymap/geometry/converter/_tool.py +0 -71
  78. shinymap-0.2.1/src/shinymap/www/shinymap-shiny.js +0 -369
  79. {shinymap-0.2.1 → shinymap-0.3.0}/examples/data/scripts/README.md +0 -0
  80. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/binary.py +0 -0
  81. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/cycle.py +0 -0
  82. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/neutral.py +0 -0
  83. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/qualitative.py +0 -0
  84. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/scale.py +0 -0
  85. {shinymap-0.2.1/src/shinymap → shinymap-0.3.0/src/shinymap/aes}/color/sequential.py +0 -0
@@ -23,3 +23,12 @@ r/shinyjpmap/.Rproj.user/
23
23
 
24
24
  # temporary
25
25
  archive
26
+
27
+ # Documentation build artifacts
28
+ docs/_site/
29
+ docs/.quarto/
30
+ docs/python/
31
+ docs/typescript/
32
+
33
+ # Playwright MCP session artifacts
34
+ .playwright-mcp/
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: shinymap
3
+ Version: 0.3.0
4
+ Summary: Interactive SVG map components for Shiny for Python
5
+ Project-URL: Homepage, https://github.com/kenjisato/shinymap
6
+ Author: shinymap contributors
7
+ License: MIT
8
+ Keywords: interactive,maps,shiny,svg,visualization
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Scientific/Engineering :: Visualization
15
+ Requires-Python: >=3.12
16
+ Requires-Dist: shiny>=1.4.0
17
+ Requires-Dist: svg-py<2.0.0,>=1.9.0
18
+ Provides-Extra: demo
19
+ Requires-Dist: shiny-querynav>=0.1.0; extra == 'demo'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # shinymap (Python)
23
+
24
+ Shiny for Python adapter for the core `shinymap` renderer. It bundles the prebuilt JS assets and exposes helpers to drop maps into Shiny apps without touching React.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install shinymap
30
+ ```
31
+
32
+ Or with uv:
33
+
34
+ ```bash
35
+ uv add shinymap
36
+ ```
37
+
38
+ ## API
39
+
40
+ ```python
41
+ from shinymap import Map, input_map, output_map, render_map, aes
42
+ from shinymap.aes.color import scale_sequential, scale_qualitative
43
+ from shinymap.mode import Single, Multiple, Cycle, Count, Display
44
+ from shinymap.outline import Outline
45
+ ```
46
+
47
+ ### Map Components
48
+
49
+ - `input_map(id, outline, mode, ...)` renders an interactive input.
50
+ - Mode classes:
51
+ - `Single()` or `mode="single"`: returns `str | None`
52
+ - `Multiple()` or `mode="multiple"`: returns `list[str]`
53
+ - `Cycle(n=4)`: cycles through n states, returns `dict[str, int]`
54
+ - `Count()`: counting mode, returns `dict[str, int]` (`Count(max_count=10)` caps the indexed aesthetic, not the value)
55
+ - Aesthetics via `aes` parameter:
56
+ - `aes.ByState(base=..., hover=..., select=...)`: state-based styling
57
+ - `aes.ByGroup(__all=..., region_id=...)`: per-region styling
58
+ - `aes.Indexed(fill_color=[...])`: indexed colors for cycle/count modes
59
+ - `raw=True` returns the `dict[str, int]` value in every mode
60
+ - Works inside Shiny modules (ids are resolved through the module namespace)
61
+ - `output_map("map", outline, ...)` adds a placeholder with static parameters.
62
+ - `mode=Display()`: hover-only output map
63
+ - `mode=Display(clickable=True)`: output map with click events (`input_id=` to choose the input name)
64
+ - `Map` provides a fluent API for building map payloads with method chaining.
65
+ - `render_map` decorator serializes a `Map` and mounts the React output map.
66
+ - `scale_sequential()` and `scale_qualitative()` (in `shinymap.aes.color`) generate fill color maps.
67
+
68
+ ### Outline Utilities
69
+
70
+ The `shinymap.outline` subpackage provides tools for working with SVG outlines:
71
+
72
+ - **`Outline.from_svg(svg_path)`**: Extract geometry from SVG files (polymorphic elements)
73
+ - **`Outline.from_json(json_path)`**: Load geometry from shinymap JSON files
74
+ - **`outline.relabel({...})`**: Rename or merge regions
75
+ - **`outline.set_overlays([...])`**: Mark overlay regions
76
+ - **`outline.move_layer("overlay", "a", "b")`**: Assign regions to `underlay` / `overlay` / `hidden` (or back to `main`)
77
+ - **`outline.move_group("group", "a", "b")`**: Merge regions into a group
78
+ - **`outline.path_as_line("_dividers")`**: Mark regions as lines for stroke-only rendering
79
+ - **`outline.to_json(path)`**: Export to JSON file
80
+
81
+ **SVG element classes** (`Circle`, `Rect`, `Ellipse`, `Path`, `Polygon`, `Line`, `Text`) live in `shinymap.svg`.
82
+
83
+ ### Preparing SVG files (`shinymap.kit`)
84
+
85
+ ```bash
86
+ # Interactive app: rename regions, set groups and layers, mark lines,
87
+ # then download the JSON and the Python code that reproduces it
88
+ uv run python -m shinymap.kit.sketch -f map.svg
89
+
90
+ # Reference SVG with region IDs overlaid
91
+ uv run python -m shinymap.kit.caption map.svg
92
+ ```
93
+
94
+ ## Minimal example
95
+
96
+ ```python
97
+ from shiny import App, ui
98
+ from shinymap import Map, input_map, output_map, render_map, aes
99
+ from shinymap.mode import Count
100
+ from shinymap.outline import Outline
101
+
102
+ DEMO_OUTLINE = Outline.from_dict({
103
+ "circle": [{"type": "circle", "cx": 25, "cy": 50, "r": 20}],
104
+ "square": [{"type": "rect", "x": 10, "y": 10, "width": 30, "height": 30}],
105
+ "triangle": [{"type": "path", "d": "M75 70 L90 40 L60 40 Z"}],
106
+ "_metadata": {"viewBox": "0 0 100 100"},
107
+ })
108
+
109
+ TOOLTIPS = {"circle": "Circle", "square": "Square", "triangle": "Triangle"}
110
+
111
+
112
+ app_ui = ui.page_fluid(
113
+ ui.h2("shinymap demo"),
114
+ ui.layout_columns(
115
+ input_map(
116
+ "region",
117
+ DEMO_OUTLINE,
118
+ tooltips=TOOLTIPS,
119
+ mode="single", # Returns str | None
120
+ ),
121
+ output_map("summary", DEMO_OUTLINE, tooltips=TOOLTIPS),
122
+ ),
123
+ ui.br(),
124
+ ui.h4("Counts"),
125
+ ui.layout_columns(
126
+ input_map(
127
+ "clicks",
128
+ DEMO_OUTLINE,
129
+ tooltips=TOOLTIPS,
130
+ mode=Count(), # Returns dict[str, int]
131
+ ),
132
+ output_map("counts", DEMO_OUTLINE, tooltips=TOOLTIPS),
133
+ ),
134
+ )
135
+
136
+
137
+ def server(input, output, session):
138
+ @render_map
139
+ def summary():
140
+ selected = input.region()
141
+ # Value dict: selected region has value=1
142
+ value = {selected: 1} if selected else {}
143
+ return Map().with_value(value)
144
+
145
+ @render_map
146
+ def counts():
147
+ counts_data = input.clicks() or {}
148
+ return Map().with_value(counts_data)
149
+
150
+
151
+ app = App(app_ui, server)
152
+ ```
@@ -0,0 +1,131 @@
1
+ # shinymap (Python)
2
+
3
+ Shiny for Python adapter for the core `shinymap` renderer. It bundles the prebuilt JS assets and exposes helpers to drop maps into Shiny apps without touching React.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install shinymap
9
+ ```
10
+
11
+ Or with uv:
12
+
13
+ ```bash
14
+ uv add shinymap
15
+ ```
16
+
17
+ ## API
18
+
19
+ ```python
20
+ from shinymap import Map, input_map, output_map, render_map, aes
21
+ from shinymap.aes.color import scale_sequential, scale_qualitative
22
+ from shinymap.mode import Single, Multiple, Cycle, Count, Display
23
+ from shinymap.outline import Outline
24
+ ```
25
+
26
+ ### Map Components
27
+
28
+ - `input_map(id, outline, mode, ...)` renders an interactive input.
29
+ - Mode classes:
30
+ - `Single()` or `mode="single"`: returns `str | None`
31
+ - `Multiple()` or `mode="multiple"`: returns `list[str]`
32
+ - `Cycle(n=4)`: cycles through n states, returns `dict[str, int]`
33
+ - `Count()`: counting mode, returns `dict[str, int]` (`Count(max_count=10)` caps the indexed aesthetic, not the value)
34
+ - Aesthetics via `aes` parameter:
35
+ - `aes.ByState(base=..., hover=..., select=...)`: state-based styling
36
+ - `aes.ByGroup(__all=..., region_id=...)`: per-region styling
37
+ - `aes.Indexed(fill_color=[...])`: indexed colors for cycle/count modes
38
+ - `raw=True` returns the `dict[str, int]` value in every mode
39
+ - Works inside Shiny modules (ids are resolved through the module namespace)
40
+ - `output_map("map", outline, ...)` adds a placeholder with static parameters.
41
+ - `mode=Display()`: hover-only output map
42
+ - `mode=Display(clickable=True)`: output map with click events (`input_id=` to choose the input name)
43
+ - `Map` provides a fluent API for building map payloads with method chaining.
44
+ - `render_map` decorator serializes a `Map` and mounts the React output map.
45
+ - `scale_sequential()` and `scale_qualitative()` (in `shinymap.aes.color`) generate fill color maps.
46
+
47
+ ### Outline Utilities
48
+
49
+ The `shinymap.outline` subpackage provides tools for working with SVG outlines:
50
+
51
+ - **`Outline.from_svg(svg_path)`**: Extract geometry from SVG files (polymorphic elements)
52
+ - **`Outline.from_json(json_path)`**: Load geometry from shinymap JSON files
53
+ - **`outline.relabel({...})`**: Rename or merge regions
54
+ - **`outline.set_overlays([...])`**: Mark overlay regions
55
+ - **`outline.move_layer("overlay", "a", "b")`**: Assign regions to `underlay` / `overlay` / `hidden` (or back to `main`)
56
+ - **`outline.move_group("group", "a", "b")`**: Merge regions into a group
57
+ - **`outline.path_as_line("_dividers")`**: Mark regions as lines for stroke-only rendering
58
+ - **`outline.to_json(path)`**: Export to JSON file
59
+
60
+ **SVG element classes** (`Circle`, `Rect`, `Ellipse`, `Path`, `Polygon`, `Line`, `Text`) live in `shinymap.svg`.
61
+
62
+ ### Preparing SVG files (`shinymap.kit`)
63
+
64
+ ```bash
65
+ # Interactive app: rename regions, set groups and layers, mark lines,
66
+ # then download the JSON and the Python code that reproduces it
67
+ uv run python -m shinymap.kit.sketch -f map.svg
68
+
69
+ # Reference SVG with region IDs overlaid
70
+ uv run python -m shinymap.kit.caption map.svg
71
+ ```
72
+
73
+ ## Minimal example
74
+
75
+ ```python
76
+ from shiny import App, ui
77
+ from shinymap import Map, input_map, output_map, render_map, aes
78
+ from shinymap.mode import Count
79
+ from shinymap.outline import Outline
80
+
81
+ DEMO_OUTLINE = Outline.from_dict({
82
+ "circle": [{"type": "circle", "cx": 25, "cy": 50, "r": 20}],
83
+ "square": [{"type": "rect", "x": 10, "y": 10, "width": 30, "height": 30}],
84
+ "triangle": [{"type": "path", "d": "M75 70 L90 40 L60 40 Z"}],
85
+ "_metadata": {"viewBox": "0 0 100 100"},
86
+ })
87
+
88
+ TOOLTIPS = {"circle": "Circle", "square": "Square", "triangle": "Triangle"}
89
+
90
+
91
+ app_ui = ui.page_fluid(
92
+ ui.h2("shinymap demo"),
93
+ ui.layout_columns(
94
+ input_map(
95
+ "region",
96
+ DEMO_OUTLINE,
97
+ tooltips=TOOLTIPS,
98
+ mode="single", # Returns str | None
99
+ ),
100
+ output_map("summary", DEMO_OUTLINE, tooltips=TOOLTIPS),
101
+ ),
102
+ ui.br(),
103
+ ui.h4("Counts"),
104
+ ui.layout_columns(
105
+ input_map(
106
+ "clicks",
107
+ DEMO_OUTLINE,
108
+ tooltips=TOOLTIPS,
109
+ mode=Count(), # Returns dict[str, int]
110
+ ),
111
+ output_map("counts", DEMO_OUTLINE, tooltips=TOOLTIPS),
112
+ ),
113
+ )
114
+
115
+
116
+ def server(input, output, session):
117
+ @render_map
118
+ def summary():
119
+ selected = input.region()
120
+ # Value dict: selected region has value=1
121
+ value = {selected: 1} if selected else {}
122
+ return Map().with_value(value)
123
+
124
+ @render_map
125
+ def counts():
126
+ counts_data = input.clicks() or {}
127
+ return Map().with_value(counts_data)
128
+
129
+
130
+ app = App(app_ui, server)
131
+ ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "shinymap"
7
- version = "0.2.1"
7
+ version = "0.3.0"
8
8
  description = "Interactive SVG map components for Shiny for Python"
9
9
  readme = "README.md"
10
10
  authors = [{name = "shinymap contributors"}]
@@ -43,6 +43,7 @@ dev = [
43
43
  "mypy>=1.19.0",
44
44
  "pytest>=9.0.1",
45
45
  "pytest-asyncio>=1.3.0",
46
+ "pytest-playwright>=0.7.0",
46
47
  "ruff>=0.14.8",
47
48
  ]
48
49
 
@@ -73,8 +74,10 @@ python_functions = ["test_*"]
73
74
  addopts = "-v --strict-markers"
74
75
  markers = [
75
76
  "unit: Unit tests",
76
- "integration: Integration tests",
77
+ "integration: Integration tests (require Playwright)",
77
78
  ]
79
+ asyncio_mode = "auto"
80
+ asyncio_default_fixture_loop_scope = "function"
78
81
 
79
82
  [tool.mypy]
80
83
  python_version = "3.12"
@@ -0,0 +1,60 @@
1
+ """Core Shiny for Python bindings for the shinymap renderer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.3.0"
6
+
7
+ from . import aes, outline, svg, types, ui, utils
8
+ from ._map import Map
9
+ from ._stilllife import StillLife
10
+ from .outline import Outline
11
+ from .relative import (
12
+ PARENT,
13
+ AestheticConfig,
14
+ RegionState,
15
+ RelativeExpr,
16
+ preview_region,
17
+ resolve_region,
18
+ )
19
+
20
+ # Re-export from ui for convenience
21
+ from .ui import (
22
+ input_checkbox_group,
23
+ input_map,
24
+ input_radio_buttons,
25
+ output_map,
26
+ render_map,
27
+ update_map,
28
+ )
29
+ from .uicore import Wash
30
+
31
+ __all__ = [
32
+ "__version__",
33
+ "Outline",
34
+ "Map",
35
+ "StillLife",
36
+ "render_map",
37
+ "input_map",
38
+ "input_radio_buttons",
39
+ "input_checkbox_group",
40
+ "output_map",
41
+ "update_map",
42
+ # Wash factory (watercolor-inspired aesthetic configuration)
43
+ "Wash",
44
+ # Aesthetic module (aes.Shape(), aes.Line(), aes.color, aes.line, aes.default)
45
+ "aes",
46
+ # PARENT proxy and relative expressions
47
+ "PARENT",
48
+ "RelativeExpr",
49
+ # Aesthetic debugging utilities
50
+ "RegionState",
51
+ "AestheticConfig",
52
+ "resolve_region",
53
+ "preview_region",
54
+ # Subpackages
55
+ "outline", # Outline utilities
56
+ "svg", # SVG element classes (Circle, Path, etc.)
57
+ "types", # Type definitions (MapBuilder, etc.)
58
+ "ui", # UI components (input_map, output_map, etc.)
59
+ "utils", # Utility functions (linspace, path_bb, strip_unit)
60
+ ]
@@ -0,0 +1,236 @@
1
+ """Map data model for shinymap.
2
+
3
+ This module provides the core Map/MapBuilder classes for constructing
4
+ map payloads that can be rendered by UI components.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from .aes._core import BaseAesthetic, ByGroup, ByState
13
+ from .types import CountMap, TooltipMap
14
+ from .uicore._util import _normalize_outline, _strip_none, _validate_value
15
+
16
+ if TYPE_CHECKING:
17
+ from .outline import Outline
18
+
19
+ # Type alias for resolved aesthetics stored in MapBuilder
20
+ ResolvedAesType = ByGroup | None
21
+
22
+ # Type aliases
23
+ AesType = ByGroup | ByState | BaseAesthetic | Mapping[str, Mapping[str, Any] | None] | None
24
+
25
+
26
+ def _viewbox_to_str(view_box: tuple[float, float, float, float] | str | None) -> str | None:
27
+ """Convert viewBox tuple to string format, or pass through string."""
28
+ if view_box is None:
29
+ return None
30
+ if isinstance(view_box, str):
31
+ return view_box
32
+ return f"{view_box[0]} {view_box[1]} {view_box[2]} {view_box[3]}"
33
+
34
+
35
+ class MapBuilder:
36
+ """Fluent builder for constructing map payloads with method chaining.
37
+
38
+ Parameters can be provided here or via output_map(). When both are provided,
39
+ builder parameters take precedence.
40
+
41
+ Example (traditional):
42
+ @render_map
43
+ def my_map():
44
+ return (
45
+ Map(outline, tooltips=tooltips, view_box=viewbox)
46
+ .with_value(my_counts)
47
+ )
48
+
49
+ Example (with static params in output_map()):
50
+ # UI layer
51
+ output_map("my_map", outline, tooltips=TOOLTIPS, view_box=VIEWBOX)
52
+
53
+ # Server layer
54
+ @render_map
55
+ def my_map():
56
+ return Map().with_value(my_counts)
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ regions: Mapping[str, Any] | None = None,
62
+ *,
63
+ tooltips: TooltipMap = None,
64
+ view_box: tuple[float, float, float, float] | None = None,
65
+ _outline: Outline | None = None,
66
+ _resolved_aes: ResolvedAesType = None,
67
+ ):
68
+ """Internal constructor - use Map() function instead.
69
+
70
+ Args:
71
+ regions: Dict of main regions {regionId: [element1, ...]}
72
+ tooltips: Optional region tooltips
73
+ view_box: ViewBox as tuple (x, y, width, height)
74
+ _outline: (Private) Full Outline object for StillLife analysis
75
+ _resolved_aes: (Private) Pre-resolved ByGroup aesthetics from Wash
76
+ """
77
+ self._regions: Mapping[str, Any] | None = regions
78
+ self._tooltips = tooltips
79
+ self._value: CountMap = None
80
+ self._view_box = view_box
81
+ self._aes: AesType = None
82
+ self._layers: Mapping[str, list[str] | None] | None = None
83
+ # Private fields for StillLife static analysis
84
+ self._outline: Outline | None = _outline
85
+ self._resolved_aes: ResolvedAesType = _resolved_aes
86
+
87
+ def with_tooltips(self, tooltips: TooltipMap) -> MapBuilder:
88
+ """Set region tooltips."""
89
+ self._tooltips = tooltips
90
+ return self
91
+
92
+ def with_value(self, value: CountMap) -> MapBuilder:
93
+ """Set region values (counts, selection state).
94
+
95
+ Values determine both visual state and selection:
96
+ - value = 0: not selected (base aesthetic)
97
+ - value > 0: selected (select aesthetic applied)
98
+ """
99
+ self._value = value
100
+ return self
101
+
102
+ def with_view_box(self, view_box: tuple[float, float, float, float]) -> MapBuilder:
103
+ """Set the SVG viewBox as tuple (x, y, width, height)."""
104
+ self._view_box = view_box
105
+ return self
106
+
107
+ def with_aes(self, aes: AesType) -> MapBuilder:
108
+ """Set aesthetic configuration.
109
+
110
+ Args:
111
+ aes: Aesthetic config (ByGroup, ByState, or BaseAesthetic)
112
+ """
113
+ self._aes = aes
114
+ return self
115
+
116
+ def with_layers(self, layers: Mapping[str, list[str] | None]) -> MapBuilder:
117
+ """Set layer configuration.
118
+
119
+ Args:
120
+ layers: Nested dict with keys 'underlay', 'overlay', 'hidden'
121
+ """
122
+ self._layers = layers
123
+ return self
124
+
125
+ def with_outline_metadata(self, metadata: Mapping[str, Any]) -> MapBuilder:
126
+ """Set outline metadata (viewBox, groups)."""
127
+ self._outline_metadata = metadata
128
+ return self
129
+
130
+ def as_json(self) -> Mapping[str, Any]:
131
+ """Convert to JSON dict for JavaScript consumption.
132
+
133
+ Returns snake_case keys. JavaScript (shinymap-shiny.js) handles
134
+ conversion to camelCase.
135
+ """
136
+ data: dict[str, Any] = {}
137
+
138
+ if self._regions is not None:
139
+ data["regions"] = _normalize_outline(self._regions)
140
+ if self._tooltips is not None:
141
+ data["tooltips"] = self._tooltips
142
+ if self._value is not None:
143
+ data["value"] = self._value
144
+ if self._view_box is not None:
145
+ data["view_box"] = _viewbox_to_str(self._view_box)
146
+ if self._aes is not None:
147
+ # Use to_js_dict() for aes objects, pass through dicts
148
+ if hasattr(self._aes, "to_js_dict"):
149
+ data["aes"] = self._aes.to_js_dict()
150
+ elif hasattr(self._aes, "to_dict"):
151
+ data["aes"] = self._aes.to_dict()
152
+ else:
153
+ data["aes"] = self._aes
154
+ if self._layers is not None:
155
+ data["layers"] = self._layers
156
+ if hasattr(self, "_outline_metadata") and self._outline_metadata is not None:
157
+ data["outline_metadata"] = self._outline_metadata
158
+
159
+ return _strip_none(data)
160
+
161
+
162
+ def Map(
163
+ outline: Outline | None = None,
164
+ *,
165
+ view_box: tuple[float, float, float, float] | None = None,
166
+ tooltips: dict[str, str] | None = None,
167
+ value: dict[str, int] | None = None,
168
+ aes: AesType = None,
169
+ layers: Mapping[str, list[str] | None] | None = None,
170
+ ) -> MapBuilder:
171
+ """Create map from Outline object.
172
+
173
+ When used with output_map() that provides static outline, you can call Map()
174
+ without arguments. Otherwise, provide an Outline object.
175
+
176
+ Args:
177
+ outline: Outline object with regions, viewBox, metadata.
178
+ Optional when used with output_map()
179
+ view_box: Override viewBox tuple (for zoom/pan).
180
+ If None, uses outline.viewbox()
181
+ tooltips: Region tooltips
182
+ value: Region values (counts, selection state).
183
+ Values determine both visual state and selection:
184
+ - value = 0: not selected (base aesthetic)
185
+ - value > 0: selected (select aesthetic applied)
186
+ aes: Aesthetic configuration (ByGroup, ByState, or BaseAesthetic).
187
+ ByState and single aesthetics apply to every region.
188
+ layers: Layer configuration (nested dict: underlay, overlay, hidden)
189
+
190
+ Examples:
191
+ ```pycon
192
+ # Standalone usage
193
+ geo = Outline.from_dict(data)
194
+ Map(geo, value={"a": 1, "b": 1, "c": 0})
195
+
196
+ # With output_map() providing static outline
197
+ output_map("my_map", OUTLINE, tooltips=TOOLTIPS)
198
+ @render_map
199
+ def my_map():
200
+ return Map().with_value(counts)
201
+ ```
202
+ Returns:
203
+ MapBuilder instance for method chaining
204
+ """
205
+ # Validate value (must be non-negative integers)
206
+ _validate_value(value, "value")
207
+
208
+ if outline is None:
209
+ # No outline provided - will be merged from output_map() static params
210
+ builder = MapBuilder(
211
+ None, # Will be filled by _apply_static_params
212
+ view_box=view_box,
213
+ tooltips=tooltips,
214
+ )
215
+ else:
216
+ # Extract regions using Outline methods
217
+ main_regions = outline.main_regions()
218
+
219
+ # Create MapBuilder with extracted data
220
+ # Pass _outline for aes group expansion in _build_payload
221
+ builder = MapBuilder(
222
+ main_regions,
223
+ view_box=view_box or outline.viewbox(),
224
+ tooltips=tooltips,
225
+ _outline=outline,
226
+ )
227
+
228
+ # Apply optional parameters
229
+ if value is not None:
230
+ builder = builder.with_value(value)
231
+ if aes is not None:
232
+ builder = builder.with_aes(aes)
233
+ if layers is not None:
234
+ builder = builder.with_layers(layers)
235
+
236
+ return builder