Skip to content

Commit 475d989

Browse files
committed
added the react example from the C version
1 parent 9bf6f5b commit 475d989

File tree

24 files changed

+18142
-1
lines changed

24 files changed

+18142
-1
lines changed

PyPI/Package/src/webui/webui.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,7 @@ def _c_handler(filename_ptr, length_ptr):
936936
length_ptr[0] = 0
937937
return 0
938938

939-
data = response_str.encode("utf-8")
939+
data = response_str.encode("latin-1")
940940
length_ptr[0] = len(data)
941941

942942
# allocate and pin

examples/react/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
## React WebUI Example
2+
3+
This is a basic example of how to use WebUI with React to generate a portable single executable program. WebUI will run the internal web server and use any installed web browser as GUI to show the React UI.
4+
__NOTE: To make an executable for python, look into pyinstaller or similar type libraries (pathing may have to be automated in some places to differentiate runtime and built file locations)__
5+
6+
A simple Python script `vfs.py` is used to generate `vfs.h` to embed the whole react's build folder into the portable single executable program.
7+
8+
![Screenshot](webui_react.png)
9+
10+
### How to use it?
11+
12+
1. Run script `build_react` to re-build the React project and run the pyhton file
13+
14+
### How to create a React WebUI project from scratch?
15+
16+
1. Run `npx create-react-app my-react-app` to create a React app using NPM
17+
2. Add `<script src="webui.js"></script>` into `public/index.html` to connect UI with the backend
18+
3. Copy or make your own vfs functions similar to how it's done in main.py
19+
4. Build the react-app portion with `npm run build`; This step must be done every change you make to the react portion of the app
20+
5. Now, run `python main.py` or whatever your main entry script is.
21+
22+
### Other backend languages examples:
23+
24+
- Coming soon...

examples/react/build_react.bat

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
@echo off
2+
3+
echo.
4+
echo * Build React project...
5+
6+
cd webui-react-example
7+
call npm install
8+
call npm run build
9+
cd ..
10+
11+
echo.
12+
echo * Running main.py
13+
14+
python main.py

examples/react/build_react.sh

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
echo
2+
echo "* Build React project..."
3+
4+
cd webui-react-example
5+
npm install || exit
6+
npm run build || exit
7+
cd ..
8+
9+
echo
10+
echo "* Running main.py"
11+
12+
python3 main.py

examples/react/main.py

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import os
2+
import mimetypes
3+
from typing import Optional
4+
from dataclasses import dataclass
5+
from webui import webui
6+
7+
8+
@dataclass
9+
class VirtualFile:
10+
path: str
11+
body: str
12+
13+
14+
virtual_files: list[VirtualFile] = []
15+
# flat list: [dir_key, index_path, dir_key, index_path, …]
16+
index_files: list[str] = []
17+
18+
19+
def build_vfs(directory: str):
20+
"""
21+
Scan a directory tree and populate the global virtual file lists.
22+
23+
Walks through every file under `directory`, reads its contents as raw bytes
24+
(decoded via Latin-1 to preserve 1:1 byte -> character mapping), and appends
25+
a `VirtualFile(path, body)` entry to `virtual_files`. Detects any files
26+
named `index.*`, recording them in `index_files`.
27+
28+
Args:
29+
directory: The root directory whose files will be loaded into memory.
30+
31+
Globals:
32+
virtual_files: Cleared and then extended with VirtualFile instances
33+
for each file found.
34+
index_files: Cleared and then populated with flat [dir_key, index_path]
35+
pairs corresponding to each directory’s index file.
36+
"""
37+
global virtual_files, index_files
38+
virtual_files.clear()
39+
index_files.clear()
40+
41+
index_map: dict[str,str] = {}
42+
43+
for root, _, filenames in os.walk(directory):
44+
rel_dir = os.path.relpath(root, directory).replace('\\','/')
45+
if rel_dir == '.':
46+
rel_dir = ''
47+
48+
for fn in filenames:
49+
full = os.path.join(root, fn)
50+
vpath = f"/{rel_dir}/{fn}".replace('//','/')
51+
52+
# read raw bytes → latin-1 so we preserve 1:1 in the str
53+
with open(full, 'rb') as f:
54+
body = f.read().decode('latin-1')
55+
56+
virtual_files.append(VirtualFile(path=vpath, body=body))
57+
58+
if fn.startswith("index."):
59+
dir_key = f"/{rel_dir}/".replace('//','/')
60+
if dir_key not in index_map:
61+
index_map[dir_key] = vpath
62+
63+
# flatten map into list
64+
for dk, ip in index_map.items():
65+
index_files.extend([dk, ip])
66+
67+
68+
def virtual_file_system(path: str) -> Optional[VirtualFile]:
69+
"""
70+
Returns the matching VirtualFile or None.
71+
"""
72+
global virtual_files
73+
74+
for vf in virtual_files:
75+
if vf.path == path:
76+
return vf
77+
return None
78+
79+
80+
def vfs(path: str) -> Optional[str]:
81+
"""
82+
Handler function for set_file_handler(),
83+
Type needed: Callable[[str], Optional[str]]
84+
- If exact file found, return "200 OK" headers + body.
85+
- Else, check index_files for a 302 redirect.
86+
- Else, return None.
87+
"""
88+
global index_files
89+
90+
# Try exact file
91+
vf = virtual_file_system(path)
92+
if vf is not None:
93+
length = len(vf.body) # latin-1 str length == byte length
94+
ctype = mimetypes.guess_type(path)[0] or "application/octet-stream"
95+
header = (
96+
"HTTP/1.1 200 OK\r\n"
97+
f"Content-Type: {ctype}\r\n"
98+
f"Content-Length: {length}\r\n"
99+
"Cache-Control: no-cache\r\n\r\n"
100+
)
101+
return header + vf.body
102+
103+
# Not found; check for index redirect
104+
redirect_path = path
105+
if not redirect_path.endswith('/'):
106+
redirect_path += '/'
107+
108+
for i in range(0, len(index_files), 2):
109+
if index_files[i] == redirect_path:
110+
location = index_files[i+1]
111+
header = (
112+
"HTTP/1.1 302 Found\r\n"
113+
f"Location: {location}\r\n"
114+
"Cache-Control: no-cache\r\n\r\n"
115+
)
116+
return header
117+
118+
# No match; will default to normal WebUI file system behavior
119+
return None
120+
121+
122+
def exit_app(e: webui.Event):
123+
webui.exit()
124+
125+
126+
def main():
127+
# Create new window
128+
react_window = webui.Window()
129+
130+
# Set window size
131+
react_window.set_size(550, 450)
132+
133+
# Set window position
134+
react_window.set_position(250, 250)
135+
136+
# Allow multi-user connection to WebUI window
137+
webui.set_config(webui.Config.multi_client, True)
138+
139+
# Disable WebUI's cookies
140+
webui.set_config(webui.Config.use_cookies, True)
141+
142+
# Bind react HTML element IDs with a python function
143+
react_window.bind("Exit", exit_app)
144+
145+
# VFS (Virtual File System) Example
146+
#
147+
# 1. Build your list of files
148+
149+
# 2. Create a function with this type:
150+
# Callable[[str], Optional[str]]
151+
#
152+
# 3. The parameter should be for a file name
153+
# and the return string is the header + body.
154+
# Ex.
155+
# def my_handler(filename: str) -> Optional[str]:
156+
# response_body = "Hello, World!"
157+
# response_headers = (
158+
# "HTTP/1.1 200 OK\r\n"
159+
# "Content-Type: text/plain\r\n"
160+
# f"Content-Length: {len(response_body)}\r\n"
161+
# "\r\n"
162+
# )
163+
# return response_headers + response_body
164+
#
165+
# 4. pass that function into the set_file_handler(<handler>)
166+
167+
# Build out the vfs and index list
168+
build_vfs("./webui-react-example/build")
169+
170+
# Set a custom files handler
171+
react_window.set_file_handler(vfs)
172+
173+
# Show the React window
174+
# react_window.show_browser("index.html", webui.Browser.Chrome)
175+
react_window.show("index.html")
176+
177+
# Wait until all windows get closed
178+
webui.wait()
179+
180+
# Free all memory resources (Optional)
181+
webui.clean()
182+
183+
print('Thank you.')
184+
185+
186+
if __name__ == "__main__":
187+
main()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Getting Started with Create React App
2+
3+
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4+
5+
## Available Scripts
6+
7+
In the project directory, you can run:
8+
9+
### `npm start`
10+
11+
Runs the app in the development mode.\
12+
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
13+
14+
The page will reload when you make changes.\
15+
You may also see any lint errors in the console.
16+
17+
### `npm test`
18+
19+
Launches the test runner in the interactive watch mode.\
20+
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21+
22+
### `npm run build`
23+
24+
Builds the app for production to the `build` folder.\
25+
It correctly bundles React in production mode and optimizes the build for the best performance.
26+
27+
The build is minified and the filenames include the hashes.\
28+
Your app is ready to be deployed!
29+
30+
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31+
32+
### `npm run eject`
33+
34+
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
35+
36+
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37+
38+
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
39+
40+
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
41+
42+
## Learn More
43+
44+
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45+
46+
To learn React, check out the [React documentation](https://reactjs.org/).
47+
48+
### Code Splitting
49+
50+
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51+
52+
### Analyzing the Bundle Size
53+
54+
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55+
56+
### Making a Progressive Web App
57+
58+
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59+
60+
### Advanced Configuration
61+
62+
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63+
64+
### Deployment
65+
66+
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67+
68+
### `npm run build` fails to minify
69+
70+
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

0 commit comments

Comments
 (0)