(file_or_name: Path | str)
| 74 | |
| 75 | |
| 76 | def _load_one_example(file_or_name: Path | str) -> ComponentType: |
| 77 | if isinstance(file_or_name, str): |
| 78 | file = get_main_example_file_by_name(file_or_name) |
| 79 | else: |
| 80 | file = file_or_name |
| 81 | |
| 82 | if not file.exists(): |
| 83 | raise FileNotFoundError(str(file)) |
| 84 | |
| 85 | print_buffer = _PrintBuffer() |
| 86 | |
| 87 | def capture_print(*args, **kwargs): |
| 88 | buffer = StringIO() |
| 89 | print(*args, file=buffer, **kwargs) |
| 90 | print_buffer.write(buffer.getvalue()) |
| 91 | |
| 92 | captured_component_constructor = None |
| 93 | |
| 94 | def capture_component(component_constructor): |
| 95 | nonlocal captured_component_constructor |
| 96 | captured_component_constructor = component_constructor |
| 97 | |
| 98 | reactpy.run = capture_component |
| 99 | try: |
| 100 | code = compile(file.read_text(), str(file), "exec") |
| 101 | exec( |
| 102 | code, |
| 103 | { |
| 104 | "print": capture_print, |
| 105 | "__file__": str(file), |
| 106 | "__name__": file.stem, |
| 107 | }, |
| 108 | ) |
| 109 | except Exception: |
| 110 | return _make_error_display(format_exc()) |
| 111 | finally: |
| 112 | reactpy.run = RUN_ReactPy |
| 113 | |
| 114 | if captured_component_constructor is None: |
| 115 | return _make_example_did_not_run(str(file)) |
| 116 | |
| 117 | @reactpy.component |
| 118 | def Wrapper(): |
| 119 | return reactpy.html.div(captured_component_constructor(), PrintView()) |
| 120 | |
| 121 | @reactpy.component |
| 122 | def PrintView(): |
| 123 | text, set_text = reactpy.hooks.use_state(print_buffer.getvalue()) |
| 124 | print_buffer.set_callback(set_text) |
| 125 | return ( |
| 126 | reactpy.html.pre({"class_name": "printout"}, text) |
| 127 | if text |
| 128 | else reactpy.html.div() |
| 129 | ) |
| 130 | |
| 131 | return Wrapper() |
| 132 | |
| 133 |
no test coverage detected