Skip to content

API Reference

Main Module

Bases: Generic[BuilderType]

RouteLit is a class that provides a framework for handling HTTP requests and generating responses in a web application. It manages the routing and view functions that define how the application responds to different requests.

The class maintains a registry of fragment functions and uses a builder pattern to construct responses. It supports both GET and POST requests, handling them differently based on the request method.

Key features: - Session storage management - Fragment registry for reusable view components - Support for both GET and POST request handling - Builder pattern for constructing responses - Support for dependency injection in view functions

The class is designed to be flexible, allowing for custom builder classes and session storage implementations.

Source code in src/routelit/routelit.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
class RouteLit(Generic[BuilderType]):
    """
    RouteLit is a class that provides a framework for handling HTTP requests and generating responses in a web application. It manages the routing and view functions that define how the application responds to different requests.

    The class maintains a registry of fragment functions and uses a builder pattern to construct responses. It supports both GET and POST requests, handling them differently based on the request method.

    Key features:
    - Session storage management
    - Fragment registry for reusable view components
    - Support for both GET and POST request handling
    - Builder pattern for constructing responses
    - Support for dependency injection in view functions

    The class is designed to be flexible, allowing for custom builder classes and session storage implementations.
    """

    def __init__(
        self,
        BuilderClass: Type[BuilderType] = RouteLitBuilder,  # type: ignore[assignment]
        session_storage: Optional[MutableMapping[str, Any]] = None,
        should_inject_builder: bool = True,
    ):
        self.BuilderClass = BuilderClass
        self.session_storage = session_storage or {}
        self.fragment_registry: Dict[str, Callable[[RouteLitBuilder], Any]] = {}
        self._session_builder_context: contextvars.ContextVar[RouteLitBuilder] = contextvars.ContextVar(
            "session_builder"
        )
        self.should_inject_builder = should_inject_builder

    @contextmanager
    def _set_builder_context(self, builder: BuilderType) -> Generator[BuilderType, None, None]:
        try:
            token = self._session_builder_context.set(builder)
            yield builder
        finally:
            self._session_builder_context.reset(token)

    @property
    def ui(self) -> BuilderType:
        """
        The current builder instance.
        Use this in conjunction with `response(..., should_inject_builder=False)`
        example:
        ```python
        rl = RouteLit()

        def my_view():
            rl.ui.text("Hello, world!")

        request = ...
        response = rl.response(my_view, request, should_inject_builder=False)
        ```
        """
        return cast(BuilderType, self._session_builder_context.get())

    def response(
        self,
        view_fn: ViewFn,
        request: RouteLitRequest,
        should_inject_builder: Optional[bool] = None,
        *args: Any,
        **kwargs: Any,
    ) -> Union[RouteLitResponse, Dict[str, Any]]:
        """Handle the request and return the response.

        Args:
            view_fn (ViewFn): (Callable[[RouteLitBuilder], Any]) The view function to handle the request.
            request (RouteLitRequest): The request object.
            **kwargs (Dict[str, Any]): Additional keyword arguments.

        Returns:
            RouteLitResponse | Dict[str, Any]:
                The response object.
                where Dict[str, Any] is a dictionary that contains the following keys:
                actions (List[Action]), target (Literal["app", "fragment"])

        Example:
        ```python
        from routelit import RouteLit, RouteLitBuilder

        rl = RouteLit()

        def my_view(rl: RouteLitBuilder):
            rl.text("Hello, world!")

        request = ...
        response = rl.response(my_view, request)

        # example with dependency
        def my_view(rl: RouteLitBuilder, name: str):
            rl.text(f"Hello, {name}!")

        request = ...
        response = rl.response(my_view, request, name="John")
        ```
        """
        if request.method == "GET":
            return self.handle_get_request(request, **kwargs)
        elif request.method == "POST":
            return self.handle_post_request(view_fn, request, should_inject_builder, *args, **kwargs)
        else:
            # set custom exception for unsupported request method
            raise ValueError(request.method)

    def handle_get_request(
        self,
        request: RouteLitRequest,
        **kwargs: Any,
    ) -> RouteLitResponse:
        """ "
        Handle a GET request.
        If the session state is present, it will be cleared.
        The head title and description can be passed as kwargs.
        Example:
        ```python
        return routelit_adapter.response(build_signup_view, head_title="Signup", head_description="Signup page")
        ```

        Args:
            request (RouteLitRequest): The request object.
            **kwargs (Dict[str, Any]): Additional keyword arguments.
                head_title (Optional[str]): The title of the head.
                head_description (Optional[str]): The description of the head.

        Returns:
            RouteLitResponse: The response object.
        """
        session_keys = request.get_session_keys()
        ui_key, state_key, fragment_addresses_key, fragment_params_key = session_keys
        if state_key in self.session_storage:
            self.session_storage.pop(ui_key, None)
            self.session_storage.pop(state_key, None)
            self.session_storage.pop(fragment_addresses_key, None)
            self.session_storage.pop(fragment_params_key, None)
        return RouteLitResponse(
            elements=[],
            head=Head(
                title=kwargs.get("head_title"),
                description=kwargs.get("head_description"),
            ),
        )

    def _get_prev_keys(self, request: RouteLitRequest, session_keys: SessionKeys) -> Tuple[bool, SessionKeys]:
        maybe_event = request.ui_event
        if maybe_event and maybe_event["type"] == "navigate":
            new_session_keys = request.get_session_keys(use_referer=True)
            return True, new_session_keys
        return False, session_keys

    def _write_session_state(
        self,
        *,
        session_keys: SessionKeys,
        prev_elements: List[RouteLitElement],
        prev_fragments: MutableMapping[str, List[int]],
        elements: List[RouteLitElement],
        session_state: MutableMapping[str, Any],
        fragments: MutableMapping[str, List[int]],
        fragment_id: Optional[str] = None,
    ) -> None:
        if fragment_id and (fragment_address := prev_fragments.get(fragment_id, [])) and len(fragment_address) > 0:
            fragment_elements = elements

            new_elements = set_elements_at_address(prev_elements, fragment_address, fragment_elements)
        else:
            new_elements = elements

        ui_key, state_key, fragment_addresses_key, _ = session_keys
        self.session_storage[ui_key] = new_elements
        self.session_storage[state_key] = session_state
        self.session_storage[fragment_addresses_key] = {**prev_fragments, **fragments}

    def _get_prev_elements_at_fragment(
        self, session_keys: SessionKeys, fragment_id: Optional[str]
    ) -> Tuple[List[RouteLitElement], Optional[List[RouteLitElement]]]:
        """
        Returns the previous elements of the full page and the previous elements of the fragment if address is provided.
        """
        prev_elements = self.session_storage.get(session_keys.ui_key, [])
        if fragment_id:
            fragment_address = self.session_storage.get(session_keys.fragment_addresses_key, {}).get(fragment_id, [])
            fragment_elements = get_elements_at_address(prev_elements, fragment_address)
            return prev_elements, fragment_elements
        return prev_elements, None

    def _maybe_handle_form_event(self, request: RouteLitRequest, session_keys: SessionKeys) -> bool:
        event = request.ui_event
        if event and event.get("type") != "submit" and (form_id := event.get("formId")):
            session_state = self.session_storage.get(session_keys.state_key, {})
            events = session_state.get(f"__events4later_{form_id}", {})
            events[event["componentId"]] = event
            self.session_storage[session_keys.state_key] = {
                **session_state,
                f"__events4later_{form_id}": events,
            }
            return True
        return False

    def handle_post_request(
        self,
        view_fn: ViewFn,
        request: RouteLitRequest,
        should_inject_builder: Optional[bool] = None,
        *args: Any,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        should_inject_builder = (
            should_inject_builder if should_inject_builder is not None else self.should_inject_builder
        )
        app_view_fn = view_fn
        session_keys = request.get_session_keys()
        try:
            if self._maybe_handle_form_event(request, session_keys):
                return asdict(ActionsResponse(actions=[], target="app"))
            fragment_id = request.fragment_id
            if fragment_id and fragment_id in self.fragment_registry:
                view_fn = self.fragment_registry[fragment_id]
            self._maybe_clear_session_state(request, session_keys)
            is_navigation_event, prev_session_keys = self._get_prev_keys(request, session_keys)
            prev_elements, maybe_prev_fragment_elements = self._get_prev_elements_at_fragment(
                prev_session_keys, fragment_id
            )
            if is_navigation_event:
                self._clear_session_state(prev_session_keys)
            prev_session_state = self.session_storage.get(prev_session_keys.state_key, {})
            prev_fragments = self.session_storage.get(prev_session_keys.fragment_addresses_key, {})
            builder = self.BuilderClass(
                request,
                session_state=PropertyDict(prev_session_state),
                fragments=prev_fragments,
                initial_fragment_id=fragment_id,
            )
            with self._set_builder_context(builder):
                if should_inject_builder:
                    view_fn(builder, *args, **kwargs)
                else:
                    view_fn(*args, **kwargs)
            builder.on_end()
            elements = builder.get_elements()
            self._write_session_state(
                session_keys=session_keys,
                prev_elements=prev_elements,
                prev_fragments=prev_fragments,
                elements=elements,
                session_state=builder.session_state.get_data(),
                fragments=builder.get_fragments(),
                fragment_id=fragment_id,
            )
            actions = compare_elements(maybe_prev_fragment_elements or prev_elements, elements)
            target: Literal["app", "fragment"] = "app" if fragment_id is None else "fragment"
            action_response = ActionsResponse(actions=actions, target=target)
            return asdict(action_response)
        except RerunException as e:
            self.session_storage[session_keys.state_key] = e.state
            if e.scope == "app":
                return self.handle_post_request(app_view_fn, request, should_inject_builder, *args, **kwargs)
            else:
                return self.handle_post_request(view_fn, request, should_inject_builder, *args, **kwargs)
        except EmptyReturnException:
            # No need to return anything
            return asdict(ActionsResponse(actions=[], target="app"))

    def get_builder_class(self) -> Type[RouteLitBuilder]:
        return self.BuilderClass

    def _clear_session_state(self, session_keys: SessionKeys) -> None:
        self.session_storage.pop(session_keys.state_key, None)
        self.session_storage.pop(session_keys.ui_key, None)
        self.session_storage.pop(session_keys.fragment_addresses_key, None)
        self.session_storage.pop(session_keys.fragment_params_key, None)

    def _maybe_clear_session_state(self, request: RouteLitRequest, session_keys: SessionKeys) -> None:
        if request.get_query_param("__routelit_clear_session_state"):
            self._clear_session_state(session_keys)
            raise EmptyReturnException()

    def client_assets(self) -> List[ViteComponentsAssets]:
        """
        Render the vite assets for BuilderClass components.
        This function will return a list of ViteComponentsAssets.
        This should be called by the web framework to render the assets.
        """
        assets = []
        for static_path in self.BuilderClass.get_client_resource_paths():
            vite_assets = get_vite_components_assets(static_path["package_name"])
            assets.append(vite_assets)

        return assets

    def default_client_assets(self) -> ViteComponentsAssets:
        return get_vite_components_assets("routelit")

    def _register_fragment(self, key: str, fragment: Callable[[RouteLitBuilder], Any]) -> None:
        self.fragment_registry[key] = fragment

    def _preprocess_fragment_params(
        self, fragment_key: str, args: Tuple[Any, ...], kwargs: Dict[str, Any]
    ) -> Tuple[BuilderType, bool, Tuple[Any, ...], Dict[str, Any]]:
        is_builder_1st_arg = args is not None and len(args) > 0 and isinstance(args[0], RouteLitBuilder)
        rl: BuilderType = cast(RouteLitBuilder, args[0]) if is_builder_1st_arg else self.ui  # type: ignore[assignment]
        if is_builder_1st_arg:
            args = args[1:]
        is_fragment_request = rl.request.fragment_id is not None
        session_keys = rl.request.get_session_keys()
        if not is_fragment_request:
            fragment_params_by_key = {
                fragment_key: {
                    "args": args,
                    "kwargs": kwargs,
                }
            }
            all_fragment_params = self.session_storage.get(session_keys.fragment_params_key, {})
            self.session_storage[session_keys.fragment_params_key] = {
                **all_fragment_params,
                **fragment_params_by_key,
            }
        else:
            fragment_params = self.session_storage.get(session_keys.fragment_params_key, {}).get(fragment_key, {})
            args = fragment_params.get("args", [])
            kwargs = fragment_params.get("kwargs", {})

        return rl, is_builder_1st_arg, args, kwargs

    def fragment(self, key: Optional[str] = None) -> Callable[[ViewFn], ViewFn]:
        """
        Decorator to register a fragment.

        Args:
            key: The key to register the fragment with.

        Returns:
            The decorator function.

        Example:
        ```python
        from routelit import RouteLit, RouteLitBuilder

        rl = RouteLit()

        @rl.fragment()
        def my_fragment(ui: RouteLitBuilder):
            ui.text("Hello, world!")

        @rl.fragment()
        def my_fragment2():
            ui = rl.ui
            ui.text("Hello, world!")
        ```
        """

        def decorator_fragment(view_fn: ViewFn) -> ViewFn:
            fragment_key = key or view_fn.__name__

            @functools.wraps(view_fn)
            def wrapper(*args: Any, **kwargs: Any) -> Any:
                rl, is_builder_1st_arg, args, kwargs = self._preprocess_fragment_params(fragment_key, args, kwargs)

                with rl._fragment(fragment_key):
                    res = view_fn(rl, *args, **kwargs) if is_builder_1st_arg else view_fn(*args, **kwargs)
                    return res

            self._register_fragment(fragment_key, wrapper)
            return wrapper

        return decorator_fragment

    def dialog(self, key: Optional[str] = None) -> Callable[[ViewFn], ViewFn]:
        """Decorator to register a dialog.

        Args:
            key (Optional[str]): The key to register the dialog with.

        Returns:
            The decorator function.

        Example:
        ```python
        from routelit import RouteLit, RouteLitBuilder

        rl = RouteLit()

        @rl.dialog()
        def my_dialog(ui: RouteLitBuilder):
            ui.text("Hello, world!")

        def my_main_view(ui: RouteLitBuilder):
            if ui.button("Open dialog"):
                my_dialog(ui)

        @rl.dialog()
        def my_dialog2():
            ui = rl.ui
            ui.text("Hello, world!")

        def my_main_view2():
            ui = rl.ui
            if ui.button("Open dialog"):
                my_dialog2()
        ```
        """

        def decorator_dialog(view_fn: ViewFn) -> ViewFn:
            fragment_key = key or view_fn.__name__
            dialog_key = f"{fragment_key}-dialog"

            @functools.wraps(view_fn)
            def wrapper(*args: Any, **kwargs: Any) -> Any:
                rl, is_builder_1st_arg, args, kwargs = self._preprocess_fragment_params(fragment_key, args, kwargs)

                with rl._fragment(fragment_key), rl._dialog(dialog_key):
                    res = view_fn(rl, *args, **kwargs) if is_builder_1st_arg else view_fn(*args, **kwargs)
                    return res

            self._register_fragment(fragment_key, wrapper)
            return wrapper

        return decorator_dialog

ui property

The current builder instance. Use this in conjunction with response(..., should_inject_builder=False) example:

rl = RouteLit()

def my_view():
    rl.ui.text("Hello, world!")

request = ...
response = rl.response(my_view, request, should_inject_builder=False)

client_assets()

Render the vite assets for BuilderClass components. This function will return a list of ViteComponentsAssets. This should be called by the web framework to render the assets.

Source code in src/routelit/routelit.py
318
319
320
321
322
323
324
325
326
327
328
329
def client_assets(self) -> List[ViteComponentsAssets]:
    """
    Render the vite assets for BuilderClass components.
    This function will return a list of ViteComponentsAssets.
    This should be called by the web framework to render the assets.
    """
    assets = []
    for static_path in self.BuilderClass.get_client_resource_paths():
        vite_assets = get_vite_components_assets(static_path["package_name"])
        assets.append(vite_assets)

    return assets

dialog(key=None)

Decorator to register a dialog.

Parameters:

Name Type Description Default
key Optional[str]

The key to register the dialog with.

None

Returns:

Type Description
Callable[[ViewFn], ViewFn]

The decorator function.

Example:

from routelit import RouteLit, RouteLitBuilder

rl = RouteLit()

@rl.dialog()
def my_dialog(ui: RouteLitBuilder):
    ui.text("Hello, world!")

def my_main_view(ui: RouteLitBuilder):
    if ui.button("Open dialog"):
        my_dialog(ui)

@rl.dialog()
def my_dialog2():
    ui = rl.ui
    ui.text("Hello, world!")

def my_main_view2():
    ui = rl.ui
    if ui.button("Open dialog"):
        my_dialog2()
Source code in src/routelit/routelit.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def dialog(self, key: Optional[str] = None) -> Callable[[ViewFn], ViewFn]:
    """Decorator to register a dialog.

    Args:
        key (Optional[str]): The key to register the dialog with.

    Returns:
        The decorator function.

    Example:
    ```python
    from routelit import RouteLit, RouteLitBuilder

    rl = RouteLit()

    @rl.dialog()
    def my_dialog(ui: RouteLitBuilder):
        ui.text("Hello, world!")

    def my_main_view(ui: RouteLitBuilder):
        if ui.button("Open dialog"):
            my_dialog(ui)

    @rl.dialog()
    def my_dialog2():
        ui = rl.ui
        ui.text("Hello, world!")

    def my_main_view2():
        ui = rl.ui
        if ui.button("Open dialog"):
            my_dialog2()
    ```
    """

    def decorator_dialog(view_fn: ViewFn) -> ViewFn:
        fragment_key = key or view_fn.__name__
        dialog_key = f"{fragment_key}-dialog"

        @functools.wraps(view_fn)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            rl, is_builder_1st_arg, args, kwargs = self._preprocess_fragment_params(fragment_key, args, kwargs)

            with rl._fragment(fragment_key), rl._dialog(dialog_key):
                res = view_fn(rl, *args, **kwargs) if is_builder_1st_arg else view_fn(*args, **kwargs)
                return res

        self._register_fragment(fragment_key, wrapper)
        return wrapper

    return decorator_dialog

fragment(key=None)

Decorator to register a fragment.

Parameters:

Name Type Description Default
key Optional[str]

The key to register the fragment with.

None

Returns:

Type Description
Callable[[ViewFn], ViewFn]

The decorator function.

Example:

from routelit import RouteLit, RouteLitBuilder

rl = RouteLit()

@rl.fragment()
def my_fragment(ui: RouteLitBuilder):
    ui.text("Hello, world!")

@rl.fragment()
def my_fragment2():
    ui = rl.ui
    ui.text("Hello, world!")
Source code in src/routelit/routelit.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def fragment(self, key: Optional[str] = None) -> Callable[[ViewFn], ViewFn]:
    """
    Decorator to register a fragment.

    Args:
        key: The key to register the fragment with.

    Returns:
        The decorator function.

    Example:
    ```python
    from routelit import RouteLit, RouteLitBuilder

    rl = RouteLit()

    @rl.fragment()
    def my_fragment(ui: RouteLitBuilder):
        ui.text("Hello, world!")

    @rl.fragment()
    def my_fragment2():
        ui = rl.ui
        ui.text("Hello, world!")
    ```
    """

    def decorator_fragment(view_fn: ViewFn) -> ViewFn:
        fragment_key = key or view_fn.__name__

        @functools.wraps(view_fn)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            rl, is_builder_1st_arg, args, kwargs = self._preprocess_fragment_params(fragment_key, args, kwargs)

            with rl._fragment(fragment_key):
                res = view_fn(rl, *args, **kwargs) if is_builder_1st_arg else view_fn(*args, **kwargs)
                return res

        self._register_fragment(fragment_key, wrapper)
        return wrapper

    return decorator_fragment

handle_get_request(request, **kwargs)

" Handle a GET request. If the session state is present, it will be cleared. The head title and description can be passed as kwargs. Example:

return routelit_adapter.response(build_signup_view, head_title="Signup", head_description="Signup page")

Parameters:

Name Type Description Default
request RouteLitRequest

The request object.

required
**kwargs Dict[str, Any]

Additional keyword arguments. head_title (Optional[str]): The title of the head. head_description (Optional[str]): The description of the head.

{}

Returns:

Name Type Description
RouteLitResponse RouteLitResponse

The response object.

Source code in src/routelit/routelit.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def handle_get_request(
    self,
    request: RouteLitRequest,
    **kwargs: Any,
) -> RouteLitResponse:
    """ "
    Handle a GET request.
    If the session state is present, it will be cleared.
    The head title and description can be passed as kwargs.
    Example:
    ```python
    return routelit_adapter.response(build_signup_view, head_title="Signup", head_description="Signup page")
    ```

    Args:
        request (RouteLitRequest): The request object.
        **kwargs (Dict[str, Any]): Additional keyword arguments.
            head_title (Optional[str]): The title of the head.
            head_description (Optional[str]): The description of the head.

    Returns:
        RouteLitResponse: The response object.
    """
    session_keys = request.get_session_keys()
    ui_key, state_key, fragment_addresses_key, fragment_params_key = session_keys
    if state_key in self.session_storage:
        self.session_storage.pop(ui_key, None)
        self.session_storage.pop(state_key, None)
        self.session_storage.pop(fragment_addresses_key, None)
        self.session_storage.pop(fragment_params_key, None)
    return RouteLitResponse(
        elements=[],
        head=Head(
            title=kwargs.get("head_title"),
            description=kwargs.get("head_description"),
        ),
    )

response(view_fn, request, should_inject_builder=None, *args, **kwargs)

Handle the request and return the response.

Parameters:

Name Type Description Default
view_fn ViewFn

(Callable[[RouteLitBuilder], Any]) The view function to handle the request.

required
request RouteLitRequest

The request object.

required
**kwargs Dict[str, Any]

Additional keyword arguments.

{}

Returns:

Type Description
Union[RouteLitResponse, Dict[str, Any]]

RouteLitResponse | Dict[str, Any]: The response object. where Dict[str, Any] is a dictionary that contains the following keys: actions (List[Action]), target (Literal["app", "fragment"])

Example:

from routelit import RouteLit, RouteLitBuilder

rl = RouteLit()

def my_view(rl: RouteLitBuilder):
    rl.text("Hello, world!")

request = ...
response = rl.response(my_view, request)

# example with dependency
def my_view(rl: RouteLitBuilder, name: str):
    rl.text(f"Hello, {name}!")

request = ...
response = rl.response(my_view, request, name="John")
Source code in src/routelit/routelit.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def response(
    self,
    view_fn: ViewFn,
    request: RouteLitRequest,
    should_inject_builder: Optional[bool] = None,
    *args: Any,
    **kwargs: Any,
) -> Union[RouteLitResponse, Dict[str, Any]]:
    """Handle the request and return the response.

    Args:
        view_fn (ViewFn): (Callable[[RouteLitBuilder], Any]) The view function to handle the request.
        request (RouteLitRequest): The request object.
        **kwargs (Dict[str, Any]): Additional keyword arguments.

    Returns:
        RouteLitResponse | Dict[str, Any]:
            The response object.
            where Dict[str, Any] is a dictionary that contains the following keys:
            actions (List[Action]), target (Literal["app", "fragment"])

    Example:
    ```python
    from routelit import RouteLit, RouteLitBuilder

    rl = RouteLit()

    def my_view(rl: RouteLitBuilder):
        rl.text("Hello, world!")

    request = ...
    response = rl.response(my_view, request)

    # example with dependency
    def my_view(rl: RouteLitBuilder, name: str):
        rl.text(f"Hello, {name}!")

    request = ...
    response = rl.response(my_view, request, name="John")
    ```
    """
    if request.method == "GET":
        return self.handle_get_request(request, **kwargs)
    elif request.method == "POST":
        return self.handle_post_request(view_fn, request, should_inject_builder, *args, **kwargs)
    else:
        # set custom exception for unsupported request method
        raise ValueError(request.method)

Builder Module

ColumnsGap = Literal['none', 'small', 'medium', 'large'] module-attribute

The gap between the columns.

TextInputType = Literal['text', 'number', 'email', 'password', 'search', 'tel', 'url', 'date', 'time', 'datetime-local', 'month', 'week'] module-attribute

The type of the text input.

VerticalAlignment = Literal['top', 'center', 'bottom'] module-attribute

The vertical alignment of the elements.

RouteLitBuilder

Source code in src/routelit/builder.py
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
class RouteLitBuilder:
    static_assets_targets: ClassVar[List[AssetTarget]] = []

    def __init__(
        self,
        request: RouteLitRequest,
        session_state: PropertyDict,
        fragments: MutableMapping[str, List[int]],
        initial_fragment_id: Optional[str] = None,
        prefix: Optional[str] = None,
        parent_element: Optional[RouteLitElement] = None,
        parent_builder: Optional["RouteLitBuilder"] = None,
        address: Optional[List[int]] = None,
        elements: Optional[List[RouteLitElement]] = None,
    ):
        self.request = request
        self.initial_fragment_id = initial_fragment_id
        self.fragments = fragments
        self.address = address
        self.head = Head()
        # Set prefix based on parent element if not explicitly provided
        if prefix is None:
            self.prefix = parent_element.key if parent_element else ""
        else:
            self.prefix = prefix
        self.elements: List[RouteLitElement] = elements or []
        self.num_non_widget = 0
        self.session_state = session_state
        self.parent_element = parent_element
        self.parent_builder = parent_builder
        if parent_element:
            parent_element.children = self.elements
        self.active_child_builder: Optional[RouteLitBuilder] = None
        self._prev_active_child_builder: Optional[RouteLitBuilder] = None
        if prefix is None:
            self._on_init()

    def _on_init(self) -> None:
        pass

    def get_request(self) -> RouteLitRequest:
        return self.request

    def _get_prefix(self) -> str:
        # Simplify to just use the current prefix which is already properly initialized
        return self.prefix

    def _get_next_address(self) -> List[int]:
        if self.active_child_builder:
            return [
                *(self.active_child_builder.address or []),
                len(self.active_child_builder.elements),
            ]
        else:
            return [*(self.address or []), len(self.elements)]

    def _get_last_address(self) -> List[int]:
        if self.active_child_builder:
            return [
                *(self.active_child_builder.address or []),
                len(self.active_child_builder.elements) - 1,
            ]
        else:
            return [*(self.address or []), len(self.elements) - 1]

    def _build_nested_builder(self, element: RouteLitElement) -> "RouteLitBuilder":
        builder = self.__class__(
            self.request,
            fragments=self.fragments,
            prefix=element.key,
            session_state=self.session_state,
            parent_element=element,
            parent_builder=self,
            address=self._get_last_address(),
        )
        return builder

    def _get_parent_form_id(self) -> Optional[str]:
        if self.parent_element and self.parent_element.name == "form":
            return self.parent_element.key
        if self.active_child_builder:
            return self.active_child_builder._get_parent_form_id()
        if self._prev_active_child_builder:
            return self._prev_active_child_builder._get_parent_form_id()
        return None

    def _new_text_id(self, name: str) -> str:
        no_of_non_widgets = (
            self.num_non_widget if not self.active_child_builder else self.active_child_builder.num_non_widget
        )
        prefix = self.active_child_builder._get_prefix() if self.active_child_builder else self._get_prefix()
        return f"{prefix}_{name}_{no_of_non_widgets}"

    def _new_widget_id(self, name: str, label: str) -> str:
        hashed = hashlib.sha256(label.encode()).hexdigest()[:8]
        prefix = self.active_child_builder._get_prefix() if self.active_child_builder else self._get_prefix()
        return f"{prefix}_{name}_{hashed}"

    def _maybe_get_event(self, component_id: str) -> Optional[RouteLitEvent]:
        event = self.request.ui_event
        if (
            event
            and event.get("type") == "submit"
            and (event_form_id := event.get("formId"))
            and self.session_state.get("__ignore_submit") != event_form_id
            and (form_id := self._get_parent_form_id())
            and event_form_id == form_id
        ):
            events = self.session_state.get(f"__events4later_{form_id}", {})
            self.session_state.pop(f"__events4later_{form_id}", None)
            self.session_state[f"__events_{form_id}"] = events
            self.session_state["__ignore_submit"] = form_id
            self.rerun(scope="app", clear_event=False)

        if event and event.get("componentId") == component_id:
            return event
        if (
            (form_id := self._get_parent_form_id())
            and (events := self.session_state.get(f"__events_{form_id}", {}))
            and component_id in events
        ):
            _event: RouteLitEvent = events[component_id]
            events.pop(component_id, None)
            self.session_state[f"__events_{form_id}"] = events
            return _event
        return None

    def _get_event_value(self, component_id: str, event_type: str, attribute: Optional[str] = None) -> Tuple[bool, Any]:
        """
        Check if the last event is of the given type and component_id.
        If attribute is not None, check if the event has the given attribute.
        Returns a tuple of (has_event, event_data).
        """
        event = self._maybe_get_event(component_id)
        if event is not None and event.get("type") == event_type:
            if attribute is None:
                return True, event["data"]
            else:
                return True, event["data"].get(attribute)
        return False, None

    def _append_element(self, element: RouteLitElement) -> None:
        """
        Append an element to the current builder.
        Returns the index of the element in the builder.
        Do not use this method directly, use the other methods instead, unless you are creating a custom element.
        """
        if self.active_child_builder:
            self.active_child_builder._append_element(element)
        else:
            self.elements.append(element)
            if element.name == "fragment" and element.key != self.initial_fragment_id:
                element_address = element.address
                if element_address is not None:
                    self.fragments[element.key] = element_address

    def _add_non_widget(self, element: RouteLitElement) -> RouteLitElement:
        self._append_element(element)
        if not self.active_child_builder:
            self.num_non_widget += 1
        else:
            self.active_child_builder.num_non_widget += 1
        return element

    def _add_widget(self, element: RouteLitElement) -> None:
        self._append_element(element)

    def _create_element(
        self,
        name: str,
        key: str,
        props: Optional[Dict[str, Any]] = None,
        children: Optional[List[RouteLitElement]] = None,
    ) -> RouteLitElement:
        element = RouteLitElement(key=key, name=name, props=props or {}, children=children)
        self._add_widget(element)
        return element

    def _create_non_widget_element(
        self,
        name: str,
        key: str,
        props: Optional[Dict[str, Any]] = None,
        children: Optional[List[RouteLitElement]] = None,
        address: Optional[List[int]] = None,
    ) -> RouteLitElement:
        element = RouteLitElement(key=key, name=name, props=props or {}, address=address, children=children)
        self._add_non_widget(element)
        return element

    def _fragment(self, key: Optional[str] = None) -> "RouteLitBuilder":
        key = key or self._new_text_id("fragment")
        fragment = self._create_non_widget_element(
            name="fragment",
            key=key,
            props={"id": key},
            address=self._get_next_address(),
        )
        return self._build_nested_builder(fragment)

    def _dialog(self, key: Optional[str] = None, closable: bool = True) -> "RouteLitBuilder":
        key = key or self._new_text_id("dialog")
        is_closed, _ = self._get_event_value(key, "close")
        if is_closed:
            self.rerun(scope="app")
        dialog = self._create_non_widget_element(
            name="dialog",
            key=key,
            props={"id": key, "open": True, "closable": closable},
        )
        return self._build_nested_builder(dialog)

    def form(self, key: str) -> "RouteLitBuilder":
        """
        Creates a form area that do not submit input values to the server until the form is submitted.
        Use button(..., event_name="submit") to submit the form.

        Args:
            key (str): The key of the form.

        Returns:
            RouteLitBuilder: A builder for the form.

        Example:
        ```python
        with ui.form("login"):
            username = ui.text_input("Username")
            password = ui.text_input("Password", type="password")
            is_submitted = ui.button("Login", event_name="submit")
            if is_submitted:
                ui.text(f"Login successful for {username}")
        ```
        """
        form = self._create_non_widget_element(
            name="form",
            key=key,
            props={"id": key},
        )
        return self._build_nested_builder(form)

    def link(
        self,
        href: str,
        text: str = "",
        replace: bool = False,
        is_external: bool = False,
        key: Optional[str] = None,
        **kwargs: Any,
    ) -> RouteLitElement:
        """
        Creates a link component. Use this to navigate to a different page.

        Args:
            href (str): The href of the link.
            text (str): The text of the link.
            replace (bool): Whether to replace the current page from the history.
            is_external (bool): Whether the link is external to the current app.
            key (Optional[str]): The key of the link.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the link.

        Example:
        ```python
        ui.link("/signup", text="Signup")
        ui.link("/login", text="Login", replace=True)
        ui.link("https://www.google.com", text="Google", is_external=True)
        ```
        """
        new_element = self._create_non_widget_element(
            name="link",
            key=key or self._new_text_id("link"),
            props={
                "href": href,
                "replace": replace,
                "isExternal": is_external,
                "text": text,
                **kwargs,
            },
        )
        return new_element

    def link_area(
        self,
        href: str,
        replace: bool = False,
        is_external: bool = False,
        key: Optional[str] = None,
        className: Optional[str] = None,
        **kwargs: Any,
    ) -> "RouteLitBuilder":
        """
        Creates a link area component. Use this element which is a container of other elements.

        Args:
            href (str): The href of the link.
            replace (bool): Whether to replace the current page.
            is_external (bool): Whether the link is external.
            key (Optional[str]): The key of the link area.
            className (Optional[str]): The class name of the link area.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the link area.

        Example:
        ```python
        with ui.link_area("https://www.google.com"):
            with ui.flex(direction="row", gap="small"):
                ui.image("https://www.google.com/favicon.ico", width="24px", height="24px")
                ui.text("Google")
        ```
        """
        link_element = self.link(
            href,
            replace=replace,
            is_external=is_external,
            key=key,
            className=f"rl-no-link-decoration {className or ''}",
            **kwargs,
        )
        return self._build_nested_builder(link_element)

    def container(self, key: Optional[str] = None, height: Optional[str] = None, **kwargs: Any) -> "RouteLitBuilder":
        """
        Creates a container component.

        Args:
            key (Optional[str]): The key of the container.
            height (Optional[str]): The height of the container.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the container.

        Example:
        ```python
        with ui.container(height="100px"):
            ui.text("Container")
        ```
        """
        container = self._create_non_widget_element(
            name="container",
            key=key or self._new_text_id("container"),
            props={"style": {"height": height}, **kwargs},
        )
        return self._build_nested_builder(container)

    def markdown(
        self,
        body: str,
        *,
        allow_unsafe_html: bool = False,
        key: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        """
        Creates a markdown component.

        Args:
            body (str): The body of the markdown.
            allow_unsafe_html (bool): Whether to allow unsafe HTML.
            key (Optional[str]): The key of the markdown.

        Example:
        ```python
        ui.markdown("**Bold** *italic* [link](https://www.google.com)")
        ```
        """
        self._create_non_widget_element(
            name="markdown",
            key=key or self._new_text_id("markdown"),
            props={"body": body, "allowUnsafeHtml": allow_unsafe_html, **kwargs},
        )

    def text(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
        """
        Creates a text component.

        Args:
            body (str): The body of the text.
            key (Optional[str]): The key of the text.

        Example:
        ```python
        ui.text("Text")
        ```
        """
        self.markdown(body, allow_unsafe_html=False, key=key, **kwargs)

    def title(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
        """
        Creates a title component.

        Args:
            body (str): The body of the title.
            key (Optional[str]): The key of the title.

        Example:
        ```python
        ui.title("Title")
        ```
        """
        self._create_non_widget_element(
            name="title",
            key=key or self._new_text_id("title"),
            props={"body": body, **kwargs},
        )

    def header(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
        """
        Creates a header component.

        Args:
            body (str): The body of the header.
            key (Optional[str]): The key of the header.

        Example:
        ```python
        ui.header("Header")
        ```
        """
        self._create_non_widget_element(
            name="header",
            key=key or self._new_text_id("header"),
            props={"body": body, **kwargs},
        )

    def subheader(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
        """
        Creates a subheader component.

        Args:
            body (str): The body of the subheader.
            key (Optional[str]): The key of the subheader.

        Example:
        ```python
        ui.subheader("Subheader")
        ```
        """
        self._create_non_widget_element(
            name="subheader",
            key=key or self._new_text_id("subheader"),
            props={"body": body, **kwargs},
        )

    def image(self, src: str, *, key: Optional[str] = None, **kwargs: Any) -> None:
        """
        Creates an image component.

        Args:
            src (str): The source of the image.
            key (Optional[str]): The key of the image.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the image.

        Example:
        ```python
        ui.image("https://www.google.com/favicon.ico", alt="Google", width="24px", height="24px")
        ```
        """
        self._create_non_widget_element(
            name="image",
            key=key or self._new_text_id("image"),
            props={"src": src, **kwargs},
        )

    def expander(self, title: str, *, open: Optional[bool] = None, key: Optional[str] = None) -> "RouteLitBuilder":
        """
        Creates an expander component that can be used as both a context manager and a regular function call.

        Args:
            title (str): The title of the expander.
            open (Optional[bool]): Whether the expander is open.
            key (Optional[str]): The key of the expander.

        Returns:
            RouteLitBuilder: A builder for the expander.
        ```python
        Usage:
            def build_index_view(ui: RouteLitBuilder):
                # Context manager style
                with ui.expander("Title"):
                    ui.text("Content")

                with ui.expander("Title", open=True) as exp0:
                    exp0.text("Content")

                # Function call style
                exp = ui.expander("Title")
                exp.text("Content")
        ```
        """
        new_key = key or self._new_widget_id("expander", title)
        new_element = self._create_element(
            name="expander",
            key=new_key,
            props={"title": title, "open": open},
        )
        return self._build_nested_builder(new_element)

    def columns(
        self,
        spec: Union[int, List[int]],
        *,
        key: Optional[str] = None,
        vertical_alignment: VerticalAlignment = "top",
        columns_gap: ColumnsGap = "small",
    ) -> List["RouteLitBuilder"]:
        """Creates a flexbox layout with several columns with the given spec.

        Args:
            spec (int | List[int]): The specification of the columns. Can be an integer or a list of integers.
            key (Optional[str]): The key of the container.
            vertical_alignment (VerticalAlignment): The vertical alignment of the columns: "top", "center", "bottom".
            columns_gap (ColumnsGap): The gap between the columns: "none", "small", "medium", "large".

        Returns:
            List[RouteLitBuilder]: A list of builders for the columns.

        Examples:
        ```python
            # 2 columns with equal width
            col1, col2 = ui.columns(2)
            # usage inline
            col1.text("Column 1")
            col2.text("Column 2")
            # usage as context manager
            with col1:
                ui.text("Column 1")
            with col2:
                ui.text("Column 2")
            # usage with different widths
            col1, col2, col3 = ui.columns([2, 1, 1])
            col1.text("Column 1")
            col2.text("Column 2")
            col3.text("Column 3")
        ```
        """
        if isinstance(spec, int):
            spec = [1] * spec
        container_key = key or self._new_text_id("container")
        container = self._create_non_widget_element(
            name="container",
            key=container_key,
            props={
                "className": "rl-flex rl-flex-row",
                "style": {
                    "alignItems": verticalAlignmentMap.get(vertical_alignment, "top"),
                    "columnGap": columnsGapMap.get(columns_gap, "small"),
                },
            },
        )
        container_builder = self._build_nested_builder(container)
        with container_builder:
            element_builders = []
            for column_spec in spec:
                column = self._create_non_widget_element(
                    name="container",
                    key=self._new_text_id("col"),
                    props={"style": {"flex": column_spec}},
                )
                element_builders.append(self._build_nested_builder(column))
        return element_builders

    def flex(
        self,
        direction: Literal["row", "col"] = "col",
        wrap: Literal["wrap", "nowrap"] = "nowrap",
        justify_content: Literal["start", "end", "center", "between", "around", "evenly"] = "start",
        align_items: Literal["normal", "start", "end", "center", "baseline", "stretch"] = "normal",
        align_content: Literal["normal", "start", "end", "center", "between", "around", "evenly"] = "normal",
        gap: Optional[str] = None,
        key: Optional[str] = None,
        **kwargs: Any,
    ) -> "RouteLitBuilder":
        """
        Creates a flex container with the given direction, wrap, justify content, align items, align content, gap, and key.
        """
        container = self._create_non_widget_element(
            name="flex",
            key=key or self._new_text_id("flex"),
            props={
                "direction": direction,
                "flexWrap": wrap,
                "justifyContent": justify_content,
                "alignItems": align_items,
                "alignContent": align_content,
                "gap": gap,
                **kwargs,
            },
        )
        return self._build_nested_builder(container)

    def button(
        self,
        text: str,
        *,
        event_name: Literal["click", "submit"] = "click",
        key: Optional[str] = None,
        on_click: Optional[Callable[[], None]] = None,
        **kwargs: Any,
    ) -> bool:
        """
        Creates a button with the given text, event name, key, on click, and keyword arguments.

        Args:
            text (str): The text of the button.
            event_name (Optional[Literal["click", "submit"]]): The name of the event to listen for.
            key (Optional[str]): The key of the button.
            on_click (Optional[Callable[[], None]]): The function to call when the button is clicked.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the button.

        Returns:
            bool: Whether the button was clicked.

        Example:
        ```python
        is_clicked = ui.button("Click me", on_click=lambda: print("Button clicked"))
        if is_clicked:
            ui.text("Button clicked")
        ```
        """
        button = self._create_element(
            name="button",
            key=key or self._new_widget_id("button", text),
            props={"text": text, "eventName": event_name, **kwargs},
        )
        is_clicked, _ = self._get_event_value(button.key, event_name)
        if is_clicked and on_click:
            on_click()
        return is_clicked

    def _x_input(
        self,
        element_type: str,
        label: str,
        value: Optional[Any] = None,
        key: Optional[str] = None,
        on_change: Optional[Callable[[Any], None]] = None,
        event_name: str = "change",
        value_attribute: str = "value",
        **kwargs: Any,
    ) -> str:
        component_id = key or self._new_widget_id(element_type, label)
        new_value = self.session_state.get(component_id, value) or ""
        has_changed, event_value = self._get_event_value(component_id, event_name, value_attribute)
        if has_changed:
            new_value = event_value or ""
            self.session_state[component_id] = new_value
            if on_change:
                on_change(new_value)
        self._create_element(
            name=element_type,
            key=component_id,
            props={
                "label": label,
                value_attribute: new_value,
                **kwargs,
            },
        )
        return new_value

    def _x_radio_select(
        self,
        element_type: Literal["radio", "select"],
        label: str,
        options: List[Union[Dict[str, Any], str]],
        value: Optional[Any] = None,
        key: Optional[str] = None,
        on_change: Optional[Callable[[Any], None]] = None,
        **kwargs: Any,
    ) -> Any:
        component_id = key or self._new_widget_id(element_type, label)
        new_value = self.session_state.get(component_id, value)
        has_changed, event_value = self._get_event_value(component_id, "change", "value")
        if has_changed:
            new_value = event_value
            self.session_state[component_id] = new_value
            if on_change:
                on_change(new_value)
        self._create_element(
            name=element_type,
            key=component_id,
            props={
                "label": label,
                "value": new_value,
                "options": options,
                **kwargs,
            },
        )
        return new_value

    def text_input(
        self,
        label: str,
        *,
        type: TextInputType = "text",
        value: Optional[str] = None,
        key: Optional[str] = None,
        on_change: Optional[Callable[[str], None]] = None,
        **kwargs: Any,
    ) -> str:
        """
        Creates a text input with the given label and value.

        Args:
            label (str): The label of the text input.
            type (TextInputType): The type of the text input.
            value (Optional[str]): The value of the text input.
            key (Optional[str]): The key of the text input.
            on_change (Optional[Callable[[str], None]]): The function to call when the value changes. The function will be called with the new value.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the text input.

        Returns:
            str: The text value of the text input.

        Example:
        ```python
        name = ui.text_input("Name", value="John", on_change=lambda value: print(f"Name changed to {value}"))
        ui.text(f"Name is {name}")
        ```
        """
        return self._x_input("text-input", label, value, key, on_change, type=type, **kwargs)

    def textarea(
        self,
        label: str,
        *,
        value: Optional[str] = None,
        key: Optional[str] = None,
        on_change: Optional[Callable[[str], None]] = None,
        **kwargs: Any,
    ) -> str:
        """
        Creates a textarea with the given label and value.

        Args:
            label (str): The label of the textarea.
            value (Optional[str]): The value of the textarea.
            key (Optional[str]): The key of the textarea.
            on_change (Optional[Callable[[str], None]]): The function to call when the value changes. The function will be called with the new value.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the textarea.

        Returns:
            str: The text value of the textarea.

        Example:
        ```python
        text = ui.textarea("Text", value="Hello, world!", on_change=lambda value: print(f"Text changed to {value}"))
        ui.text(f"Text is {text}")
        ```
        """
        return self._x_input("textarea", label, value, key, on_change, **kwargs)

    def radio(
        self,
        label: str,
        options: List[Union[Dict[str, Any], str]],
        *,
        value: Optional[Any] = None,
        key: Optional[str] = None,
        on_change: Optional[Callable[[Any], None]] = None,
        flex_direction: Literal["row", "col"] = "col",
        **kwargs: Any,
    ) -> Any:
        """
        Creates a radio group with the given label and options.

        Args:
            label (str): The label of the radio group.
            options (List[Dict[str, Any] | str]): The options of the radio group. Each option can be a string or a dictionary with the following keys:
                - label: The label of the option.
                - value: The value of the option.
                - caption: The caption of the option.
                - disabled: Whether the option is disabled.
            value (str | int | None): The value of the radio group.
            key (str | None): The key of the radio group.
            on_change (Callable[[str | int | None], None] | None): The function to call when the value changes. The function will be called with the new value.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the radio group.
        Returns:
            str | int | None: The value of the selected radio option.

        Example:
        ```python
        value = ui.radio("Radio", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value="Option 1", on_change=lambda value: print(f"Radio value changed to {value}"))
        ui.text(f"Radio value is {value}")
        ```
        """
        return self._x_radio_select(
            "radio",
            label,
            options,
            value,
            key,
            on_change,
            flexDirection=flex_direction,
            **kwargs,
        )

    def select(
        self,
        label: str,
        options: List[Union[Dict[str, Any], str]],
        *,
        value: Any = "",
        key: Optional[str] = None,
        on_change: Optional[Callable[[Any], None]] = None,
        **kwargs: Any,
    ) -> Any:
        """
        Creates a select dropdown with the given label and options.

        Args:
            label (str): The label of the select dropdown.
            options (List[Dict[str, Any] | str]): The options of the select dropdown. Each option can be a string or a dictionary with the following keys: (label, value, disabled)
                - label: The label of the option.
                - value: The value of the option.
                - disabled: Whether the option is disabled.
            value (str | int): The value of the select dropdown.
            key (str | None): The key of the select dropdown.
            on_change (Callable[[str | int | None], None] | None): The function to call when the value changes. The function will be called with the new value.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the select dropdown.

        Returns:
            Any: The value of the select dropdown.

        Example:
        ```python
        value = ui.select("Select", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value="Option 1", on_change=lambda value: print(f"Select value changed to {value}"))
        ui.text(f"Select value is {value}")
        ```
        """
        return self._x_radio_select("select", label, options, value, key, on_change, **kwargs)

    def checkbox(
        self,
        label: str,
        *,
        checked: bool = False,
        key: Optional[str] = None,
        on_change: Optional[Callable[[bool], None]] = None,
        **kwargs: Any,
    ) -> bool:
        """
        Creates a checkbox with the given label and value.

        Args:
            label (str): The label of the checkbox.
            checked (bool): Whether the checkbox is checked.
            key (str | None): The key of the checkbox.
            on_change (Callable[[bool], None] | None): The function to call when the value changes.
            kwargs (Dict[str, Any]): The keyword arguments to pass to the checkbox.

        Returns:
            bool: Whether the checkbox is checked.

        Example:
        ```python
        is_checked = ui.checkbox("Check me", on_change=lambda checked: print(f"Checkbox is {'checked' if checked else 'unchecked'}"))
        if is_checked:
            ui.text("Checkbox is checked")
        """
        component_id = key or self._new_widget_id("checkbox", label)
        new_value = self.session_state.get(component_id, checked)
        if not isinstance(new_value, bool):
            new_value = bool(new_value) if new_value is not None else checked
        has_changed, event_value = self._get_event_value(component_id, "change", "checked")
        if has_changed:
            new_value = bool(event_value) if event_value is not None else False
            self.session_state[component_id] = new_value
            if on_change:
                on_change(new_value)
        self._create_element(
            name="checkbox",
            key=component_id,
            props={
                "label": label,
                "checked": new_value,
                **kwargs,
            },
        )
        return bool(new_value)

    def checkbox_group(
        self,
        label: str,
        options: List[Union[Dict[str, Any], str]],
        *,
        value: Optional[List[Any]] = None,
        key: Optional[str] = None,
        on_change: Optional[Callable[[List[Any]], None]] = None,
        flex_direction: Literal["row", "col"] = "col",
        **kwargs: Any,
    ) -> List[Any]:
        """
        Creates a checkbox group with the given label and options.

        Args:
            label (str): The label of the checkbox group.
            options (List[Dict[str, Any] | str]): The options of the checkbox group.
            value (List[str | int] | None): The value of the checkbox group.
            key (str | None): The key of the checkbox group.
            on_change (Callable[[List[str | int]], None] | None): The function to call when the value changes.
            flex_direction (Literal["row", "col"]): The direction of the checkbox group: "row", "col".
            kwargs (Dict[str, Any]): The keyword arguments to pass to the checkbox group.
        Returns:
            List[str | int]: The value of the checkbox group.

        Example:
        ```python
        selected_options = ui.checkbox_group("Checkbox Group", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value=["Option 1"], on_change=lambda value: print(f"Checkbox group value changed to {value}"))
        ui.text(f"Selected options: {', '.join(selected_options) if selected_options else 'None'}")
        ```
        """
        component_id = key or self._new_widget_id("checkbox-group", label)
        new_value = self.session_state.get(component_id, value) or []
        if not isinstance(new_value, list):
            new_value = value or []
        has_changed, event_value = self._get_event_value(component_id, "change", "value")
        if has_changed:
            new_value = event_value if isinstance(event_value, list) else []
            self.session_state[component_id] = new_value
            if on_change:
                on_change(new_value)
        self._create_element(
            name="checkbox-group",
            key=component_id,
            props={
                "label": label,
                "value": new_value,
                "options": options,
                "flexDirection": flex_direction,
                **kwargs,
            },
        )
        # Ensure return type is List[str | int]
        if isinstance(new_value, list):
            return new_value
        return []

    def rerun(self, scope: RerunType = "auto", clear_event: bool = True) -> None:
        """
        Reruns the current page. Use this to rerun the app or the fragment depending on the context.

        Args:
            scope (RerunType): The scope of the rerun. "auto" will rerun the app or the fragment depending on the context, "app" will rerun the entire app
            clear_event (bool): Whether to clear the event.

        Example:
        ```python
        counter = ui.session_state.get("counter", 0)
        ui.text(f"Counter is {counter}")
        should_increase = ui.button("Increment")
        if should_increase:
            ui.session_state["counter"] = counter + 1
            ui.rerun()
        ```
        """
        self.elements.clear()
        if clear_event:
            self.request.clear_event()
        if scope == "app":
            self.request.clear_fragment_id()
        raise RerunException(self.session_state.get_data(), scope=scope)

    def get_head(self) -> Head:
        return self.head

    def set_page_config(self, page_title: Optional[str] = None, page_description: Optional[str] = None) -> None:
        """
        Sets the page title and description.

        Args:
            page_title (str | None): The title of the page.
            page_description (str | None): The description of the page.
        """
        self.head = Head(title=page_title, description=page_description)
        self._create_non_widget_element(
            name="head",
            key="__head__",
            props={
                "title": page_title,
                "description": page_description,
            },
        )

    def __enter__(self) -> "RouteLitBuilder":
        # When using with builder.element():
        # Make parent builder redirect to this one
        if self.parent_builder:
            self._prev_active_child_builder = self.parent_builder.active_child_builder
            self.parent_builder.active_child_builder = self
        return self

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        # Reset parent's active child when exiting context
        if self.parent_builder:
            if self._prev_active_child_builder:
                self.parent_builder.active_child_builder = self._prev_active_child_builder
                self._prev_active_child_builder = None
            else:
                self.parent_builder.active_child_builder = None

    def __call__(self, *args: Any, **kwds: Any) -> "RouteLitBuilder":
        return self

    def get_elements(self) -> List[RouteLitElement]:
        if self.initial_fragment_id and self.elements:
            first_element_children = self.elements[0].children
            return first_element_children if first_element_children is not None else []
        return self.elements

    def get_fragments(self) -> MutableMapping[str, List[int]]:
        return self.fragments

    def on_end(self) -> None:
        self.session_state.pop("__ignore_submit", None)

    @classmethod
    def get_client_resource_paths(cls) -> List[AssetTarget]:
        static_assets_targets = []
        for c in cls.__mro__:
            if hasattr(c, "static_assets_targets") and isinstance(c.static_assets_targets, list):
                static_assets_targets.extend(c.static_assets_targets)
        # Remove duplicates while preserving order (works with unhashable types like dictionaries)
        seen = []
        result = []
        for item in static_assets_targets:
            if item not in seen:
                seen.append(item)
                result.append(item)
        return result

button(text, *, event_name='click', key=None, on_click=None, **kwargs)

Creates a button with the given text, event name, key, on click, and keyword arguments.

Parameters:

Name Type Description Default
text str

The text of the button.

required
event_name Optional[Literal['click', 'submit']]

The name of the event to listen for.

'click'
key Optional[str]

The key of the button.

None
on_click Optional[Callable[[], None]]

The function to call when the button is clicked.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the button.

{}

Returns:

Name Type Description
bool bool

Whether the button was clicked.

Example:

is_clicked = ui.button("Click me", on_click=lambda: print("Button clicked"))
if is_clicked:
    ui.text("Button clicked")
Source code in src/routelit/builder.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
def button(
    self,
    text: str,
    *,
    event_name: Literal["click", "submit"] = "click",
    key: Optional[str] = None,
    on_click: Optional[Callable[[], None]] = None,
    **kwargs: Any,
) -> bool:
    """
    Creates a button with the given text, event name, key, on click, and keyword arguments.

    Args:
        text (str): The text of the button.
        event_name (Optional[Literal["click", "submit"]]): The name of the event to listen for.
        key (Optional[str]): The key of the button.
        on_click (Optional[Callable[[], None]]): The function to call when the button is clicked.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the button.

    Returns:
        bool: Whether the button was clicked.

    Example:
    ```python
    is_clicked = ui.button("Click me", on_click=lambda: print("Button clicked"))
    if is_clicked:
        ui.text("Button clicked")
    ```
    """
    button = self._create_element(
        name="button",
        key=key or self._new_widget_id("button", text),
        props={"text": text, "eventName": event_name, **kwargs},
    )
    is_clicked, _ = self._get_event_value(button.key, event_name)
    if is_clicked and on_click:
        on_click()
    return is_clicked

checkbox(label, *, checked=False, key=None, on_change=None, **kwargs)

Creates a checkbox with the given label and value.

Parameters:

Name Type Description Default
label str

The label of the checkbox.

required
checked bool

Whether the checkbox is checked.

False
key str | None

The key of the checkbox.

None
on_change Callable[[bool], None] | None

The function to call when the value changes.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the checkbox.

{}

Returns:

Name Type Description
bool bool

Whether the checkbox is checked.

Example: ```python is_checked = ui.checkbox("Check me", on_change=lambda checked: print(f"Checkbox is {'checked' if checked else 'unchecked'}")) if is_checked: ui.text("Checkbox is checked")

Source code in src/routelit/builder.py
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
def checkbox(
    self,
    label: str,
    *,
    checked: bool = False,
    key: Optional[str] = None,
    on_change: Optional[Callable[[bool], None]] = None,
    **kwargs: Any,
) -> bool:
    """
    Creates a checkbox with the given label and value.

    Args:
        label (str): The label of the checkbox.
        checked (bool): Whether the checkbox is checked.
        key (str | None): The key of the checkbox.
        on_change (Callable[[bool], None] | None): The function to call when the value changes.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the checkbox.

    Returns:
        bool: Whether the checkbox is checked.

    Example:
    ```python
    is_checked = ui.checkbox("Check me", on_change=lambda checked: print(f"Checkbox is {'checked' if checked else 'unchecked'}"))
    if is_checked:
        ui.text("Checkbox is checked")
    """
    component_id = key or self._new_widget_id("checkbox", label)
    new_value = self.session_state.get(component_id, checked)
    if not isinstance(new_value, bool):
        new_value = bool(new_value) if new_value is not None else checked
    has_changed, event_value = self._get_event_value(component_id, "change", "checked")
    if has_changed:
        new_value = bool(event_value) if event_value is not None else False
        self.session_state[component_id] = new_value
        if on_change:
            on_change(new_value)
    self._create_element(
        name="checkbox",
        key=component_id,
        props={
            "label": label,
            "checked": new_value,
            **kwargs,
        },
    )
    return bool(new_value)

checkbox_group(label, options, *, value=None, key=None, on_change=None, flex_direction='col', **kwargs)

Creates a checkbox group with the given label and options.

Parameters:

Name Type Description Default
label str

The label of the checkbox group.

required
options List[Dict[str, Any] | str]

The options of the checkbox group.

required
value List[str | int] | None

The value of the checkbox group.

None
key str | None

The key of the checkbox group.

None
on_change Callable[[List[str | int]], None] | None

The function to call when the value changes.

None
flex_direction Literal['row', 'col']

The direction of the checkbox group: "row", "col".

'col'
kwargs Dict[str, Any]

The keyword arguments to pass to the checkbox group.

{}

Returns: List[str | int]: The value of the checkbox group.

Example:

selected_options = ui.checkbox_group("Checkbox Group", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value=["Option 1"], on_change=lambda value: print(f"Checkbox group value changed to {value}"))
ui.text(f"Selected options: {', '.join(selected_options) if selected_options else 'None'}")
Source code in src/routelit/builder.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
def checkbox_group(
    self,
    label: str,
    options: List[Union[Dict[str, Any], str]],
    *,
    value: Optional[List[Any]] = None,
    key: Optional[str] = None,
    on_change: Optional[Callable[[List[Any]], None]] = None,
    flex_direction: Literal["row", "col"] = "col",
    **kwargs: Any,
) -> List[Any]:
    """
    Creates a checkbox group with the given label and options.

    Args:
        label (str): The label of the checkbox group.
        options (List[Dict[str, Any] | str]): The options of the checkbox group.
        value (List[str | int] | None): The value of the checkbox group.
        key (str | None): The key of the checkbox group.
        on_change (Callable[[List[str | int]], None] | None): The function to call when the value changes.
        flex_direction (Literal["row", "col"]): The direction of the checkbox group: "row", "col".
        kwargs (Dict[str, Any]): The keyword arguments to pass to the checkbox group.
    Returns:
        List[str | int]: The value of the checkbox group.

    Example:
    ```python
    selected_options = ui.checkbox_group("Checkbox Group", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value=["Option 1"], on_change=lambda value: print(f"Checkbox group value changed to {value}"))
    ui.text(f"Selected options: {', '.join(selected_options) if selected_options else 'None'}")
    ```
    """
    component_id = key or self._new_widget_id("checkbox-group", label)
    new_value = self.session_state.get(component_id, value) or []
    if not isinstance(new_value, list):
        new_value = value or []
    has_changed, event_value = self._get_event_value(component_id, "change", "value")
    if has_changed:
        new_value = event_value if isinstance(event_value, list) else []
        self.session_state[component_id] = new_value
        if on_change:
            on_change(new_value)
    self._create_element(
        name="checkbox-group",
        key=component_id,
        props={
            "label": label,
            "value": new_value,
            "options": options,
            "flexDirection": flex_direction,
            **kwargs,
        },
    )
    # Ensure return type is List[str | int]
    if isinstance(new_value, list):
        return new_value
    return []

columns(spec, *, key=None, vertical_alignment='top', columns_gap='small')

Creates a flexbox layout with several columns with the given spec.

Parameters:

Name Type Description Default
spec int | List[int]

The specification of the columns. Can be an integer or a list of integers.

required
key Optional[str]

The key of the container.

None
vertical_alignment VerticalAlignment

The vertical alignment of the columns: "top", "center", "bottom".

'top'
columns_gap ColumnsGap

The gap between the columns: "none", "small", "medium", "large".

'small'

Returns:

Type Description
List[RouteLitBuilder]

List[RouteLitBuilder]: A list of builders for the columns.

Examples:

    # 2 columns with equal width
    col1, col2 = ui.columns(2)
    # usage inline
    col1.text("Column 1")
    col2.text("Column 2")
    # usage as context manager
    with col1:
        ui.text("Column 1")
    with col2:
        ui.text("Column 2")
    # usage with different widths
    col1, col2, col3 = ui.columns([2, 1, 1])
    col1.text("Column 1")
    col2.text("Column 2")
    col3.text("Column 3")
Source code in src/routelit/builder.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def columns(
    self,
    spec: Union[int, List[int]],
    *,
    key: Optional[str] = None,
    vertical_alignment: VerticalAlignment = "top",
    columns_gap: ColumnsGap = "small",
) -> List["RouteLitBuilder"]:
    """Creates a flexbox layout with several columns with the given spec.

    Args:
        spec (int | List[int]): The specification of the columns. Can be an integer or a list of integers.
        key (Optional[str]): The key of the container.
        vertical_alignment (VerticalAlignment): The vertical alignment of the columns: "top", "center", "bottom".
        columns_gap (ColumnsGap): The gap between the columns: "none", "small", "medium", "large".

    Returns:
        List[RouteLitBuilder]: A list of builders for the columns.

    Examples:
    ```python
        # 2 columns with equal width
        col1, col2 = ui.columns(2)
        # usage inline
        col1.text("Column 1")
        col2.text("Column 2")
        # usage as context manager
        with col1:
            ui.text("Column 1")
        with col2:
            ui.text("Column 2")
        # usage with different widths
        col1, col2, col3 = ui.columns([2, 1, 1])
        col1.text("Column 1")
        col2.text("Column 2")
        col3.text("Column 3")
    ```
    """
    if isinstance(spec, int):
        spec = [1] * spec
    container_key = key or self._new_text_id("container")
    container = self._create_non_widget_element(
        name="container",
        key=container_key,
        props={
            "className": "rl-flex rl-flex-row",
            "style": {
                "alignItems": verticalAlignmentMap.get(vertical_alignment, "top"),
                "columnGap": columnsGapMap.get(columns_gap, "small"),
            },
        },
    )
    container_builder = self._build_nested_builder(container)
    with container_builder:
        element_builders = []
        for column_spec in spec:
            column = self._create_non_widget_element(
                name="container",
                key=self._new_text_id("col"),
                props={"style": {"flex": column_spec}},
            )
            element_builders.append(self._build_nested_builder(column))
    return element_builders

container(key=None, height=None, **kwargs)

Creates a container component.

Parameters:

Name Type Description Default
key Optional[str]

The key of the container.

None
height Optional[str]

The height of the container.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the container.

{}

Example:

with ui.container(height="100px"):
    ui.text("Container")
Source code in src/routelit/builder.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def container(self, key: Optional[str] = None, height: Optional[str] = None, **kwargs: Any) -> "RouteLitBuilder":
    """
    Creates a container component.

    Args:
        key (Optional[str]): The key of the container.
        height (Optional[str]): The height of the container.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the container.

    Example:
    ```python
    with ui.container(height="100px"):
        ui.text("Container")
    ```
    """
    container = self._create_non_widget_element(
        name="container",
        key=key or self._new_text_id("container"),
        props={"style": {"height": height}, **kwargs},
    )
    return self._build_nested_builder(container)

expander(title, *, open=None, key=None)

Creates an expander component that can be used as both a context manager and a regular function call.

Parameters:

Name Type Description Default
title str

The title of the expander.

required
open Optional[bool]

Whether the expander is open.

None
key Optional[str]

The key of the expander.

None

Returns:

Name Type Description
RouteLitBuilder RouteLitBuilder

A builder for the expander.

Usage:
    def build_index_view(ui: RouteLitBuilder):
        # Context manager style
        with ui.expander("Title"):
            ui.text("Content")

        with ui.expander("Title", open=True) as exp0:
            exp0.text("Content")

        # Function call style
        exp = ui.expander("Title")
        exp.text("Content")
Source code in src/routelit/builder.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def expander(self, title: str, *, open: Optional[bool] = None, key: Optional[str] = None) -> "RouteLitBuilder":
    """
    Creates an expander component that can be used as both a context manager and a regular function call.

    Args:
        title (str): The title of the expander.
        open (Optional[bool]): Whether the expander is open.
        key (Optional[str]): The key of the expander.

    Returns:
        RouteLitBuilder: A builder for the expander.
    ```python
    Usage:
        def build_index_view(ui: RouteLitBuilder):
            # Context manager style
            with ui.expander("Title"):
                ui.text("Content")

            with ui.expander("Title", open=True) as exp0:
                exp0.text("Content")

            # Function call style
            exp = ui.expander("Title")
            exp.text("Content")
    ```
    """
    new_key = key or self._new_widget_id("expander", title)
    new_element = self._create_element(
        name="expander",
        key=new_key,
        props={"title": title, "open": open},
    )
    return self._build_nested_builder(new_element)

flex(direction='col', wrap='nowrap', justify_content='start', align_items='normal', align_content='normal', gap=None, key=None, **kwargs)

Creates a flex container with the given direction, wrap, justify content, align items, align content, gap, and key.

Source code in src/routelit/builder.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def flex(
    self,
    direction: Literal["row", "col"] = "col",
    wrap: Literal["wrap", "nowrap"] = "nowrap",
    justify_content: Literal["start", "end", "center", "between", "around", "evenly"] = "start",
    align_items: Literal["normal", "start", "end", "center", "baseline", "stretch"] = "normal",
    align_content: Literal["normal", "start", "end", "center", "between", "around", "evenly"] = "normal",
    gap: Optional[str] = None,
    key: Optional[str] = None,
    **kwargs: Any,
) -> "RouteLitBuilder":
    """
    Creates a flex container with the given direction, wrap, justify content, align items, align content, gap, and key.
    """
    container = self._create_non_widget_element(
        name="flex",
        key=key or self._new_text_id("flex"),
        props={
            "direction": direction,
            "flexWrap": wrap,
            "justifyContent": justify_content,
            "alignItems": align_items,
            "alignContent": align_content,
            "gap": gap,
            **kwargs,
        },
    )
    return self._build_nested_builder(container)

form(key)

Creates a form area that do not submit input values to the server until the form is submitted. Use button(..., event_name="submit") to submit the form.

Parameters:

Name Type Description Default
key str

The key of the form.

required

Returns:

Name Type Description
RouteLitBuilder RouteLitBuilder

A builder for the form.

Example:

with ui.form("login"):
    username = ui.text_input("Username")
    password = ui.text_input("Password", type="password")
    is_submitted = ui.button("Login", event_name="submit")
    if is_submitted:
        ui.text(f"Login successful for {username}")
Source code in src/routelit/builder.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def form(self, key: str) -> "RouteLitBuilder":
    """
    Creates a form area that do not submit input values to the server until the form is submitted.
    Use button(..., event_name="submit") to submit the form.

    Args:
        key (str): The key of the form.

    Returns:
        RouteLitBuilder: A builder for the form.

    Example:
    ```python
    with ui.form("login"):
        username = ui.text_input("Username")
        password = ui.text_input("Password", type="password")
        is_submitted = ui.button("Login", event_name="submit")
        if is_submitted:
            ui.text(f"Login successful for {username}")
    ```
    """
    form = self._create_non_widget_element(
        name="form",
        key=key,
        props={"id": key},
    )
    return self._build_nested_builder(form)

header(body, key=None, **kwargs)

Creates a header component.

Parameters:

Name Type Description Default
body str

The body of the header.

required
key Optional[str]

The key of the header.

None

Example:

ui.header("Header")
Source code in src/routelit/builder.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
def header(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
    """
    Creates a header component.

    Args:
        body (str): The body of the header.
        key (Optional[str]): The key of the header.

    Example:
    ```python
    ui.header("Header")
    ```
    """
    self._create_non_widget_element(
        name="header",
        key=key or self._new_text_id("header"),
        props={"body": body, **kwargs},
    )

image(src, *, key=None, **kwargs)

Creates an image component.

Parameters:

Name Type Description Default
src str

The source of the image.

required
key Optional[str]

The key of the image.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the image.

{}

Example:

ui.image("https://www.google.com/favicon.ico", alt="Google", width="24px", height="24px")
Source code in src/routelit/builder.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
def image(self, src: str, *, key: Optional[str] = None, **kwargs: Any) -> None:
    """
    Creates an image component.

    Args:
        src (str): The source of the image.
        key (Optional[str]): The key of the image.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the image.

    Example:
    ```python
    ui.image("https://www.google.com/favicon.ico", alt="Google", width="24px", height="24px")
    ```
    """
    self._create_non_widget_element(
        name="image",
        key=key or self._new_text_id("image"),
        props={"src": src, **kwargs},
    )

Creates a link component. Use this to navigate to a different page.

Parameters:

Name Type Description Default
href str

The href of the link.

required
text str

The text of the link.

''
replace bool

Whether to replace the current page from the history.

False
is_external bool

Whether the link is external to the current app.

False
key Optional[str]

The key of the link.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the link.

{}

Example:

ui.link("/signup", text="Signup")
ui.link("/login", text="Login", replace=True)
ui.link("https://www.google.com", text="Google", is_external=True)
Source code in src/routelit/builder.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def link(
    self,
    href: str,
    text: str = "",
    replace: bool = False,
    is_external: bool = False,
    key: Optional[str] = None,
    **kwargs: Any,
) -> RouteLitElement:
    """
    Creates a link component. Use this to navigate to a different page.

    Args:
        href (str): The href of the link.
        text (str): The text of the link.
        replace (bool): Whether to replace the current page from the history.
        is_external (bool): Whether the link is external to the current app.
        key (Optional[str]): The key of the link.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the link.

    Example:
    ```python
    ui.link("/signup", text="Signup")
    ui.link("/login", text="Login", replace=True)
    ui.link("https://www.google.com", text="Google", is_external=True)
    ```
    """
    new_element = self._create_non_widget_element(
        name="link",
        key=key or self._new_text_id("link"),
        props={
            "href": href,
            "replace": replace,
            "isExternal": is_external,
            "text": text,
            **kwargs,
        },
    )
    return new_element

Creates a link area component. Use this element which is a container of other elements.

Parameters:

Name Type Description Default
href str

The href of the link.

required
replace bool

Whether to replace the current page.

False
is_external bool

Whether the link is external.

False
key Optional[str]

The key of the link area.

None
className Optional[str]

The class name of the link area.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the link area.

{}

Example:

with ui.link_area("https://www.google.com"):
    with ui.flex(direction="row", gap="small"):
        ui.image("https://www.google.com/favicon.ico", width="24px", height="24px")
        ui.text("Google")
Source code in src/routelit/builder.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def link_area(
    self,
    href: str,
    replace: bool = False,
    is_external: bool = False,
    key: Optional[str] = None,
    className: Optional[str] = None,
    **kwargs: Any,
) -> "RouteLitBuilder":
    """
    Creates a link area component. Use this element which is a container of other elements.

    Args:
        href (str): The href of the link.
        replace (bool): Whether to replace the current page.
        is_external (bool): Whether the link is external.
        key (Optional[str]): The key of the link area.
        className (Optional[str]): The class name of the link area.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the link area.

    Example:
    ```python
    with ui.link_area("https://www.google.com"):
        with ui.flex(direction="row", gap="small"):
            ui.image("https://www.google.com/favicon.ico", width="24px", height="24px")
            ui.text("Google")
    ```
    """
    link_element = self.link(
        href,
        replace=replace,
        is_external=is_external,
        key=key,
        className=f"rl-no-link-decoration {className or ''}",
        **kwargs,
    )
    return self._build_nested_builder(link_element)

markdown(body, *, allow_unsafe_html=False, key=None, **kwargs)

Creates a markdown component.

Parameters:

Name Type Description Default
body str

The body of the markdown.

required
allow_unsafe_html bool

Whether to allow unsafe HTML.

False
key Optional[str]

The key of the markdown.

None

Example:

ui.markdown("**Bold** *italic* [link](https://www.google.com)")
Source code in src/routelit/builder.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def markdown(
    self,
    body: str,
    *,
    allow_unsafe_html: bool = False,
    key: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """
    Creates a markdown component.

    Args:
        body (str): The body of the markdown.
        allow_unsafe_html (bool): Whether to allow unsafe HTML.
        key (Optional[str]): The key of the markdown.

    Example:
    ```python
    ui.markdown("**Bold** *italic* [link](https://www.google.com)")
    ```
    """
    self._create_non_widget_element(
        name="markdown",
        key=key or self._new_text_id("markdown"),
        props={"body": body, "allowUnsafeHtml": allow_unsafe_html, **kwargs},
    )

radio(label, options, *, value=None, key=None, on_change=None, flex_direction='col', **kwargs)

Creates a radio group with the given label and options.

Parameters:

Name Type Description Default
label str

The label of the radio group.

required
options List[Dict[str, Any] | str]

The options of the radio group. Each option can be a string or a dictionary with the following keys: - label: The label of the option. - value: The value of the option. - caption: The caption of the option. - disabled: Whether the option is disabled.

required
value str | int | None

The value of the radio group.

None
key str | None

The key of the radio group.

None
on_change Callable[[str | int | None], None] | None

The function to call when the value changes. The function will be called with the new value.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the radio group.

{}

Returns: str | int | None: The value of the selected radio option.

Example:

value = ui.radio("Radio", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value="Option 1", on_change=lambda value: print(f"Radio value changed to {value}"))
ui.text(f"Radio value is {value}")
Source code in src/routelit/builder.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
def radio(
    self,
    label: str,
    options: List[Union[Dict[str, Any], str]],
    *,
    value: Optional[Any] = None,
    key: Optional[str] = None,
    on_change: Optional[Callable[[Any], None]] = None,
    flex_direction: Literal["row", "col"] = "col",
    **kwargs: Any,
) -> Any:
    """
    Creates a radio group with the given label and options.

    Args:
        label (str): The label of the radio group.
        options (List[Dict[str, Any] | str]): The options of the radio group. Each option can be a string or a dictionary with the following keys:
            - label: The label of the option.
            - value: The value of the option.
            - caption: The caption of the option.
            - disabled: Whether the option is disabled.
        value (str | int | None): The value of the radio group.
        key (str | None): The key of the radio group.
        on_change (Callable[[str | int | None], None] | None): The function to call when the value changes. The function will be called with the new value.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the radio group.
    Returns:
        str | int | None: The value of the selected radio option.

    Example:
    ```python
    value = ui.radio("Radio", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value="Option 1", on_change=lambda value: print(f"Radio value changed to {value}"))
    ui.text(f"Radio value is {value}")
    ```
    """
    return self._x_radio_select(
        "radio",
        label,
        options,
        value,
        key,
        on_change,
        flexDirection=flex_direction,
        **kwargs,
    )

rerun(scope='auto', clear_event=True)

Reruns the current page. Use this to rerun the app or the fragment depending on the context.

Parameters:

Name Type Description Default
scope RerunType

The scope of the rerun. "auto" will rerun the app or the fragment depending on the context, "app" will rerun the entire app

'auto'
clear_event bool

Whether to clear the event.

True

Example:

counter = ui.session_state.get("counter", 0)
ui.text(f"Counter is {counter}")
should_increase = ui.button("Increment")
if should_increase:
    ui.session_state["counter"] = counter + 1
    ui.rerun()
Source code in src/routelit/builder.py
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
def rerun(self, scope: RerunType = "auto", clear_event: bool = True) -> None:
    """
    Reruns the current page. Use this to rerun the app or the fragment depending on the context.

    Args:
        scope (RerunType): The scope of the rerun. "auto" will rerun the app or the fragment depending on the context, "app" will rerun the entire app
        clear_event (bool): Whether to clear the event.

    Example:
    ```python
    counter = ui.session_state.get("counter", 0)
    ui.text(f"Counter is {counter}")
    should_increase = ui.button("Increment")
    if should_increase:
        ui.session_state["counter"] = counter + 1
        ui.rerun()
    ```
    """
    self.elements.clear()
    if clear_event:
        self.request.clear_event()
    if scope == "app":
        self.request.clear_fragment_id()
    raise RerunException(self.session_state.get_data(), scope=scope)

select(label, options, *, value='', key=None, on_change=None, **kwargs)

Creates a select dropdown with the given label and options.

Parameters:

Name Type Description Default
label str

The label of the select dropdown.

required
options List[Dict[str, Any] | str]

The options of the select dropdown. Each option can be a string or a dictionary with the following keys: (label, value, disabled) - label: The label of the option. - value: The value of the option. - disabled: Whether the option is disabled.

required
value str | int

The value of the select dropdown.

''
key str | None

The key of the select dropdown.

None
on_change Callable[[str | int | None], None] | None

The function to call when the value changes. The function will be called with the new value.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the select dropdown.

{}

Returns:

Name Type Description
Any Any

The value of the select dropdown.

Example:

value = ui.select("Select", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value="Option 1", on_change=lambda value: print(f"Select value changed to {value}"))
ui.text(f"Select value is {value}")
Source code in src/routelit/builder.py
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
def select(
    self,
    label: str,
    options: List[Union[Dict[str, Any], str]],
    *,
    value: Any = "",
    key: Optional[str] = None,
    on_change: Optional[Callable[[Any], None]] = None,
    **kwargs: Any,
) -> Any:
    """
    Creates a select dropdown with the given label and options.

    Args:
        label (str): The label of the select dropdown.
        options (List[Dict[str, Any] | str]): The options of the select dropdown. Each option can be a string or a dictionary with the following keys: (label, value, disabled)
            - label: The label of the option.
            - value: The value of the option.
            - disabled: Whether the option is disabled.
        value (str | int): The value of the select dropdown.
        key (str | None): The key of the select dropdown.
        on_change (Callable[[str | int | None], None] | None): The function to call when the value changes. The function will be called with the new value.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the select dropdown.

    Returns:
        Any: The value of the select dropdown.

    Example:
    ```python
    value = ui.select("Select", options=["Option 1", {"label": "Option 2", "value": "option2"}, {"label": "Option 3", "value": "option3", "disabled": True}], value="Option 1", on_change=lambda value: print(f"Select value changed to {value}"))
    ui.text(f"Select value is {value}")
    ```
    """
    return self._x_radio_select("select", label, options, value, key, on_change, **kwargs)

set_page_config(page_title=None, page_description=None)

Sets the page title and description.

Parameters:

Name Type Description Default
page_title str | None

The title of the page.

None
page_description str | None

The description of the page.

None
Source code in src/routelit/builder.py
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
def set_page_config(self, page_title: Optional[str] = None, page_description: Optional[str] = None) -> None:
    """
    Sets the page title and description.

    Args:
        page_title (str | None): The title of the page.
        page_description (str | None): The description of the page.
    """
    self.head = Head(title=page_title, description=page_description)
    self._create_non_widget_element(
        name="head",
        key="__head__",
        props={
            "title": page_title,
            "description": page_description,
        },
    )

subheader(body, key=None, **kwargs)

Creates a subheader component.

Parameters:

Name Type Description Default
body str

The body of the subheader.

required
key Optional[str]

The key of the subheader.

None

Example:

ui.subheader("Subheader")
Source code in src/routelit/builder.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def subheader(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
    """
    Creates a subheader component.

    Args:
        body (str): The body of the subheader.
        key (Optional[str]): The key of the subheader.

    Example:
    ```python
    ui.subheader("Subheader")
    ```
    """
    self._create_non_widget_element(
        name="subheader",
        key=key or self._new_text_id("subheader"),
        props={"body": body, **kwargs},
    )

text(body, key=None, **kwargs)

Creates a text component.

Parameters:

Name Type Description Default
body str

The body of the text.

required
key Optional[str]

The key of the text.

None

Example:

ui.text("Text")
Source code in src/routelit/builder.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def text(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
    """
    Creates a text component.

    Args:
        body (str): The body of the text.
        key (Optional[str]): The key of the text.

    Example:
    ```python
    ui.text("Text")
    ```
    """
    self.markdown(body, allow_unsafe_html=False, key=key, **kwargs)

text_input(label, *, type='text', value=None, key=None, on_change=None, **kwargs)

Creates a text input with the given label and value.

Parameters:

Name Type Description Default
label str

The label of the text input.

required
type TextInputType

The type of the text input.

'text'
value Optional[str]

The value of the text input.

None
key Optional[str]

The key of the text input.

None
on_change Optional[Callable[[str], None]]

The function to call when the value changes. The function will be called with the new value.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the text input.

{}

Returns:

Name Type Description
str str

The text value of the text input.

Example:

name = ui.text_input("Name", value="John", on_change=lambda value: print(f"Name changed to {value}"))
ui.text(f"Name is {name}")
Source code in src/routelit/builder.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def text_input(
    self,
    label: str,
    *,
    type: TextInputType = "text",
    value: Optional[str] = None,
    key: Optional[str] = None,
    on_change: Optional[Callable[[str], None]] = None,
    **kwargs: Any,
) -> str:
    """
    Creates a text input with the given label and value.

    Args:
        label (str): The label of the text input.
        type (TextInputType): The type of the text input.
        value (Optional[str]): The value of the text input.
        key (Optional[str]): The key of the text input.
        on_change (Optional[Callable[[str], None]]): The function to call when the value changes. The function will be called with the new value.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the text input.

    Returns:
        str: The text value of the text input.

    Example:
    ```python
    name = ui.text_input("Name", value="John", on_change=lambda value: print(f"Name changed to {value}"))
    ui.text(f"Name is {name}")
    ```
    """
    return self._x_input("text-input", label, value, key, on_change, type=type, **kwargs)

textarea(label, *, value=None, key=None, on_change=None, **kwargs)

Creates a textarea with the given label and value.

Parameters:

Name Type Description Default
label str

The label of the textarea.

required
value Optional[str]

The value of the textarea.

None
key Optional[str]

The key of the textarea.

None
on_change Optional[Callable[[str], None]]

The function to call when the value changes. The function will be called with the new value.

None
kwargs Dict[str, Any]

The keyword arguments to pass to the textarea.

{}

Returns:

Name Type Description
str str

The text value of the textarea.

Example:

text = ui.textarea("Text", value="Hello, world!", on_change=lambda value: print(f"Text changed to {value}"))
ui.text(f"Text is {text}")
Source code in src/routelit/builder.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def textarea(
    self,
    label: str,
    *,
    value: Optional[str] = None,
    key: Optional[str] = None,
    on_change: Optional[Callable[[str], None]] = None,
    **kwargs: Any,
) -> str:
    """
    Creates a textarea with the given label and value.

    Args:
        label (str): The label of the textarea.
        value (Optional[str]): The value of the textarea.
        key (Optional[str]): The key of the textarea.
        on_change (Optional[Callable[[str], None]]): The function to call when the value changes. The function will be called with the new value.
        kwargs (Dict[str, Any]): The keyword arguments to pass to the textarea.

    Returns:
        str: The text value of the textarea.

    Example:
    ```python
    text = ui.textarea("Text", value="Hello, world!", on_change=lambda value: print(f"Text changed to {value}"))
    ui.text(f"Text is {text}")
    ```
    """
    return self._x_input("textarea", label, value, key, on_change, **kwargs)

title(body, key=None, **kwargs)

Creates a title component.

Parameters:

Name Type Description Default
body str

The body of the title.

required
key Optional[str]

The key of the title.

None

Example:

ui.title("Title")
Source code in src/routelit/builder.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def title(self, body: str, key: Optional[str] = None, **kwargs: Any) -> None:
    """
    Creates a title component.

    Args:
        body (str): The body of the title.
        key (Optional[str]): The key of the title.

    Example:
    ```python
    ui.title("Title")
    ```
    """
    self._create_non_widget_element(
        name="title",
        key=key or self._new_text_id("title"),
        props={"body": body, **kwargs},
    )

Domain Module

COOKIE_SESSION_KEY = 'ROUTELIT_SESSION_ID' module-attribute

The key of the session id in the cookie.

RerunType = Literal['auto', 'app'] module-attribute

"auto" will rerun the fragment if it is called from a fragment otherwise it will rerun the app. "app" will rerun the app.

Action dataclass

Source code in src/routelit/domain.py
74
75
76
77
78
79
80
@dataclass
class Action:
    address: List[int]
    """
      (List[int]) The address is the list of indices to the array tree of elements in the session state
      from the root to the target element.
    """

address instance-attribute

(List[int]) The address is the list of indices to the array tree of elements in the session state from the root to the target element.

ActionsResponse dataclass

The actions to be executed by the RouteLit app.

Source code in src/routelit/domain.py
115
116
117
118
119
120
121
122
@dataclass
class ActionsResponse:
    """
    The actions to be executed by the RouteLit app.
    """

    actions: List[Action]
    target: Literal["app", "fragment"]

AddAction dataclass

Bases: Action

The action to add an element.

Source code in src/routelit/domain.py
83
84
85
86
87
88
89
90
91
@dataclass
class AddAction(Action):
    """
    The action to add an element.
    """

    element: RouteLitElement
    key: str
    type: Literal["add"] = "add"

PropertyDict

A dictionary that can be accessed as attributes. Example:

session_state = PropertyDict({"name": "John"})
print(session_state.name)  # "John"
print(session_state["name"])  # "John"
session_state.name = "Jane"
print(session_state.name)  # "Jane"
print(session_state["name"])  # "Jane"
del session_state.name
print(session_state.name)  # None
print(session_state["name"])  # None
Source code in src/routelit/domain.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class PropertyDict:
    """
    A dictionary that can be accessed as attributes.
    Example:
    ```python
    session_state = PropertyDict({"name": "John"})
    print(session_state.name)  # "John"
    print(session_state["name"])  # "John"
    session_state.name = "Jane"
    print(session_state.name)  # "Jane"
    print(session_state["name"])  # "Jane"
    del session_state.name
    print(session_state.name)  # None
    print(session_state["name"])  # None
    ```
    """

    def __init__(self, initial_dict: Optional[MutableMapping[str, Any]] = None):
        self._data = initial_dict or {}

    def __getattr__(self, name: str) -> Any:
        try:
            return self._data[name]
        except KeyError:
            return None

    def __setattr__(self, name: str, value: Any) -> None:
        if name.startswith("_"):
            super().__setattr__(name, value)
        else:
            self._data[name] = value

    def __repr__(self) -> str:
        return f"PropertyDict({self._data!r})"

    def __str__(self) -> str:
        return str(self._data)

    def __getitem__(self, key: str) -> Any:
        return self._data[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self._data[key] = value

    def __delitem__(self, key: str) -> None:
        del self._data[key]

    def __iter__(self) -> Iterator[str]:
        return iter(self._data)

    def __len__(self) -> int:
        return len(self._data)

    def __contains__(self, key: str) -> bool:
        return key in self._data

    def pop(self, key: str, *args: Any) -> Any:
        return self._data.pop(key, *args)

    def get(self, key: str, default: Any = None) -> Any:
        return self._data.get(key, default)

    def get_data(self) -> MutableMapping[str, Any]:
        return self._data

RemoveAction dataclass

Bases: Action

The action to remove an element.

Source code in src/routelit/domain.py
 94
 95
 96
 97
 98
 99
100
101
@dataclass
class RemoveAction(Action):
    """
    The action to remove an element.
    """

    key: str
    type: Literal["remove"] = "remove"

RouteLitElement dataclass

The element to be rendered by the RouteLit app.

Source code in src/routelit/domain.py
61
62
63
64
65
66
67
68
69
70
71
@dataclass
class RouteLitElement:
    """
    The element to be rendered by the RouteLit app.
    """

    name: str
    props: Dict[str, Any]
    key: str
    children: Optional[List["RouteLitElement"]] = None
    address: Optional[List[int]] = None

RouteLitEvent

Bases: TypedDict

The event to be executed by the RouteLit app.

Source code in src/routelit/domain.py
31
32
33
34
35
36
37
38
39
class RouteLitEvent(TypedDict):
    """
    The event to be executed by the RouteLit app.
    """

    type: Literal["click", "changed", "navigate"]
    componentId: str
    data: Dict[str, Any]
    formId: Optional[str]

RouteLitRequest

Bases: ABC

The request class for the RouteLit app. This class should be implemented by the web framework you want to integrate with.

Source code in src/routelit/domain.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class RouteLitRequest(ABC):
    """
    The request class for the RouteLit app.
    This class should be implemented by the web framework you want to integrate with.
    """

    def __init__(self) -> None:
        self._ui_event = self._get_ui_event()
        self._fragment_id = self._get_fragment_id()

    @abstractmethod
    def get_headers(self) -> Dict[str, str]:
        pass

    @abstractmethod
    def get_path_params(self) -> Optional[Mapping[str, Any]]:
        pass

    @abstractmethod
    def get_referrer(self) -> Optional[str]:
        pass

    @abstractmethod
    def is_json(self) -> bool:
        pass

    @abstractmethod
    def get_json(self) -> Optional[Dict[str, Any]]:
        pass

    def _get_internal_referrer(self) -> Optional[str]:
        return self.get_headers().get("X-Referer") or self.get_referrer()

    def _get_ui_event(self) -> Optional[RouteLitEvent]:
        if self.is_json() and (json_data := self.get_json()) and isinstance(json_data, dict):
            return json_data.get("uiEvent")
        else:
            return None

    @property
    def ui_event(self) -> Optional[RouteLitEvent]:
        return self._ui_event

    def clear_event(self) -> None:
        self._ui_event = None

    @abstractmethod
    def get_query_param(self, key: str) -> Optional[str]:
        pass

    @abstractmethod
    def get_query_param_list(self, key: str) -> List[str]:
        pass

    @abstractmethod
    def get_session_id(self) -> str:
        pass

    @abstractmethod
    def get_pathname(self) -> str:
        pass

    @abstractmethod
    def get_host(self) -> str:
        pass

    @property
    @abstractmethod
    def method(self) -> str:
        pass

    def clear_fragment_id(self) -> None:
        self._fragment_id = None

    def _get_fragment_id(self) -> Optional[str]:
        if not self.is_json():
            return None
        json_data = self.get_json()
        if isinstance(json_data, dict):
            return json_data.get("fragmentId")
        return None

    @property
    def fragment_id(self) -> Optional[str]:
        return self._fragment_id

    def get_host_pathname(self, use_referer: bool = False) -> str:
        if use_referer:
            referrer = self._get_internal_referrer()
            if referrer:
                url = urlparse(referrer)
                if url.netloc and url.path:
                    return url.netloc + url.path
        return self.get_host() + self.get_pathname()

    def get_ui_session_keys(self, use_referer: bool = False) -> Tuple[str, str]:
        session_id = self.get_session_id()
        host_pathname = self.get_host_pathname(use_referer)
        # fragment_id = self.get_fragment_id()
        ui_session_key = f"{session_id}:{host_pathname}"
        session_state_key = f"{session_id}:{host_pathname}:state"
        return ui_session_key, session_state_key

    def get_session_keys(self, use_referer: bool = False) -> SessionKeys:
        session_id = self.get_session_id()
        host_pathname = self.get_host_pathname(use_referer)
        ui_session_key = f"{session_id}:{host_pathname}:ui"
        session_state_key = f"{session_id}:{host_pathname}:state"
        fragment_addresses_key = f"{ui_session_key}:fragments"
        fragment_params_key = f"{ui_session_key}:fragment_params"
        return SessionKeys(
            ui_session_key,
            session_state_key,
            fragment_addresses_key,
            fragment_params_key,
        )

SessionKeys

Bases: NamedTuple

The keys to the session state of the RouteLit app.

Source code in src/routelit/domain.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class SessionKeys(NamedTuple):
    """
    The keys to the session state of the RouteLit app.
    """

    ui_key: str
    state_key: str
    fragment_addresses_key: str
    """
      Key to the addresses of the fragments in the session state.
      The address is a List of indices to the array tree of elements in the session state
      from the root to the target element.
    """
    fragment_params_key: str
    """
      Key to the parameters of the fragments in the session state.
    """

fragment_addresses_key instance-attribute

Key to the addresses of the fragments in the session state. The address is a List of indices to the array tree of elements in the session state from the root to the target element.

fragment_params_key instance-attribute

Key to the parameters of the fragments in the session state.

UpdateAction dataclass

Bases: Action

The action to update the props of an element.

Source code in src/routelit/domain.py
104
105
106
107
108
109
110
111
112
@dataclass
class UpdateAction(Action):
    """
    The action to update the props of an element.
    """

    props: Dict[str, Any]
    key: str
    type: Literal["update"] = "update"