-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
516 lines (456 loc) · 20.2 KB
/
main.py
File metadata and controls
516 lines (456 loc) · 20.2 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
import os
import yaml
from datetime import datetime
def define_env(env):
"""
This is the hook for defining variables, macros and filters
"""
# Explicitly load devices.yaml to be robust against path issues
devices_path = os.path.join(env.project_dir, 'docs', '_data', 'devices.yaml')
if os.path.exists(devices_path):
try:
with open(devices_path, 'r', encoding='utf-8') as f:
env.conf['extra']['devices'] = yaml.safe_load(f)
# Also make it available directly as a variable if macros want it
env.variables['devices'] = env.conf['extra']['devices']
except Exception as e:
print(f"Error loading devices.yaml: {e}")
else:
print(f"Warning: devices.yaml not found at {devices_path}")
def get_articles(env):
articles_dir = os.path.join(env.project_dir, 'docs', 'articles')
articles = []
# Walk through the articles directory
for root, dirs, files in os.walk(articles_dir):
for file in files:
# Ignore the index file itself to prevent recursion
if file.endswith('.md') and file != 'index.md':
file_path = os.path.join(root, file)
# Read frontmatter
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Simple frontmatter parsing (assuming standard --- format)
if content.startswith('---'):
try:
# Extract YAML frontmatter
parts = content.split('---', 2)
if len(parts) >= 3:
frontmatter = yaml.safe_load(parts[1])
if frontmatter and 'date' in frontmatter:
# Construct article object
is_draft = frontmatter.get('draft', False)
# We don't filter drafts here, we let the macros decide
article = {
'title': frontmatter.get('title', 'No Title'),
'date': frontmatter.get('date'),
'image': frontmatter.get('image', 'https://via.placeholder.com/300x200'),
'description': frontmatter.get('description', ''),
'draft': is_draft,
'highlight': frontmatter.get('highlight', False),
'tags': frontmatter.get('tags', [])
}
# Link Calculation
rel_path_from_articles = os.path.relpath(file_path, articles_dir)
link_url = rel_path_from_articles.replace('.md', '').replace('\\', '/')
article['url'] = link_url
# Image Path Calculation
img_path = article['image']
if not img_path.startswith('http'):
article_sub_dir = os.path.dirname(rel_path_from_articles)
if article_sub_dir:
article['image'] = f"{article_sub_dir}/{img_path}".replace('\\', '/')
else:
article['image'] = img_path.replace('\\', '/')
articles.append(article)
except Exception as e:
print(f"Error parsing {file}: {e}")
# Sort articles by date descending
articles.sort(key=lambda x: str(x['date']), reverse=True)
return articles
@env.macro
def list_highlights_grid():
articles = get_articles(env)
# Filter: Highlights Only, No Drafts
highlight_articles = [a for a in articles if a['highlight'] and not a['draft']]
# HTML Grid: 3 Columns (Original Style) -> Responsive
html = '''
<style>
.highlights-grid-responsive {
display: grid;
grid-template-columns: repeat(3, 1fr) !important;
gap: 20px;
padding: 0;
}
@media screen and (max-width: 900px) {
.highlights-grid-responsive { grid-template-columns: repeat(2, 1fr) !important; }
}
@media screen and (max-width: 480px) {
.highlights-grid-responsive { grid-template-columns: 1fr !important; }
}
</style>
'''
html += '<div class="grid cards highlights-grid-responsive" borderless>\n'
for article in highlight_articles:
tags_html = ''
if article['tags']:
for tag in article['tags']:
tags_html += f'<span style="display: inline-block; background: #333; color: #fff; padding: 2px 8px; border-radius: 10px; font-size: 0.7em; margin-right: 5px; margin-top: 5px;">{tag}</span>'
html += f'''
<div class="card">
<a href="{article['url']}" style="text-decoration: none; color: inherit; display: block;">
<img src="{article['image']}" alt="{article['title']}" style="width:100%; aspect-ratio: 1/1; object-fit: cover; border-radius: 8px 8px 0 0;">
<div style="padding: 10px;">
<h3>{article['title']}</h3>
<p>{article['description']}</p>
<div style="margin-top: 8px;">{tags_html}</div>
</div>
</a>
</div>
'''
html += '</div>'
return html
@env.macro
def list_articles_grid():
articles = get_articles(env)
# Filter: No Drafts
display_articles = [a for a in articles if not a['draft']]
# 1. Collect all unique tags (Case Insensitive Merging)
# Map: lowercase_tag -> Display Tag
tag_map = {}
for article in display_articles:
if article['tags']:
for tag in article['tags']:
low_tag = tag.lower().strip()
# If not yet recorded, or if the new version looks 'nicer' (has more capitals), update it?
# For stability, let's just keep the first one or favor upper case.
# Simple heuristic: if existing is all lower, and new has upper, take new.
if low_tag not in tag_map:
tag_map[low_tag] = tag.strip()
else:
# Optional: implementation to prefer "Home Assistant" over "home assistant"
current_display = tag_map[low_tag]
if current_display.islower() and not tag.islower():
tag_map[low_tag] = tag.strip()
# Sort tags by their display name for the UI
sorted_keys = sorted(tag_map.keys(), key=lambda k: tag_map[k].lower())
# 2. Build the Filter Cloud HTML
# Mobile-friendly CSS
html = '''
<style>
.article-grid-responsive {
display: grid;
grid-template-columns: repeat(4, 1fr) !important;
gap: 15px;
padding: 0;
}
.filter-controls {
display: flex;
align-items: center;
flex-wrap: wrap;
margin-bottom: 20px;
gap: 10px;
}
.toggle-container {
display: flex;
align-items: center;
margin-left: auto; /* Push to right on desktop */
background: rgba(255, 255, 255, 0.05);
padding: 5px 10px;
border-radius: 15px;
border: 1px solid #444;
}
[data-md-color-scheme="default"] .toggle-container {
background: rgba(0, 0, 0, 0.05);
border: 1px solid #ddd;
}
.toggle-label {
font-size: 0.9em;
margin-left: 8px;
cursor: pointer;
user-select: none;
}
@media screen and (max-width: 1100px) {
.article-grid-responsive { grid-template-columns: repeat(3, 1fr) !important; }
}
@media screen and (max-width: 768px) {
.article-grid-responsive { grid-template-columns: repeat(2, 1fr) !important; }
.toggle-container { margin-left: 0; width: 100%; justify-content: center; }
}
@media screen and (max-width: 480px) {
.article-grid-responsive { grid-template-columns: 1fr !important; }
}
</style>
'''
html += '<div class="filter-controls">'
# Tags Container
html += '<div style="flex: 1;">'
# 'All' button
html += '<button data-tag="all" onclick="toggleFilter(\'all\')" style="margin-right: 5px; margin-bottom: 5px; padding: 5px 10px; border: 1px solid #444; background: #00C853; color: white; cursor: pointer; border-radius: 15px;">All</button>'
for key in sorted_keys:
display_name = tag_map[key]
# data-tag uses the lowercase key for logic
html += f'<button data-tag="{key}" onclick="toggleFilter(\'{key}\')" style="margin-right: 5px; margin-bottom: 5px; padding: 5px 10px; border: 1px solid #444; background: #252933; color: #ccc; cursor: pointer; border-radius: 15px;">{display_name}</button>'
html += '</div>'
# Match All Toggle
html += '''
<div class="toggle-container" onclick="toggleMatchMode()">
<input type="checkbox" id="match-all-toggle" style="cursor: pointer;">
<label for="match-all-toggle" class="toggle-label">Match All Selected</label>
</div>
'''
html += '</div>' # End filter-controls
# 3. Build the Grid
# Removed inline style logic in favor of .article-grid-responsive class
html += '<div id="article-grid" class="grid cards article-grid-responsive" borderless>\n'
for article in display_articles:
# Prepare tag string for data attribute (LOWERCASE for logic match)
if article['tags']:
# We assume the article tags match the keys in our map (by lowering)
article_tags_lower = [t.lower().strip() for t in article['tags']]
article_tags_str = ",".join(article_tags_lower)
else:
article_tags_str = ""
# Prepare visual pills (Keep original display)
tags_html = ''
if article['tags']:
for tag in article['tags']:
tags_html += f'<span style="display: inline-block; background: #333; color: #fff; padding: 2px 8px; border-radius: 10px; font-size: 0.7em; margin-right: 5px; margin-top: 5px;">{tag}</span>'
html += f'''
<div class="card article-card" data-tags="{article_tags_str}">
<a href="{article['url']}" style="text-decoration: none; color: inherit; display: block;">
<img src="{article['image']}" alt="{article['title']}" style="width:100%; aspect-ratio: 4/3; object-fit: cover; border-radius: 8px 8px 0 0;">
<div style="padding: 8px;">
<h3 style="margin: 0; font-size: 1.0em; line-height: 1.2;">{article['title']}</h3>
<p style="margin-top: 4px; font-size: 0.8em; color: #aaa;">{article['date']}</p>
<p style="margin-top: 4px; font-size: 0.85em; line-height: 1.4;">{article['description']}</p>
<div style="margin-top: 6px;">{tags_html}</div>
</div>
</a>
</div>
'''
html += '</div>'
# 4. Inject Client-Side Filtering Script (Multi-Select + Logic Toggle)
html += '''
<script>
// State to track selected tags
var activeTags = new Set();
var matchAllMode = false;
function toggleMatchMode() {
// Toggle state (handling interactions with container vs input)
const checkbox = document.getElementById('match-all-toggle');
// If usage clicked label/div, checkbox might not have updated yet or we need to sync?
// Easiest is to just read the current checkbox state after a microtask, or trust native click.
// Let's just listen to change on input is safer, but here we wrapper div onclick.
// Better approach: Let native checkbox handle click if target is checkbox.
// If target is div/label, toggle checkbox manually.
// For simplicity, let's just read the checkbox in applyFilter and ensure applyFilter is called.
setTimeout(() => {
matchAllMode = checkbox.checked;
applyFilter();
}, 10);
}
// Ensure checkbox listener updates if clicked directly
document.addEventListener('DOMContentLoaded', () => {
const cb = document.getElementById('match-all-toggle');
if(cb) {
cb.addEventListener('change', (e) => {
matchAllMode = e.target.checked;
applyFilter();
});
}
});
function toggleFilter(tag) {
// 1. Update State
if (tag === 'all') {
activeTags.clear();
} else {
if (activeTags.has(tag)) {
activeTags.delete(tag);
} else {
activeTags.add(tag);
}
}
applyFilter();
}
function applyFilter() {
const buttons = document.querySelectorAll('button[data-tag]');
const cards = document.querySelectorAll('.article-card');
// 2. Update Buttons UI
buttons.forEach(btn => {
const btnTag = btn.getAttribute('data-tag');
const isActive = activeTags.has(btnTag);
const isAllActive = activeTags.size === 0 && btnTag === 'all';
if (isActive || isAllActive) {
btn.style.background = '#00C853';
btn.style.color = '#fff';
} else {
// Inactive Style
// Re-apply light/dark aware colors if possible or fixed colors
// For now using the fixed colors defined in HTML, we might lose theme awareness for inactive buttons if not careful
// But we are setting explicit colors so it overrides.
btn.style.background = btnTag === 'all' ? '#333' : '#252933';
btn.style.color = btnTag === 'all' ? '#fff' : '#ccc';
}
});
// 3. Filter Cards
cards.forEach(card => {
const cardTags = card.getAttribute('data-tags').split(',');
if (activeTags.size === 0) {
// Show all if no filter
card.style.display = 'block';
} else {
// Check based on mode
let hasMatch = false;
if (matchAllMode) {
// AND Logic: Must have ALL active tags
// Every tag in activeTags must be present in cardTags
hasMatch = Array.from(activeTags).every(t => cardTags.includes(t));
} else {
// OR Logic: Must have AT LEAST ONE active tag
hasMatch = cardTags.some(t => activeTags.has(t));
}
card.style.display = hasMatch ? 'block' : 'none';
}
});
}
</script>
'''
return html
@env.macro
def hero_overlay(title, subtitle, link):
"""
Creates an overlay card for the hero video section.
"""
html = f'''
<div class="hero-overlay-container">
<a href="{link}" class="overlay-card">
<span class="overlay-badge">{subtitle}</span>
<h4 class="overlay-title">{title}</h4>
<p class="overlay-link">Read more →</p>
</a>
</div>
<style>
.hero-overlay-container {{
position: absolute;
bottom: 60px; /* Raised higher */
left: 40px; /* Moved inward */
z-index: 20;
width: auto;
min-width: 140px;
max-width: 340px; /* Wider to fit content */
pointer-events: auto;
}}
.hero-overlay-container .overlay-card {{
display: flex !important;
flex-direction: column;
padding: 24px !important; /* Specificity boost + larger padding */
background: rgba(22, 24, 28, 0.25);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-left: 4px solid var(--md-accent-fg-color);
border-radius: 8px;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
text-decoration: none !important;
transition: all 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.1);
animation: slideUpFade 0.8s ease-out 0.5s both;
line-height: normal !important;
text-align: left;
margin: 0 !important;
box-sizing: border-box !important;
width: 100%;
}}
[data-md-color-scheme="default"] .hero-overlay-container .overlay-card {{
background: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(0,0,0,0.1);
box-shadow: 0 8px 25px rgba(0,0,0,0.2);
}}
.hero-overlay-container .overlay-card:hover {{
transform: translateY(-5px);
background: rgba(22, 24, 28, 0.65);
box-shadow: 0 15px 40px rgba(0,0,0,0.6);
}}
[data-md-color-scheme="default"] .hero-overlay-container .overlay-card:hover {{
background: #fff;
}}
.overlay-badge {{
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 1px;
color: rgba(255, 255, 255, 0.7);
margin-bottom: 0px;
font-weight: 500;
line-height: 1;
}}
[data-md-color-scheme="default"] .overlay-badge {{
color: #555;
}}
.overlay-title {{
margin: 0 0 4px 0;
color: #fff !important;
font-weight: 700;
font-size: 1.2rem;
line-height: 1 !important;
}}
[data-md-color-scheme="default"] .overlay-title {{
color: #222 !important;
}}
.overlay-link {{
margin: 0;
font-size: 0.9rem;
font-weight: 600;
color: var(--md-accent-fg-color) !important;
align-self: flex-start;
line-height: 1;
}}
@keyframes slideUpFade {{
from {{ opacity: 0; transform: translateY(20px); }}
to {{ opacity: 1; transform: translateY(0); }}
}}
@media screen and (max-width: 600px) {{
.hero-overlay-container {{
bottom: 25px;
left: 20px;
right: 20px;
max-width: none;
}}
.overlay-title {{
font-size: 1.2rem;
}}
.overlay-card {{
padding: 16px 20px !important;
}}
}}
</style>
'''
return html
@env.macro
def package_image(page_name):
"""
Dynamically finds the image for a package (png/jpg) or returns placeholder.
Usage: {{ package_image(page.file.name) }}
"""
import os
# 1. Clean filename (remove extension)
stem = page_name.rsplit('.', 1)[0] if '.' in page_name else page_name
# 2. Define search path (Assumes assets are in specific 'assets' subfolder relative to Smart Home Packages)
# Note: This path is specific to where the markdown files live.
# For robustness, we check the absolute path.
base_assets_path = os.path.join(env.project_dir, 'docs', 'smart-home', 'packages', 'assets')
extensions = ['.png', '.jpg', '.jpeg']
# 3. Search for existing image
found_image = None
for ext in extensions:
img_name = f"{stem}{ext}"
if os.path.exists(os.path.join(base_assets_path, img_name)):
found_image = f"assets/{img_name}"
break
# 4. Return HTML
if found_image:
return f''
else:
# Fallback Placeholder (Optional: Return empty string or specific placeholder)
# return f''
return "" # Return empty if no image found, cleaner than broken placeholder?
# User asked for similar to devices cards... devices show placeholder.
return f''