One type system for the hero, proven in the .pen

- The Pencil frames had the term->value pairs as a single $font-body text
  node, so labels like КОМАНДА rendered in Roboto while every other label is
  Montserrat. They are now a frame with Термин ($font-heading 700/11 upper)
  and Описание ($font-body 400/14), same in V1/V2/390 frames.
- The planet art in the five new frames is an image fill again instead of a
  black rectangle (the generator wrote a solid fill).
- Nine hero roles pinned to production computed styles, written into
  DESIGN.md and checked by scripts/verify-pen.py: 0 violations on the canon.
- .pen reserialised, previous state kept in archive/snapshot-2026-11-15-b.pen.
  src/ is untouched: production already matched the table, the drift was only
  in the design file.
This commit is contained in:
FastD committed 2026-11-15 21:02:32 +03:00
1 parent 5325b929cc
commit 446ed39da8
7 files changed
+28949 -999

No files matched your search

+450
View File
@@ -0,0 +1,450 @@
#!/usr/bin/env python3
# generate-hero-frames-v2.py — пересобирает пять hero-кадров в каноне .pen (JSON 2.21)
# из ОДНОЙ таблицы типографических ролей (ROLES / ROLES_1366 / ROLES_390).
#
# Источник значений — computed styles прода (headless Chromium, src/index.html,
# light theme): measure-hero.json. Допуск по кеглю — 0 px.
#
# Правило: заголовки и метки — только $font-heading (Montserrat), проза — только $font-body (Roboto).
# Пары «термин → значение» — ДВА узла: Термин ($font-heading 700/11 uppercase) + Описание ($font-body).
#
# Запуск: py generate-hero-frames-v2.py <canon.pen> <out.pen>
import json, sys, pathlib, copy
HEAD = "$font-heading"
BODY = "$font-body"
# ---------------------------------------------------------------- таблица ролей
# weight — ЧИСЛО: OpenPencil 0.16 читает `fontWeight` только числом; строку "800"
# он молча отбрасывает и рисует Regular (замер: get_node → fontWeight 400).
def role(family, weight, size, lh, ls=0, align=None):
return dict(family=family, weight=int(weight), size=size, lh=lh, ls=ls, align=align)
ROLES = {
"h1": role(HEAD, 800, 54, 1.1, 1),
"offer": role(BODY, 400, 19, 1.5, 0),
"bar_title": role(HEAD, 700, 18, 1.1, 0.5),
"bar_lead": role(BODY, 400, 14, 1.38, 0),
"stat_value": role(HEAD, 800, 23, 1.0, 0),
"stat_label": role(HEAD, 600, 10, 1.5, 0.8),
"card_title": role(HEAD, 700, 12, 1.1, 1.2),
"card_lead": role(BODY, 400, 14, 1.36, 0),
"term": role(HEAD, 700, 11, 1.5, 1),
"desc": role(BODY, 400, 14, 1.36, 0),
"chip": role(HEAD, 600, 12, 1.5, 1),
"cta": role(HEAD, 700, 14, 1.0, 1),
"nav": role(HEAD, 600, 13, 1.2, 1),
"logo": role(HEAD, 800, 20, 1.2, 1),
"ticker": role(HEAD, 600, 14, 1.5, 1),
}
ROLES_1366 = dict(ROLES, **{
"bar_title": role(HEAD, 700, 17, 1.1, 0.5),
"bar_lead": role(BODY, 400, 14, 1.32, 0),
"stat_value": role(HEAD, 800, 20, 1.0, 0),
"card_lead": role(BODY, 400, 14, 1.32, 0),
"desc": role(BODY, 400, 14, 1.32, 0),
})
ROLES_390 = dict(ROLES, **{
"h1": role(HEAD, 800, 34, 1.1, 1),
"logo": role(HEAD, 800, 16, 1.2, 1),
"bar_title": role(HEAD, 700, 20, 1.1, 1),
"bar_lead": role(BODY, 400, 14, 1.55, 0),
"stat_value": role(HEAD, 800, 20, 1.0, 0),
"stat_label": role(HEAD, 600, 10, 1.5, 1),
"card_lead": role(BODY, 400, 15, 1.5, 0),
"desc": role(BODY, 400, 15, 1.5, 0),
})
# ---------------------------------------------------------------- контент (утверждён)
BAR_TITLE = "Студия полного цикла"
BAR_LEAD = ("Аутсорс-студия полного цикла: пять руководителей направлений ведут продукт "
"от идеи до релиза и поддержки — внутри студии, без передачи на сторону.")
STATS = [("5", "НАПРАВЛЕНИЙ"), ("20", "ПРОЕКТОВ"), ("5", "РЕЛИЗОВ"), ("100%", "СВОЙ ПРОДАКШН")]
CARD1_TITLE, CARD2_TITLE = "КТО МЫ", "СТЕК И ТЕХНОЛОГИИ"
CARD1_LEAD = ("Аутсорс-студия полного цикла — геймдев, мобильные приложения и веб-сервисы под ключ. "
"Работаем над проектом — от прототипа до релиза и поддержки.")
CARD2_LEAD = ("Для разных задач — разные движки. Крупные 3D-проекты собираем на Unreal Engine, "
"браузерные и мобильные игры — на Godot. Полюбили его за простоту.")
PAIRS = [("КОМАНДА", "Пять руководителей направлений: разработка и стратегия, продукт-менеджмент, "
"3D и анимация, backend и сети, аналитика."),
("ПОРТФОЛИО", "20 проектов в каталоге: пять релизов, четыре проекта в работе, остальные — "
"в разработке. NDA-проекты показываем только с разрешения заказчика."),
("ФОРМАТЫ", "Outstaff, outsourcing и fixed price — подбираем под задачу и бюджет.")]
# натуральные ширины подписей, замер в canvas-шрифте (Montserrat 600 12 + ls 1):
# measure-chip.mjs, chromium-1223. Рамка чипа = подпись + 24 px (padding 4/12 из прода).
CHIP_TEXT_W = {"UNREAL ENGINE": 118, "UNITY": 44, "GODOT": 52, "C++": 26, "C#": 20,
"THREE.JS": 68, "WEBGL": 53}
CHIP_GROUPS = [("ДВИЖКИ", ["UNREAL ENGINE", "UNITY", "GODOT"]),
("ЯЗЫКИ", ["C++", "C#"]),
("WEB 3D", ["THREE.JS", "WEBGL"])]
TICKER_TEXT = ("5 РУКОВОДИТЕЛЕЙ НАПРАВЛЕНИЙ · 20 ПРОЕКТОВ В КАТАЛОГЕ · 5 РЕЛИЗОВ · "
"СВОЙ ПРОДАКШН · UNREAL ENGINE · UNITY · GODOT")
LABEL_TRACK = 104 # --brief-label:104px
PAIR_GAP = 16 # --brief-gap 16px
PLANET_ASPECT = 400 / 311 # арт планеты 400×311
# ---------------------------------------------------------------- хелперы
class Ids:
def __init__(self, taken):
self.taken = set(taken)
self.n = 0
def __call__(self):
while True:
self.n += 1
cand = "hz%04d" % self.n
if cand not in self.taken:
self.taken.add(cand)
return cand
def collect_ids(node, acc):
if isinstance(node, dict):
if "id" in node and isinstance(node["id"], str):
acc.add(node["id"])
for v in node.values():
collect_ids(v, acc)
elif isinstance(node, list):
for v in node:
collect_ids(v, acc)
return acc
# OpenPencil 0.16 игнорирует ключ `stroke` — границу несёт только массив `strokes`
# (замер: get_node по узлу с "stroke": "$line-strong" отдаёт fills без strokes, рамка
# не рисуется). Поэтому переменная резолвится в RGBA светлой темы и пишется в `strokes`;
# ключ `stroke` оставлен как исторический дубль формата Pencil-JSON.
VARS = {}
def hex_rgba(h):
h = h.strip().lstrip("#")
if len(h) == 8:
r, g, b, a = (int(h[i:i+2], 16) for i in (0, 2, 4, 6))
return dict(r=r/255, g=g/255, b=b/255, a=a/255)
r, g, b = (int(h[i:i+2], 16) for i in (0, 2, 4))
return dict(r=r/255, g=g/255, b=b/255, a=1)
def resolve(var):
"""'$b-line-strong' → {'r':..,'g':..,'b':..,'a':..} по светлому значению переменной."""
if not var:
return None
name = var[1:] if var.startswith("$") else var
v = VARS.get(name)
if not v:
raise SystemExit(f"неизвестная переменная: {var}")
val = v.get("value")
if isinstance(val, list):
light = next((x["value"] for x in val if x.get("theme", {}).get("mode") == "light"), None)
val = light or val[0]["value"]
if not isinstance(val, str) or not val.startswith("#"):
raise SystemExit(f"переменная {var} не цвет: {val!r}")
return hex_rgba(val)
def T(nid, name, content, r, width, fill, *, grow="fixed-width", h=None):
n = {"type": "text", "id": nid(), "name": name, "fill": fill,
"textGrowth": grow, "width": round(width, 2), "content": content,
"lineHeight": r["lh"], "fontFamily": r["family"], "fontSize": r["size"],
"fontWeight": r["weight"], "letterSpacing": r["ls"]}
if r["align"]:
n["textAlign"] = r["align"]
if h is not None:
n["height"] = round(h, 2)
return n
def F(nid, name, width, *, height=None, layout="vertical", gap=None, padding=None,
fill=None, radius=None, items=None, justify=None, stroke=None, stroke_width=None,
x=None, y=None, theme=None, clip=False):
n = {"type": "frame", "id": nid(), "name": name, "width": round(width, 2)}
if height is not None: n["height"] = round(height, 2)
if x is not None: n["x"] = x
if y is not None: n["y"] = y
if layout: n["layout"] = layout
if gap: n["gap"] = gap
if padding: n["padding"] = padding
if fill: n["fill"] = fill
if radius is not None: n["cornerRadius"] = radius
if items: n["alignItems"] = items
if justify: n["justifyContent"] = justify
if stroke:
n["stroke"] = stroke
n["strokes"] = [{"type": "SOLID", "color": resolve(stroke),
"weight": stroke_width or 1, "opacity": 1,
"visible": True, "align": "INSIDE"}]
if stroke_width: n["strokeWidth"] = stroke_width
if theme: n["theme"] = {"mode": theme}
if clip: n["clip"] = True
n["children"] = []
return n
def add(parent, *nodes):
parent["children"].extend(nodes)
return parent
# ---------------------------------------------------------------- блоки
def navbar(nid, R, w, side_pad):
nb = F(nid, "Navbar", w, height=85, layout="horizontal", padding=[0, side_pad, 0, side_pad],
fill="$b-nav", items="center", justify="space-between")
add(nb,
T(nid, "Логотип", "HARVEY MONSTER TEAM", R["logo"], 320, "$b-text-1"),
add(F(nid, "Ссылки", 480, layout="horizontal", gap=34, items="center"),
*[T(nid, f"Надпись {x}", x.upper(), R["nav"], 100, "$b-text-2")
for x in ("Работы", "Подход", "Команда", "Контакты")]),
add(F(nid, "CTA в баре", 192, height=48, layout="horizontal", fill="$b-brand", radius=12,
items="center", justify="center"),
T(nid, "Подпись кнопки", "НАПИСАТЬ НАМ", R["cta"], 140, "$b-on-brand", )))
nb["children"][-1]["children"][0]["textAlign"] = "center"
return nb
def copy_block(nid, R, w):
c = F(nid, "Копия", w, layout="vertical", gap=12)
cta = F(nid, "CTA", 384, height=48, layout="horizontal", gap=14)
b1 = add(F(nid, "Кнопка primary", 192, height=48, layout="horizontal", fill="$b-brand",
radius=12, items="center", justify="center"),
T(nid, "Написать нам", "НАПИСАТЬ НАМ", R["cta"], 140, "$b-on-brand"))
b1["children"][0]["textAlign"] = "center"
b2 = add(F(nid, "Кнопка ghost", 192, height=48, layout="horizontal", radius=12,
stroke="$b-brand-deep", stroke_width=2, items="center", justify="center"),
T(nid, "Наши работы", "НАШИ РАБОТЫ", R["cta"], 140, "$b-brand-deep"))
b2["children"][0]["textAlign"] = "center"
add(cta, b1, b2)
add(c,
T(nid, "H1", "ИГРЫ И СЕРВИСЫ ПОД КЛЮЧ", R["h1"], w, "$b-text-1"),
T(nid, "Оффер", "Разрабатываем игры, мобильные приложения и веб-сервисы.",
R["offer"], w, "$b-text-2"),
cta)
return c
def planet(nid, w):
return F(nid, "Арт планеты (Work_files/Planet)", w, height=round(w / PLANET_ASPECT, 2),
fill="#000000", radius=16)
def visual_col(nid, col_w, planet_w):
v = F(nid, "Колонка визуала", col_w, layout="horizontal", items="center", justify="center")
add(v, planet(nid, planet_w))
return v
def stat_cell(nid, R, v, l, cell_w, pad_left=0, hairline=False):
sf = F(nid, f"Стат {v}", cell_w, layout="vertical", gap=3,
padding=[0, 0, 0, pad_left] if pad_left else None)
if hairline:
sf["stroke"] = "$b-hairline"; sf["strokeWidth"] = 1
inner_w = cell_w - pad_left
add(sf,
T(nid, "Значение", v, R["stat_value"], inner_w, "$b-text-1"),
T(nid, "Подпись", l, R["stat_label"], inner_w, "$b-text-3"))
return sf
def bar_wide(nid, R, w=1200, h=87, gap=28, pad=20, intro_w=556, stats_w=546):
"""V2: полоса на всю ширину — заголовок · лид | цифры в ряд."""
b = F(nid, "Строка 2 · полоса на всю ширину", w, height=h, layout="horizontal",
gap=gap, padding=[12, pad, 12, pad], fill="$b-card", radius=16, items="center")
add(b,
add(F(nid, "Вступление полосы", intro_w, layout="vertical", gap=4),
T(nid, "Титул полосы", BAR_TITLE.upper(), R["bar_title"], intro_w, "$b-text-1"),
T(nid, "Лид полосы", BAR_LEAD, R["bar_lead"], intro_w, "$b-text-2")),
(lambda st: (add(st, *[stat_cell(nid, R, v, l,
132 if i == 0 else 138,
0 if i == 0 else 16,
hairline=(i > 0))
for i, (v, l) in enumerate(STATS)]), st)[1])(
F(nid, "Статы", stats_w, layout="horizontal", gap=0, items="center")))
return b
def bar_compact(nid, R, w, pad_x=18, pad_y=16):
"""V1: полоса в узкой колонке, цифры в ряд."""
b = F(nid, "Полоса «Студия полного цикла»", w, layout="vertical", gap=8,
padding=[pad_y, pad_x, pad_y, pad_x], fill="$b-card", radius=16)
inner = w - 2 * pad_x
add(b, T(nid, "Титул полосы", BAR_TITLE.upper(), R["bar_title"], inner, "$b-text-1"),
T(nid, "Лид полосы", BAR_LEAD, R["bar_lead"], inner, "$b-text-2"))
cell_w = (inner - 3 * 14) / 4
add(b, add(F(nid, "Статы", inner, layout="horizontal", gap=14),
*[stat_cell(nid, R, v, l, cell_w) for v, l in STATS]))
return b
def bar_mobile(nid, R, w, pad=18):
b = F(nid, "Строка 2 · полоса на всю ширину", w, layout="vertical", gap=16,
padding=[pad, pad, pad, pad], fill="$b-card", radius=16)
inner = w - 2 * pad
title_box = F(nid, "Титул блок", inner, height=44, layout="vertical")
add(title_box, T(nid, "Титул полосы", "СТУДИЯ ПОЛНОГО ЦИКЛА", R["bar_title"], inner, "$b-text-1"))
add(b, title_box,
T(nid, "Лид полосы", BAR_LEAD, R["bar_lead"], inner, "$b-text-2"))
half = (inner - 22) / 2
st = F(nid, "Статы", inner, layout="horizontal", gap=22)
col1 = F(nid, "Статы колонка 1", half, layout="vertical", gap=10)
col2 = F(nid, "Статы колонка 2", half, layout="vertical", gap=10)
for i, (v, l) in enumerate(STATS):
add(col1 if i % 2 == 0 else col2, stat_cell(nid, R, v, l, half))
add(st, col1, col2)
add(b, st)
return b
def card_header(nid, R, inner, text, dot):
row = F(nid, "Заголовок с маркером", inner, layout="horizontal", gap=9, items="center")
if dot:
add(row, F(nid, "Маркер", 8, height=8, fill="$b-accent", radius=2))
add(row, T(nid, "Заголовок плашки", text, R["card_title"], inner - (17 if dot else 0), "$b-text-1"))
return row
def pair(nid, R, term, body, inner):
"""«термин → значение» = ДВА узла: метка-роль Montserrat + проза Roboto (висячий отступ)."""
row = F(nid, "Пара " + term, inner, layout="horizontal", gap=PAIR_GAP)
add(row,
T(nid, "Термин", term, R["term"], LABEL_TRACK, "$b-brand-deep"),
T(nid, "Описание", body, R["desc"], inner - LABEL_TRACK - PAIR_GAP, "$b-text-2"))
return row
def pair_stacked(nid, R, term, body, inner):
"""≤767: трек сворачивается — метка над значением (DESIGN.md, Layout)."""
box = F(nid, "Пара " + term, inner, layout="vertical", gap=2)
add(box,
T(nid, "Термин", term, R["term"], inner, "$b-brand-deep"),
T(nid, "Описание", body, R["desc"], inner, "$b-text-2"))
return box
def card_kto(nid, R, w, h, *, dot, stacked_pairs):
c = F(nid, "Плашка «Кто мы»", w, height=h, layout="vertical", gap=10,
padding=[12, 20, 10, 20], fill="$b-card", radius=12,
stroke="$b-hairline", stroke_width=1)
inner = w - 40
add(c, card_header(nid, R, inner, CARD1_TITLE, dot),
T(nid, "Лид плашки", CARD1_LEAD, R["card_lead"], inner, "$b-text-2"))
for term, body in PAIRS:
add(c, (pair_stacked if stacked_pairs else pair)(nid, R, term, body, inner))
return c
def card_stack(nid, R, w, h, *, dot, stacked_pairs):
c = F(nid, "Плашка «Стек и технологии»", w, height=h, layout="vertical", gap=10,
padding=[12, 20, 10, 20], fill="$b-card", radius=12,
stroke="$b-hairline", stroke_width=1)
inner = w - 40
add(c, card_header(nid, R, inner, CARD2_TITLE, dot),
T(nid, "Лид плашки", CARD2_LEAD, R["card_lead"], inner, "$b-text-2"))
for label, chips in CHIP_GROUPS:
g = F(nid, "Группа " + label, inner, layout="vertical" if stacked_pairs else "horizontal",
gap=6 if stacked_pairs else PAIR_GAP, items=None if stacked_pairs else "center")
add(g, T(nid, "Метка группы", label, R["term"], inner if stacked_pairs else LABEL_TRACK,
"$b-brand-deep"))
wrap = F(nid, "Чипы", inner if stacked_pairs else inner - LABEL_TRACK - PAIR_GAP,
layout="horizontal", gap=8, items="center")
for ch in chips:
cw_chip = 24 + CHIP_TEXT_W.get(ch, round(len(ch) * 9.2)) # замер: canvas measureText
chip = F(nid, "Чип " + ch, cw_chip, height=32, layout="horizontal", fill="$b-card",
radius=999, stroke="$b-line-strong", stroke_width=1,
items="center", justify="center")
lab = T(nid, "Чип-подпись", ch, R["chip"], cw_chip - 24, "$b-text-2")
lab["textAlign"] = "center"
add(wrap, add(chip, lab))
add(g, wrap)
add(c, g)
return c
def cards_row(nid, R, w, h_card, *, dot=True, stacked_pairs=False):
row = F(nid, "Строка 3 · плашки «о нас», одной высоты", w, height=h_card,
layout="horizontal", gap=16, items="stretch")
cw = (w - 16) / 2
add(row, card_kto(nid, R, cw, h_card, dot=dot, stacked_pairs=stacked_pairs),
card_stack(nid, R, cw, h_card, dot=dot, stacked_pairs=stacked_pairs))
return row
def ticker(nid, R, w, pad, h=49):
t = F(nid, "Тикер первого экрана", w, height=h, layout="horizontal",
padding=[0, pad, 0, pad], fill="$b-card", items="center", justify="center")
add(t, T(nid, "Тикер", TICKER_TEXT, R["ticker"], w - 2 * pad, "$b-text-2"))
return t
# ---------------------------------------------------------------- кадры
def frame_v1(nid, R, w, vh, hero_h, planet_w, cards_h, side_pad, y):
root = F(nid, f"Hero — as shipped (V1) · {w}×{vh}", w, height=vh, layout="vertical",
x=0, y=y, fill="$b-bg", clip=True, theme="light")
hero = F(nid, "Hero", w, height=hero_h, layout="vertical", gap=12,
padding=[12, side_pad, 8, side_pad])
copy_w = 590
col_w = 1200 - copy_w - 48
row1 = F(nid, "Строка 1 · копия и полоса слева, планета справа", 1200,
layout="horizontal", gap=48, items="start")
left = F(nid, "Левая колонка", copy_w, layout="vertical", gap=12)
add(left, copy_block(nid, R, copy_w), bar_compact(nid, R, copy_w))
add(row1, left, visual_col(nid, col_w, planet_w))
add(hero, row1, cards_row(nid, R, 1200, cards_h, dot=False, stacked_pairs=False))
add(root, navbar(nid, R, w, side_pad), hero, ticker(nid, R, w, side_pad))
return root
def frame_v2(nid, R, w, vh, hero_h, planet_w, cards_h, bar_h, side_pad, y):
root = F(nid, f"Hero — 3 полосы, раскрытые · {w}×{vh}", w, height=vh, layout="vertical",
x=0, y=y, fill="$b-bg", clip=True, theme="light")
hero = F(nid, "Hero", w, height=hero_h, layout="vertical", gap=16,
padding=[12, side_pad, 8, side_pad])
copy_w = 582
col_w = 1200 - copy_w - 48
row1 = F(nid, "Строка 1 · копия и планета", 1200, layout="horizontal", gap=48, items="center")
add(row1, copy_block(nid, R, copy_w), visual_col(nid, col_w, planet_w))
add(hero, row1, bar_wide(nid, R, 1200, bar_h), cards_row(nid, R, 1200, cards_h))
add(root, navbar(nid, R, w, side_pad), hero, ticker(nid, R, w, side_pad))
return root
def frame_mobile(nid, R, y, nav_h=73, pad=24):
root = F(nid, "Hero — 3 полосы, раскрытые · 390×844", 390, height=844, layout="vertical",
x=0, y=y, fill="$b-bg", clip=True, theme="light")
w = 390
nav = F(nid, "MNav", w, height=nav_h, layout="horizontal", padding=[0, pad, 0, pad],
fill="$b-nav", items="center", justify="space-between")
add(nav, T(nid, "Логотип", "HARVEY MONSTER TEAM", R["logo"], 240, "$b-text-1"),
F(nid, "Бургер", 24, height=24, fill="$b-text-1", radius=3))
inner = w - 2 * pad
hero = F(nid, "Hero", w, layout="vertical", gap=24, padding=[pad, pad, pad, pad])
btns = F(nid, "Кнопки", inner, layout="vertical", gap=12)
for label, node_name, fill, stroke, ink in (
("НАПИСАТЬ НАМ", "Кнопка primary", "$b-brand", None, "$b-on-brand"),
("НАШИ РАБОТЫ", "Кнопка ghost", None, "$b-brand-deep", "$b-brand-deep")):
b = F(nid, node_name, inner, height=48, layout="horizontal", fill=fill, radius=12,
stroke=stroke, stroke_width=2 if stroke else None,
items="center", justify="center")
t = T(nid, node_name.replace("Кнопка ", "").capitalize() + " — подпись",
label, R["cta"], inner - 40, ink)
t["textAlign"] = "center"
add(btns, add(b, t))
cards = F(nid, "Строка 3 · плашки «о нас»", inner, layout="vertical", gap=12)
add(cards, card_kto(nid, R, inner, None, dot=True, stacked_pairs=True),
card_stack(nid, R, inner, None, dot=True, stacked_pairs=True))
h1_box = F(nid, "H1 блок", inner, height=112.2, layout="vertical")
add(h1_box, T(nid, "H1", "ИГРЫ И СЕРВИСЫ ПОД КЛЮЧ", R["h1"], inner, "$b-text-1"))
add(hero,
h1_box,
T(nid, "Оффер", "Разрабатываем игры, мобильные приложения и веб-сервисы.",
R["offer"], inner, "$b-text-2"),
btns,
planet(nid, inner),
bar_mobile(nid, R, inner),
cards)
add(root, nav, hero, ticker(nid, R, w, pad))
return root
# ---------------------------------------------------------------- main
def main():
src, dst = sys.argv[1], sys.argv[2]
data = json.loads(pathlib.Path(src).read_text(encoding="utf-8"))
VARS.update(data.get("variables") or {})
taken = collect_ids(data, set())
nid = Ids(taken)
old = [c for c in data["children"] if str(c.get("name", "")).startswith("Hero — ")]
keep = [c for c in data["children"] if not str(c.get("name", "")).startswith("Hero — ")]
base_y = min([c.get("y", 0) for c in old] or [6200])
frames = [
frame_v1(nid, ROLES, 1440, 900, 766, 519, 248, 120, base_y),
frame_v1(nid, ROLES_1366, 1366, 768, 634, 457, 240, 83, base_y + 1000),
frame_v2(nid, ROLES, 1440, 900, 766, 481, 248, 86, 120, base_y + 2000),
frame_v2(nid, ROLES_1366, 1366, 768, 634, 329, 240, 82, 83, base_y + 3000),
frame_mobile(nid, ROLES_390, base_y + 4000),
]
data["children"] = keep + frames
pathlib.Path(dst).write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"replaced {len(old)} hero frames → {len(frames)}; top-level {len(data['children'])}; "
f"bytes {pathlib.Path(dst).stat().st_size}")
if __name__ == "__main__":
main()
+112
View File
@@ -0,0 +1,112 @@
// measure-hero.mjs — computed styles + geometry of the hero roles, on the live page.
// Usage: node measure-hero.mjs <url> <out.json>
import { createRequire } from 'node:module';
const require = createRequire('C:/Users/deeen/AppData/Local/hermes/hermes-agent/node_modules/');
const { chromium } = require('C:/Users/deeen/AppData/Local/hermes/hermes-agent/node_modules/.pnpm/playwright-core@1.64.0/node_modules/playwright-core');
import { writeFileSync } from 'node:fs';
const URL_ = process.argv[2] || 'http://127.0.0.1:8765/src/';
const OUT = process.argv[3] || 'measure.json';
const VIEWPORTS = [
[1920, 1080], [1600, 1000], [1536, 864], [1440, 900], [1366, 768], [820, 1180], [390, 844],
];
const ROLES = {
h1: '.hero__copy .h1, .hero__copy h1',
offer: '.hero__offer',
cta_primary: '.hero__copy .btn--primary, .hero__copy .btn',
bar_title: '.hero-about__title',
bar_lead: '.hero-about__lead',
stat_value: '.hero-stat__value',
stat_label: '.hero-stat__label',
card_title: '.about-acc__card-title',
card_lead: '.about-acc__lead',
term: '.about-acc__term',
desc: '.about-acc__desc',
chip: '.about-acc__chips .chip',
ticker_item: '.hero-ticker__item',
eyebrow: '.eyebrow',
};
const browser = await chromium.launch({ executablePath: 'C:/Users/deeen/AppData/Local/ms-playwright/chromium-1223/chrome-win64/chrome.exe' });
const out = { url: URL_, viewports: {}, roles: {}, heroText: null, sha1: null };
const crypto = await import('node:crypto');
const HERO_TEXT_SHA1 = [];
for (const [w, h] of VIEWPORTS) {
const page = await browser.newPage({ viewport: { width: w, height: h } });
await page.goto(URL_, { waitUntil: 'load' });
await page.waitForTimeout(400);
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.waitForTimeout(150);
const geom = await page.evaluate(() => {
const q = (s) => document.querySelector(s);
const box = (el) => { if (!el) return null; const r = el.getBoundingClientRect(); return { x: +r.x.toFixed(1), y: +r.y.toFixed(1), w: +r.width.toFixed(1), h: +r.height.toFixed(1), bottom: +r.bottom.toFixed(1) }; };
const hero = q('.hero');
const grid = q('.hero__grid');
const gs = grid ? getComputedStyle(grid) : null;
const tick = q('.hero-ticker');
const heroR = hero ? hero.getBoundingClientRect() : null;
const doc = document.documentElement;
return {
vw: innerWidth, vh: innerHeight,
overflowX: +(doc.scrollWidth - innerWidth).toFixed(1),
overflowY: +(doc.scrollHeight - innerHeight).toFixed(1),
gridAreas: gs ? gs.gridTemplateAreas : null,
gridCols: gs ? gs.gridTemplateColumns : null,
gridRows: gs ? gs.gridTemplateRows : null,
hero: box(hero),
ticker: box(tick),
tickerBottom: tick ? +tick.getBoundingClientRect().bottom.toFixed(1) : null,
heroVisibleHeight: heroR ? +(Math.min(heroR.bottom, innerHeight) - Math.max(heroR.top, 0)).toFixed(1) : null,
planet: box(q('.hero__visual .planet') || q('.hero__visual')),
planetAspect: (() => { const el = q('.hero__visual .planet') || q('.hero__visual'); if (!el) return null; const r = el.getBoundingClientRect(); return +(r.width / r.height).toFixed(4); })(),
copy: box(q('.hero__copy')),
bar: box(q('.hero-about')),
cards: box(q('.about-acc')),
card1: box(q('.about-acc .faq-item')),
statRow: (() => {
const st = q('.hero-about__stats');
if (!st) return null;
const kids = [...st.children].map((k) => { const r = k.getBoundingClientRect(); return { y: +r.y.toFixed(1), h: +r.height.toFixed(1), w: +r.width.toFixed(1) }; });
const rows = [...new Set(kids.map((k) => k.y))];
return { rows: rows.length, perRow: kids.length / rows.length, kids };
})(),
pairs: [...document.querySelectorAll('.about-acc__row')].map((r) => {
const b = r.getBoundingClientRect();
return { w: +b.width.toFixed(1), h: +b.height.toFixed(1) };
}),
};
});
const roles = await page.evaluate((ROLES) => {
const res = {};
for (const [k, sel] of Object.entries(ROLES)) {
const el = document.querySelector(sel);
if (!el) { res[k] = null; continue; }
const cs = getComputedStyle(el);
res[k] = {
sel, text: (el.textContent || '').trim().slice(0, 40),
fontFamily: cs.fontFamily, fontSize: cs.fontSize, fontWeight: cs.fontWeight,
lineHeight: cs.lineHeight, letterSpacing: cs.letterSpacing,
textTransform: cs.textTransform, color: cs.color,
};
}
return res;
}, ROLES);
const heroText = await page.evaluate(() => (document.querySelector('.hero')?.innerText || '').replace(/\s+/g, ' ').trim());
out.viewports[`${w}x${h}`] = geom;
if (!out.roles[`${w}x${h}`]) out.roles[`${w}x${h}`] = roles;
out.heroText = out.heroText || heroText;
HERO_TEXT_SHA1.push([`${w}x${h}`, crypto.createHash('sha1').update(heroText).digest('hex').slice(0, 12)]);
await page.close();
}
out.sha1 = HERO_TEXT_SHA1;
writeFileSync(OUT, JSON.stringify(out, null, 2), 'utf8');
await browser.close();
console.log('written', OUT);
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
# verify-pen.py — механическая проверка типографической системы hero в .pen (JSON 2.21).
#
# Правила (контракт карточки t_10311aff):
# R1 ни одна метка/термин/заголовок не набран $font-body → «0 нарушений»
# R2 пары «термин → значение» — два узла ($font-heading 700/11 + $font-body 400/14-15)
# R3 в hero-кадрах ровно три строки (desktop), статы полосы в один ряд, тикер на кромке
# R4 кегли/веса/интерлиньяжи совпадают с таблицей ролей (допуск 0 px)
#
# Запуск: py verify-pen.py <canon.pen>
import json, sys, pathlib
HEAD, BODY = "$font-heading", "$font-body"
# роль → (family, weight, size|None, lh, ls) «None» = кегль зависит от кадра (см. EXPECT ниже)
EXPECT = {
"H1": (HEAD, "800", None, 1.1, 1),
"Титул полосы": (HEAD, "700", None, 1.1, None),
"Значение": (HEAD, "800", None, 1.0, 0),
"Подпись": (HEAD, "600", 10, 1.5, None),
"Заголовок плашки": (HEAD, "700", 12, 1.1, 1.2),
"Термин": (HEAD, "700", 11, 1.5, 1),
"Метка группы": (HEAD, "700", 11, 1.5, 1),
"Чип-подпись": (HEAD, "600", 12, 1.5, 1),
"Логотип": (HEAD, "800", None, 1.2, 1),
"Тикер": (HEAD, "600", 14, 1.5, 1),
"Лид полосы": (BODY, "400", 14, None, 0),
"Лид плашки": (BODY, "400", None, None, 0),
"Описание": (BODY, "400", None, None, 0),
"Оффер": (BODY, "400", 19, 1.5, 0),
}
LABEL_ROLES = {"H1", "Титул полосы", "Значение", "Подпись", "Заголовок плашки", "Термин",
"Метка группы", "Чип-подпись", "Логотип", "Тикер"}
# кегль роли по кадру (замер прода, px): кадр → роль → size
SIZE_BY_FRAME = {
"1440": {"Титул полосы": 18, "Значение": 23, "H1": 54, "Логотип": 20,
"Лид плашки": 14, "Описание": 14},
"1366": {"Титул полосы": 17, "Значение": 20, "H1": 54, "Логотип": 20,
"Лид плашки": 14, "Описание": 14},
"390": {"Титул полосы": 20, "Значение": 20, "H1": 34, "Логотип": 16,
"Лид плашки": 15, "Описание": 15},
}
LH_BY_FRAME = {
"1440": {"Лид полосы": 1.38, "Лид плашки": 1.36, "Описание": 1.36},
"1366": {"Лид полосы": 1.32, "Лид плашки": 1.32, "Описание": 1.32},
"390": {"Лид полосы": 1.55, "Лид плашки": 1.5, "Описание": 1.5},
}
def frame_key(name):
if "390" in name: return "390"
if "1366" in name: return "1366"
return "1440"
def walk(node, path=""):
p = f"{path}/{node.get('name','?')}"
yield node, p
for c in node.get("children") or []:
yield from walk(c, p)
def main():
data = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
heroes = [c for c in data["children"] if str(c.get("name", "")).startswith("Hero — ")]
violations, notes = [], []
if len(heroes) != 5:
violations.append(f"кадров hero {len(heroes)}, ожидалось 5")
for frame in heroes:
fname = frame.get("name")
fk = frame_key(fname)
sizes = SIZE_BY_FRAME[fk]
lhs = LH_BY_FRAME[fk]
texts = 0
for node, path in walk(frame):
if node.get("type") != "text":
continue
texts += 1
nm = node.get("name", "")
fam = node.get("fontFamily")
content = str(node.get("content", ""))
# R1a — роль метки набрана прозой
if nm in LABEL_ROLES and fam != HEAD:
violations.append(f"R1 {fname} :: {path} — роль «{nm}» набрана {fam}")
# R1b — содержание в верхнем регистре (метка) не может быть Roboto
letters = [ch for ch in content if ch.isalpha()]
if letters and content == content.upper() and content != content.lower() and fam != HEAD:
violations.append(f"R1 {fname} :: {path} — uppercase-метка {content[:28]!r} набрана {fam}")
# R2 — пара «термин → значение» одним узлом
if nm.startswith("Пара ") and len(content) > 16:
violations.append(f"R2 {fname} :: {path} — пара собрана одним текстовым узлом")
# R5 — вес записан числом (OpenPencil 0.16 строковый fontWeight отбрасывает → Regular)
if not isinstance(node.get("fontWeight"), int):
violations.append(f"R5 {fname} :: {path} — вес %r не число" % (node.get("fontWeight"),))
# R4 — соответствие таблице ролей
if nm in EXPECT:
exp_fam, exp_w, exp_size, exp_lh, exp_ls = EXPECT[nm]
if fam != exp_fam:
violations.append(f"R4 {fname} :: {path} — гарнитура {fam}, ожидалось {exp_fam}")
if str(node.get("fontWeight")) != exp_w:
violations.append(f"R4 {fname} :: {path} — вес {node.get('fontWeight')}, ожидалось {exp_w}")
size = sizes.get(nm, exp_size)
if size is not None and node.get("fontSize") != size:
violations.append(f"R4 {fname} :: {path} — кегль {node.get('fontSize')}, ожидалось {size}")
lh = lhs.get(nm, exp_lh)
if lh is not None and abs(float(node.get("lineHeight", 0)) - lh) > 0.001:
violations.append(f"R4 {fname} :: {path} — интерлиньяж {node.get('lineHeight')}, ожидалось {lh}")
if exp_ls is not None and abs(float(node.get("letterSpacing", 0)) - exp_ls) > 0.001:
violations.append(f"R4 {fname} :: {path} — трекинг {node.get('letterSpacing')}, ожидалось {exp_ls}")
# R3 — статы полосы в один ряд
# конец обхода текстов
# R3 — три строки + тикер на кромке (desktop)
hero_frame = next((n for n in frame.get("children") or [] if n.get("name") == "Hero"), None)
tick = next((n for n in frame.get("children") or [] if n.get("name") == "Тикер первого экрана"), None)
if fk != "390" and "3 полосы" in fname:
if not hero_frame:
violations.append(f"R3 {fname} — нет узла Hero")
else:
rows = [n for n in hero_frame.get("children") or []]
if len(rows) != 3:
violations.append(f"R3 {fname} — строк {len(rows)}, ожидалось 3: "
f"{[r.get('name') for r in rows]}")
for r in rows:
if r.get("width") != 1200:
violations.append(f"R3 {fname} — строка «{r.get('name')}» шириной {r.get('width')}, "
f"ожидалось 1200")
# статы полосы в один ряд
bar = next((r for r in rows if r.get("name", "").startswith("Строка 2")), None)
st = None
if bar:
st = next((n for n in bar.get("children") or [] if n.get("name") == "Статы"), None)
if st:
if st.get("layout") != "horizontal":
violations.append(f"R3 {fname} — Статы не в ряд (layout={st.get('layout')})")
if len(st.get("children") or []) != 4:
violations.append(f"R3 {fname} — статов {len(st.get('children') or [])}, ожидалось 4")
cell_h = 0
for c in st.get("children") or []:
cell_h = max(cell_h, (c.get("height") or 0))
if st.get("height") and cell_h > st["height"] + 0.5:
violations.append(f"R3 {fname} — статы переносятся: ячейка {cell_h} > ряд {st['height']}")
else:
violations.append(f"R3 {fname} — в полосе нет узла Статы")
# плашки одной высоты
cards = next((r for r in rows if r.get("name", "").startswith("Строка 3")), None)
if cards:
hs = {(c.get("height")) for c in cards.get("children") or []}
if len(hs) > 1:
violations.append(f"R3 {fname} — плашки разной высоты: {sorted(hs)}")
ch_list = [(c.get("name"), c.get("height")) for c in cards.get("children") or []]
if cards.get("height") and all(h is not None for _, h in ch_list):
for nm_, h_ in ch_list:
if h_ > cards["height"] + 0.5:
violations.append(f"R3 {fname} — плашка «{nm_}» {h_} > строки {cards['height']}")
if tick and fk != "390":
kids = frame.get("children") or []
total = sum((k.get("height") or 0) for k in kids)
if abs(total - frame["height"]) > 0.5:
violations.append(f"R3 {fname} — колонка кадра {total} ≠ высоте {frame['height']}: "
f"тикер не на кромке")
if kids[-1].get("name") != "Тикер первого экрана":
violations.append(f"R3 {fname} — тикер не последний в колонке кадра")
if not tick:
violations.append(f"R3 {fname} — нет тикера")
# отчёт
print("=" * 78)
print(f"ФАЙЛ: {sys.argv[1]}")
print(f"КАДРОВ HERO: {len(heroes)} — {', '.join(f['name'] for f in heroes)}")
print(f"НАРУШЕНИЙ: {len(violations)}")
for v in violations[:80]:
print(" ✗", v)
print("=" * 78)
sys.exit(1 if violations else 0)
if __name__ == "__main__":
main()