2
2
3
3
import re
4
4
from dataclasses import dataclass
5
- from fnmatch import translate as fnmatch_translate
6
5
from pathlib import Path
7
6
from typing import Any , Callable , Iterator , Sequence
7
+ from urllib .parse import parse_qs
8
8
9
- from idom import component , create_context , use_context , use_state
9
+ from idom import component , create_context , use_context , use_memo , use_state
10
10
from idom .core .types import VdomAttributesAndChildren , VdomDict
11
11
from idom .core .vdom import coalesce_attributes_and_children
12
12
from idom .types import BackendImplementation , ComponentType , Context , Location
13
13
from idom .web .module import export , module_from_file
14
+ from starlette .routing import compile_path
14
15
15
16
try :
16
17
from typing import Protocol
17
- except ImportError :
18
- from typing_extensions import Protocol
18
+ except ImportError : # pragma: no cover
19
+ from typing_extensions import Protocol # type: ignore
19
20
20
21
21
- class Routes (Protocol ):
22
+ class RoutesConstructor (Protocol ):
22
23
def __call__ (self , * routes : Route ) -> ComponentType :
23
24
...
24
25
25
26
26
27
def configure (
27
28
implementation : BackendImplementation [Any ] | Callable [[], Location ]
28
- ) -> Routes :
29
+ ) -> RoutesConstructor :
29
30
if isinstance (implementation , BackendImplementation ):
30
31
use_location = implementation .use_location
31
32
elif callable (implementation ):
32
33
use_location = implementation
33
34
else :
34
35
raise TypeError (
35
- "Expected a BackendImplementation or "
36
- f"` use_location` hook, not { implementation } "
36
+ "Expected a ' BackendImplementation' or "
37
+ f"' use_location' hook, not { implementation } "
37
38
)
38
39
39
40
@component
40
- def Router (* routes : Route ) -> ComponentType | None :
41
+ def routes (* routes : Route ) -> ComponentType | None :
41
42
initial_location = use_location ()
42
43
location , set_location = use_state (initial_location )
43
- for p , r in _compile_routes (routes ):
44
- match = p .match (location .pathname )
44
+ compiled_routes = use_memo (
45
+ lambda : _iter_compile_routes (routes ), dependencies = routes
46
+ )
47
+ for r in compiled_routes :
48
+ match = r .pattern .match (location .pathname )
45
49
if match :
46
50
return _LocationStateContext (
47
51
r .element ,
48
- value = _LocationState (location , set_location , match ),
49
- key = p .pattern ,
52
+ value = _LocationState (
53
+ location ,
54
+ set_location ,
55
+ {k : r .converters [k ](v ) for k , v in match .groupdict ().items ()},
56
+ ),
57
+ key = r .pattern .pattern ,
50
58
)
51
59
return None
52
60
53
- return Router
54
-
55
-
56
- def use_location () -> Location :
57
- return _use_location_state ().location
58
-
59
-
60
- def use_match () -> re .Match [str ]:
61
- return _use_location_state ().match
61
+ return routes
62
62
63
63
64
64
@dataclass
65
65
class Route :
66
- path : str | re . Pattern [ str ]
66
+ path : str
67
67
element : Any
68
+ routes : Sequence [Route ]
69
+
70
+ def __init__ (self , path : str , element : Any | None , * routes : Route ) -> None :
71
+ self .path = path
72
+ self .element = element
73
+ self .routes = routes
68
74
69
75
70
76
@component
71
- def Link (* attributes_or_children : VdomAttributesAndChildren , to : str ) -> VdomDict :
77
+ def link (* attributes_or_children : VdomAttributesAndChildren , to : str ) -> VdomDict :
72
78
attributes , children = coalesce_attributes_and_children (attributes_or_children )
73
79
set_location = _use_location_state ().set_location
74
80
attrs = {
@@ -79,15 +85,54 @@ def Link(*attributes_or_children: VdomAttributesAndChildren, to: str) -> VdomDic
79
85
return _Link (attrs , * children )
80
86
81
87
82
- def _compile_routes (routes : Sequence [Route ]) -> Iterator [tuple [re .Pattern [str ], Route ]]:
88
+ def use_location () -> Location :
89
+ """Get the current route location"""
90
+ return _use_location_state ().location
91
+
92
+
93
+ def use_params () -> dict [str , Any ]:
94
+ """Get parameters from the currently matching route pattern"""
95
+ return _use_location_state ().params
96
+
97
+
98
+ def use_query (
99
+ keep_blank_values : bool = False ,
100
+ strict_parsing : bool = False ,
101
+ errors : str = "replace" ,
102
+ max_num_fields : int | None = None ,
103
+ separator : str = "&" ,
104
+ ) -> dict [str , list [str ]]:
105
+ """See :func:`urllib.parse.parse_qs` for parameter info."""
106
+ return parse_qs (
107
+ use_location ().search [1 :],
108
+ keep_blank_values = keep_blank_values ,
109
+ strict_parsing = strict_parsing ,
110
+ errors = errors ,
111
+ max_num_fields = max_num_fields ,
112
+ separator = separator ,
113
+ )
114
+
115
+
116
+ def _iter_compile_routes (routes : Sequence [Route ]) -> Iterator [_CompiledRoute ]:
117
+ for path , element in _iter_routes (routes ):
118
+ pattern , _ , converters = compile_path (path )
119
+ yield _CompiledRoute (
120
+ pattern , {k : v .convert for k , v in converters .items ()}, element
121
+ )
122
+
123
+
124
+ def _iter_routes (routes : Sequence [Route ]) -> Iterator [tuple [str , Any ]]:
83
125
for r in routes :
84
- if isinstance (r .path , re .Pattern ):
85
- yield r .path , r
86
- continue
87
- if not r .path .startswith ("/" ):
88
- raise ValueError ("Path pattern must begin with '/'" )
89
- pattern = re .compile (fnmatch_translate (r .path ))
90
- yield pattern , r
126
+ for path , element in _iter_routes (r .routes ):
127
+ yield r .path + path , element
128
+ yield r .path , r .element
129
+
130
+
131
+ @dataclass
132
+ class _CompiledRoute :
133
+ pattern : re .Pattern [str ]
134
+ converters : dict [str , Callable [[Any ], Any ]]
135
+ element : Any
91
136
92
137
93
138
def _use_location_state () -> _LocationState :
@@ -100,7 +145,7 @@ def _use_location_state() -> _LocationState:
100
145
class _LocationState :
101
146
location : Location
102
147
set_location : Callable [[Location ], None ]
103
- match : re . Match [str ]
148
+ params : dict [str , Any ]
104
149
105
150
106
151
_LocationStateContext : Context [_LocationState | None ] = create_context (None )
0 commit comments