synth-shell-theme 1.3.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. synth_shell_theme/__init__.py +7 -0
  2. synth_shell_theme/__main__.py +8 -0
  3. synth_shell_theme/assets/studio.html +1920 -0
  4. synth_shell_theme/cli.py +887 -0
  5. synth_shell_theme/core.py +1695 -0
  6. synth_shell_theme/ecosystem.py +537 -0
  7. synth_shell_theme/patches.py +1853 -0
  8. synth_shell_theme/paths.py +363 -0
  9. synth_shell_theme/separators.py +320 -0
  10. synth_shell_theme/server.py +506 -0
  11. synth_shell_theme/themes/01-screenshot-match.conf +30 -0
  12. synth_shell_theme/themes/02-current-live-theme.conf +30 -0
  13. synth_shell_theme/themes/03-dracula-punch.conf +30 -0
  14. synth_shell_theme/themes/04-nord-ice.conf +30 -0
  15. synth_shell_theme/themes/05-matrix-green.conf +30 -0
  16. synth_shell_theme/themes/06-amber-heat.conf +30 -0
  17. synth_shell_theme/themes/07-cloud-ops.conf +30 -0
  18. synth_shell_theme/themes/08-catppuccin-mauve.conf +30 -0
  19. synth_shell_theme/themes/09-solarized-night.conf +30 -0
  20. synth_shell_theme/themes/10-gruvbox-dark.conf +30 -0
  21. synth_shell_theme/themes/11-monokai-neon.conf +30 -0
  22. synth_shell_theme/themes/12-tokyo-night.conf +30 -0
  23. synth_shell_theme/themes/13-synthwave-pink.conf +30 -0
  24. synth_shell_theme/themes/14-forest-mint.conf +30 -0
  25. synth_shell_theme/themes/15-ruby-steel.conf +30 -0
  26. synth_shell_theme/themes/16-ice-gold.conf +30 -0
  27. synth_shell_theme/themes/17-aqua-slate.conf +30 -0
  28. synth_shell_theme/themes/18-cyber-lime.conf +30 -0
  29. synth_shell_theme/themes/19-lavender-sunset.conf +30 -0
  30. synth_shell_theme/themes/20-minimal-mono.conf +30 -0
  31. synth_shell_theme/themes/21-rose-pine.conf +30 -0
  32. synth_shell_theme/themes/22-kanagawa.conf +30 -0
  33. synth_shell_theme/themes/23-everforest.conf +30 -0
  34. synth_shell_theme/themes/24-one-dark.conf +30 -0
  35. synth_shell_theme/themes/25-ayu-dark.conf +30 -0
  36. synth_shell_theme/themes/26-nightfox.conf +30 -0
  37. synth_shell_theme/themes/27-palenight.conf +30 -0
  38. synth_shell_theme/themes/28-cyberdream.conf +30 -0
  39. synth_shell_theme/themes/29-moonlight.conf +30 -0
  40. synth_shell_theme/themes/30-poimandres.conf +30 -0
  41. synth_shell_theme/themes/31-tokyo-storm.conf +30 -0
  42. synth_shell_theme/themes/32-catppuccin-mocha.conf +30 -0
  43. synth_shell_theme/themes/33-nordic-aurora.conf +30 -0
  44. synth_shell_theme/themes/34-horizon-synth.conf +30 -0
  45. synth_shell_theme/themes/35-gruvbox-material.conf +30 -0
  46. synth_shell_theme/themes/36-oxocarbon.conf +30 -0
  47. synth_shell_theme/themes/37-catppuccin-latte.conf +30 -0
  48. synth_shell_theme/themes/38-tokyo-twilight.conf +30 -0
  49. synth_shell_theme/themes/39-solarized-ocean.conf +30 -0
  50. synth_shell_theme/themes/40-vaporwave-sunset.conf +30 -0
  51. synth_shell_theme/themes/41-deep-abyss.conf +30 -0
  52. synth_shell_theme/themes/42-sakura-blossom.conf +30 -0
  53. synth_shell_theme/themes/43-emerald-forest.conf +30 -0
  54. synth_shell_theme/themes/44-vesper.conf +30 -0
  55. synth_shell_theme/themes/45-cobalt-neon.conf +30 -0
  56. synth_shell_theme/themes/46-desert-dunes.conf +30 -0
  57. synth_shell_theme/themes/47-cyber-samurai.conf +30 -0
  58. synth_shell_theme/themes/48-glacier-mint.conf +30 -0
  59. synth_shell_theme/themes/49-carbon-titanium.conf +30 -0
  60. synth_shell_theme/themes/50-matcha-latte.conf +30 -0
  61. synth_shell_theme/themes/51-volcanic-magma.conf +30 -0
  62. synth_shell_theme/themes/52-catppuccin-frappe.conf +30 -0
  63. synth_shell_theme/themes/53-bioluminescence.conf +30 -0
  64. synth_shell_theme/themes/54-mocha-caramel.conf +30 -0
  65. synth_shell_theme/themes/55-neon-genesis.conf +30 -0
  66. synth_shell_theme/themes/56-midnight-amethyst.conf +30 -0
  67. synth_shell_theme/themes/57-andromeda.conf +30 -0
  68. synth_shell_theme/themes/58-golden-velvet.conf +30 -0
  69. synth_shell_theme/themes/59-miami-vice.conf +30 -0
  70. synth_shell_theme/themes/60-zen-garden.conf +30 -0
  71. synth_shell_theme/themes/61-google-cloud.conf +30 -0
  72. synth_shell_theme/themes/62-github-dark.conf +30 -0
  73. synth_shell_theme/themes/63-cyberpunk-edgerunners.conf +30 -0
  74. synth_shell_theme/themes/64-vscode-dark.conf +30 -0
  75. synth_shell_theme/themes.py +580 -0
  76. synth_shell_theme/tui.py +632 -0
  77. synth_shell_theme-1.3.9.dist-info/METADATA +261 -0
  78. synth_shell_theme-1.3.9.dist-info/RECORD +82 -0
  79. synth_shell_theme-1.3.9.dist-info/WHEEL +5 -0
  80. synth_shell_theme-1.3.9.dist-info/entry_points.txt +3 -0
  81. synth_shell_theme-1.3.9.dist-info/licenses/LICENSE +21 -0
  82. synth_shell_theme-1.3.9.dist-info/top_level.txt +1 -0
@@ -0,0 +1,580 @@
1
+ """Theme catalog, 256-color/RGB palette math, and ANSI terminal rendering for synth-shell-theme."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+ from pathlib import Path
8
+
9
+ from synth_shell_theme.paths import get_themes_dir, get_user_themes_dir
10
+
11
+ RESET = "\033[0m"
12
+ BOLD = "\033[1m"
13
+ DIM = "\033[2m"
14
+
15
+ NAMED_COLORS: dict[str, int] = {
16
+ "black": 0,
17
+ "red": 1,
18
+ "green": 2,
19
+ "yellow": 3,
20
+ "blue": 4,
21
+ "purple": 5,
22
+ "magenta": 5,
23
+ "pink": 5,
24
+ "cyan": 6,
25
+ "light-gray": 7,
26
+ "dark-gray": 8,
27
+ "light-red": 9,
28
+ "light-green": 10,
29
+ "light-yellow": 11,
30
+ "light-blue": 12,
31
+ "light-purple": 13,
32
+ "light-magenta": 13,
33
+ "light-cyan": 14,
34
+ "white": 15,
35
+ }
36
+
37
+ # Crisp dark-terminal 16 ANSI base colors matching xterm / modern terminal emulators
38
+ ANSI_16_HEX: tuple[str, ...] = (
39
+ "#000000", # 0 black
40
+ "#cc3333", # 1 red
41
+ "#2eb85c", # 2 green
42
+ "#d9a300", # 3 yellow
43
+ "#3377dd", # 4 blue
44
+ "#9944cc", # 5 purple
45
+ "#1fb2c2", # 6 cyan
46
+ "#d0d0d0", # 7 light-gray
47
+ "#585858", # 8 dark-gray
48
+ "#ff5f5f", # 9 light-red
49
+ "#5fd787", # 10 light-green
50
+ "#ffd75f", # 11 light-yellow
51
+ "#5fafff", # 12 light-blue
52
+ "#d787ff", # 13 light-purple
53
+ "#5fffff", # 14 light-cyan
54
+ "#ffffff", # 15 white
55
+ )
56
+
57
+ _CUBE_STEPS: tuple[int, ...] = (0, 95, 135, 175, 215, 255)
58
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
59
+
60
+ SEGMENT_KEYS: tuple[str, ...] = (
61
+ "user",
62
+ "host",
63
+ "pwd",
64
+ "git",
65
+ "pyenv",
66
+ "tf",
67
+ "kube",
68
+ "clock",
69
+ "status",
70
+ "duration",
71
+ "aws",
72
+ "gcp",
73
+ "docker",
74
+ "node",
75
+ "ssh",
76
+ "jobs",
77
+ "direnv",
78
+ "shlvl",
79
+ "rust",
80
+ "go",
81
+ "battery",
82
+ "sudo",
83
+ "jj",
84
+ "custom",
85
+ "input",
86
+ )
87
+
88
+ DEFAULT_SEGMENT_COLORS: dict[str, tuple[str, str]] = {
89
+ "user": ("white", "blue"),
90
+ "host": ("white", "237"),
91
+ "pwd": ("black", "255"),
92
+ "git": ("black", "71"),
93
+ "pyenv": ("white", "63"),
94
+ "tf": ("black", "228"),
95
+ "kube": ("black", "135"),
96
+ "clock": ("white", "240"),
97
+ "status": ("white", "196"),
98
+ "duration": ("black", "220"),
99
+ "aws": ("black", "208"),
100
+ "gcp": ("white", "33"),
101
+ "docker": ("white", "39"),
102
+ "node": ("black", "76"),
103
+ "ssh": ("white", "125"),
104
+ "jobs": ("black", "214"),
105
+ "direnv": ("black", "114"),
106
+ "shlvl": ("white", "99"),
107
+ "rust": ("white", "166"),
108
+ "go": ("black", "81"),
109
+ "battery": ("black", "114"),
110
+ "sudo": ("white", "196"),
111
+ "jj": ("black", "214"),
112
+ "custom": ("black", "219"),
113
+ "input": ("white", "none"),
114
+ }
115
+
116
+ _HEX_COLOR_RE = re.compile(r"^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$")
117
+
118
+
119
+ def normalize_hex_color(token: str | int | None) -> str | None:
120
+ """Return normalized `#rrggbb` lowercase hex string if `token` is a hex color, else None."""
121
+ if not isinstance(token, str):
122
+ return None
123
+ clean = token.strip().strip('"').strip("'")
124
+ m = _HEX_COLOR_RE.match(clean)
125
+ if not m:
126
+ return None
127
+ raw = m.group(1).lower()
128
+ if len(raw) == 3:
129
+ raw = "".join(ch * 2 for ch in raw)
130
+ return f"#{raw}"
131
+
132
+
133
+ def hex_to_nearest_256(hex_color: str) -> int:
134
+ """Map a `#rrggbb` TrueColor hex string to the nearest xterm-256 index (16..255)."""
135
+ norm = normalize_hex_color(hex_color)
136
+ if not norm:
137
+ return 15
138
+ r = int(norm[1:3], 16)
139
+ g = int(norm[3:5], 16)
140
+ b = int(norm[5:7], 16)
141
+
142
+ best_idx = 16
143
+ best_dist = 10**9
144
+ for idx in range(16, 256):
145
+ hx = index_to_hex(idx)
146
+ if not hx:
147
+ continue
148
+ cr = int(hx[1:3], 16)
149
+ cg = int(hx[3:5], 16)
150
+ cb = int(hx[5:7], 16)
151
+ dist = (r - cr) ** 2 + (g - cg) ** 2 + (b - cb) ** 2
152
+ if dist < best_dist:
153
+ best_dist = dist
154
+ best_idx = idx
155
+ return best_idx
156
+
157
+
158
+ def color_index(token: str | int | None) -> int | None:
159
+ """Resolve a synth-shell color token (0-255, named color, or #rrggbb) to an xterm-256 index."""
160
+ if token is None:
161
+ return None
162
+ if isinstance(token, int):
163
+ return token if 0 <= token <= 255 else None
164
+ clean = str(token).strip().strip('"').strip("'").lower()
165
+ if clean in ("none", "transparent", "default", ""):
166
+ return None
167
+ hx = normalize_hex_color(clean)
168
+ if hx:
169
+ return hex_to_nearest_256(hx)
170
+ if clean in NAMED_COLORS:
171
+ return NAMED_COLORS[clean]
172
+ try:
173
+ num = int(clean)
174
+ if 0 <= num <= 255:
175
+ return num
176
+ except ValueError:
177
+ pass
178
+ return None
179
+
180
+
181
+ def index_to_hex(idx: int | None) -> str | None:
182
+ """Convert an xterm-256 color index (0..255) into a `#rrggbb` CSS hex color."""
183
+ if idx is None or not (0 <= idx <= 255):
184
+ return None
185
+ if idx < 16:
186
+ return ANSI_16_HEX[idx]
187
+ if idx < 232:
188
+ offset = idx - 16
189
+ r = _CUBE_STEPS[(offset // 36) % 6]
190
+ g = _CUBE_STEPS[(offset // 6) % 6]
191
+ b = _CUBE_STEPS[offset % 6]
192
+ return f"#{r:02x}{g:02x}{b:02x}"
193
+ gray = 8 + 10 * (idx - 232)
194
+ return f"#{gray:02x}{gray:02x}{gray:02x}"
195
+
196
+
197
+ def token_to_hex(token: str | int | None, fallback: str | None = None) -> str | None:
198
+ """Resolve any synth-shell color token (including #rrggbb TrueColor) directly to `#rrggbb`."""
199
+ hx = normalize_hex_color(token)
200
+ if hx:
201
+ return hx
202
+ idx = color_index(token)
203
+ if idx is None:
204
+ return fallback
205
+ return index_to_hex(idx) or fallback
206
+
207
+
208
+ def ansi_fg(idx: int | None) -> str:
209
+ """Return 256-color ANSI foreground escape sequence."""
210
+ return f"\033[38;5;{idx}m" if idx is not None else ""
211
+
212
+
213
+ def ansi_bg(idx: int | None) -> str:
214
+ """Return 256-color ANSI background escape sequence."""
215
+ return f"\033[48;5;{idx}m" if idx is not None else ""
216
+
217
+
218
+ def visible_len(text: str) -> int:
219
+ """Calculate printable display column width after stripping ANSI escape sequences."""
220
+ plain = _ANSI_RE.sub("", text)
221
+ width = 0
222
+ for ch in plain:
223
+ cat = unicodedata.east_asian_width(ch)
224
+ width += 2 if cat in ("W", "F") else 1
225
+ return width
226
+
227
+
228
+ def pad_to(text: str, width: int) -> str:
229
+ """Pad `text` with trailing spaces to reach `width` visible columns."""
230
+ diff = width - visible_len(text)
231
+ return text + (" " * max(diff, 0))
232
+
233
+
234
+ def is_color_key(key: str) -> bool:
235
+ """Return True if `key` is a prompt segment color variable (`font_color_*` or `background_*`)."""
236
+ return (key.startswith("font_color_") or key.startswith("background_")) and not key.startswith("_")
237
+
238
+
239
+ def parse_theme(path: Path) -> dict[str, object]:
240
+ """Parse a bundled or custom `.conf` theme file into a structured dictionary."""
241
+ stem = path.stem
242
+ m_id = re.match(r"^(\d+)[-_]?(.*)$", stem)
243
+ theme_id = int(m_id.group(1)) if m_id else 0
244
+ slug = (m_id.group(2) if m_id and m_id.group(2) else stem).lower()
245
+
246
+ data: dict[str, object] = {
247
+ "id": theme_id,
248
+ "slug": slug,
249
+ "name": slug.replace("-", " ").title(),
250
+ "badge": "Theme",
251
+ "description": "",
252
+ "swatch256": [],
253
+ "_name": "",
254
+ "_path": path,
255
+ }
256
+
257
+ for raw_line in path.read_text(encoding="utf-8").splitlines():
258
+ line = raw_line.strip()
259
+ if not line:
260
+ continue
261
+ m_title = re.match(r"^#\s*Theme\s+\d+:\s*(.+)$", line)
262
+ if m_title:
263
+ title = m_title.group(1).strip()
264
+ data["name"] = title
265
+ data["_name"] = title
266
+ continue
267
+ m_swatch = re.match(r"^#\s*swatch256:\s*(.+)$", line)
268
+ if m_swatch:
269
+ swatches = [int(tok) for tok in m_swatch.group(1).split() if tok.isdigit()]
270
+ data["swatch256"] = swatches
271
+ continue
272
+ m_badge = re.match(r"^#\s*badge:\s*(.+)$", line)
273
+ if m_badge:
274
+ data["badge"] = m_badge.group(1).strip()
275
+ continue
276
+ m_desc = re.match(r"^#\s*description:\s*(.+)$", line)
277
+ if m_desc:
278
+ data["description"] = m_desc.group(1).strip()
279
+ continue
280
+ if line.startswith("#"):
281
+ continue
282
+ m_kv = re.match(r"^(\w+)\s*=\s*\$?['\"]?([^'\"]*)['\"]?\s*$", line)
283
+ if m_kv:
284
+ data[m_kv.group(1)] = m_kv.group(2).strip()
285
+
286
+ if not data["_name"]:
287
+ data["_name"] = data["name"]
288
+ return data
289
+
290
+
291
+ def load_themes(
292
+ themes_dir: Path | None = None,
293
+ include_user_themes: bool = True,
294
+ config_dir: Path | None = None,
295
+ ) -> list[dict[str, object]]:
296
+ """Load all bundled `.conf` themes plus any user-created custom themes in `~/.config/synth-shell/themes/`."""
297
+ directory = themes_dir if themes_dir is not None else get_themes_dir()
298
+ if not directory.is_dir():
299
+ raise FileNotFoundError(f"Themes directory not found: {directory}")
300
+ files = sorted(directory.glob("*.conf"))
301
+ if not files:
302
+ raise FileNotFoundError(f"No .conf theme files found in: {directory}")
303
+ themes = [parse_theme(f) for f in files]
304
+ for idx, t in enumerate(themes, 1):
305
+ t["custom"] = False
306
+ if not t.get("id"):
307
+ t["id"] = idx
308
+
309
+ if include_user_themes and themes_dir is None:
310
+ user_dir = get_user_themes_dir(config_dir)
311
+ if user_dir.is_dir():
312
+ for uf in sorted(user_dir.glob("*.conf")):
313
+ ut = parse_theme(uf)
314
+ ut["custom"] = True
315
+ ut["id"] = len(themes) + 1
316
+ themes.append(ut)
317
+
318
+ return themes
319
+
320
+
321
+ def save_custom_theme(
322
+ name: str,
323
+ colors: dict[str, str],
324
+ description: str = "",
325
+ badge: str = "Custom",
326
+ config_dir: Path | None = None,
327
+ ) -> dict[str, object]:
328
+ """Save a custom theme (supporting 256-color and #RRGGBB TrueColor) into `~/.config/synth-shell/themes/`."""
329
+ clean_name = name.strip()
330
+ if not clean_name:
331
+ raise ValueError("Theme name cannot be empty.")
332
+ slug = re.sub(r"[^a-z0-9]+", "-", clean_name.lower()).strip("-") or "custom-theme"
333
+ user_dir = get_user_themes_dir(config_dir)
334
+ user_dir.mkdir(parents=True, exist_ok=True)
335
+ dest = user_dir / f"{slug}.conf"
336
+
337
+ h_idx = color_index(colors.get("background_host", "237")) or 237
338
+ p_idx = color_index(colors.get("background_pwd", "255")) or 255
339
+ g_idx = color_index(colors.get("background_git", "71")) or 71
340
+
341
+ lines = [
342
+ f"# Theme 0: {clean_name}",
343
+ f"# swatch256: {h_idx} {p_idx} {g_idx}",
344
+ f"# badge: {badge.strip() or 'Custom'}",
345
+ f"# description: {description.strip() or 'Custom user theme created in Synth-Shell Theme Studio.'}",
346
+ 'format="HOST PWD GIT PYENV TF KUBE"',
347
+ 'separator_char="\\uE0B4"',
348
+ 'separator_char_end="\\uE0B0"',
349
+ 'enable_vertical_padding="true"',
350
+ 'enable_command_on_new_line="true"',
351
+ "",
352
+ ]
353
+ for seg in SEGMENT_KEYS:
354
+ def_fg, def_bg = DEFAULT_SEGMENT_COLORS[seg]
355
+ fg_k = f"font_color_{seg}"
356
+ bg_k = f"background_{seg}"
357
+ fg_val = str(colors.get(fg_k, def_fg)).strip() or def_fg
358
+ bg_val = str(colors.get(bg_k, def_bg)).strip() or def_bg
359
+ if fg_k in colors or seg in ("host", "pwd", "git", "pyenv", "tf", "kube", "input"):
360
+ lines.append(f'{fg_k}="{fg_val}"')
361
+ if bg_k in colors or seg in ("host", "pwd", "git", "pyenv", "tf", "kube", "input"):
362
+ lines.append(f'{bg_k}="{bg_val}"')
363
+
364
+ dest.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
365
+ parsed = parse_theme(dest)
366
+ parsed["custom"] = True
367
+ return parsed
368
+
369
+
370
+ def find_theme(
371
+ query: str | int,
372
+ themes: list[dict[str, object]],
373
+ ) -> tuple[dict[str, object] | None, int | None]:
374
+ """Find a theme by 1-based index, slug, or name. Returns `(theme, 1-based-index)`."""
375
+ if isinstance(query, int) or (isinstance(query, str) and query.strip().isdigit()):
376
+ idx = int(str(query).strip())
377
+ if 1 <= idx <= len(themes):
378
+ return themes[idx - 1], idx
379
+ return None, None
380
+
381
+ q = str(query).strip().lower().replace("-", " ").replace("_", " ")
382
+ if not q:
383
+ return None, None
384
+
385
+ # 1. Exact name match
386
+ for i, t in enumerate(themes, 1):
387
+ t_name = str(t.get("name", "")).lower().replace("-", " ").replace("_", " ")
388
+ if t_name == q:
389
+ return t, i
390
+
391
+ # 2. Exact slug / stem match
392
+ for i, t in enumerate(themes, 1):
393
+ slug = str(t.get("slug", "")).lower().replace("-", " ").replace("_", " ")
394
+ stem = Path(t["_path"]).stem.lower().replace("-", " ").replace("_", " ") # type: ignore[arg-type]
395
+ if q in (slug, stem):
396
+ return t, i
397
+
398
+ # 3. Unique substring match
399
+ matches: list[tuple[dict[str, object], int]] = []
400
+ raw_q = str(query).strip().lower()
401
+ for i, t in enumerate(themes, 1):
402
+ t_name = str(t.get("name", "")).lower()
403
+ slug = str(t.get("slug", "")).lower()
404
+ if raw_q in t_name or raw_q in slug or q in t_name.replace("-", " "):
405
+ matches.append((t, i))
406
+ if len(matches) == 1:
407
+ return matches[0]
408
+
409
+ return None, None
410
+
411
+
412
+ def filter_themes(
413
+ query: str,
414
+ themes: list[dict[str, object]],
415
+ badge: str = "",
416
+ ) -> list[tuple[int, dict[str, object]]]:
417
+ """Return `(1-based-index, theme)` pairs matching `query` and optional `badge`."""
418
+ q = query.strip().lower()
419
+ b = badge.strip().lower()
420
+ results: list[tuple[int, dict[str, object]]] = []
421
+ for i, t in enumerate(themes, 1):
422
+ if b and str(t.get("badge", "")).lower() != b:
423
+ continue
424
+ if not q:
425
+ results.append((i, t))
426
+ continue
427
+ haystack = " ".join(
428
+ [
429
+ str(t.get("name", "")),
430
+ str(t.get("slug", "")),
431
+ str(t.get("badge", "")),
432
+ str(t.get("description", "")),
433
+ f"#{i:02d}",
434
+ ]
435
+ ).lower()
436
+ if q in haystack:
437
+ results.append((i, t))
438
+ return results
439
+
440
+
441
+ def render_segment(text: str, fg: int | None, bg: int | None) -> str:
442
+ """Render a single padded segment in 256-color ANSI."""
443
+ parts: list[str] = []
444
+ if bg is not None:
445
+ parts.append(ansi_bg(bg))
446
+ if fg is not None:
447
+ parts.append(ansi_fg(fg))
448
+ parts.append(BOLD)
449
+ parts.append(f" {text} ")
450
+ return "".join(parts)
451
+
452
+
453
+ def render_separator(prev_bg: int | None, next_bg: int | None, sep: str) -> str:
454
+ """Render a Powerline transition glyph between `prev_bg` and `next_bg`."""
455
+ parts: list[str] = []
456
+ if prev_bg is not None:
457
+ parts.append(ansi_fg(prev_bg))
458
+ if next_bg is not None:
459
+ parts.append(ansi_bg(next_bg))
460
+ else:
461
+ parts.append(RESET)
462
+ if prev_bg is not None:
463
+ parts.append(ansi_fg(prev_bg))
464
+ parts.append(sep)
465
+ return "".join(parts)
466
+
467
+
468
+ def render_prompt_line(
469
+ theme: dict[str, object],
470
+ segments: list[tuple[str, str]],
471
+ command: str,
472
+ sep: str = "\ue0b4",
473
+ sep_end: str | None = "\ue0b0",
474
+ force_white: bool = False,
475
+ ) -> str:
476
+ """Render a complete sample prompt line with dual separator and input command preview."""
477
+ out: list[str] = []
478
+ final_sep = sep_end if sep_end else sep
479
+ for i, (key, text) in enumerate(segments):
480
+ fg_token = "white" if force_white else str(theme.get(f"font_color_{key}", "white"))
481
+ fg = color_index(fg_token)
482
+ bg = color_index(str(theme.get(f"background_{key}", "0")))
483
+ out.append(render_segment(text, fg, bg))
484
+ if i + 1 < len(segments):
485
+ next_key = segments[i + 1][0]
486
+ next_bg = color_index(str(theme.get(f"background_{next_key}", "0")))
487
+ out.append(render_separator(bg, next_bg, sep))
488
+ else:
489
+ out.append(render_separator(bg, None, final_sep))
490
+
491
+ input_fg = color_index(str(theme.get("font_color_input", "white")))
492
+ out.append(RESET)
493
+ if input_fg is not None:
494
+ out.append(ansi_fg(input_fg))
495
+ out.append(BOLD)
496
+ out.append(f" {command}")
497
+ out.append(RESET)
498
+ return "".join(out)
499
+
500
+
501
+ def build_card_lines(
502
+ theme: dict[str, object],
503
+ index: int,
504
+ current_name: str | None,
505
+ sep: str = "\ue0b4",
506
+ sep_end: str | None = "\ue0b0",
507
+ force_white: bool = False,
508
+ ) -> list[str]:
509
+ """Build a 3-line terminal preview card for a theme."""
510
+ name = str(theme.get("name", "Unknown"))
511
+ badge = str(theme.get("badge", ""))
512
+ tag = f" \033[33;1m← active{RESET}" if current_name and name == current_name else ""
513
+ badge_str = f" {DIM}[{badge}]{RESET}" if badge else ""
514
+
515
+ h_bg = color_index(str(theme.get("background_host", "0")))
516
+ p_bg = color_index(str(theme.get("background_pwd", "0")))
517
+ g_bg = color_index(str(theme.get("background_git", "0")))
518
+ swatch = f" {ansi_bg(h_bg)} {ansi_bg(p_bg)} {ansi_bg(g_bg)} {RESET}"
519
+
520
+ num_label = f"{BOLD}{DIM}#{index:02d}{RESET}"
521
+ return [
522
+ f"{num_label} {BOLD}{name}{RESET}{badge_str}{swatch}{tag}",
523
+ render_prompt_line(
524
+ theme,
525
+ [("host", "dev"), ("pwd", "~/workspace/app"), ("git", "main")],
526
+ "git status",
527
+ sep=sep,
528
+ sep_end=sep_end,
529
+ force_white=force_white,
530
+ ),
531
+ render_prompt_line(
532
+ theme,
533
+ [
534
+ ("host", "dev"),
535
+ ("pwd", "~/api"),
536
+ ("git", "feat ◔"),
537
+ ("pyenv", ".venv"),
538
+ ("tf", "prod"),
539
+ ("kube", "☸ gke"),
540
+ ],
541
+ "kubectl get pods",
542
+ sep=sep,
543
+ sep_end=sep_end,
544
+ force_white=force_white,
545
+ ),
546
+ ]
547
+
548
+
549
+ def serialize_theme_for_web(theme: dict[str, object], index: int) -> dict[str, object]:
550
+ """Serialize a parsed theme with precomputed `#rrggbb` CSS hex colors for Web Studio."""
551
+ segments_css: dict[str, dict[str, str | None]] = {}
552
+ raw_colors: dict[str, str] = {}
553
+
554
+ for seg in SEGMENT_KEYS:
555
+ def_fg, def_bg = DEFAULT_SEGMENT_COLORS[seg]
556
+ fg_tok = str(theme.get(f"font_color_{seg}", def_fg))
557
+ bg_tok = str(theme.get(f"background_{seg}", def_bg))
558
+ raw_colors[f"font_color_{seg}"] = fg_tok
559
+ raw_colors[f"background_{seg}"] = bg_tok
560
+ segments_css[seg] = {
561
+ "fg": token_to_hex(fg_tok, "#ffffff"),
562
+ "bg": token_to_hex(bg_tok, None),
563
+ "fg_token": fg_tok,
564
+ "bg_token": bg_tok,
565
+ }
566
+
567
+ return {
568
+ "id": index,
569
+ "slug": str(theme.get("slug", "")),
570
+ "name": str(theme.get("name", "")),
571
+ "badge": str(theme.get("badge", "Theme")),
572
+ "description": str(theme.get("description", "")),
573
+ "swatch": [
574
+ segments_css["host"]["bg"] or "#333333",
575
+ segments_css["pwd"]["bg"] or "#666666",
576
+ segments_css["git"]["bg"] or "#444444",
577
+ ],
578
+ "segments": segments_css,
579
+ "raw_colors": raw_colors,
580
+ }