-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtemplates.py
More file actions
871 lines (718 loc) ยท 25.9 KB
/
Copy pathtemplates.py
File metadata and controls
871 lines (718 loc) ยท 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
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
"""Templates to use in the reflex compiler."""
from __future__ import annotations
import json
import re
from collections.abc import Iterable, Mapping
from typing import TYPE_CHECKING, Any, Literal
from reflex_base import constants
from reflex_base.constants import Hooks
from reflex_base.utils import memo_paths
from reflex_base.utils.format import format_state_name, json_dumps
from reflex_base.vars.base import VarData
if TYPE_CHECKING:
from reflex.compiler.utils import _ImportDict
from reflex_base.components.component import Component
def _sort_hooks(
hooks: dict[str, VarData | None],
) -> tuple[list[str], list[str], list[str]]:
"""Sort the hooks by their position.
Args:
hooks: The hooks to sort.
Returns:
The sorted hooks.
"""
internal_hooks = []
pre_trigger_hooks = []
post_trigger_hooks = []
for hook, data in hooks.items():
if data and data.position and data.position == Hooks.HookPosition.INTERNAL:
internal_hooks.append(hook)
elif not data or (
not data.position
or data.position == constants.Hooks.HookPosition.PRE_TRIGGER
):
pre_trigger_hooks.append(hook)
elif (
data
and data.position
and data.position == constants.Hooks.HookPosition.POST_TRIGGER
):
post_trigger_hooks.append(hook)
return internal_hooks, pre_trigger_hooks, post_trigger_hooks
class _RenderUtils:
@staticmethod
def render(component: Mapping[str, Any] | str) -> str:
if isinstance(component, str):
return component or "null"
if "iterable" in component:
return _RenderUtils.render_iterable_tag(component)
if "match_cases" in component:
return _RenderUtils.render_match_tag(component)
if "cond_state" in component:
return _RenderUtils.render_condition_tag(component)
if (contents := component.get("contents")) is not None:
return contents or "null"
return _RenderUtils.render_tag(component)
@staticmethod
def render_tag(component: Mapping[str, Any]) -> str:
name = component.get("name") or "Fragment"
props = f"{{{','.join(component['props'])}}}"
rendered_children = [
_RenderUtils.render(child)
for child in component.get("children", [])
if child
]
return f"jsx({name},{props},{','.join(rendered_children)})"
@staticmethod
def render_condition_tag(component: Any) -> str:
return f"({component['cond_state']}?({_RenderUtils.render(component['true_value'])}):({_RenderUtils.render(component['false_value'])}))"
@staticmethod
def render_iterable_tag(component: Any) -> str:
children_rendered = "".join([
_RenderUtils.render(child) for child in component.get("children", [])
])
return f"Array.prototype.map.call({component['iterable_state']} ?? [],(({component['arg_name']},{component['arg_index']})=>({children_rendered})))"
@staticmethod
def render_match_tag(component: Any) -> str:
cases_code = ""
for conditions, return_value in component["match_cases"]:
for condition in conditions:
cases_code += f" case JSON.stringify({condition}):\n"
cases_code += f""" return {_RenderUtils.render(return_value)};
break;
"""
return f"""(() => {{
switch (JSON.stringify({component["cond"]})) {{
{cases_code} default:
return {_RenderUtils.render(component["default"])};
break;
}}
}})()"""
@staticmethod
def get_import(module: _ImportDict) -> str:
default_import = module["default"]
rest_imports = module["rest"]
if default_import and rest_imports:
rest_imports_str = ",".join(sorted(rest_imports))
return f'import {default_import}, {{{rest_imports_str}}} from "{module["lib"]}"'
if default_import:
return f'import {default_import} from "{module["lib"]}"'
if rest_imports:
rest_imports_str = ",".join(sorted(rest_imports))
return f'import {{{rest_imports_str}}} from "{module["lib"]}"'
return f'import "{module["lib"]}"'
def rxconfig_template(app_name: str):
"""Template for the Reflex config file.
Args:
app_name: The name of the application.
Returns:
Rendered Reflex config file content as string.
"""
return f"""import reflex as rx
config = rx.Config(
app_name="{app_name}",
plugins=[
rx.plugins.SitemapPlugin(),
rx.plugins.TailwindV4Plugin(),
rx.plugins.RadixThemesPlugin(),
]
)"""
def document_root_template(*, imports: list[_ImportDict], document: dict[str, Any]):
"""Template for the document root.
Args:
imports: List of import statements.
document: Document root component.
Returns:
Rendered document root code as string.
"""
imports_rendered = "\n".join([_RenderUtils.get_import(mod) for mod in imports])
return f"""{imports_rendered}
export function Layout({{children}}) {{
return (
{_RenderUtils.render(document)}
)
}}"""
def app_root_template(
*,
imports: list[_ImportDict],
custom_codes: Iterable[str],
hooks: dict[str, VarData | None],
window_libraries: list[tuple[str, str]],
render: dict[str, Any],
dynamic_imports: set[str],
hydrate_fallback_export: str | None = None,
):
"""Template for the App root.
Args:
imports: The list of import statements.
custom_codes: The set of custom code snippets.
hooks: The dictionary of hooks.
window_libraries: The list of window libraries.
render: The dictionary of render functions.
dynamic_imports: The set of dynamic imports.
hydrate_fallback_export: The exported name of the hydrate-fallback memo module to re-export as ``HydrateFallback``, or None for no fallback.
Returns:
Rendered App root component as string.
"""
imports_str = "\n".join([_RenderUtils.get_import(mod) for mod in imports])
dynamic_imports_str = "\n".join(dynamic_imports)
hydrate_fallback_str = ""
if hydrate_fallback_export is not None:
hydrate_fallback_str = (
f"export {{ {hydrate_fallback_export} as HydrateFallback }} "
f'from "{memo_paths.unmirrored_library_specifier(hydrate_fallback_export)}";'
)
custom_code_str = "\n".join(custom_codes)
import_window_libraries = "\n".join([
f'import * as {lib_alias} from "{lib_path}";'
for lib_alias, lib_path in window_libraries
])
window_imports_str = "\n".join([
f' "{lib_path}": {lib_alias},' for lib_alias, lib_path in window_libraries
])
return f"""
{imports_str}
{dynamic_imports_str}
import {{ defaultColorMode }} from "$/utils/context";
import {{ ThemeProvider }} from '$/utils/react-theme';
import {{ Layout as AppLayout }} from './_document';
import {{ Outlet }} from 'react-router';
{import_window_libraries}
{custom_code_str}
function ReflexProviders({{children}}) {{
useEffect(() => {{
// Make contexts and state objects available globally for dynamic eval'd components
let windowImports = {{
{window_imports_str}
}};
window["__reflex"] = windowImports;
}}, []);
return jsx(ThemeProvider, {{defaultTheme: defaultColorMode, attribute: "class"}},
jsx(AppWrap, {{}}, children)
);
}}
function AppWrap({{children}}) {{
{_render_hooks(hooks)}
return ({_RenderUtils.render(render)})
}}
export function Layout({{children}}) {{
return jsx(AppLayout, {{}}, jsx(ReflexProviders, {{}}, children));
}}
// Used by entry.client.js when mount_target is configured: skips the document
// shell (which renders react-router's <Meta>/<Scripts>/<Links> and requires a
// framework router context) but keeps the runtime providers.
export function EmbedLayout({{children}}) {{
return jsx(ReflexProviders, {{}}, children);
}}
export default function App() {{
return jsx(Outlet, {{}});
}}
{hydrate_fallback_str}
"""
def theme_template(theme: str):
"""Template for the theme file.
Args:
theme: The theme to render.
Returns:
Rendered theme file content as string.
"""
return f"""export default {theme}"""
def context_template(
*,
is_dev_mode: bool,
default_color_mode: str,
initial_state: dict[str, Any] | None = None,
state_name: str | None = None,
client_storage: dict[str, dict[str, dict[str, Any]]] | None = None,
):
"""Template for the context file.
Args:
initial_state: The initial state for the context.
state_name: The name of the state.
client_storage: The client storage for the context.
is_dev_mode: Whether the app is in development mode.
default_color_mode: The default color mode for the context.
Returns:
Rendered context file content as string.
"""
initial_state = initial_state or {}
state_contexts_str = "".join([
f"{format_state_name(state_name)}: createContext(null),"
for state_name in initial_state
])
state_str = (
rf"""
export const state_name = "{state_name}"
export const exception_state_name = "{constants.CompileVars.FRONTEND_EXCEPTION_STATE_FULL}"
// These events are triggered on initial load and each page navigation.
export const onLoadInternalEvent = () => {{
const internal_events = [];
// Get tracked cookie and local storage vars to send to the backend.
const client_storage_vars = hydrateClientStorage(clientStorage);
// But only send the vars if any are actually set in the browser.
if (client_storage_vars && Object.keys(client_storage_vars).length !== 0) {{
internal_events.push(
ReflexEvent(
'{state_name}.{constants.CompileVars.UPDATE_VARS_INTERNAL}',
{{vars: client_storage_vars}},
),
);
}}
// `on_load_internal` triggers the correct on_load event(s) for the current page.
// If the page does not define any on_load event, this will just set `is_hydrated = true`.
internal_events.push(ReflexEvent('{state_name}.{constants.CompileVars.ON_LOAD_INTERNAL}'));
return internal_events;
}}
// The following events are sent when the websocket connects or reconnects.
export const initialEvents = () => [
ReflexEvent('{state_name}.{constants.CompileVars.HYDRATE}'),
...onLoadInternalEvent()
]
"""
if state_name
else """
export const state_name = undefined
export const exception_state_name = undefined
export const onLoadInternalEvent = () => []
export const initialEvents = () => []
"""
)
state_reducer_str = "\n".join(
rf'const [{format_state_name(state_name)}, dispatch_{format_state_name(state_name)}] = useReducer(applyDelta, initialState["{state_name}"])'
for state_name in initial_state
)
create_state_contexts_str = "\n".join(
rf"createElement(StateContexts.{format_state_name(state_name)},{{value: {format_state_name(state_name)}}},"
for state_name in initial_state
)
dispatchers_str = "\n".join(
f'"{state_name}": dispatch_{format_state_name(state_name)},'
for state_name in initial_state
)
return rf"""import {{ createContext, useContext, useMemo, useReducer, useState, createElement, useEffect }} from "react"
import {{ applyDelta, ReflexEvent, hydrateClientStorage, useEventLoop, refs }} from "$/utils/state"
import {{ jsx }} from "@emotion/react";
export const initialState = {"{}" if not initial_state else json_dumps(initial_state)}
export const defaultColorMode = {default_color_mode}
export const ColorModeContext = createContext({{
colorMode: defaultColorMode,
resolvedColorMode: defaultColorMode === "dark" ? "dark" : "light",
toggleColorMode: () => {{}},
setColorMode: () => {{}},
}});
export const UploadFilesContext = createContext(null);
export const DispatchContext = createContext(null);
export const StateContexts = {{{state_contexts_str}}};
export const EventLoopContext = createContext(null);
export const clientStorage = {"{}" if client_storage is None else json.dumps(client_storage)}
{state_str}
export const isDevMode = {json.dumps(is_dev_mode)};
// Module-level event dispatchers populated by ``EventLoopProvider`` on each
// render. Components reach addEvents/connectErrors via this import instead of
// hoisting ``useContext(EventLoopContext)`` so JSX literals (e.g.
// ``ErrorBoundary.onError``) constructed in any JS scope can dispatch events
// without depending on lexical hook hoisting.
let _addEventsImpl = (events, args, event_actions) => {{
console.warn("addEvents called before EventLoopProvider mounted", events);
}};
let _connectErrorsImpl = [];
export function addEvents(events, args, event_actions) {{
return _addEventsImpl(events, args, event_actions);
}}
export function getConnectErrors() {{
return _connectErrorsImpl;
}}
export function UploadFilesProvider({{ children }}) {{
const [filesById, setFilesById] = useState({{}})
refs["__clear_selected_files"] = (id) => setFilesById(filesById => {{
const newFilesById = {{...filesById}}
delete newFilesById[id]
return newFilesById
}})
return createElement(
UploadFilesContext.Provider,
{{ value: [filesById, setFilesById] }},
children
);
}}
export function ClientSide(component) {{
return ({{ children, ...props }}) => {{
const [Component, setComponent] = useState(null);
useEffect(() => {{
async function load() {{
const comp = await component();
setComponent(() => comp);
}}
load();
}}, []);
return Component ? jsx(Component, props, children) : null;
}};
}}
export function EventLoopProvider({{ children }}) {{
const dispatch = useContext(DispatchContext)
const [addEventsLocal, connectErrors] = useEventLoop(
dispatch,
initialEvents,
clientStorage,
)
// Populate the module-level dispatchers so JSX literals constructed
// outside the React-tree path (e.g. ``ErrorBoundary.onError``) can call
// ``addEvents`` without needing the events hook hoisted in their scope.
_addEventsImpl = addEventsLocal;
_connectErrorsImpl = connectErrors;
return createElement(
EventLoopContext.Provider,
{{ value: [addEventsLocal, connectErrors] }},
children
);
}}
export function StateProvider({{ children }}) {{
{state_reducer_str}
const dispatchers = useMemo(() => {{
return {{
{dispatchers_str}
}}
}}, [])
return (
{create_state_contexts_str}
createElement(DispatchContext, {{value: dispatchers}}, children)
{")" * len(initial_state)}
)
}}"""
def component_template(component: Component):
"""Template to render a component tag.
Args:
component: The component to render.
Returns:
Rendered component as string.
"""
return _RenderUtils.render(component.render())
def page_template(
imports: Iterable[_ImportDict],
dynamic_imports: Iterable[str],
custom_codes: Iterable[str],
hooks: dict[str, VarData | None],
render: dict[str, Any],
):
"""Template for a single react page.
Args:
imports: List of import statements.
dynamic_imports: List of dynamic import statements.
custom_codes: List of custom code snippets.
hooks: Dictionary of hooks.
render: Render function for the component.
Returns:
Rendered React page component as string.
"""
imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports])
custom_code_str = "\n".join(custom_codes)
dynamic_imports_str = "\n".join(dynamic_imports)
hooks_str = _render_hooks(hooks)
return f"""{imports_str}
{dynamic_imports_str}
{custom_code_str}
export default function Component() {{
{hooks_str}
return (
{_RenderUtils.render(render)}
)
}}"""
def package_json_template(
scripts: dict[str, str],
dependencies: dict[str, str],
dev_dependencies: dict[str, str],
overrides: dict[str, str],
**additional_keys: Any,
):
"""Template for package.json.
Args:
scripts: The scripts to include in the package.json file.
dependencies: The dependencies to include in the package.json file.
dev_dependencies: The devDependencies to include in the package.json file.
overrides: The overrides to include in the package.json file.
additional_keys: Additional keys to include in the package.json file.
Returns:
Rendered package.json content as string.
"""
# Ensure "type" is not duplicated since it's always set to "module"
additional_keys.pop("type", None)
return json.dumps({
"name": additional_keys.pop("name", "reflex"),
"type": "module",
"scripts": scripts,
"dependencies": dependencies,
"devDependencies": dev_dependencies,
"overrides": overrides,
**additional_keys,
})
def vite_config_template(
base: str,
hmr: bool,
force_full_reload: bool,
experimental_hmr: bool,
sourcemap: bool | Literal["inline", "hidden"],
allowed_hosts: bool | list[str] = False,
):
"""Template for vite.config.js.
Args:
base: The base path for the Vite config (for handling frontend_path config).
hmr: Whether to enable hot module replacement.
force_full_reload: Whether to force a full reload on changes.
experimental_hmr: Whether to enable experimental HMR features.
sourcemap: The sourcemap configuration.
allowed_hosts: Allow all hosts (True), specific hosts (list of strings), or only localhost (False).
Returns:
Rendered vite.config.js content as string.
"""
if allowed_hosts is True:
allowed_hosts_line = "\n allowedHosts: true,"
elif isinstance(allowed_hosts, list) and allowed_hosts:
allowed_hosts_line = f"\n allowedHosts: {json.dumps(allowed_hosts)},"
else:
allowed_hosts_line = ""
return rf"""import {{ fileURLToPath, URL }} from "url";
import {{ reactRouter }} from "@react-router/dev/vite";
import {{ defineConfig }} from "vite";
import safariCacheBustPlugin from "./vite-plugin-safari-cachebust";
// Ensure that bun always uses the react-dom/server.node functions.
function alwaysUseReactDomServerNode() {{
return {{
name: "vite-plugin-always-use-react-dom-server-node",
enforce: "pre",
resolveId(source, importer) {{
if (
typeof importer === "string" &&
importer.endsWith("/entry.server.node.tsx") &&
source.includes("react-dom/server")
) {{
return this.resolve("react-dom/server.node", importer, {{
skipSelf: true,
}});
}}
return null;
}},
}};
}}
function fullReload() {{
return {{
name: "full-reload",
enforce: "pre",
handleHotUpdate({{ server }}) {{
server.ws.send({{
type: "full-reload",
}});
return [];
}}
}};
}}
export default defineConfig((config) => ({{
base: "{base}",
plugins: [
alwaysUseReactDomServerNode(),
reactRouter(),
safariCacheBustPlugin(),
].concat({"[fullReload()]" if force_full_reload else "[]"}),
build: {{
sourcemap: {"true" if sourcemap is True else "false" if sourcemap is False else repr(sourcemap)},
rollupOptions: {{
onwarn(warning, warn) {{
if (warning.code === "EVAL" && warning.id && warning.id.endsWith("state.js")) return;
warn(warning);
}},
jsx: {{}},
output: {{
advancedChunks: {{
groups: [
{{
test: /env.json/,
name: "reflex-env",
}},
],
}},
}},
}},
}},
experimental: {{
enableNativePlugin: false,
hmr: {"true" if experimental_hmr else "false"},
}},
server: {{
port: process.env.PORT,{allowed_hosts_line}
hmr: {"true" if hmr else "false"},
watch: {{
ignored: [
"**/.web/backend/**",
"**/.web/reflex.install_frontend_packages.cached",
],
}},
}},
resolve: {{
mainFields: ["browser", "module", "jsnext"],
alias: [
{{
find: "$",
replacement: fileURLToPath(new URL("./", import.meta.url)),
}},
{{
find: "@",
replacement: fileURLToPath(new URL("./public", import.meta.url)),
}},
],
}},
}}));"""
def dynamic_component_template(
tag_name: str, component: Component, export: bool
) -> str:
"""Template for a dynamic SSR component function declaration.
Args:
tag_name: The tag name for the component.
component: The component to render.
export: Whether to export the component.
Returns:
Rendered dynamic component code as string.
"""
all_hooks = component._get_all_hooks()
return f"""
{"export " if export else ""}function {tag_name} () {{
{_render_hooks(all_hooks)}
return (
{_RenderUtils.render(component.render())}
)
}}
"""
def dynamic_components_module_template(
imports: list[_ImportDict], memoized_code: str
) -> str:
"""Template for a dynamic-SSR components module.
Args:
imports: List of import statements.
memoized_code: Code for the module body.
Returns:
Rendered module code as string.
"""
imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports])
return f"{imports_str}\n{memoized_code}"
# Wrapper expressions that are unambiguous JS callees โ identifier or member
# chains like ``memo`` / ``React.memo``. Anything else (an inline arrow
# function, a call expression, bracket access) is parenthesized before the
# component function is appended, so the parens bind as the wrapper's call
# rather than being swallowed by the wrapper expression's own grammar (e.g.
# ``(c) => track(c)`` followed by ``(...)`` would otherwise parse the call as
# part of the arrow body).
_MEMO_WRAPPER_CALLEE_RE = re.compile(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*")
def _render_memo_component(component: dict[str, Any]) -> str:
"""Render the ``export const`` statement for one memoized component.
Args:
component: The component render dict (name, signature, render, hooks,
and the optional ``wrapper`` JS expression the function component
is wrapped in).
Returns:
Rendered component export as string.
"""
function_expr = f"""(({component["signature"]}) => {{
{_render_hooks(component.get("hooks", {}))}
return(
{_RenderUtils.render(component["render"])}
)
}})"""
wrapper = component.get("wrapper")
if wrapper and not _MEMO_WRAPPER_CALLEE_RE.fullmatch(wrapper):
wrapper = f"({wrapper})"
export_expr = f"{wrapper}{function_expr}" if wrapper else function_expr
return f"\nexport const {component['name']} = {export_expr};\n"
def memo_components_template(
imports: list[_ImportDict],
components: list[dict[str, Any]],
functions: list[dict[str, Any]],
dynamic_imports: Iterable[str],
custom_codes: Iterable[str],
) -> str:
"""Template for custom component.
Args:
imports: List of import statements.
components: List of component definitions.
functions: List of function definitions.
dynamic_imports: List of dynamic import statements.
custom_codes: List of custom code snippets.
Returns:
Rendered custom component code as string.
"""
imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports])
dynamic_imports_str = "\n".join(dynamic_imports)
custom_code_str = "\n".join(custom_codes)
components_code = "".join(map(_render_memo_component, components))
functions_code = ""
for function in functions:
functions_code += (
f"\nexport const {function['name']} = {function['function']};\n"
)
return f"""
{imports_str}
{dynamic_imports_str}
{custom_code_str}
{functions_code}
{components_code}"""
def memo_single_component_template(
imports: list[_ImportDict],
component: dict[str, Any],
dynamic_imports: Iterable[str],
custom_codes: Iterable[str],
) -> str:
"""Template for a single memoized component in its own module.
Args:
imports: List of import statements for this memo only.
component: The single component definition to render.
dynamic_imports: Dynamic import statements scoped to this memo.
custom_codes: Custom code snippets scoped to this memo.
Returns:
The rendered standalone memo module code.
"""
imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports])
dynamic_imports_str = "\n".join(dynamic_imports)
custom_code_str = "\n".join(custom_codes)
component_code = _render_memo_component(component)
return f"""
{imports_str}
{dynamic_imports_str}
{custom_code_str}
{component_code}"""
def memo_single_function_template(
imports: list[_ImportDict],
function: dict[str, Any],
) -> str:
"""Template for a single function memo in its own module.
Args:
imports: List of import statements for this memo only.
function: The single function memo definition.
Returns:
The rendered standalone function memo module code.
"""
imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports])
return f"""
{imports_str}
export const {function["name"]} = {function["function"]};
"""
def styles_template(stylesheets: list[str]) -> str:
"""Template for styles.css.
Args:
stylesheets: List of stylesheets to include.
Returns:
Rendered styles.css content as string.
"""
return "@layer __reflex_base;\n" + "\n".join([
f"@import url('{sheet_name}');" for sheet_name in stylesheets
])
def _render_hooks(hooks: dict[str, VarData | None], memo: list | None = None) -> str:
"""Render hooks for macros.
Args:
hooks: Dictionary of hooks to render.
memo: Optional list of memo hooks.
Returns:
Rendered hooks code as string.
"""
internal, pre_trigger, post_trigger = _sort_hooks(hooks)
internal_str = "\n".join(internal)
pre_trigger_str = "\n".join(pre_trigger)
post_trigger_str = "\n".join(post_trigger)
memo_str = "\n".join(memo) if memo is not None else ""
return f"{internal_str}\n{pre_trigger_str}\n{memo_str}\n{post_trigger_str}"