-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.py
204 lines (175 loc) · 9.06 KB
/
main.py
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
from fasthtml.common import *
import configparser, os
from pathlib import Path
from utils import *
from importlib import import_module
from monsterui.all import *
def get_route(p): return '/'.join(Path(p).parts[1:])
def get_module_path(p,base_dir): return f'{base_dir}.{".".join(Path(p).parts[1:])}.app'
application_routes = [Mount(f"/app/{get_route(root)}", import_module(get_module_path(root,'examples')).app) for root, dirs, files in os.walk('examples') if 'app.py' in files]
descr = 'A gallery of FastHTML components showing common patterns in FastHTML apps, including chat bubbles, cascading dropdowns, interactive charts, etc.'
HLJS_THEMES = {
'dark': 'https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/atom-one-dark.css',
'light': 'https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/atom-one-light.css'}
hjs = (
# Basic highlight.js setup
Script(src='https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/highlight.min.js'),
Script(src='https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/languages/python.min.js'),
# Copy button setup
Script(src='https://cdn.jsdelivr.net/gh/arronhunt/highlightjs-copy/dist/highlightjs-copy.min.js'),
Link(rel='stylesheet', href='https://cdn.jsdelivr.net/gh/arronhunt/highlightjs-copy/dist/highlightjs-copy.min.css'),
Style('''
.hljs-copy-button { background-color: #2d2b57; }
html.dark .hljs-copy-button { background-color: #e0e0e0; color: #2d2b57; }
'''),
# Theme stylesheets
Link(rel='stylesheet', href=HLJS_THEMES['dark'], id='hljs-dark-theme', disabled=True),
Link(rel='stylesheet', href=HLJS_THEMES['light'], id='hljs-light-theme', disabled=True),
# Theme switching logic
Script('''
function updateCodeTheme() {
const isDark = document.documentElement.classList.contains('dark');
document.getElementById('hljs-dark-theme').disabled = !isDark;
document.getElementById('hljs-light-theme').disabled = isDark;
}
// Watch for theme changes
new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.target.tagName === 'HTML' && mutation.attributeName === 'class') {
updateCodeTheme();
}
});
}).observe(document.documentElement, { attributes: true });
// Initial setup
document.addEventListener('DOMContentLoaded', updateCodeTheme);
'''),
# Highlight.js initialization
Script('''
hljs.configure({ ignoreUnescapedHTML: true });
hljs.addPlugin(new CopyButtonPlugin());
htmx.onLoad(hljs.highlightAll);
''', type='module'),
)
hdrs = (*hjs,
#Script(defer=True, data_domain="gallery.fastht.ml", src="https://plausible-analytics-ce-production-dba0.up.railway.app/js/script.js"),
*Socials(title='FastHTML Gallery', description=descr, site_name='gallery.fastht.ml', twitter_site='@isaac_flath', image=f'/social.png', url=''),
toggle_script,
*Theme.blue.headers(),)
app = FastHTML(routes=application_routes+ [Mount('/files', StaticFiles(directory='.')),], hdrs=hdrs, pico=False)
def NavBar(dir_path, info=True, active=''):
nav_items = [
Li(A("Back to Gallery", href="/")),
Li(A("Split", href=f"/split/{dir_path.parts[1]}/{dir_path.parts[2]}"), cls='uk-active' if active == 'split' else ''),
Li(A("Code", href=f"/code/{dir_path.parts[1]}/{dir_path.parts[2]}"), cls='uk-active' if active == 'code' else ''),
Li(A("App", href=f"/app/{dir_path.parts[1]}/{dir_path.parts[2]}"), cls='uk-active' if active == 'app' else '')]
if info:nav_items.insert(1, Li(A("Info", href=f"/info/{dir_path.parts[1]}/{dir_path.parts[2]}"), cls='uk-active' if active == 'info' else ''))
return NavBarContainer(
NavBarLSide(H1(f"{dir_path.name.replace('_',' ').title()}"), cls="hidden md:block"),
NavBarRSide(NavBarNav(*nav_items)))
@app.get('/split/{category}/{project}')
def split_view(category: str, project: str):
dir_path = Path('examples')/category/project
code_text = (dir_path/'app.py').read_text().strip()
info = (dir_path/'info.md').exists()
return (
NavBar(dir_path, info=info, active='split'),
Title(f"{dir_path.name} - Split View"),
Grid(Div(Pre(Code(code_text, cls='language-python'))),
Div(Iframe(src=f"/app/{category}/{project}/",style="width: 100%; height: 100%; border: none;")),
cols_sm=1, cols_md=1, cols_lg=2))
@app.get('/code/{category}/{project}')
def application_code(category:str, project:str):
dir_path = Path('examples')/category/project
code_text = (dir_path/'app.py').read_text().strip()
info = (dir_path/'info.md').exists()
return (NavBar(dir_path, info=info, active='code'), Title(f"{dir_path.name} - Code"), Container(Pre(Code(code_text, cls='language-python'))))
@app.get('/info/{category}/{project}')
def application_info(category:str, project:str):
dir_path = Path('examples')/category/project
md_text = (dir_path/'info.md').read_text()
return (NavBar(dir_path, info=True, active='info'), Title(f"{dir_path.name} - Info"), Container(render_md(md_text)))
def ImageCard(dir_path):
metadata = configparser.ConfigParser()
metadata.read(dir_path/'metadata.ini')
meta = metadata['REQUIRED']
dpath = dir_path.parts[1]+'/'+dir_path.parts[2]
text_md_exists = (dir_path/'info.md').exists()
return Card(
A(Img(
src=f"{'/files'/dir_path/'card_thumbnail.gif'}", alt=meta['ImageAltText'],
style="width: 100%; height: 350px; object-fit: cover;",
data_png=f"{'/files'/dir_path/'card_thumbnail.png'}",
loading="lazy",
cls="card-img-top"),
href=f"/split/{dpath}"),
Div(P(meta['ComponentName'], cls=(TextT.bold, TextT.large)),
render_md(P(meta['ComponentDescription'])),#, cls=(TextT.muted, TextT.large)),
style="height: 150px; overflow: auto;"),
footer=DivFullySpaced(
A(Button("Split", cls=ButtonT.primary), href=f"/split/{dpath}"),
A(Button("Code", cls=ButtonT.secondary), href=f"/code/{dpath}"),
A(Button("App", ), href=f"/app/{dpath}"),
A(Button("Info"), href=f"/info/{dpath}") if text_md_exists else None))
directories = [Path(f"examples/{x}") for x in [
'dynamic_user_interface_(htmx)',
'visualizations',
'widgets',
'svg',
'todo_series',
'applications']]
def is_example_dir(d):
return d.is_dir() and not d.name.startswith('_') and (d/'metadata.ini').exists()
@app.get("/")
def homepage():
### HEADERS ###
all_cards = []
for section in directories:
all_cards.append(
Section(Details(
Summary(H1(section.name.replace('_',' ').title(), cls='mt-6 mb-4 pb-2 text-center text-3xl font-bold border-b-2 border-gray-300')),
Grid(*[ImageCard(dir) for dir in sorted(section.iterdir()) if is_example_dir(dir)],
cols_min=1, cols_sm=1, cols_md=2, cols_lg=3, cols_xl=3),
cls='pt-6', open=True)))
return (NavBarContainer(
NavBarLSide(H1("FastHTML Gallery" )),
NavBarRSide(
Button(submit=False)("Toggle Animations", onclick="toggleAnimations()"),
A(Button("Table View"), href="/table"))),
Container(*all_cards))
def TableRow(dir_path):
metadata = configparser.ConfigParser()
metadata.read(dir_path/'metadata.ini')
meta = metadata['REQUIRED']
dpath = dir_path.parts[1]+'/'+dir_path.parts[2]
text_md_exists = (dir_path/'info.md').exists()
return Tr(
Td(meta['ComponentName']),
Td(render_md(meta['ComponentDescription'])),
Td(DivLAligned(
A(Button("Split", cls=ButtonT.primary), href=f"/split/{dpath}"),
A(Button("Code", cls=ButtonT.secondary), href=f"/code/{dpath}"),
A(Button("App"), href=f"/app/{dpath}"),
A(Button("Info"), href=f"/info/{dpath}") if text_md_exists else None),
cls='uk-table-shrink'))
def SectionTable(section):
section_id = f"section-{section.name}"
return Section(Details(
Summary(H1(section.name.replace('_',' ').title(),
cls='mt-6 mb-4 pb-2 text-center text-3xl font-bold border-b-2 border-gray-300 cursor-pointer')),
Table(
Thead(Tr(map(Th, ("Component", "Description", "Actions")))),
Tbody(*[TableRow(dir) for dir in sorted(section.iterdir())
if is_example_dir(dir)]),
cls=(TableT.middle, TableT.divider, TableT.hover, TableT.small)),
# open=True,
id=section_id),
cls='py-2')
@app.get("/table")
def table_view():
return (NavBarContainer(
NavBarLSide(H1("FastHTML Gallery Table View")),
NavBarRSide(
Button(submit=False)("Toggle Animations", onclick="toggleAnimations()"),
A(Button("Card View"), href="/"))),
Container(*[SectionTable(section) for section in directories]))
serve()