fix(i18n): 🐞 infer RTL for mixed-script previews (#588)

* fix(i18n): 🐞 infer RTL for mixed-script previews

Infer preview direction from RTL letters in queries and project names without treating digits as letters. Allow callers to set the language and direction explicitly, and cover the behavior in the generated preview tests.

* fix(i18n): 🐞 refresh the preview relevance fingerprint

Refresh the runtime fingerprint while preserving the relevance thresholds and case results. Document and test explicit Persian and Urdu preview locales, and sync the upstream assets.
This commit is contained in:
Ash 2026-11-23 09:38:08 +05:30 committed by GitHub
parent 6ec2bb5833
commit 281e4537af
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 369 additions and 45 deletions

View File

@ -22,6 +22,7 @@ import re
import sys
import io
import tempfile
import unicodedata
from datetime import datetime
from pathlib import Path
from core import search, DATA_DIR
@ -37,6 +38,30 @@ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
# ============ CONFIGURATION ============
REASONING_FILE = "ui-reasoning.csv"
_RTL_LANGUAGES = {"ar", "fa", "he", "ps", "ur", "yi"}
def resolve_preview_locale(text: str, lang: str = None, direction: str = None) -> tuple:
"""Resolve preview language and direction; only letters count for inference."""
if lang:
default_direction = "rtl" if lang.split("-")[0].lower() in _RTL_LANGUAGES else "ltr"
return lang, direction or default_direction
for character in text:
if not character.isalpha() or unicodedata.bidirectional(character) not in {"R", "AL"}:
continue
name = unicodedata.name(character, "")
if name.startswith("ARABIC "):
inferred_lang = "ar"
elif name.startswith("HEBREW "):
inferred_lang = "he"
else:
inferred_lang = "und"
return inferred_lang, direction or "rtl"
return "en", direction or "ltr"
SEARCH_CONFIG = {
"product": {"max_results": 1},
"style": {"max_results": 3},
@ -472,7 +497,8 @@ class DesignSystemGenerator:
return search_result.get("results", [])
def generate(self, query: str, project_name: str = None,
variance: int = None, motion: int = None, density: int = None) -> dict:
variance: int = None, motion: int = None, density: int = None,
lang: str = None, direction: str = None) -> dict:
"""Generate complete design system recommendation.
variance/motion/density are optional 1-10 dials (see DIAL_TIERS) that bias
@ -543,8 +569,14 @@ class DesignSystemGenerator:
reasoning_effects = reasoning.get("key_effects", "")
combined_effects = style_effects if style_effects else reasoning_effects
preview_lang, preview_direction = resolve_preview_locale(query, lang=lang)
if not lang and preview_direction == "ltr" and project_name:
preview_lang, preview_direction = resolve_preview_locale(project_name)
return {
"project_name": project_name or query.upper(),
"lang": preview_lang,
"direction": direction or preview_direction,
"category": category,
"pattern": {
"name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
@ -1108,7 +1140,8 @@ def generate_design_system(query: str, project_name: str = None, output_format:
persist: bool = False, page: str = None, output_dir: str = None,
variance: int = None, motion: int = None, density: int = None,
force: bool = False, preview: bool = False,
token_format: str = None) -> dict:
token_format: str = None, lang: str = None,
direction: str = None) -> dict:
"""
Main entry point for design system generation.
@ -1125,6 +1158,8 @@ def generate_design_system(query: str, project_name: str = None, output_format:
force: If True, overwrite an existing MASTER.md; otherwise persistence
is skipped (with a status message) when one already exists
preview: If True, write a self-contained preview.html of this system
lang: Optional preview language tag (for example, "ar" or "he")
direction: Optional preview text direction ("ltr" or "rtl")
token_format: Optional "dtcg" or "css". When set, "text" is the token
document and persist writes tokens.json (and tokens.css for css)
next to MASTER.md. Tokens are master-level only; --page does not
@ -1138,7 +1173,10 @@ def generate_design_system(query: str, project_name: str = None, output_format:
(result of write_preview_html(), or None if preview=False)
"""
generator = DesignSystemGenerator()
design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
design_system = generator.generate(
query, project_name, variance=variance, motion=motion, density=density,
lang=lang, direction=direction,
)
tokens = build_design_tokens(design_system) if token_format else None

View File

@ -19,6 +19,7 @@ from design_system import (
_contrast_ratio,
_palette_is_dark,
_write_persisted_file,
resolve_preview_locale,
safe_slug,
)
@ -109,17 +110,14 @@ def _role_contrast(colors: dict, key: str):
def format_preview_html(design_system: dict) -> str:
"""Render a dependency-free HTML page for the generated design system."""
project = design_system.get("project_name") or "Design system"
# Detect RTL preview via explicit direction/lang metadata or Arabic script in project_name.
is_arabic = bool(
design_system.get("direction") == "rtl"
or design_system.get("lang") == "ar"
or re.search(r"[\u0600-\u06FF]", str(project))
html_lang, direction = resolve_preview_locale(
str(project), lang=design_system.get("lang"), direction=design_system.get("direction"),
)
html_lang = "ar" if is_arabic else "en"
html_dir = ' dir="rtl"' if is_arabic else ""
eyebrow_spacing = "0" if is_arabic else "0.08em"
eyebrow_transform = "none" if is_arabic else "uppercase"
badge_spacing = "0" if is_arabic else "0.04em"
is_rtl = direction == "rtl"
html_dir = ' dir="rtl"' if is_rtl else ""
eyebrow_spacing = "0" if is_rtl else "0.08em"
eyebrow_transform = "none" if is_rtl else "uppercase"
badge_spacing = "0" if is_rtl else "0.04em"
category = design_system.get("category") or ""
style = design_system.get("style") or {}
colors = design_system.get("colors") or {}
@ -220,7 +218,7 @@ def format_preview_html(design_system: dict) -> str:
anti_html = "".join(anti_items)
return f"""<!DOCTYPE html>
<html lang="{html_lang}"{html_dir}>
<html lang="{escape(html_lang)}"{html_dir}>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

View File

@ -34,6 +34,8 @@ Persistence (Master + Overrides pattern):
--preview Write preview.html for the generated system (requires --design-system).
With --persist, the file is written next to MASTER.md. Without --persist,
it is written to --output-dir or to a temp file whose path is printed.
--lang Set the preview language tag (e.g. ar, he)
--direction Set the preview text direction (ltr or rtl)
"""
import argparse
@ -134,6 +136,8 @@ if __name__ == "__main__":
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)")
parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)")
parser.add_argument("--preview", action="store_true", help="Write a self-contained preview.html of the generated design system (requires --design-system)")
parser.add_argument("--lang", help="Set the preview language tag, e.g. ar or he (requires --design-system)")
parser.add_argument("--direction", choices=["ltr", "rtl"], help="Set the preview text direction (requires --design-system)")
parser.add_argument("--tokens", choices=["dtcg", "css"], default=None,
help="Export design tokens as W3C DTCG JSON or CSS variables (requires --design-system)")
# Design dials (1-10), only applied with --design-system
@ -145,6 +149,8 @@ if __name__ == "__main__":
if args.preview and not args.design_system:
parser.error("--preview requires --design-system")
if (args.lang is not None or args.direction is not None) and not args.design_system:
parser.error("--lang and --direction require --design-system")
if args.tokens and not args.design_system:
parser.error("--tokens requires --design-system")
@ -174,6 +180,8 @@ if __name__ == "__main__":
force=args.force,
preview=args.preview,
token_format=args.tokens,
lang=args.lang,
direction=args.direction,
)
if args.json:

View File

@ -2,7 +2,7 @@
"schemaVersion": 1,
"status": "provisional-baseline-regression-gate",
"baselineRevision": "97eb2a2",
"runtimeFingerprint": "6f50331454236ff817a9617fdabbf8393309276e3b98e0005c0e007ccc933dbd",
"runtimeFingerprint": "1d07cd4f5994d613efe74c64d6f3a2c23e74364842d1781b6aa8c2e273154d5e",
"oracleFingerprint": "02e7226428c64a995ec24ae104ce4d186f5f91bf0f062556e90ef9b0fcb6d67a",
"approvingMaintainer": "repository maintainer approved Phase 1 testing checkpoint; second judgment review remains required before final-target promotion",
"units": "All metrics are ratios in [0,1]. Precision treats missing ranks as non-relevant. Negative abstention is measured across the hard-negative by domain/stack cross-product.",

View File

@ -15,6 +15,7 @@ import csv
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
@ -196,6 +197,65 @@ class ArabicSynonymsAndRtlPreviewTest(unittest.TestCase):
self.assertIn('<html lang="en">', en_html)
self.assertNotIn('dir="rtl">', en_html)
def test_generated_preview_uses_query_direction_with_an_english_brand(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
design_system = DesignSystemGenerator().generate("عيادة طبية", "Clinic")
self.assertIn('<html lang="ar" dir="rtl">', format_preview_html(design_system))
design_system = DesignSystemGenerator().generate("clinic", "عيادة طبية")
self.assertIn('<html lang="ar" dir="rtl">', format_preview_html(design_system))
def test_arabic_indic_digits_do_not_make_an_english_brand_rtl(self):
from preview import format_preview_html
self.assertIn('<html lang="en">', format_preview_html({"project_name": "Clinic ٢٠٢٦"}))
def test_rtl_query_can_start_with_a_latin_acronym(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
generator = DesignSystemGenerator()
design_system = generator.generate("SaaS لوحة تحكم", "Acme")
self.assertEqual(format_preview_html(design_system).splitlines()[1],
'<html lang="ar" dir="rtl">')
design_system = generator.generate("SaaS لوحة تحكم", "Acme", direction="ltr")
self.assertEqual(format_preview_html(design_system).splitlines()[1], '<html lang="ar">')
def test_rtl_project_name_can_start_with_a_latin_brand(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
for project_name, lang in (("Clinic — عيادة", "ar"), ("Clinic — מרפאה", "he")):
with self.subTest(project_name=project_name):
expected = f'<html lang="{lang}" dir="rtl">'
design_system = DesignSystemGenerator().generate("clinic", project_name)
self.assertEqual(format_preview_html(design_system).splitlines()[1], expected)
self.assertEqual(format_preview_html({"project_name": project_name}).splitlines()[1],
expected)
def test_design_system_cli_can_set_language_and_direction_independently(self):
with tempfile.TemporaryDirectory() as output_dir:
command = [sys.executable, str(SCRIPTS_DIR / "search.py"), "clinic",
"--design-system", "--preview", "--json", "--output-dir", output_dir]
for options, html_tag, direction in (
(["--lang", "he"], '<html lang="he" dir="rtl">', "rtl"),
(["--lang", "fa"], '<html lang="fa" dir="rtl">', "rtl"),
(["--lang", "ur"], '<html lang="ur" dir="rtl">', "rtl"),
(["--lang", "he", "--direction", "ltr"], '<html lang="he">', "ltr"),
(["--direction", "rtl"], '<html lang="en" dir="rtl">', "rtl"),
):
with self.subTest(options=options):
result = subprocess.run(command + ["--force", *options],
capture_output=True, text=True, encoding="utf-8")
self.assertEqual(result.returncode, 0, result.stderr)
payload = json.loads(result.stdout)
self.assertEqual(payload["design_system"]["direction"], direction)
preview_path = Path(payload["preview"]["preview_file"])
self.assertEqual(preview_path.read_text(encoding="utf-8").splitlines()[1], html_tag)
if __name__ == "__main__":
unittest.main()

View File

@ -531,6 +531,18 @@ python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design
`--preview` requires `--design-system`. With `--persist` it writes `preview.html` next to `MASTER.md`. Without `--persist`, pass `--output-dir` to write `preview.html` there, or omit it to get a temp file whose path is printed. Existing files are skipped unless you also pass `--force`.
The preview uses RTL layout when it finds an RTL letter in the query or, if
the query has none, in the project name. A leading Latin brand or acronym does
not prevent RTL inference, and digits alone do not trigger it. Use `--lang` to
set the HTML language tag and `--direction rtl` or `--direction ltr` to set
the layout direction explicitly. Arabic-script text defaults to `ar`. For
Persian or Urdu previews, pass `--lang fa` or `--lang ur` to set the language
while keeping the RTL layout.
```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "clinic" --design-system --preview -p "Clinic" --lang ar --direction rtl
```
`--tokens dtcg` prints W3C Design Tokens JSON; `--tokens css` prints `:root` CSS variables named the same way as `cli/assets/skills/design-system/scripts/generate-tokens.cjs`. Both require `--design-system`. With `--persist`, `tokens.json` is written beside `MASTER.md` (and `tokens.css` when `--tokens css`). `--page` overrides do not emit token files.
This creates a `design-system/` folder structure:

View File

@ -22,6 +22,7 @@ import re
import sys
import io
import tempfile
import unicodedata
from datetime import datetime
from pathlib import Path
from core import search, DATA_DIR
@ -37,6 +38,30 @@ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
# ============ CONFIGURATION ============
REASONING_FILE = "ui-reasoning.csv"
_RTL_LANGUAGES = {"ar", "fa", "he", "ps", "ur", "yi"}
def resolve_preview_locale(text: str, lang: str = None, direction: str = None) -> tuple:
"""Resolve preview language and direction; only letters count for inference."""
if lang:
default_direction = "rtl" if lang.split("-")[0].lower() in _RTL_LANGUAGES else "ltr"
return lang, direction or default_direction
for character in text:
if not character.isalpha() or unicodedata.bidirectional(character) not in {"R", "AL"}:
continue
name = unicodedata.name(character, "")
if name.startswith("ARABIC "):
inferred_lang = "ar"
elif name.startswith("HEBREW "):
inferred_lang = "he"
else:
inferred_lang = "und"
return inferred_lang, direction or "rtl"
return "en", direction or "ltr"
SEARCH_CONFIG = {
"product": {"max_results": 1},
"style": {"max_results": 3},
@ -472,7 +497,8 @@ class DesignSystemGenerator:
return search_result.get("results", [])
def generate(self, query: str, project_name: str = None,
variance: int = None, motion: int = None, density: int = None) -> dict:
variance: int = None, motion: int = None, density: int = None,
lang: str = None, direction: str = None) -> dict:
"""Generate complete design system recommendation.
variance/motion/density are optional 1-10 dials (see DIAL_TIERS) that bias
@ -543,8 +569,14 @@ class DesignSystemGenerator:
reasoning_effects = reasoning.get("key_effects", "")
combined_effects = style_effects if style_effects else reasoning_effects
preview_lang, preview_direction = resolve_preview_locale(query, lang=lang)
if not lang and preview_direction == "ltr" and project_name:
preview_lang, preview_direction = resolve_preview_locale(project_name)
return {
"project_name": project_name or query.upper(),
"lang": preview_lang,
"direction": direction or preview_direction,
"category": category,
"pattern": {
"name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
@ -1108,7 +1140,8 @@ def generate_design_system(query: str, project_name: str = None, output_format:
persist: bool = False, page: str = None, output_dir: str = None,
variance: int = None, motion: int = None, density: int = None,
force: bool = False, preview: bool = False,
token_format: str = None) -> dict:
token_format: str = None, lang: str = None,
direction: str = None) -> dict:
"""
Main entry point for design system generation.
@ -1125,6 +1158,8 @@ def generate_design_system(query: str, project_name: str = None, output_format:
force: If True, overwrite an existing MASTER.md; otherwise persistence
is skipped (with a status message) when one already exists
preview: If True, write a self-contained preview.html of this system
lang: Optional preview language tag (for example, "ar" or "he")
direction: Optional preview text direction ("ltr" or "rtl")
token_format: Optional "dtcg" or "css". When set, "text" is the token
document and persist writes tokens.json (and tokens.css for css)
next to MASTER.md. Tokens are master-level only; --page does not
@ -1138,7 +1173,10 @@ def generate_design_system(query: str, project_name: str = None, output_format:
(result of write_preview_html(), or None if preview=False)
"""
generator = DesignSystemGenerator()
design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
design_system = generator.generate(
query, project_name, variance=variance, motion=motion, density=density,
lang=lang, direction=direction,
)
tokens = build_design_tokens(design_system) if token_format else None

View File

@ -19,6 +19,7 @@ from design_system import (
_contrast_ratio,
_palette_is_dark,
_write_persisted_file,
resolve_preview_locale,
safe_slug,
)
@ -109,17 +110,14 @@ def _role_contrast(colors: dict, key: str):
def format_preview_html(design_system: dict) -> str:
"""Render a dependency-free HTML page for the generated design system."""
project = design_system.get("project_name") or "Design system"
# Detect RTL preview via explicit direction/lang metadata or Arabic script in project_name.
is_arabic = bool(
design_system.get("direction") == "rtl"
or design_system.get("lang") == "ar"
or re.search(r"[\u0600-\u06FF]", str(project))
html_lang, direction = resolve_preview_locale(
str(project), lang=design_system.get("lang"), direction=design_system.get("direction"),
)
html_lang = "ar" if is_arabic else "en"
html_dir = ' dir="rtl"' if is_arabic else ""
eyebrow_spacing = "0" if is_arabic else "0.08em"
eyebrow_transform = "none" if is_arabic else "uppercase"
badge_spacing = "0" if is_arabic else "0.04em"
is_rtl = direction == "rtl"
html_dir = ' dir="rtl"' if is_rtl else ""
eyebrow_spacing = "0" if is_rtl else "0.08em"
eyebrow_transform = "none" if is_rtl else "uppercase"
badge_spacing = "0" if is_rtl else "0.04em"
category = design_system.get("category") or ""
style = design_system.get("style") or {}
colors = design_system.get("colors") or {}
@ -220,7 +218,7 @@ def format_preview_html(design_system: dict) -> str:
anti_html = "".join(anti_items)
return f"""<!DOCTYPE html>
<html lang="{html_lang}"{html_dir}>
<html lang="{escape(html_lang)}"{html_dir}>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

View File

@ -34,6 +34,8 @@ Persistence (Master + Overrides pattern):
--preview Write preview.html for the generated system (requires --design-system).
With --persist, the file is written next to MASTER.md. Without --persist,
it is written to --output-dir or to a temp file whose path is printed.
--lang Set the preview language tag (e.g. ar, he)
--direction Set the preview text direction (ltr or rtl)
"""
import argparse
@ -134,6 +136,8 @@ if __name__ == "__main__":
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)")
parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)")
parser.add_argument("--preview", action="store_true", help="Write a self-contained preview.html of the generated design system (requires --design-system)")
parser.add_argument("--lang", help="Set the preview language tag, e.g. ar or he (requires --design-system)")
parser.add_argument("--direction", choices=["ltr", "rtl"], help="Set the preview text direction (requires --design-system)")
parser.add_argument("--tokens", choices=["dtcg", "css"], default=None,
help="Export design tokens as W3C DTCG JSON or CSS variables (requires --design-system)")
# Design dials (1-10), only applied with --design-system
@ -145,6 +149,8 @@ if __name__ == "__main__":
if args.preview and not args.design_system:
parser.error("--preview requires --design-system")
if (args.lang is not None or args.direction is not None) and not args.design_system:
parser.error("--lang and --direction require --design-system")
if args.tokens and not args.design_system:
parser.error("--tokens requires --design-system")
@ -174,6 +180,8 @@ if __name__ == "__main__":
force=args.force,
preview=args.preview,
token_format=args.tokens,
lang=args.lang,
direction=args.direction,
)
if args.json:

View File

@ -2,7 +2,7 @@
"schemaVersion": 1,
"status": "provisional-baseline-regression-gate",
"baselineRevision": "97eb2a2",
"runtimeFingerprint": "6f50331454236ff817a9617fdabbf8393309276e3b98e0005c0e007ccc933dbd",
"runtimeFingerprint": "1d07cd4f5994d613efe74c64d6f3a2c23e74364842d1781b6aa8c2e273154d5e",
"oracleFingerprint": "02e7226428c64a995ec24ae104ce4d186f5f91bf0f062556e90ef9b0fcb6d67a",
"approvingMaintainer": "repository maintainer approved Phase 1 testing checkpoint; second judgment review remains required before final-target promotion",
"units": "All metrics are ratios in [0,1]. Precision treats missing ranks as non-relevant. Negative abstention is measured across the hard-negative by domain/stack cross-product.",

View File

@ -15,6 +15,7 @@ import csv
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
@ -196,6 +197,65 @@ class ArabicSynonymsAndRtlPreviewTest(unittest.TestCase):
self.assertIn('<html lang="en">', en_html)
self.assertNotIn('dir="rtl">', en_html)
def test_generated_preview_uses_query_direction_with_an_english_brand(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
design_system = DesignSystemGenerator().generate("عيادة طبية", "Clinic")
self.assertIn('<html lang="ar" dir="rtl">', format_preview_html(design_system))
design_system = DesignSystemGenerator().generate("clinic", "عيادة طبية")
self.assertIn('<html lang="ar" dir="rtl">', format_preview_html(design_system))
def test_arabic_indic_digits_do_not_make_an_english_brand_rtl(self):
from preview import format_preview_html
self.assertIn('<html lang="en">', format_preview_html({"project_name": "Clinic ٢٠٢٦"}))
def test_rtl_query_can_start_with_a_latin_acronym(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
generator = DesignSystemGenerator()
design_system = generator.generate("SaaS لوحة تحكم", "Acme")
self.assertEqual(format_preview_html(design_system).splitlines()[1],
'<html lang="ar" dir="rtl">')
design_system = generator.generate("SaaS لوحة تحكم", "Acme", direction="ltr")
self.assertEqual(format_preview_html(design_system).splitlines()[1], '<html lang="ar">')
def test_rtl_project_name_can_start_with_a_latin_brand(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
for project_name, lang in (("Clinic — عيادة", "ar"), ("Clinic — מרפאה", "he")):
with self.subTest(project_name=project_name):
expected = f'<html lang="{lang}" dir="rtl">'
design_system = DesignSystemGenerator().generate("clinic", project_name)
self.assertEqual(format_preview_html(design_system).splitlines()[1], expected)
self.assertEqual(format_preview_html({"project_name": project_name}).splitlines()[1],
expected)
def test_design_system_cli_can_set_language_and_direction_independently(self):
with tempfile.TemporaryDirectory() as output_dir:
command = [sys.executable, str(SCRIPTS_DIR / "search.py"), "clinic",
"--design-system", "--preview", "--json", "--output-dir", output_dir]
for options, html_tag, direction in (
(["--lang", "he"], '<html lang="he" dir="rtl">', "rtl"),
(["--lang", "fa"], '<html lang="fa" dir="rtl">', "rtl"),
(["--lang", "ur"], '<html lang="ur" dir="rtl">', "rtl"),
(["--lang", "he", "--direction", "ltr"], '<html lang="he">', "ltr"),
(["--direction", "rtl"], '<html lang="en" dir="rtl">', "rtl"),
):
with self.subTest(options=options):
result = subprocess.run(command + ["--force", *options],
capture_output=True, text=True, encoding="utf-8")
self.assertEqual(result.returncode, 0, result.stderr)
payload = json.loads(result.stdout)
self.assertEqual(payload["design_system"]["direction"], direction)
preview_path = Path(payload["preview"]["preview_file"])
self.assertEqual(preview_path.read_text(encoding="utf-8").splitlines()[1], html_tag)
if __name__ == "__main__":
unittest.main()

View File

@ -22,6 +22,7 @@ import re
import sys
import io
import tempfile
import unicodedata
from datetime import datetime
from pathlib import Path
from core import search, DATA_DIR
@ -37,6 +38,30 @@ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
# ============ CONFIGURATION ============
REASONING_FILE = "ui-reasoning.csv"
_RTL_LANGUAGES = {"ar", "fa", "he", "ps", "ur", "yi"}
def resolve_preview_locale(text: str, lang: str = None, direction: str = None) -> tuple:
"""Resolve preview language and direction; only letters count for inference."""
if lang:
default_direction = "rtl" if lang.split("-")[0].lower() in _RTL_LANGUAGES else "ltr"
return lang, direction or default_direction
for character in text:
if not character.isalpha() or unicodedata.bidirectional(character) not in {"R", "AL"}:
continue
name = unicodedata.name(character, "")
if name.startswith("ARABIC "):
inferred_lang = "ar"
elif name.startswith("HEBREW "):
inferred_lang = "he"
else:
inferred_lang = "und"
return inferred_lang, direction or "rtl"
return "en", direction or "ltr"
SEARCH_CONFIG = {
"product": {"max_results": 1},
"style": {"max_results": 3},
@ -472,7 +497,8 @@ class DesignSystemGenerator:
return search_result.get("results", [])
def generate(self, query: str, project_name: str = None,
variance: int = None, motion: int = None, density: int = None) -> dict:
variance: int = None, motion: int = None, density: int = None,
lang: str = None, direction: str = None) -> dict:
"""Generate complete design system recommendation.
variance/motion/density are optional 1-10 dials (see DIAL_TIERS) that bias
@ -543,8 +569,14 @@ class DesignSystemGenerator:
reasoning_effects = reasoning.get("key_effects", "")
combined_effects = style_effects if style_effects else reasoning_effects
preview_lang, preview_direction = resolve_preview_locale(query, lang=lang)
if not lang and preview_direction == "ltr" and project_name:
preview_lang, preview_direction = resolve_preview_locale(project_name)
return {
"project_name": project_name or query.upper(),
"lang": preview_lang,
"direction": direction or preview_direction,
"category": category,
"pattern": {
"name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
@ -1108,7 +1140,8 @@ def generate_design_system(query: str, project_name: str = None, output_format:
persist: bool = False, page: str = None, output_dir: str = None,
variance: int = None, motion: int = None, density: int = None,
force: bool = False, preview: bool = False,
token_format: str = None) -> dict:
token_format: str = None, lang: str = None,
direction: str = None) -> dict:
"""
Main entry point for design system generation.
@ -1125,6 +1158,8 @@ def generate_design_system(query: str, project_name: str = None, output_format:
force: If True, overwrite an existing MASTER.md; otherwise persistence
is skipped (with a status message) when one already exists
preview: If True, write a self-contained preview.html of this system
lang: Optional preview language tag (for example, "ar" or "he")
direction: Optional preview text direction ("ltr" or "rtl")
token_format: Optional "dtcg" or "css". When set, "text" is the token
document and persist writes tokens.json (and tokens.css for css)
next to MASTER.md. Tokens are master-level only; --page does not
@ -1138,7 +1173,10 @@ def generate_design_system(query: str, project_name: str = None, output_format:
(result of write_preview_html(), or None if preview=False)
"""
generator = DesignSystemGenerator()
design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
design_system = generator.generate(
query, project_name, variance=variance, motion=motion, density=density,
lang=lang, direction=direction,
)
tokens = build_design_tokens(design_system) if token_format else None

View File

@ -19,6 +19,7 @@ from design_system import (
_contrast_ratio,
_palette_is_dark,
_write_persisted_file,
resolve_preview_locale,
safe_slug,
)
@ -109,17 +110,14 @@ def _role_contrast(colors: dict, key: str):
def format_preview_html(design_system: dict) -> str:
"""Render a dependency-free HTML page for the generated design system."""
project = design_system.get("project_name") or "Design system"
# Detect RTL preview via explicit direction/lang metadata or Arabic script in project_name.
is_arabic = bool(
design_system.get("direction") == "rtl"
or design_system.get("lang") == "ar"
or re.search(r"[\u0600-\u06FF]", str(project))
html_lang, direction = resolve_preview_locale(
str(project), lang=design_system.get("lang"), direction=design_system.get("direction"),
)
html_lang = "ar" if is_arabic else "en"
html_dir = ' dir="rtl"' if is_arabic else ""
eyebrow_spacing = "0" if is_arabic else "0.08em"
eyebrow_transform = "none" if is_arabic else "uppercase"
badge_spacing = "0" if is_arabic else "0.04em"
is_rtl = direction == "rtl"
html_dir = ' dir="rtl"' if is_rtl else ""
eyebrow_spacing = "0" if is_rtl else "0.08em"
eyebrow_transform = "none" if is_rtl else "uppercase"
badge_spacing = "0" if is_rtl else "0.04em"
category = design_system.get("category") or ""
style = design_system.get("style") or {}
colors = design_system.get("colors") or {}
@ -220,7 +218,7 @@ def format_preview_html(design_system: dict) -> str:
anti_html = "".join(anti_items)
return f"""<!DOCTYPE html>
<html lang="{html_lang}"{html_dir}>
<html lang="{escape(html_lang)}"{html_dir}>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

View File

@ -34,6 +34,8 @@ Persistence (Master + Overrides pattern):
--preview Write preview.html for the generated system (requires --design-system).
With --persist, the file is written next to MASTER.md. Without --persist,
it is written to --output-dir or to a temp file whose path is printed.
--lang Set the preview language tag (e.g. ar, he)
--direction Set the preview text direction (ltr or rtl)
"""
import argparse
@ -134,6 +136,8 @@ if __name__ == "__main__":
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)")
parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)")
parser.add_argument("--preview", action="store_true", help="Write a self-contained preview.html of the generated design system (requires --design-system)")
parser.add_argument("--lang", help="Set the preview language tag, e.g. ar or he (requires --design-system)")
parser.add_argument("--direction", choices=["ltr", "rtl"], help="Set the preview text direction (requires --design-system)")
parser.add_argument("--tokens", choices=["dtcg", "css"], default=None,
help="Export design tokens as W3C DTCG JSON or CSS variables (requires --design-system)")
# Design dials (1-10), only applied with --design-system
@ -145,6 +149,8 @@ if __name__ == "__main__":
if args.preview and not args.design_system:
parser.error("--preview requires --design-system")
if (args.lang is not None or args.direction is not None) and not args.design_system:
parser.error("--lang and --direction require --design-system")
if args.tokens and not args.design_system:
parser.error("--tokens requires --design-system")
@ -174,6 +180,8 @@ if __name__ == "__main__":
force=args.force,
preview=args.preview,
token_format=args.tokens,
lang=args.lang,
direction=args.direction,
)
if args.json:

View File

@ -2,7 +2,7 @@
"schemaVersion": 1,
"status": "provisional-baseline-regression-gate",
"baselineRevision": "97eb2a2",
"runtimeFingerprint": "6f50331454236ff817a9617fdabbf8393309276e3b98e0005c0e007ccc933dbd",
"runtimeFingerprint": "1d07cd4f5994d613efe74c64d6f3a2c23e74364842d1781b6aa8c2e273154d5e",
"oracleFingerprint": "02e7226428c64a995ec24ae104ce4d186f5f91bf0f062556e90ef9b0fcb6d67a",
"approvingMaintainer": "repository maintainer approved Phase 1 testing checkpoint; second judgment review remains required before final-target promotion",
"units": "All metrics are ratios in [0,1]. Precision treats missing ranks as non-relevant. Negative abstention is measured across the hard-negative by domain/stack cross-product.",

View File

@ -15,6 +15,7 @@ import csv
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
@ -196,6 +197,65 @@ class ArabicSynonymsAndRtlPreviewTest(unittest.TestCase):
self.assertIn('<html lang="en">', en_html)
self.assertNotIn('dir="rtl">', en_html)
def test_generated_preview_uses_query_direction_with_an_english_brand(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
design_system = DesignSystemGenerator().generate("عيادة طبية", "Clinic")
self.assertIn('<html lang="ar" dir="rtl">', format_preview_html(design_system))
design_system = DesignSystemGenerator().generate("clinic", "عيادة طبية")
self.assertIn('<html lang="ar" dir="rtl">', format_preview_html(design_system))
def test_arabic_indic_digits_do_not_make_an_english_brand_rtl(self):
from preview import format_preview_html
self.assertIn('<html lang="en">', format_preview_html({"project_name": "Clinic ٢٠٢٦"}))
def test_rtl_query_can_start_with_a_latin_acronym(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
generator = DesignSystemGenerator()
design_system = generator.generate("SaaS لوحة تحكم", "Acme")
self.assertEqual(format_preview_html(design_system).splitlines()[1],
'<html lang="ar" dir="rtl">')
design_system = generator.generate("SaaS لوحة تحكم", "Acme", direction="ltr")
self.assertEqual(format_preview_html(design_system).splitlines()[1], '<html lang="ar">')
def test_rtl_project_name_can_start_with_a_latin_brand(self):
from design_system import DesignSystemGenerator
from preview import format_preview_html
for project_name, lang in (("Clinic — عيادة", "ar"), ("Clinic — מרפאה", "he")):
with self.subTest(project_name=project_name):
expected = f'<html lang="{lang}" dir="rtl">'
design_system = DesignSystemGenerator().generate("clinic", project_name)
self.assertEqual(format_preview_html(design_system).splitlines()[1], expected)
self.assertEqual(format_preview_html({"project_name": project_name}).splitlines()[1],
expected)
def test_design_system_cli_can_set_language_and_direction_independently(self):
with tempfile.TemporaryDirectory() as output_dir:
command = [sys.executable, str(SCRIPTS_DIR / "search.py"), "clinic",
"--design-system", "--preview", "--json", "--output-dir", output_dir]
for options, html_tag, direction in (
(["--lang", "he"], '<html lang="he" dir="rtl">', "rtl"),
(["--lang", "fa"], '<html lang="fa" dir="rtl">', "rtl"),
(["--lang", "ur"], '<html lang="ur" dir="rtl">', "rtl"),
(["--lang", "he", "--direction", "ltr"], '<html lang="he">', "ltr"),
(["--direction", "rtl"], '<html lang="en" dir="rtl">', "rtl"),
):
with self.subTest(options=options):
result = subprocess.run(command + ["--force", *options],
capture_output=True, text=True, encoding="utf-8")
self.assertEqual(result.returncode, 0, result.stderr)
payload = json.loads(result.stdout)
self.assertEqual(payload["design_system"]["direction"], direction)
preview_path = Path(payload["preview"]["preview_file"])
self.assertEqual(preview_path.read_text(encoding="utf-8").splitlines()[1], html_tag)
if __name__ == "__main__":
unittest.main()