Add Site Studio themes and Theme Manager
Support categorized fragments, theme presets, block widths, and server-backed theme editing with onboarding and preview. Include Site Studio, design sources, specification and verification reports; remove the legacy studio-site example.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline smoke test of Site Studio's width-mode example."""
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
p = Path(__file__).resolve().parents[1]
|
||||
theme = yaml.safe_load((p/'theme.yaml').read_text())
|
||||
c = theme['overrides']['ui']['container']
|
||||
assert c['mode'] in {'boxed','fluid','full'}
|
||||
assert 720 <= c['max_width'] <= 1920
|
||||
assert all(isinstance(x,int) and 0<=x<=96 for x in c['gutter'].values())
|
||||
raw=(p/'pages/index.md').read_text()
|
||||
yaml_text=raw[4:].split('\n---\n')[0]
|
||||
blocks=yaml.safe_load(yaml_text)['regions']['main']
|
||||
assert blocks[0]['layout']=={'section_width':'full','content_width':'boxed'}
|
||||
assert blocks[1]['layout']=={'section_width':'fluid','content_width':'fluid'}
|
||||
assert blocks[-1]['layout']=={'section_width':'full','content_width':'boxed'}
|
||||
index=(p/'preview-dist/index.html').read_text()
|
||||
for mode in ['data-section-width="full" data-content-width="boxed"','data-section-width="fluid" data-content-width="fluid"']:
|
||||
assert mode in index
|
||||
print('Container settings and preview: OK')
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline example renderer (NOT the Site Engine production BuildService).
|
||||
|
||||
Converts the Site Studio demo's YAML/Markdown/Jinja fragments into portable HTML.
|
||||
Needs PyYAML, Jinja2, mistune; no FastAPI, server or external CDN.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import yaml
|
||||
import mistune
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / 'preview-dist'
|
||||
load = lambda path: yaml.safe_load(path.read_text(encoding='utf8'))
|
||||
|
||||
|
||||
def parse_md(path):
|
||||
text = path.read_text(encoding='utf8')
|
||||
if not text.startswith('---\n'):
|
||||
raise ValueError(f'Missing front matter: {path}')
|
||||
raw, body = text[4:].split('\n---\n', 1)
|
||||
return yaml.safe_load(raw), body
|
||||
|
||||
|
||||
def route_path(route):
|
||||
if not isinstance(route, str) or not route.startswith('/') or '..' in Path(route).parts:
|
||||
raise ValueError(f'Unsafe route: {route}')
|
||||
return Path('index.html') if route == '/' else Path(route.strip('/')) / 'index.html'
|
||||
|
||||
|
||||
site = load(ROOT/'site.yaml')
|
||||
theme = load(ROOT/'theme.yaml')
|
||||
company = load(ROOT/'data/company.yaml')
|
||||
menus = {p.stem: load(p)['items'] for p in (ROOT/'menus').glob('*.yaml')}
|
||||
forms = {p.stem: load(p) for p in (ROOT/'forms').glob('*.yaml')}
|
||||
layouts = {d.name: load(d/'layout.yaml') for d in (ROOT/'layouts').iterdir() if d.is_dir()}
|
||||
fragments = {p.parent.name: p.parent.relative_to(ROOT) for p in (ROOT/'fragments').glob('*/*/fragment.yaml')}
|
||||
env = Environment(loader=FileSystemLoader(ROOT), autoescape=select_autoescape(['html','j2']))
|
||||
|
||||
entries = []
|
||||
for file in (ROOT/'content').glob('*/*.md'):
|
||||
data, body = parse_md(file)
|
||||
schema = load(ROOT/'collections'/f'{file.parent.name}.yaml')
|
||||
data.update({'collection': file.parent.name, 'body': body,
|
||||
'url': schema['route'].replace('{slug}', data['slug'])})
|
||||
entries.append(data)
|
||||
entry_by_key = {e['collection']+'/'+e['slug']: e for e in entries}
|
||||
CURRENT = Path('index.html')
|
||||
|
||||
|
||||
def site_link(route):
|
||||
return '../' * len(CURRENT.parent.parts) + route_path(route).as_posix()
|
||||
|
||||
|
||||
def asset_url(path):
|
||||
if not isinstance(path, str) or not path.startswith('assets/') or '..' in Path(path).parts:
|
||||
raise ValueError('Unsafe asset reference '+repr(path))
|
||||
return '../' * len(CURRENT.parent.parts) + path
|
||||
|
||||
|
||||
def read_bind(key, page, entry):
|
||||
parts = key.split('.')
|
||||
value = {'page': page, 'entry': entry or {}, 'data': {'company': company}}.get(parts.pop(0), {})
|
||||
for part in parts:
|
||||
if not isinstance(value, dict): return ''
|
||||
value = value.get(part, '')
|
||||
return value
|
||||
|
||||
|
||||
def resolve(value, page, entry):
|
||||
if isinstance(value, dict):
|
||||
if 'bind' in value: return read_bind(value['bind'], page, entry)
|
||||
return {k: resolve(v, page, entry) for k,v in value.items()}
|
||||
if isinstance(value, list): return [resolve(v, page, entry) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def query_entries(collection, sort='order', limit=6):
|
||||
schema_file = ROOT/'collections'/f'{collection}.yaml'
|
||||
if not schema_file.is_file() or not load(schema_file).get('enabled', True): return []
|
||||
result = [e for e in entries if e['collection']==collection and e.get('status')=='published']
|
||||
sort = str(sort)
|
||||
reverse = sort.startswith('-')
|
||||
field = sort.lstrip('-')
|
||||
result.sort(key=lambda e: e.get(field, 999) if field=='order' else str(e.get(field,'')), reverse=reverse)
|
||||
return result[:min(int(limit), 30)]
|
||||
|
||||
|
||||
def entry_by_ref(ref):
|
||||
e = entry_by_key.get(ref)
|
||||
return e if e and e.get('status')=='published' else None
|
||||
|
||||
|
||||
def gradients(role):
|
||||
settings = theme.get('overrides', {}).get('gradients', {})
|
||||
if not settings.get('enabled'): return ''
|
||||
definition = settings.get('definitions', {}).get(role)
|
||||
if not definition or definition.get('type') != 'linear': return ''
|
||||
stops = ', '.join(str(s['color'])+' '+str(s['at'])+'%' for s in definition['stops'])
|
||||
return f"linear-gradient({definition['angle']}deg, {stops})"
|
||||
|
||||
|
||||
VALID_CONTAINER_MODES = {'boxed','fluid','full'}
|
||||
|
||||
def get_container_config():
|
||||
raw = theme.get('overrides',{}).get('ui',{}).get('container',1080)
|
||||
if isinstance(raw,(int,float)): raw={'mode':'boxed','max_width':int(raw)}
|
||||
raw = raw if isinstance(raw,dict) else {}
|
||||
mode = raw.get('mode','boxed')
|
||||
max_width = int(raw.get('max_width',1080))
|
||||
gutter = {'desktop':36,'tablet':24,'mobile':16} | (raw.get('gutter',{}) or {})
|
||||
if mode not in VALID_CONTAINER_MODES or not 720 <= max_width <= 1920:
|
||||
raise ValueError('Invalid theme container mode/max_width')
|
||||
if any(not isinstance(x,int) or not 0 <= x <= 96 for x in gutter.values()):
|
||||
raise ValueError('Invalid responsive gutters')
|
||||
return {'mode':mode,'max_width':max_width,'gutter':gutter}
|
||||
|
||||
|
||||
def block_layout(block):
|
||||
raw = block.get('layout') or {}
|
||||
defaults = {'section_width':'full' if block['fragment'] in ('hero','cta_banner','site_header','site_footer') else 'inherit', 'content_width':'inherit'}
|
||||
result = defaults | raw
|
||||
for key in defaults:
|
||||
if result[key] not in VALID_CONTAINER_MODES | {'inherit'}:
|
||||
raise ValueError(f"Invalid {key} for {block.get('id')}")
|
||||
return result
|
||||
|
||||
|
||||
def effective_width(mode):
|
||||
return get_container_config()['mode'] if mode=='inherit' else mode
|
||||
|
||||
|
||||
def theme_style():
|
||||
overrides = theme.get('overrides', {})
|
||||
tokens = []
|
||||
for key, value in overrides.get('colors', {}).items(): tokens.append(('--color-'+key, value))
|
||||
for key, value in overrides.get('custom_colors', {}).items(): tokens.append(('--color-'+key.replace('_','-'), value))
|
||||
ui = overrides.get('ui', {})
|
||||
if 'radius' in ui: tokens.append(('--radius', str(ui['radius'])+'px'))
|
||||
container = get_container_config()
|
||||
tokens.extend([('--container', str(container['max_width'])+'px'),
|
||||
('--container-max',str(container['max_width'])+'px'),
|
||||
('--gutter-desktop',str(container['gutter']['desktop'])+'px'),
|
||||
('--gutter-tablet',str(container['gutter']['tablet'])+'px'),
|
||||
('--gutter-mobile',str(container['gutter']['mobile'])+'px')])
|
||||
typography = overrides.get('type', {})
|
||||
for part in ('heading','body'):
|
||||
if part in typography: tokens.append(('--font-'+part, typography[part]))
|
||||
tokens += [('--hero-gradient', gradients('hero') or '#1e2735'),
|
||||
('--button-gradient', gradients('button') or overrides['colors']['accent']),
|
||||
('--cta-gradient', gradients('cta') or overrides['colors']['secondary'])]
|
||||
# Inputs are trusted example tokens; backend must validate typed values before CSS output.
|
||||
return '<style>:root{'+';'.join(k+':'+str(v) for k,v in tokens)+'}</style>'
|
||||
|
||||
|
||||
def render_fragment(block, page, entry, body):
|
||||
fid = block['fragment']
|
||||
if fid not in fragments: raise ValueError(f'Unknown Fragment: {fid}')
|
||||
if block.get('visible') is False or block.get('hidden'): return ''
|
||||
template = env.get_template(str(fragments[fid]/'template.html.j2'))
|
||||
rendered = template.render(
|
||||
props=resolve(block.get('props', {}), page, entry), block=block, page=page, entry=entry,
|
||||
site=site, company=company, menus=menus, site_link=site_link, asset_url=asset_url,
|
||||
query_entries=query_entries, entry_by_ref=entry_by_ref,
|
||||
render_markdown=lambda value: mistune.create_markdown(escape=True)(value), content_body=body,
|
||||
get_form=forms.get)
|
||||
# Section width and inner content width are independent. No raw CSS from editable content.
|
||||
width = block_layout(block)
|
||||
outer = effective_width(width['section_width'])
|
||||
inner = effective_width(width['content_width'])
|
||||
return f'<div class="block-shell" data-section-width="{outer}" data-content-width="{inner}" data-block="{block["id"]}">{rendered}</div>'
|
||||
|
||||
|
||||
def render_page(page, body, route, entry=None):
|
||||
global CURRENT
|
||||
CURRENT = route_path(route)
|
||||
lid = page['layout']
|
||||
layout = layouts[lid]
|
||||
regions = {r['id']:r for r in layout['regions']}
|
||||
allowed = set(regions['main']['allow'])
|
||||
blocks = page.get('regions',{}).get('main', [])
|
||||
for block in blocks:
|
||||
if block['fragment'] not in allowed:
|
||||
raise ValueError(f"{page['title']}: Fragment {block['fragment']} disallowed in layout {lid}")
|
||||
def render_region(name):
|
||||
region = regions[name]
|
||||
source = blocks if name=='main' else region.get('fixed',[])
|
||||
return '\n'.join(render_fragment(block, page, entry, body) for block in source)
|
||||
layout_html = env.get_template(f'layouts/{lid}/layout.html.j2')
|
||||
html = layout_html.render(page=page, site=site, layout_id=lid, container_mode=get_container_config()['mode'], region=render_region,
|
||||
theme_style=theme_style(), static_css=asset_url('assets/site.css'),
|
||||
static_js=asset_url('assets/site.js'))
|
||||
output = OUT / CURRENT
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(html, encoding='utf-8')
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
if OUT.exists(): shutil.rmtree(OUT)
|
||||
OUT.mkdir(parents=True)
|
||||
shutil.copytree(ROOT/'assets', OUT/'assets', ignore=shutil.ignore_patterns('manifest.yaml'))
|
||||
documents = []
|
||||
for f in (ROOT/'pages').rglob('*.md'):
|
||||
page, body = parse_md(f)
|
||||
documents.append(render_page(page, body, page['route']))
|
||||
for entry in entries:
|
||||
if entry['status'] != 'published': continue
|
||||
display = load(ROOT/'display'/f"{entry['collection']}.yaml")
|
||||
page = {'title':entry['title'], 'layout':display['layout'],
|
||||
'seo':{'title':entry['title'], 'description':entry['summary']},
|
||||
'regions':display['regions']}
|
||||
documents.append(render_page(page, entry['body'], entry['url'], entry))
|
||||
print(f'Generated {len(documents)} HTML pages at {OUT}')
|
||||
for d in documents: print(' - '+str(d.relative_to(OUT)))
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate sample site file graph and generated preview; not a production schema validator."""
|
||||
from pathlib import Path
|
||||
from html.parser import HTMLParser
|
||||
import re
|
||||
import yaml
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
load=lambda p:yaml.safe_load(p.read_text(encoding='utf-8'))
|
||||
|
||||
def front(p):
|
||||
raw=p.read_text(encoding='utf8')
|
||||
if not raw.startswith('---\n'):raise ValueError('No YAML front matter '+str(p))
|
||||
return yaml.safe_load(raw[4:].split('\n---\n',1)[0])
|
||||
|
||||
errors=[];warnings=[]
|
||||
def err(message):errors.append(message)
|
||||
|
||||
def validate_yaml():
|
||||
yaml_files=list(ROOT.rglob('*.yaml'))
|
||||
for p in yaml_files:
|
||||
try: load(p)
|
||||
except Exception as ex:err(f'Invalid YAML {p.relative_to(ROOT)}: {ex}')
|
||||
print('YAML files:',len(yaml_files))
|
||||
return yaml_files
|
||||
|
||||
frags={};layout_ids=set()
|
||||
for p in ROOT.glob('fragments/*/*/fragment.yaml'):
|
||||
f=load(p)
|
||||
frags[f['id']]=p
|
||||
if not (p.parent/'template.html.j2').is_file():err('Fragment template missing: '+str(p))
|
||||
for p in ROOT.glob('layouts/*/layout.yaml'):
|
||||
obj=load(p);layout_ids.add(obj['id'])
|
||||
if not (p.parent/'layout.html.j2').is_file():err('Layout template missing: '+str(p))
|
||||
|
||||
routes={}
|
||||
for p in ROOT.glob('pages/**/*.md'):
|
||||
f=front(p)
|
||||
if f.get('route') in routes:err('Duplicate route '+f['route'])
|
||||
routes[f['route']]=p
|
||||
if f.get('layout') not in layout_ids:err('Unknown layout '+str(f['layout']))
|
||||
allowed=next((set(r['allow']) for r in load(ROOT/'layouts'/f['layout']/'layout.yaml')['regions'] if r['id']=='main'),set())
|
||||
ids=set()
|
||||
for b in f.get('regions',{}).get('main',[]):
|
||||
if b['id'] in ids:err(f'Duplicate block ID {b["id"]} in {p}')
|
||||
ids.add(b['id'])
|
||||
if b['fragment'] not in frags:err(f'Unknown Fragment {b["fragment"]} in {p}')
|
||||
if b['fragment'] not in allowed:err(f'Disallowed Fragment {b["fragment"]} in {p}')
|
||||
props=b.get('props',{})
|
||||
for k in ('buttonUrl',):
|
||||
if props.get(k) and props[k] not in routes:pass # check after all files collected
|
||||
if b['fragment']=='form' and not (ROOT/'forms'/f"{props['form_id']}.yaml").is_file():err('Missing form '+props['form_id'])
|
||||
if p.name=='index.md' and len(f.get('regions',{}).get('main',[]))==0:err('Empty index')
|
||||
|
||||
entries={}
|
||||
for p in ROOT.glob('content/*/*.md'):
|
||||
f=front(p)
|
||||
key=p.parent.name+'/'+f['slug']
|
||||
if key in entries:err('Duplicate Entry '+key)
|
||||
entries[key]=f
|
||||
if not (ROOT/'collections'/f'{p.parent.name}.yaml').is_file():err('Missing collection '+p.parent.name)
|
||||
if not (ROOT/'display'/f'{p.parent.name}.yaml').is_file():err('Missing display '+p.parent.name)
|
||||
if not f.get('title'):err('Missing Entry.title '+key)
|
||||
for fk in ('hero_asset',):
|
||||
asset=f.get(fk)
|
||||
if asset and not (ROOT/asset).is_file():
|
||||
if f['status']=='draft':warnings.append(f'Expected draft warning: {key} -> {asset}')
|
||||
else:err('Missing published asset '+asset)
|
||||
for fk,target in [('related_scenarios','scenarios'),('related_services','services')]:
|
||||
for slug in f.get(fk,[]):
|
||||
if not (ROOT/f'content/{target}/{slug}.md').is_file():err(f'Missing Entry reference {key} -> {target}/{slug}')
|
||||
for p in ROOT.glob('pages/**/*.md'):
|
||||
f=front(p)
|
||||
for b in f.get('regions',{}).get('main',[]):
|
||||
props=b.get('props',{})
|
||||
for key in ('buttonUrl',):
|
||||
link=props.get(key)
|
||||
if link and link not in routes:err(f'Broken link {link} from {p}')
|
||||
for key in ('asset','background'):
|
||||
asset=props.get(key)
|
||||
if asset and not (ROOT/asset).is_file():err(f'Missing page asset {asset} in {p}')
|
||||
if b['fragment']=='collection_list' and not (ROOT/'collections'/f"{props.get('collection')}.yaml").is_file():err(f'Missing query collection {props.get("collection")}')
|
||||
if b['fragment']=='entry_card' and props.get('entry') not in entries:err('Missing entry_card ref '+str(props.get('entry')))
|
||||
for p in ROOT.glob('menus/*.yaml'):
|
||||
for item in load(p)['items']:
|
||||
if item.get('enabled',True) and item.get('page') not in routes:err(f'Menu target not found: {item.get("page")} in {p}')
|
||||
for asset in load(ROOT/'assets/manifest.yaml')['files']:
|
||||
if not (ROOT/asset['path']).is_file():err('Asset manifest path missing: '+asset['path'])
|
||||
|
||||
class Links(HTMLParser):
|
||||
def __init__(self):super().__init__();self.refs=[]
|
||||
def handle_starttag(self,tag,attrs):
|
||||
d=dict(attrs)
|
||||
if tag in ('a','link','script','img'):
|
||||
val=d.get('href') or d.get('src')
|
||||
if val:self.refs.append(val)
|
||||
|
||||
html_docs=list((ROOT/'preview-dist').rglob('*.html'))
|
||||
for p in html_docs:
|
||||
links=Links();links.feed(p.read_text(encoding='utf8'))
|
||||
for ref in links.refs:
|
||||
if ref.startswith(('#','http:','https:','mailto:','tel:','data:')):continue
|
||||
r=(p.parent/ref.split('#',1)[0]).resolve()
|
||||
if not r.is_relative_to((ROOT/'preview-dist').resolve()):err(f'Preview link outside root {p}: {ref}')
|
||||
elif not r.is_file():err(f'Broken preview href/src {p.relative_to(ROOT)} -> {ref}')
|
||||
if len(html_docs)<12:err(f'Expected 12+ rendered pages, got {len(html_docs)}')
|
||||
print('Pages:',len(routes),'Entries:',len(entries),'Fragments:',len(frags),'Layouts:',len(layout_ids),'Static HTML:',len(html_docs))
|
||||
print('Warnings:',*warnings,sep='\n ')
|
||||
if errors:
|
||||
print('ERRORS:',*errors,sep='\n - ')
|
||||
raise SystemExit(1)
|
||||
print('PASS: YAML, file paths, entry refs, block IDs, layouts, menus, HTML links')
|
||||
Reference in New Issue
Block a user