"""Build-time module registration and editable examples for the Ziran gallery.""" import argparse import json import re import subprocess import textwrap from pathlib import Path import tomllib ROOT = Path(__file__).resolve().parents[1] PROJECT = ROOT / 'examples/gallery' SITE = ROOT / 'docs/site' def write(path, text): path.parent.mkdir(parents=True, exist_ok=True) if not path.exists() or path.read_text() != text: path.write_text(text) def closing(text, start): depth, quote, escape, comment = 0, False, False, False for at in range(start, len(text)): ch = text[at] if comment: if ch == '\n': comment = False continue if quote: if escape: escape = False elif ch == '\\': escape = True elif ch == '"': quote = False continue if ch == '/' and text[at:at + 2] == '//': comment = True; continue if ch == '"': quote = True; continue if ch == '{': depth += 1 elif ch == '}': depth -= 1 if not depth: return at raise ValueError('Unclosed example body') def branches(text, start): result = [] at = start while True: opening = text.index('{', at) condition = text[at:opening].strip().removeprefix('else ').removeprefix('if ') end = closing(text, opening) result.append((None if condition == 'else' else condition, text[opening + 1:end], at)) following = re.match(r'\s*else\b', text[end + 1:]) if not following: return result, end at = end + 1 + following.end() - 4 def selected(condition, index): if condition is None: return True assert re.fullmatch(r'[a-z0-9_ <>=!&|()+-]+', condition), condition return eval(condition.replace('&&', ' and ').replace('||', ' or '), {'__builtins__': {}}, {'scene': index}) def scene_apis(fragment): apis = [] for name in re.findall(r'(? string {{\n' for entry in entries: text = value(entry) if '\n' in text: marker = 'GALLERY_SOURCE_' + str(entry['index']) result += f" if index == {entry['index']} {{ return #string {marker}\n{text}\n{marker}\n }}\n" else: result += f" if index == {entry['index']} {{ return {json.dumps(text, ensure_ascii=False)} }}\n" return result + ' return ""\n}\n' registry = '#import "kryon/geometry"\n#import "kryon/session"\n#import "palette"\n' + '\n'.join(imports) + '\n' registry += 'catalog_viewport: Rectangle = .{0.0, 0.0, 480.0, 320.0};\n' registry += f'GallerySceneCount :: {len(entries)};\n' registry += 'GalleryCompilerSearch :: () -> string {\n return #string GALLERY_COMPILER_SEARCH\n' + '\n'.join(compiler_paths(modules)) + '\nGALLERY_COMPILER_SEARCH\n}\n' registry += string_function('GallerySceneName', lambda e: e['name']) registry += string_function('GallerySceneCode', lambda e: (Path(site) / e['code']).read_text()) registry += string_function('GallerySceneId', lambda e: e['id']) registry += string_function('GallerySceneSummary', lambda e: e['summary']) core = {'kryon', 'inputs', 'overlays'} registry += string_function('GallerySceneLabel', lambda e: ( '' if e['moduleId'] in core else e['module'] + ' / ') + e['category'] + ' ยท ' + e['name']) navigation = sorted(entries, key=lambda e: (e['moduleId'] not in ('kryon', 'inputs', 'overlays'), '' if e['moduleId'] in ('kryon', 'inputs', 'overlays') else e['module'], e['category'], e['name'])) registry += string_function('GallerySceneGroup', lambda e: ( '' if e['moduleId'] in core else e['module'] + ' / ') + e['category']) registry += 'GalleryNavigationScene :: (position: s32) -> s32 {\n' for position, entry in enumerate(navigation): registry += f" if position == {position} {{ return {entry['index']} }}\n" registry += ' return 0\n}\n' registry += 'InstallGalleryPalette :: (dark: bool) {\n InstallCatalogPalette(dark)\n' + '\n'.join(styles) + '\n}\n' registry += 'catalog_reduced_motion: bool;\n' registry += 'SetGalleryPreview :: (bounds: Rectangle, live: bool, now: float32, reduced_motion: bool) {\n catalog_viewport = bounds; catalog_reduced_motion = reduced_motion\n' + '}\n' registry += 'ComposeGallery :: (session: Session, scene: s32, disabled: bool) {\n' + '\n'.join(dispatch) + '\n}\n' write(output / 'catalog.zi', registry) write(output / 'modules.json', json.dumps(modules, indent=2) + '\n') for entry in entries: related = [other['id'] for other in entries if other['id'] != entry['id'] and ( other['category'] == entry['category'] or set(other['api']) & set(entry['api']))] entry['related'] = related[:6] write(Path(site) / 'gallery-data.js', 'window.galleryModules = ' + json.dumps([{'id': m['id'], 'label': m['label']} for m in modules]) + ';\nwindow.galleryScenes = ' + json.dumps(entries, ensure_ascii=False, indent=2) + ';\n') return modules, entries if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--modules', help='Comma-separated module IDs for an isolated build') args = parser.parse_args() modules, entries = prepare(None if args.modules is None else set(args.modules.split(','))) print('Prepared module integrations: ' + ', '.join(m['label'] for m in modules))