diff --git a/docs/design/2026-09-04-inbox-functional.md b/docs/design/2026-09-04-inbox-functional.md index df54613..462eba5 100644 --- a/docs/design/2026-09-04-inbox-functional.md +++ b/docs/design/2026-09-04-inbox-functional.md @@ -121,9 +121,19 @@ Hado — сервис напоминаний. Другие сервисы (до подпись кнопки «Сделано» и две ссылки-действия. Как это озвучивается или показывается — на стороне умного дома. +## Добавлено по дизайну (хендофф 2026-09-04, `handoff/`) + +**Кнопка «+ Добавить»** в шапке раскрывает форму «Новое событие» над группами: +заголовок (обязателен), подзаголовок, срок (обязателен), время. «Создать» кладёт +событие в группу по дате: прошла → Просрочено, сегодня → Сегодня, в пределах +30 дней → Грядёт, дальше → Запланировано. Источник подписывается «вручную», кнопка +закрытия — «Сделано». «Отмена» сворачивает форму. Ошибки валидации под формой. + +**Архив** — сворачиваемый блок над настройками, в заголовке «N закрыто». Строки: +заголовок, источник и срок, ярлык закрытия (подпись кнопки, которой закрыли, или +«Истекло», если срок прошёл сам). Только чтение, действий нет. Глубина — 90 дней. + ## Чего здесь нет намеренно -- Истории закрытых событий: закрыл — исчезло, архива нет. -- Ручного создания событий: их присылают только сервисы-источники. - Откладывания «на дату»: этим занимается правило «Помню». - Настройки частоты напоминаний: она общая и не настраивается. - Мобильного приложения: iOS с бейджем, виджетом «Грядёт» и Live Activity — отдельный diff --git a/docs/design/handoff/README.md b/docs/design/handoff/README.md new file mode 100644 index 0000000..d58a2c9 --- /dev/null +++ b/docs/design/handoff/README.md @@ -0,0 +1,80 @@ +# Hado 波動 — design handoff + +Сервис напоминаний экосистемы Sekai (世界). Планета № 05. +Дизайн-система: Sekai — 和風幻想 (dark only, токены из tokens/colors.css). + +## Файлы пакета + +- `hado-inbox.dc.html` + `support.js` — рабочий прототип веб-инбокса (открыть в браузере, файлы держать рядом) +- `hado-planet.dc.html` — карточка планеты Hado отдельно +- `sekai-planets.html` — все 5 планет экосистемы, автономный HTML (формат исходного planets.html) +- `sekai-template.html` — исходный шаблон страницы сервиса (каркас, туманность, сёстры-планеты) +- `sekai-nebula.html` — исходный компонент туманности +- `functional-spec.md` — исходное функциональное описание + +## Планета 05 · HADO 波動 + +Hado = волна / пульс. Напоминание — сигнал, который уходит и возвращается. + +- Градиент тела: `radial-gradient(circle at 32% 28%, var(--ruri), #24337F 55%, var(--ink-0) 92%)` + (瑠璃 ruri — «magic / pulse» → тёмный ruri #24337F; глубокий ультрамарин, чтобы не путать с ледяным Fumi) +- Свечение: `0 0 46px rgba(53,92,214,.4)`, пульс 2.6s +- Эхо-кольца: 2 расходящихся кольца (byakugun .45 / ruri .5), skEcho 4.2s со сдвигом 2.1s +- Кольца орбит: rotateX(69deg), внешнее пунктирное rotateZ(-8deg) +- Спутники: СИГНАЛ 10px `--byakugun` (skSpin 13s) + ЭХО 7px `--ruri` (skSpinBack 30s) +- Мини-версия для навигации: круг 11px, тот же градиент, box-shadow 0 0 8px rgba(53,92,214,.45) + +## Страница инбокса (по sekai-template, без отступлений) + +Слои фона: звёзды (90) → туман → ядро полосы → пылевые разломы → звёзды полосы (170, дуга −14°). +Сёстры-планеты (hover — подпись): YUME 17%/7%, MYAKU 26%/right 8%, KIOKU 60%/4.5%, FUMI 64%/right 6%. Своей планеты на странице нет. + +Шапка: 波動 (Shippori Mincho 54px --washi) + HADO (Space Mono 13px .5em --nibi) + +бейдж-счётчик (мини-планета 11px с пульсом + число --byakugun, пилюля border ruri .55 / bg ruri .14). +Счётчик = «Сегодня» + «Просрочено»; при 0 скрыт. Заголовок вкладки: «(N) Hado». +Справа: «+ Добавить» (primary) и номер 05. Футер: 波動 HADO · 世界 SEKAI. + +## Типографика + +- UI: Space Grotesk; кандзи/заголовки групп: Shippori Mincho; мета/служебные: Space Mono +- Группы: кандзи 20px + русское имя Space Mono 11px .35em --kasumi + hairline + 今日 СЕГОДНЯ · 遅延 ПРОСРОЧЕНО · 近日 ГРЯДЁТ · 予定 ЗАПЛАНИРОВАНО (порядок фиксирован; пустая — «ПУСТО») + +## Карточка события + +bg rgba(27,33,72,.72), border --hair, radius 12, padding 16/20. +Слева плашка срока: --ink-1, border --hair-2, radius 10 — месяц (Mono 9px --nibi), +день (Shippori Mincho 24px --washi), время (Mono 10px --byakugun). +Заголовок 16px --washi (если есть ссылка в источник — dotted underline, hover --byakugun); +подзаголовок 13px --kasumi; служебная строка Mono 11px --nibi: «источник · срок YYYY-MM-DD · относительно» («сегодня», «через 6 дней», «3 дня назад» --kasumi). + +Кнопки (принципиально разные): +- «Помню» — ghost: border --hair-2, текст --kasumi, hover --byakugun. Нет в «Запланировано». +- «Сделано» — primary: bg rgba(53,92,214,.22), border --ruri, текст --byakugun, hover bg .4. + Подпись задаёт источник («Поздравил», «Оплатил», «Продлил»). +Нажатие: кнопка блокируется (opacity .45) до ответа; «Сделано» уносит карточку в архив и уменьшает счётчик. + +## Архив 書庫 + +Сворачиваемый блок над настройками, в заголовке счётчик «N закрыто». +Строки opacity .75: заголовок --kasumi, источник · срок Mono --nibi, ярлык закрытия — пилюля --fuji +(fuji = «quiet magic / decay»: закрытое событие угасает по лайфциклу системы). + +## Ручное создание («+ Добавить») + +Форма под шапкой (border dashed --hair-2): заголовок*, подзаголовок, срок*, время. +Группа определяется датой: прошла → Просрочено, сегодня → Сегодня, ≤30 дней → Грядёт, дальше → Запланировано. Источник: «вручную». + +## Настройки 設定 (свёрнуты, в заголовке логин) + +- Часовой пояс: полный IANA-список (Intl.supportedValuesOf) +- Тихие часы: обязаны переходить через полночь (22:00→09:00 верно, 08:00→22:00 — ошибка --sakura) +- Каналы: Веб (без удаления) / Telegram / Webhook (несколько), «Удалить» — ghost, hover --nadeshiko +- Добавить webhook: адрес доставки* + адрес присутствия*, оба URL http(s) +- Подключить Telegram: одноразовый код «/start XXXXXX», живёт 15 минут + +## Цветовые правила (60/30/10) + +Сумрак ≥60% (фон, карточки, бордеры). Акцент сервиса — холодный полюс (hanada/ruri/byakugun), +только кнопки-действия, бейдж, время — ~10%. Ошибки — --sakura (светлый лепесток, читается). +Насыщенный --ruri никогда не используется как текст; текст — --washi/--kasumi/--nibi/--byakugun. diff --git a/docs/design/handoff/functional-spec.md b/docs/design/handoff/functional-spec.md new file mode 100644 index 0000000..df54613 --- /dev/null +++ b/docs/design/handoff/functional-spec.md @@ -0,0 +1,130 @@ +# Hado · веб-инбокс — функциональное описание для дизайна + +Что есть на экранах и что делает каждый элемент. Без визуальных требований: +размеры, цвета, сетка, стиль — на стороне дизайна. + +## Контекст + +Hado — сервис напоминаний. Другие сервисы (документы, люди, оплаты) присылают ему +события со сроком, Hado сам решает, когда и куда напомнить: сюда в инбокс, в Telegram, +в умный дом. Веб-инбокс — единственный экран Hado. Пользователь попадает в него уже +залогиненным через общий вход экосистемы, своей формы логина здесь нет. + +Два действия над событием, они принципиально разные и должны читаться по-разному: + +- **«Помню»** — «я в курсе, отстань до следующей контрольной точки». Событие остаётся, + счётчик не меняется. Напоминание вернётся само: в день события через час, до события + на следующей контрольной точке, после события через день. +- **«Сделано»** — «закрыл вопрос». Событие уходит с экрана навсегда, счётчик падает. + Подпись кнопки может задавать сервис-источник: «Поздравил», «Оплатил», «Продлил». + По умолчанию «Сделано». + +## Понятия + +| термин | что это | +|---|---| +| Событие | одна штука со сроком: ДР Васи, седула протухает 30 сен, вылет 10 сен 08:15 | +| Срок | день события, иногда с конкретным временем | +| Источник | сервис, который прислал событие (`docs`, `people`). Показывается как подпись | +| Счётчик | число событий в группах «Сегодня» и «Просрочено». Это же число потом будет бейджем на иконке iOS | +| Ссылка в источник | у события может быть ссылка на объект в сервисе-источнике (карточка человека, документ) | + +## Экран 1. Инбокс (главная и единственная страница) + +### Шапка +- Название «Hado». +- Счётчик: число событий «Сегодня» + «Просрочено». Если ноль — не показывается. +- Заголовок вкладки браузера дублирует счётчик: «(3) Hado», чтобы видеть его в списке вкладок. + +### Группы событий +Четыре группы, всегда в этом порядке. Пустая группа показывает подпись «Пусто» +(или скрывается — решение дизайна, но порядок остальных не меняется). + +1. **Сегодня** — срок сегодня, время ещё не наступило. Самое важное, наверху. +2. **Просрочено** — срок прошёл, но событие всё ещё надо сделать (седула истекла, + аренда не оплачена). Висит, пока не нажмёшь «Сделано». +3. **Грядёт** — идёт подготовка, срок через дни или недели. В счётчик не входит. +4. **Запланировано** — Hado про событие знает, но ещё молчит. В счётчик не входит. + +Внутри группы события отсортированы по сроку, ближайший первым. + +### Карточка события +- **Заголовок** — текст от источника («Сегодня ДР — Вася»). Если у события есть ссылка + в источник, заголовок — ссылка, открывает объект в сервисе-источнике (в той же вкладке + или новой — решение дизайна). +- **Подзаголовок** — вторая строка от источника, опциональная («исполняется 34», + «осталось 30 дней»). +- **Служебная строка** — имя источника и срок: «docs · срок 2026-09-30». Если срок с + временем — «2026-09-10 08:15». +- **Кнопка «Помню»** — есть во всех группах, кроме «Запланировано» (там напоминаний + ещё нет, «помнить» нечего). После нажатия карточка остаётся на месте, ничего + визуально не должно намекать, что событие закрыто. +- **Кнопка «Сделано»** — есть везде, включая «Запланировано» (закрыть можно заранее, + хоть за два месяца). Подпись берётся у источника, если он её задал. После нажатия + карточка исчезает, счётчик уменьшается, если событие было в «Сегодня» или «Просрочено». + +Нажатие любой кнопки: кнопка блокируется до ответа сервера, затем список обновляется. +При ошибке кнопка разблокируется, карточка остаётся. + +### Блок «Настройки» +Свёрнут по умолчанию, раскрывается на той же странице. В заголовке блока — логин +пользователя. + +**Пояс и тихие часы** +- Выбор часового пояса из полного списка (IANA: `America/Montevideo`, `Asia/Shanghai`). + Пользователь много переезжает и меняет пояс руками; все напоминания сдвигаются под него. +- Тихие часы: «с» и «до». По умолчанию с 22:00 до 09:00. В тихие часы Hado молчит во + всех каналах. Ограничение: интервал обязан переходить через полночь («с 22:00 до + 09:00» верно, «с 08:00 до 22:00» — ошибка, показать сообщение). +- Кнопка «Сохранить». После сохранения страница обновляется. + +**Каналы** — куда Hado доставляет напоминания. Список: +- **Веб** — этот инбокс. Есть всегда, удалить нельзя, кнопки удаления нет. Подпись + «этот инбокс». +- **Telegram** — подпись с идентификатором чата. Появляется после привязки (ниже). + Кнопка «Удалить». +- **Webhook** — адрес, куда Hado шлёт напоминание (в жизни это умный дом). Подпись — + сам адрес. Кнопка «Удалить». Таких может быть несколько. + +**Добавить webhook** — форма из двух полей и кнопки: +- «Адрес доставки» — куда Hado отправит напоминание. +- «Адрес присутствия» — откуда Hado спросит «пользователь сейчас дома/рядом?». +- Кнопка «Добавить webhook». Оба поля обязательны, должны быть URL. Ошибки валидации + показываются у формы. + +**Подключить Telegram** — кнопка. По нажатию появляется одноразовый код и ссылка на +бота: «Отправь боту `/start ABC123` или открой». Код живёт 15 минут. После того как +пользователь отправит код боту, канал Telegram появится в списке (при следующем +открытии страницы). + +### Поведение страницы, невидимое пользователю +- Пока вкладка открыта, видима и пользователь что-то делал за последние 3 минуты, + страница сообщает серверу «я тут». Hado тогда не дёргает Telegram и умный дом: + напоминание считается доставленным в инбокс. Забытая фоновая вкладка «я тут» не + сообщает. +- Никаких всплывающих уведомлений и звуков в самом инбоксе нет: он пассивный экран. + Активные каналы — Telegram и умный дом, потом iOS. + +## Экран 0. Нет доступа +Если пользователь пришёл не через общий вход экосистемы, страница не открывается +(ответ 401). Своей заглушки у Hado нет: общий вход сам перебросит на форму логина. +Дизайнить здесь нечего, упомянуто для полноты. + +## Вне веба, но для консистентности + +**Сообщение в Telegram** — текст: заголовок и подзаголовок события. Под ним две кнопки: +«Помню» и «Сделано» (или подпись источника). После «Сделано» кнопки под сообщением +убираются. Каждое новое напоминание — новое сообщение, старые не редактируются. +Ответы бота на нажатия: «Ок, напомню позже», «Закрыто», «Уже неактуально». + +**Умный дом (webhook)** получает те же поля: заголовок, подзаголовок, источник, срок, +подпись кнопки «Сделано» и две ссылки-действия. Как это озвучивается или показывается — +на стороне умного дома. + +## Чего здесь нет намеренно +- Истории закрытых событий: закрыл — исчезло, архива нет. +- Ручного создания событий: их присылают только сервисы-источники. +- Откладывания «на дату»: этим занимается правило «Помню». +- Настройки частоты напоминаний: она общая и не настраивается. +- Мобильного приложения: iOS с бейджем, виджетом «Грядёт» и Live Activity — отдельный + проект, его описание будет отдельно. diff --git a/docs/design/handoff/hado-inbox.dc.html b/docs/design/handoff/hado-inbox.dc.html new file mode 100644 index 0000000..94fe2ae --- /dev/null +++ b/docs/design/handoff/hado-inbox.dc.html @@ -0,0 +1,456 @@ + + + + + + + + + + + + + + +
+ +
+
+
+
+
+ + +
+
+
+
+
+ YUME +
+
+
+
+
+
+
+ MYAKU +
+
+
+
+
+
+
+ KIOKU +
+
+
+
+
+
+
+ FUMI +
+
+
+
+ +
+
+ 波動 + HADO + + + + {{ counter }} + + +
+
+ + 05 +
+
+ +
+ +
+
НОВОЕ СОБЫТИЕ
+
+ + + + + + +
+ +
{{ nErr }}
+
+
+
+ +
+
+ {{ g.jp }} + {{ g.ru }} + +
+ +
ПУСТО
+
+
+ +
+
+ {{ ev.dueMonth }} + {{ ev.dueDay }} + + {{ ev.dueTime }} + +
+
+ + {{ ev.title }} + + + {{ ev.title }} + + + {{ ev.subtitle }} + + {{ ev.source }} · срок {{ ev.due }} · {{ ev.rel }} +
+
+ + + + +
+
+
+
+
+
+ + +
+ + +
+ +
ПУСТО
+
+ +
+ {{ ar.title }} + {{ ar.source }} · {{ ar.due }} + {{ ar.closedAs }} +
+
+
+
+
+ + +
+ + +
+ +
+
ПОЯС И ТИХИЕ ЧАСЫ
+
+ + + + +
+ +
{{ qErr }}
+
+ +
Сохранено — напоминания сдвинуты под пояс
+
+
+ +
+
КАНАЛЫ
+
+ +
+ {{ ch.name }} + {{ ch.note }} + + + +
+
+
+
+ +
+
ДОБАВИТЬ WEBHOOK
+
+ + + +
+ +
{{ whErr }}
+
+
+ +
+
TELEGRAM
+ + + + +
+ Отправь боту /start {{ tgCode }} или открой + Код живёт 15 минут. Канал появится в списке при следующем открытии страницы. +
+
+
+ +
+
+
+
+ + +
+
+ + + diff --git a/docs/design/handoff/hado-planet.dc.html b/docs/design/handoff/hado-planet.dc.html new file mode 100644 index 0000000..c81361f --- /dev/null +++ b/docs/design/handoff/hado-planet.dc.html @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + +
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+ +
+
+
+
+
+
+
+
波動
+
HADO · НАПОМИНАНИЯ
+
05 · 波動共鳴 · СПУТНИКИ: СИГНАЛ --byakugun + ЭХО --ruri
+
+ + МИНИ-ВЕРСИЯ ДЛЯ НАВИГАЦИИ +
+
+
+
+
+ + + diff --git a/docs/design/handoff/sekai-nebula.html b/docs/design/handoff/sekai-nebula.html new file mode 100644 index 0000000..00bbeed --- /dev/null +++ b/docs/design/handoff/sekai-nebula.html @@ -0,0 +1,129 @@ + + + + + +Sekai — 星雲 Nebula + + + + + + +
+
+
+
+
+
+ +
+
+
星雲 · SEKAI NEBULA
+

Млечная полоса мира Sekai — диск галактики, видимый с планеты Fumi с ребра, поэтому он ложится дугой через всё небо. Розовое свечение — цветение (сакура), редкие голубые вспышки — лёд и вода, а тёмные разрывы в ядре — пылевые рукава, скрывающие свет.

+
+
+
+ + + + + + diff --git a/docs/design/handoff/sekai-planets.html b/docs/design/handoff/sekai-planets.html new file mode 100644 index 0000000..f1def89 --- /dev/null +++ b/docs/design/handoff/sekai-planets.html @@ -0,0 +1,181 @@ + + + + + +Sekai — планеты (компоненты) + + + + +
+
世界 · Планеты
+
5 ПЛАНЕТ ЭКОСИСТЕМЫ · КАЖДЫЙ БЛОК — АВТОНОМНЫЙ, КОПИРУЕТСЯ ЦЕЛИКОМ
+
+ +
+ + +
+
+
+
+
+
+ +
+
+
+
+
+
+
+ +
MYAKU · ФИНАНСЫ
+
01 · 脈拍安定 · СПУТНИК: МОНЕТА --yamabuki
+
+
+ + +
+
+
+
+ +
+
+ +
+
+
+
+
+
+
+ +
KIOKU · ПАМЯТЬ
+
02 · 記憶保存 · СПУТНИК: КРИСТАЛЛ --fuji
+
+
+ + +
+
+
+
+ +
+
+ +
+
+
+
+
+
+
+ +
YUME · СОН
+
03 · 夢降下中 · СПУТНИК: ЛЕПЕСТОК --sakura
+
+
+ + +
+
+
+
+
+
+ +
+
+
+
+
+ +
+
+
+
+
+
+
+ +
FUMI · ПИСЬМО
+
04 · 文字変換 · СПУТНИКИ: ЛЁД --byakugun + КАПЛЯ --hanada
+
+
+ + + +
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+ +
+
+
+
+
+
+
+ +
HADO · НАПОМИНАНИЯ
+
05 · 波動共鳴 · СПУТНИКИ: СИГНАЛ --byakugun + ЭХО --ruri
+
+
+ +
+ +
+ МИНИ-ВЕРСИЯ (ДЛЯ НАВИГАЦИИ): КРУГ 11PX С ТЕМ ЖЕ RADIAL-GRADIENT + BOX-SHADOW 0 0 8PX АКЦЕНТА .45
+ НОВАЯ ПЛАНЕТА = СВОЙ АКЦЕНТ ИЗ ПАЛИТРЫ → ГРАДИЕНТ «АКЦЕНТ → ТЁМНЫЙ АКЦЕНТ → --ink-0 НА ~92%» + КОЛЬЦО rotateX(66–72°) + 1–2 СПУТНИКА-МЕТАФОРЫ +
+ + diff --git a/docs/design/handoff/sekai-template.html b/docs/design/handoff/sekai-template.html new file mode 100644 index 0000000..f48b6fb --- /dev/null +++ b/docs/design/handoff/sekai-template.html @@ -0,0 +1,188 @@ + + + + + +Sekai — service page template + + + + + + +
+ +
+
+
+
+
+ + +
+
YUME
+
MYAKU
+
KIOKU
+
+ +
+ + +
NO
+
+ + +
+ + +
+ + + + + + diff --git a/docs/design/handoff/support.js b/docs/design/handoff/support.js new file mode 100644 index 0000000..cb009b6 --- /dev/null +++ b/docs/design/handoff/support.js @@ -0,0 +1,1911 @@ +// GENERATED from dc-runtime/src/*.ts — do not edit. Rebuild with `cd dc-runtime && bun run build`. +"use strict"; +(() => { + var __defProp = Object.defineProperty; + var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + + // src/react.ts + function getReact() { + const R = window.React; + if (!R) throw new Error("dc-runtime: window.React is not available yet"); + return R; + } + function getReactDOM() { + const RD = window.ReactDOM; + if (!RD) throw new Error("dc-runtime: window.ReactDOM is not available yet"); + return RD; + } + var h = ((...args) => getReact().createElement( + ...args + )); + + // src/parse.ts + function parseDcDocument(doc) { + const dc = doc.querySelector("x-dc"); + if (!dc) return null; + const scriptEl = doc.querySelector("script[data-dc-script]"); + const { props, preview } = parseDataProps( + scriptEl?.getAttribute("data-props") ?? null + ); + return { + template: dc.innerHTML, + js: scriptEl ? scriptEl.textContent || "" : "", + props, + preview + }; + } + function parseDcText(src) { + const openMatch = /]*)?>/.exec(src); + if (!openMatch) return null; + const close = src.lastIndexOf(""); + if (close === -1 || close < openMatch.index) return null; + const template = src.slice(openMatch.index + openMatch[0].length, close); + const doc = new DOMParser().parseFromString(src, "text/html"); + const scriptEl = doc.querySelector("script[data-dc-script]"); + const { props, preview } = parseDataProps( + scriptEl?.getAttribute("data-props") ?? null + ); + return { + template, + js: scriptEl ? scriptEl.textContent || "" : "", + props, + preview + }; + } + function parseDataProps(raw) { + if (!raw) return { props: null, preview: null }; + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return { props: null, preview: null }; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return { props: null, preview: null }; + } + const obj = parsed; + const preview = obj.$preview && typeof obj.$preview === "object" ? obj.$preview : null; + const rest = {}; + for (const k of Object.keys(obj)) { + if (k[0] !== "$") rest[k] = obj[k]; + } + return { props: Object.keys(rest).length ? rest : null, preview }; + } + function dcNameFromPath(pathname) { + let p = pathname || ""; + try { + p = decodeURIComponent(p); + } catch { + } + const base = p.split("/").pop() || "Root"; + return base.replace(/\.dc\.html$/, "").replace(/\.html?$/, "") || "Root"; + } + + // src/boot.ts + var BASE_CSS = ` + .sc-placeholder{background:color-mix(in srgb,currentColor 8%,transparent); + border:1px solid color-mix(in srgb,currentColor 50%,transparent); + border-radius:2px;box-sizing:border-box;overflow:hidden} + @keyframes sc-shine{0%{background-position:100% 50%}100%{background-position:0% 50%}} + html.sc-dc-streaming .sc-placeholder, + html.sc-dc-streaming .sc-interp.sc-missing{position:relative; + background:color-mix(in srgb,currentColor 5%,transparent); + border-color:transparent} + html.sc-dc-streaming .sc-placeholder::before, + html.sc-dc-streaming .sc-interp.sc-missing::before{content:''; + position:absolute;inset:0;pointer-events:none; + background:linear-gradient(90deg,rgba(217,119,87,0) 25%,rgba(247,225,211,.95) 37%,rgba(217,119,87,0) 63%); + background-size:400% 100%;animation:sc-shine 1.4s ease infinite} + html.sc-dc-streaming .sc-placeholder:nth-child(n+9 of .sc-placeholder)::before, + html.sc-dc-streaming .sc-interp.sc-missing:nth-child(n+9 of .sc-interp.sc-missing)::before{animation:none; + background:color-mix(in srgb,currentColor 8%,transparent)} + .sc-placeholder-error{padding:4px 8px;font:11px/1.4 ui-monospace,monospace; + color:color-mix(in srgb,currentColor 70%,transparent);word-break:break-word} + .sc-interp.sc-missing{display:inline-block;width:2em;height:1em;overflow:hidden; + vertical-align:text-bottom;background:rgba(255,255,255,.3);border:1px solid rgba(0,0,0,.5); + border-radius:2px;box-sizing:border-box;color:transparent; + user-select:none} + .sc-interp.sc-unresolved{font-family:ui-monospace,monospace;font-size:.85em; + color:color-mix(in srgb,currentColor 50%,transparent); + background:color-mix(in srgb,currentColor 10%,transparent);border-radius:3px; + padding:0 3px} + .sc-host.sc-has-error{position:relative} + .sc-logic-error{position:absolute;top:8px;left:8px;z-index:2147483647;max-width:60ch; + padding:6px 10px;background:#b00020;color:#fff;font:12px/1.4 ui-monospace,monospace; + border-radius:4px;white-space:pre-wrap;pointer-events:none} + /* Mirrors PRINT_BASELINE_CSS in apps/web deck-stage-export.ts \u2014 keep both + in sync until dc-runtime regains a build step. */ + @media print { + @page { margin: 0.5cm; } + figure, table { break-inside: avoid; } + #dc-root, #dc-root > .sc-host { height: auto; } + *, *::before, *::after { + print-color-adjust: exact; -webkit-print-color-adjust: exact; + backdrop-filter: none !important; -webkit-backdrop-filter: none !important; + animation-delay: -99s !important; animation-duration: .001s !important; + animation-iteration-count: 1 !important; animation-fill-mode: both !important; + animation-play-state: running !important; transition-duration: 0s !important; + } + } + `; + var FULL_PAGE_CSS = "html,body{height:100%;margin:0}#dc-root,#dc-root>.sc-host{height:100%}"; + function rootNameForDocument(doc, loc) { + let bootPath = loc.pathname || ""; + if (!/\.dc\.html?$/i.test(safeDecode(bootPath))) { + try { + bootPath = new URL(doc.baseURI || "/").pathname; + } catch { + } + } + return dcNameFromPath(bootPath); + } + function safeDecode(s) { + try { + return decodeURIComponent(s); + } catch { + return s; + } + } + function boot(runtime, doc = document) { + const parsed = parseDcDocument(doc); + if (!parsed) return null; + const React = getReact(); + const rootName = rootNameForDocument(doc, location); + runtime.markFetched(rootName); + runtime.setRootName(rootName); + runtime.adoptParsed(rootName, parsed); + if (!window.__resources) { + fetch(location.href).then((res) => res.ok ? res.text() : "").then((t) => { + const raw = t ? parseDcText(t) : null; + if (raw?.template) runtime.updateHtml(rootName, raw.template); + }).catch(() => { + }); + } + const dc = doc.querySelector("x-dc"); + const hostEl = doc.createElement("div"); + hostEl.id = "dc-root"; + dc.replaceWith(hostEl); + if (!parsed.preview) { + const s = doc.createElement("style"); + s.textContent = FULL_PAGE_CSS; + doc.head.appendChild(s); + } + const Root = runtime.getDC(rootName); + const entry = runtime.registry.get(rootName); + function StandaloneRoot() { + const [, setTick] = React.useState(0); + React.useEffect(() => { + const sub = () => setTick((n) => n + 1); + entry.subs.add(sub); + return () => { + entry.subs.delete(sub); + }; + }, []); + const defaults = React.useMemo(() => { + const d = {}; + for (const k in entry.propsMeta || {}) { + const v = entry.propsMeta?.[k]?.default; + if (v !== void 0) d[k] = v; + } + return d; + }, [entry.propsMeta]); + return h(Root, { ...defaults, ...entry.propOverrides || {} }); + } + const ReactDOM = getReactDOM(); + if (ReactDOM.createRoot) + ReactDOM.createRoot(hostEl).render(h(StandaloneRoot)); + else ReactDOM.render(h(StandaloneRoot), hostEl); + return rootName; + } + + // src/expr.ts + var IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*/; + var NUMBER_RE = /^-?\d+(\.\d+)?$/; + function resolve(vals, src) { + const expr = String(src).trim(); + if (!expr) return void 0; + if (expr[0] === "(" && expr[expr.length - 1] === ")" && parensWrapWhole(expr)) { + return resolve(vals, expr.slice(1, -1)); + } + const eq = findTopLevelEquality(expr); + if (eq) { + const lv = resolve(vals, expr.slice(0, eq.index)); + const rv = resolve(vals, expr.slice(eq.index + eq.op.length)); + switch (eq.op) { + case "===": + return lv === rv; + case "!==": + return lv !== rv; + case "==": + return lv == rv; + default: + return lv != rv; + } + } + if (expr[0] === "!") return !resolve(vals, expr.slice(1)); + if (expr === "true") return true; + if (expr === "false") return false; + if (expr === "null") return null; + if (expr === "undefined") return void 0; + if (NUMBER_RE.test(expr)) return Number(expr); + if (expr.length >= 2 && (expr[0] === '"' || expr[0] === "'") && expr[expr.length - 1] === expr[0]) { + return expr.slice(1, -1); + } + return resolvePath(vals, expr); + } + function parensWrapWhole(expr) { + let depth = 0; + for (let i = 0; i < expr.length - 1; i++) { + if (expr[i] === "(") depth++; + else if (expr[i] === ")") { + depth--; + if (depth === 0) return false; + } + } + return true; + } + function findTopLevelEquality(expr) { + let depth = 0; + for (let i = 0; i < expr.length; i++) { + const c = expr[i]; + if (c === "[" || c === "(") depth++; + else if (c === "]" || c === ")") depth--; + else if (depth === 0 && (c === "=" || c === "!") && expr[i + 1] === "=") { + if (i > 0 && (expr[i - 1] === "=" || expr[i - 1] === "!")) continue; + if (!expr.slice(0, i).trim()) continue; + const op = expr[i + 2] === "=" ? c + "==" : c + "="; + return { index: i, op }; + } + } + return null; + } + function resolvePath(vals, expr) { + const head = expr.match(IDENT_RE); + if (!head) return void 0; + let cur = vals == null ? void 0 : vals[head[0]]; + let i = head[0].length; + while (i < expr.length) { + if (expr[i] === ".") { + const m = expr.slice(i + 1).match(IDENT_RE) || expr.slice(i + 1).match(/^\d+/); + if (!m) return void 0; + cur = cur == null ? void 0 : cur[m[0]]; + i += 1 + m[0].length; + } else if (expr[i] === "[") { + let depth = 1; + let j = i + 1; + while (j < expr.length && depth > 0) { + if (expr[j] === "[") depth++; + else if (expr[j] === "]") { + depth--; + if (depth === 0) break; + } + j++; + } + if (depth !== 0) return void 0; + const key = resolve(vals, expr.slice(i + 1, j)); + cur = cur == null ? void 0 : cur[key]; + i = j + 1; + } else { + return void 0; + } + } + return cur; + } + + // src/encode.ts + var CAMEL_ATTR = "sc-camel-"; + var INLINE_TEXT_TAGS = new Set( + "a abbr b bdi bdo br cite code del dfn em i ins kbd mark q s samp small span strike strong sub sup u var wbr".split( + " " + ) + ); + var RAW_WRAP = { + select: "sc-raw-select", + table: "sc-raw-table", + tbody: "sc-raw-tbody", + thead: "sc-raw-thead", + tfoot: "sc-raw-tfoot", + tr: "sc-raw-tr", + td: "sc-raw-td", + th: "sc-raw-th", + caption: "sc-raw-caption" + }; + var RAW_UNWRAP = Object.fromEntries( + Object.entries(RAW_WRAP).map(([k, v]) => [v, k]) + ); + var EVENT_MAP = { + onclick: "onClick", + onchange: "onChange", + oninput: "onInput", + onsubmit: "onSubmit", + onkeydown: "onKeyDown", + onkeyup: "onKeyUp", + onkeypress: "onKeyPress", + onmousedown: "onMouseDown", + onmouseup: "onMouseUp", + onmouseenter: "onMouseEnter", + onmouseleave: "onMouseLeave", + onfocus: "onFocus", + onblur: "onBlur", + ondoubleclick: "onDoubleClick", + oncontextmenu: "onContextMenu", + onmousemove: "onMouseMove", + onmouseover: "onMouseOver", + onmouseout: "onMouseOut", + onpointerdown: "onPointerDown", + onpointerup: "onPointerUp", + onpointermove: "onPointerMove", + onpointerenter: "onPointerEnter", + onpointerleave: "onPointerLeave", + onpointercancel: "onPointerCancel", + onpointerover: "onPointerOver", + onpointerout: "onPointerOut", + ongotpointercapture: "onGotPointerCapture", + onlostpointercapture: "onLostPointerCapture", + ontouchstart: "onTouchStart", + ontouchend: "onTouchEnd", + ontouchmove: "onTouchMove", + ontouchcancel: "onTouchCancel", + ondragstart: "onDragStart", + ondragend: "onDragEnd", + ondragenter: "onDragEnter", + ondragleave: "onDragLeave", + ondragover: "onDragOver", + onanimationstart: "onAnimationStart", + onanimationend: "onAnimationEnd", + onanimationiteration: "onAnimationIteration", + ontransitionend: "onTransitionEnd" + }; + var ATTRS = `(?:[^>"']|"[^"]*"|'[^']*')*`; + var IMPORT_SELF_CLOSE_RE = new RegExp( + "<(x-import|dc-import)(" + ATTRS + ")/>", + "gi" + ); + var CAMEL_ATTR_RE = /(\s)([a-z]+[A-Z][A-Za-z0-9]*)(\s*=)/g; + function encodeCamelAttrs(html) { + return html.replace( + CAMEL_ATTR_RE, + (_, sp, name, eq) => sp + CAMEL_ATTR + name.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()) + eq + ); + } + function encodeCase(html) { + html = html.replace( + IMPORT_SELF_CLOSE_RE, + (_, t, a) => "<" + t + a + ">" + ); + html = html.replace(/)/gi, "/gi, ""); + html = encodeCamelAttrs(html); + for (const [real, alias] of Object.entries(RAW_WRAP)) { + html = html.replace( + new RegExp("(])", "gi"), + "$1" + alias + ); + } + return html; + } + function kebabToCamel(s) { + return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); + } + function cssToObj(css) { + const o = {}; + for (const decl of css.split(";")) { + const i = decl.indexOf(":"); + if (i < 0) continue; + const prop = decl.slice(0, i).trim(); + o[prop.startsWith("--") ? prop : kebabToCamel(prop)] = decl.slice(i + 1).trim(); + } + return o; + } + function compileAttr(raw) { + const whole = raw.match(/^\s*\{\{([\s\S]+?)\}\}\s*$/); + if (whole) { + const path = whole[1]; + return (vals) => resolve(vals, path); + } + if (raw.includes("{{")) { + const parts = raw.split(/\{\{([\s\S]+?)\}\}/g); + return (vals) => parts.map((s, i) => i & 1 ? resolve(vals, s) ?? "" : s).join(""); + } + return () => raw; + } + + // src/compile.ts + function collectProps(node, kind, host) { + const propGetters = []; + const pseudoClasses = []; + let hintSize = null; + for (const { name, value } of [...node.attributes]) { + if (name === "sc-name" || name === "data-dc-tpl") continue; + let key = name; + if (key.startsWith(CAMEL_ATTR)) + key = kebabToCamel(key.slice(CAMEL_ATTR.length)); + if (key === "hint-size") { + hintSize = value; + continue; + } + if (key.startsWith("style-")) { + pseudoClasses.push(host.pseudoClass(key.slice(6), value)); + continue; + } + if (kind !== "dom") { + if (key.includes("-") && !(kind === "x-import" && (key.startsWith("aria-") || key.startsWith("data-")))) + key = kebabToCamel(key); + } else { + if (key === "class") key = "className"; + else if (key === "for") key = "htmlFor"; + else if (key.startsWith("on")) + key = EVENT_MAP[key] || "on" + key[2].toUpperCase() + key.slice(3); + } + propGetters.push([key, compileAttr(value)]); + } + return { propGetters, pseudoClasses, hintSize }; + } + var HOST_STYLE_PROPS = /* @__PURE__ */ new Set([ + "position", + "left", + "right", + "top", + "bottom", + "inset", + "width", + "height", + "z-index", + "transform" + ]); + function hostPositionStyle(style) { + const all = typeof style === "string" ? cssToObj(style) : style != null && typeof style === "object" ? style : null; + if (!all) return void 0; + const out = {}; + for (const [k, v] of Object.entries(all)) { + const kebab = k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()); + if (HOST_STYLE_PROPS.has(kebab)) out[k] = v; + } + return Object.keys(out).length ? out : void 0; + } + function compileTemplate(html, host) { + const tpl = document.createElement("template"); + //! nosemgrep: direct-inner-html-assignment + tpl.innerHTML = encodeCase(html); + let tplN = 0; + (function stamp(node) { + if (node.nodeType === Node.ELEMENT_NODE) { + node.setAttribute("data-dc-tpl", String(tplN++)); + } + for (const c of node.childNodes) stamp(c); + })(tpl.content); + const builders = walkChildren(tpl.content, host); + const render = ((vals, ctx) => builders.map((b, i) => b(vals || {}, ctx, i))); + render.__annotated = tpl.innerHTML; + return render; + } + function walkChildren(node, host) { + return [...node.childNodes].map((c) => walk(c, host)).filter((b) => b != null); + } + var SLIDE_ID_VALUE_RE = /^[0-9a-f]{8}$/; + var DECK_CONTROL_FLOW_RE = /^(sc-if|sc-for|sc-else|dc-import|x-import)$/; + var DECK_AUX_RE = /^(template|script|style|sc-helmet|helmet)$/; + function isDeckMountTag(el) { + if (el.localName === "deck-stage") return true; + return el.localName === "x-import" && (el.getAttribute("component-from-global-scope") || "") === "deck-stage"; + } + function walkDeckChildren(el, host) { + const pairs = [...el.childNodes].map((c) => ({ c, b: walk(c, host) })).filter((p) => p.b !== null); + const kids = pairs.map((p) => p.b); + const seen = /* @__PURE__ */ new Set(); + const wsSeen = /* @__PURE__ */ new Map(); + const keys = []; + const nextSlideId = new Array(pairs.length); + { + let upcoming = null; + for (let j = pairs.length - 1; j >= 0; j--) { + const n = pairs[j].c; + if (n.nodeType === Node.ELEMENT_NODE) { + const t = n.localName; + upcoming = !DECK_AUX_RE.test(t) && !DECK_CONTROL_FLOW_RE.test(t) ? n.getAttribute("data-om-slide-id") : null; + } + nextSlideId[j] = upcoming; + } + } + for (let j = 0; j < pairs.length; j++) { + const { c } = pairs[j]; + if (c.nodeType === Node.TEXT_NODE) { + if ((c.nodeValue ?? "").trim() === "") { + const base = nextSlideId[j] ? "omid-ws:" + nextSlideId[j] : "omid-ws:aux"; + const n = wsSeen.get(base) ?? 0; + wsSeen.set(base, n + 1); + keys.push(n === 0 ? base : base + ":" + n); + continue; + } + return { kids, keys: null }; + } + if (c.nodeType !== Node.ELEMENT_NODE) { + keys.push(j); + continue; + } + const child = c; + const tag = child.localName; + if (DECK_AUX_RE.test(tag)) { + keys.push(j); + continue; + } + if (DECK_CONTROL_FLOW_RE.test(tag)) return { kids, keys: null }; + const v = child.getAttribute("data-om-slide-id"); + if (!v || !SLIDE_ID_VALUE_RE.test(v) || seen.has(v)) { + return { kids, keys: null }; + } + seen.add(v); + keys.push("omid:" + v); + } + return { kids, keys }; + } + function renderDeckKids(kids, kidKeys, vals, ctx) { + return kids.map((b, j) => { + const k = kidKeys ? kidKeys[j] : j; + const out = b(vals, ctx, k); + return kidKeys != null && typeof out === "string" ? h(getReact().Fragment, { key: k }, out) : out; + }); + } + function walk(node, host) { + if (node.nodeType === Node.TEXT_NODE) return walkText(node); + if (node.nodeType !== Node.ELEMENT_NODE) return null; + const el = node; + const tag = el.tagName.toLowerCase(); + if (tag === "sc-for") return walkFor(el, host); + if (tag === "sc-if") return walkIf(el, host); + if (tag === "x-import") return walkXImport(el, host); + if (tag === "sc-helmet") return host.helmet(el); + if (tag === "dc-import") return walkComponent(el, host); + return walkElement(el, host); + } + var warnedHoles = /* @__PURE__ */ new Set(); + function warnUnresolved(ctx, what) { + const key = (ctx?.__name || "?") + "\0" + what; + if (warnedHoles.has(key)) return; + warnedHoles.add(key); + console.warn("[dc-runtime] " + (ctx?.__name || "template") + ": " + what); + } + function walkText(node) { + const txt = node.nodeValue ?? ""; + if (!txt.includes("{{")) { + if (!txt.trim() && !txt.includes(" ")) return null; + return () => txt; + } + const parts = txt.split(/\{\{([\s\S]+?)\}\}/g); + return (vals, ctx, key) => h( + getReact().Fragment, + { key }, + ...parts.map((p, i) => { + if (!(i & 1)) return p; + const v = resolve(vals, p); + if (v === void 0) { + if (!ctx?.__streamingNow) { + if (document.body?.hasAttribute("data-dc-editor-on")) { + return h( + "span", + { key: i, className: "sc-interp sc-unresolved" }, + "{{ " + p.trim() + " }}" + ); + } + warnUnresolved( + ctx, + "{{ " + p.trim() + " }} never resolved \u2014 rendered as empty" + ); + return null; + } + return h( + "span", + { key: i, className: "sc-interp sc-missing" }, + p.trim() + ); + } + if (getReact().isValidElement(v) || Array.isArray(v)) { + return h(getReact().Fragment, { key: i }, v); + } + if (v === null || typeof v === "boolean") return null; + return h("span", { key: i, className: "sc-interp" }, String(v)); + }) + ); + } + function walkFor(el, host) { + const listGet = compileAttr(el.getAttribute("list") || ""); + const asName = el.getAttribute("as") || "item"; + const hintN = parseInt(el.getAttribute("hint-placeholder-count") || "0", 10); + const kids = walkChildren(el, host); + const listSrc = el.getAttribute("list") || ""; + return (vals, ctx, key) => { + let list = listGet(vals); + if (!Array.isArray(list)) { + if (!ctx?.__streamingNow) { + if (list !== void 0 && list !== null) { + warnUnresolved( + ctx, + 'sc-for list="' + listSrc + '" is not an array (' + typeof list + ")" + ); + } + list = []; + } else { + list = hintN > 0 ? Array(hintN).fill(void 0) : []; + } + } + return h( + getReact().Fragment, + { key }, + list.map((item, i) => { + const sub = { ...vals, [asName]: item, $index: i }; + return h( + getReact().Fragment, + { key: i }, + kids.map((b, j) => b(sub, ctx, j)) + ); + }) + ); + }; + } + function walkIf(el, host) { + const valGet = compileAttr(el.getAttribute("value") || ""); + const hintRaw = el.getAttribute("hint-placeholder-val"); + const hintGet = hintRaw != null ? compileAttr(hintRaw) : null; + const kids = walkChildren(el, host); + return (vals, ctx, key) => { + let v = valGet(vals); + if (v === void 0 && hintGet && ctx?.__streamingNow) v = hintGet(vals); + return v ? h( + getReact().Fragment, + { key }, + kids.map((b, j) => b(vals, ctx, j)) + ) : null; + }; + } + function walkComponent(el, host) { + const name = el.getAttribute("name") || el.getAttribute("component") || ""; + el.removeAttribute("name"); + el.removeAttribute("component"); + const tplId = el.getAttribute("data-dc-tpl"); + const styleRaw = el.getAttribute("style"); + el.removeAttribute("style"); + const styleGet = styleRaw != null ? compileAttr(styleRaw) : null; + const { propGetters, hintSize } = collectProps(el, "dc-import", host); + const kids = walkChildren(el, host); + return (vals, ctx, key) => { + const props = { + key, + __hintSize: hintSize, + __tplId: tplId, + __hostStyle: styleGet ? hostPositionStyle(styleGet(vals)) : void 0 + }; + for (const [k, g] of propGetters) { + const v = g(vals); + if (k === "dcProps") { + if (v && typeof v === "object") Object.assign(props, v); + continue; + } + props[k] = v; + } + if (kids.length) props.children = kids.map((b, j) => b(vals, ctx, j)); + return h(host.component(name), props); + }; + } + function walkXImport(el, host) { + const globalNameGet = compileAttr( + el.getAttribute("component-from-global-scope") || "" + ); + const exportNameGet = compileAttr( + el.getAttribute("component") || el.getAttribute("name") || "" + ); + const fromRaw = el.getAttribute("from") || (el.getAttribute("component-from-global-scope") ? "" : el.getAttribute("src") || el.getAttribute("import") || ""); + const urls = fromRaw.trim() ? fromRaw.trim().split(/\s+/) : []; + const url = urls.length ? urls[urls.length - 1] : ""; + const kindOf = (u) => /\.(jsx|tsx)(\?|#|$)/i.test(u) ? "jsx" : "js"; + const tplId = el.getAttribute("data-dc-tpl"); + const styleRaw = el.getAttribute("style"); + el.removeAttribute("style"); + const styleGet = styleRaw != null ? compileAttr(styleRaw) : null; + const wrap = tplId != null || styleGet != null; + const { propGetters, hintSize } = collectProps(el, "x-import", host); + const hasContent = el.children.length > 0 || !!(el.textContent || "").trim(); + const deckKeyed = hasContent && isDeckMountTag(el) ? walkDeckChildren(el, host) : null; + const kids = deckKeyed ? deckKeyed.kids : hasContent ? walkChildren(el, host) : []; + const kidKeys = deckKeyed?.keys ?? null; + const urlBindable = fromRaw.includes("{{"); + if (urls.length && !urlBindable) { + let prev; + for (const u of urls) prev = host.loadExternal(kindOf(u), u, prev); + } + const evalName = (g, vals) => { + const v = g(vals); + const s = v == null ? "" : String(v); + return s.includes("{{") ? "" : s; + }; + return (vals, ctx, key) => { + const globalName = evalName(globalNameGet, vals); + const name = globalName || evalName(exportNameGet, vals); + const C = !name || urlBindable ? null : globalName ? host.resolveExternalGlobal(url, globalName) : host.resolveExternal(url, name); + const hostStyle = styleGet ? hostPositionStyle(styleGet(vals)) : void 0; + const wrapper = wrap ? { + key, + className: "sc-host-x", + "data-dc-tpl": tplId, + style: hostStyle || { display: "contents" } + } : null; + if (!C) { + const error = urlBindable ? "x-import `from` cannot contain {{ \u2026 }} \u2014 module URLs are resolved at parse time; use a literal URL" : host.resolveExternalError(url, name); + const ph = host.placeholder({ + key: wrapper ? void 0 : key, + name, + hintSize, + error + }); + return wrapper ? h("div", wrapper, ph) : ph; + } + const props = wrapper ? {} : { key }; + let unresolvedHole = false; + for (const [k, g] of propGetters) { + if (k === "component" || k === "componentFromGlobalScope" || k === "from") { + continue; + } + const v = g(vals); + if (v === void 0) unresolvedHole = true; + if (k === "dcProps") { + if (v && typeof v === "object") Object.assign(props, v); + continue; + } + props[k] = v; + } + if (unresolvedHole && ctx?.__htmlStreamingNow) { + const ph = host.placeholder({ + key: wrapper ? void 0 : key, + name, + hintSize, + error: null + }); + return wrapper ? h("div", wrapper, ph) : ph; + } + if (kids.length) { + props.children = renderDeckKids(kids, kidKeys, vals, ctx); + } + return wrapper ? h("div", wrapper, h(C, props)) : h(C, props); + }; + } + function contentKey(el) { + const clone = el.cloneNode(true); + for (const d of clone.querySelectorAll("*")) { + while (d.attributes.length) d.removeAttribute(d.attributes[0].name); + } + const s = clone.innerHTML; + let h2 = 5381; + for (let i = 0; i < s.length; i++) h2 = (h2 << 5) + h2 + s.charCodeAt(i) | 0; + return s.length + "." + (h2 >>> 0).toString(36); + } + var NEVER_CONTENT_KEYED = new Set( + "script style textarea option title select canvas iframe video audio".split( + " " + ) + ); + var NOT_INLINE_SELECTOR = ":not(" + [...INLINE_TEXT_TAGS].join(",") + ")"; + function walkElement(el, host) { + const realTag = RAW_UNWRAP[el.localName] || el.localName; + const tplId = el.getAttribute("data-dc-tpl"); + const inlineOnly = el.childNodes.length > 0 && !NEVER_CONTENT_KEYED.has(realTag) && el.querySelector(NOT_INLINE_SELECTOR) === null; + const keySuffix = inlineOnly ? "|" + contentKey(el) : ""; + const { propGetters, pseudoClasses } = collectProps(el, "dom", host); + const deckKeyed = isDeckMountTag(el) ? walkDeckChildren(el, host) : null; + const kids = deckKeyed ? deckKeyed.kids : walkChildren(el, host); + const kidKeys = deckKeyed?.keys ?? null; + return (vals, ctx, key) => { + const props = { + key: key + keySuffix, + "data-dc-tpl": tplId + }; + for (const [k, g] of propGetters) { + let v = g(vals); + if (k === "style" && typeof v === "string") v = cssToObj(v); + if ((k === "value" || k === "checked") && v === void 0) { + v = k === "checked" ? false : ""; + } + props[k] = v; + } + if (pseudoClasses.length) { + props.className = [props.className, ...pseudoClasses].filter(Boolean).join(" "); + } + return h(realTag, props, ...renderDeckKids(kids, kidKeys, vals, ctx)); + }; + } + + // src/logic.ts + var StreamableLogic = class { + constructor(props) { + __publicField(this, "props"); + __publicField(this, "state", {}); + /** Back-pointer to the wrapper component, installed after construction. */ + __publicField(this, "__host"); + this.props = props || {}; + } + setState(update, cb) { + this.__host && this.__host.__setLogicState(update, cb); + } + forceUpdate() { + this.__host && this.__host.forceUpdate(); + } + componentDidMount() { + } + componentDidUpdate(_prevProps) { + } + componentWillUnmount() { + } + /** The flat object the template renders against (merged over props). */ + renderVals() { + return {}; + } + }; + function evalDcLogic(src) { + //! nosemgrep: eval-and-function-constructor + const fn = new Function( + "DCLogic", + "StreamableLogic", + "React", + src + '\n;return (typeof Component!=="undefined"&&Component)||undefined;' + ); + return fn(StreamableLogic, StreamableLogic, getReact()); + } + + // src/component.ts + function shallowEqual(a, b) { + if (!b) return false; + const ak = Object.keys(a).filter((k) => k !== "children"); + const bk = Object.keys(b).filter((k) => k !== "children"); + if (ak.length !== bk.length) return false; + for (const k of ak) if (a[k] !== b[k]) return false; + return true; + } + function Placeholder({ + name, + hintSize, + streaming, + error + }) { + const [w, hgt] = (hintSize || "100%,60px").split(","); + return h( + "div", + { + className: "sc-placeholder" + (streaming ? " sc-streaming" : ""), + style: { width: w.trim(), height: hgt && hgt.trim() }, + title: name + }, + error ? h( + "div", + { className: "sc-placeholder-error" }, + (name ? name + ": " : "") + error + ) : null + ); + } + function hintToMin(hint) { + if (!hint) return void 0; + const [w, hgt] = hint.split(","); + return { minWidth: w.trim(), minHeight: hgt && hgt.trim() }; + } + function createComponentFactory(registry, ensureFetched) { + const React = getReact(); + const AncestorContext = React.createContext([]); + class StreamableComponent extends React.Component { + constructor(props) { + super(props); + __publicField(this, "__name"); + __publicField(this, "__sub"); + __publicField(this, "__needsDidMount", false); + /** Snapshot of the registry's streaming flags taken at render time — + * builders read it off the RenderCtx (this) to pick placeholder vs + * render-nothing for unresolved values. */ + __publicField(this, "__streamingNow", false); + __publicField(this, "__htmlStreamingNow", false); + /** When a construct throws, remember the (class, registry.ver, props) + * triple so render-time reconcile doesn't re-attempt it on every parent + * re-render. A registry bump (new class, template, external module + * resolving via bumpAll) changes `ver` and breaks the memo so an + * env-dependent constructor can self-heal. */ + __publicField(this, "__failedLogic", null); + __publicField(this, "__failedUserProps", null); + __publicField(this, "__failedVer", -1); + /** Per-instance constructor error — kept here (not on the registry entry) + * so one instance's successful construct can't hide a sibling's failure, + * and a construct can never wipe an eval error `updateJs` recorded on + * `r.logicError`. */ + __publicField(this, "__ctorError", null); + __publicField(this, "logic"); + this.__name = props.__name; + this.state = { __v: 0, __err: null }; + this.__sub = () => { + if (this.state.__err) this.setState({ __err: null }); + this.forceUpdate(); + }; + this.__makeLogic(registry.get(this.__name).Logic, null); + ensureFetched(this.__name); + } + /** Error-boundary hook: a render crash anywhere in this DC's subtree + * (its own template, an x-import'd component, a child DC without its + * own deeper boundary) lands here instead of unmounting the page. */ + static getDerivedStateFromError(e) { + return { __err: e instanceof Error && e.message ? e.message : String(e) }; + } + componentDidCatch(e, info) { + console.error( + "[dc-runtime] render error in <" + this.__name + ">:", + e, + info?.componentStack || "" + ); + } + /** Instantiate the logic class (or the no-op base) and adopt `prevState` + * over its initial state — used both at mount and on hot-swap. */ + __makeLogic(Logic, prevState) { + const L = Logic || StreamableLogic; + try { + this.logic = new L(this.__userProps()); + this.__failedLogic = null; + this.__failedUserProps = null; + this.__ctorError = null; + } catch (e) { + console.error(e); + this.__failedLogic = Logic; + this.__failedUserProps = this.__userProps(); + this.__failedVer = registry.get(this.__name).ver; + this.__ctorError = this.__name + ": " + (e instanceof Error && e.message ? e.message : String(e)); + this.logic = new StreamableLogic( + this.__userProps() + ); + } + this.logic.__host = this; + if (prevState) + this.logic.state = { ...this.logic.state || {}, ...prevState }; + } + /** The props the author's logic + template see — internal __-prefixed + * wiring stripped. */ + __userProps() { + const { __name, __hintSize, __tplId, __hostStyle, ...rest } = this.props; + return rest; + } + __setLogicState(update, cb) { + const prev = this.logic.state; + const patch = typeof update === "function" ? update(prev) : update; + this.logic.state = { ...prev, ...patch }; + this.setState((s) => ({ __v: s.__v + 1 }), cb); + } + /** Swap the logic instance when the registry's Logic class changed + * (streaming completion, hot reload). State carries over; didMount + * re-fires after the swap commits so refs exist. */ + __reconcileLogic() { + const r = registry.get(this.__name); + const Next = r.Logic; + const Cur = this.logic.constructor; + if (Next === Cur || !Next && Cur === StreamableLogic || Next === this.__failedLogic && r.ver === this.__failedVer && shallowEqual(this.__userProps(), this.__failedUserProps)) { + return; + } + if (!this.__needsDidMount) { + try { + this.logic.componentWillUnmount(); + } catch (e) { + console.error(e); + } + } + this.__makeLogic(Next, this.logic.state); + this.__needsDidMount = true; + } + componentDidMount() { + registry.get(this.__name).subs.add(this.__sub); + try { + this.logic.componentDidMount(); + } catch (e) { + console.error(e); + } + } + componentDidUpdate(prevProps) { + this.logic.props = this.__userProps(); + if (this.__needsDidMount) { + if (this.state.__err || !registry.get(this.__name).tpl) return; + this.__needsDidMount = false; + try { + this.logic.componentDidMount(); + } catch (e) { + console.error(e); + } + } else { + try { + this.logic.componentDidUpdate(prevProps); + } catch (e) { + console.error(e); + } + } + } + componentWillUnmount() { + registry.get(this.__name).subs.delete(this.__sub); + if (!this.__needsDidMount) { + try { + this.logic.componentWillUnmount(); + } catch (e) { + console.error(e); + } + } + } + render() { + const r = registry.get(this.__name); + const cls = "sc-host" + (r.htmlStreaming ? " sc-streaming-html" : "") + (r.jsStreaming ? " sc-streaming-js" : ""); + const hintStyle = r.htmlStreaming ? hintToMin(this.props.__hintSize) : void 0; + const hostStyle = this.props.__hostStyle || hintStyle ? { ...hintStyle || {}, ...this.props.__hostStyle || {} } : void 0; + const hostBase = { + className: cls, + style: hostStyle, + "data-sc-name": this.__name, + "data-dc-tpl": this.props.__tplId + }; + const chain = Array.isArray(this.context) ? this.context : []; + if (chain.includes(this.__name)) { + const cycle = [ + ...chain.slice(chain.indexOf(this.__name)), + this.__name + ].join(" \u2192 "); + return h( + "div", + { ...hostBase, className: cls + " sc-has-error" }, + h(Placeholder, { + name: this.__name, + hintSize: this.props.__hintSize, + error: "circular import: " + cycle + }) + ); + } + if (this.state.__err) { + return h( + "div", + { ...hostBase, className: cls + " sc-has-error" }, + h( + "div", + { className: "sc-logic-error", "data-omelette-chrome": "" }, + this.__name + ": " + this.state.__err + ), + h(Placeholder, { + name: this.__name, + hintSize: this.props.__hintSize, + error: this.state.__err + }) + ); + } + this.__reconcileLogic(); + if (!r.tpl) { + return h( + "div", + hostBase, + h(Placeholder, { name: this.__name, hintSize: this.props.__hintSize }) + ); + } + const userProps = this.__userProps(); + this.logic.props = userProps; + let vals = userProps; + let renderErr = r.logicError || this.__ctorError; + try { + vals = { ...userProps, ...this.logic.renderVals() || {} }; + } catch (e) { + console.error(e); + renderErr = this.__name + ".renderVals(): " + (e instanceof Error && e.message ? e.message : String(e)); + } + this.__streamingNow = !!(r.htmlStreaming || r.jsStreaming); + this.__htmlStreamingNow = !!r.htmlStreaming; + return h( + "div", + { ...hostBase, className: cls + (renderErr ? " sc-has-error" : "") }, + renderErr && h( + "div", + { className: "sc-logic-error", "data-omelette-chrome": "" }, + renderErr + ), + h( + AncestorContext.Provider, + { value: [...chain, this.__name] }, + r.tpl(vals, this) + ) + ); + } + } + __publicField(StreamableComponent, "contextType", AncestorContext); + const named = /* @__PURE__ */ new Map(); + function getDC(name) { + const hit = named.get(name); + if (hit) return hit; + function Dispatcher(p) { + const [, setTick] = React.useState(0); + React.useEffect(() => { + const sub = () => setTick((n) => n + 1); + registry.get(name).subs.add(sub); + return () => { + registry.get(name).subs.delete(sub); + }; + }, []); + ensureFetched(name); + return h(StreamableComponent, { ...p, __name: name }); + } + Dispatcher.displayName = name; + named.set(name, Dispatcher); + return Dispatcher; + } + return { + getDC, + StreamableComponent + }; + } + + // src/bundled.ts + function bundledBlob(url) { + const blobs = window.__resourceBlobs; + const b = blobs ? blobs[url.split("#")[0]] : void 0; + return b instanceof Blob ? b : null; + } + + // src/cdn.ts + var REACT_URL = "https://unpkg.com/react@18.3.1/umd/react.production.min.js"; + var REACT_SRI = "sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z"; + var REACT_DOM_URL = "https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js"; + var REACT_DOM_SRI = "sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1"; + var BABEL_URL = "https://unpkg.com/@babel/standalone@7.29.0/babel.min.js"; + var BABEL_SRI = "sha384-m08KidiNqLdpJqLq95G/LEi8Qvjl/xUYll3QILypMoQ65QorJ9Lvtp2RXYGBFj1y"; + function cdnScriptFor(url, sri) { + const res = window.__resources; + const v = res ? res[url] : void 0; + return typeof v === "string" && v ? { src: v } : { src: url, integrity: sri }; + } + + // src/external.ts + var isCustomElementName = (n) => !n.includes(".") && n.includes("-"); + function isRenderableType(g) { + if (typeof g === "function") return !isElementClass(g); + return typeof g === "object" && g !== null && typeof g.$$typeof === "symbol"; + } + function resolveDottedPath(root, name) { + let cur = root; + for (const seg of name.split(".")) { + if (cur == null) return void 0; + cur = cur[seg]; + } + return cur; + } + var GLOBAL_POLL_INTERVAL_MS = 50; + var GLOBAL_POLL_TIMEOUT_MS = 3e4; + function createExternalModules(onResolved) { + const cache = /* @__PURE__ */ new Map(); + let babelLoading = null; + const reportedMissing = /* @__PURE__ */ new Map(); + const polling = /* @__PURE__ */ new Set(); + function ensureBabel() { + if (window.Babel) return Promise.resolve(); + if (babelLoading) return babelLoading; + const babel = cdnScriptFor(BABEL_URL, BABEL_SRI); + babelLoading = new Promise((res, rej) => { + const s = document.createElement("script"); + s.src = babel.src; + if (babel.integrity) { + s.integrity = babel.integrity; + s.crossOrigin = "anonymous"; + } + s.onload = () => res(); + s.onerror = rej; + document.head.appendChild(s); + }); + return babelLoading; + } + const pending = /* @__PURE__ */ new Map(); + function load(kind, url, after) { + const existing = pending.get(url); + if (existing) return existing; + cache.set(url, null); + console.info("[dc-runtime] x-import: loading", url, "(" + kind + ")"); + const ready = Promise.all([ + kind === "jsx" ? ensureBabel() : Promise.resolve(), + after ?? Promise.resolve() + ]); + const p = ready.then(() => { + const pre = bundledBlob(url); + if (pre) return pre.text(); + return fetch(url).then((r) => { + if (!r.ok) throw new Error("HTTP " + r.status); + return r.text(); + }); + }).then((src) => { + const code = kind === "jsx" ? window.Babel.transform(src, { + filename: url, + presets: ["react", "typescript"] + }).code : src; + const module = { exports: {} }; + const before = new Set(Object.keys(window)); + //! nosemgrep: eval-and-function-constructor + new Function("React", "module", "exports", "require", code)( + getReact(), + module, + module.exports, + () => ({}) + ); + const globals = {}; + for (const k of Object.keys(window)) { + if (!before.has(k) && typeof window[k] === "function") { + globals[k] = window[k]; + } + } + cache.set(url, { mod: module.exports, globals }); + console.info( + "[dc-runtime] x-import: loaded", + url, + "\u2014 exports:", + Object.keys(module.exports), + "window globals:", + Object.keys(globals) + ); + onResolved(); + }).catch((e) => { + cache.set(url, { + mod: {}, + globals: {}, + error: "failed to load: " + (e instanceof Error && e.message ? e.message : String(e)) + }); + console.error( + "[dc-runtime] x-import: FAILED to load", + url, + "(" + kind + ")", + e + ); + onResolved(); + }); + pending.set(url, p); + return p; + } + function resolve2(url, name) { + const entry = cache.get(url); + if (!entry) return null; + const { mod, globals } = entry; + const C = mod && mod[name] || globals && globals[name] || typeof window !== "undefined" && window[name] || mod && mod.default; + if (typeof C === "function") return C; + const key = url + "\0" + name; + if (!reportedMissing.has(key)) { + reportedMissing.set( + key, + entry.error || 'no export named "' + name + '" (has: ' + Object.keys(mod).join(", ") + ")" + ); + console.error( + "[dc-runtime] x-import: module", + url, + "loaded but has no component named", + JSON.stringify(name), + "\u2014 available exports:", + Object.keys(mod), + "window globals:", + Object.keys(globals), + ". The module must `module.exports = {" + name + "}` or set `window." + name + "`." + ); + } + return null; + } + function waitForGlobal(name) { + if (polling.has(name)) return; + polling.add(name); + const started = Date.now(); + const isCE = isCustomElementName(name); + const tick = () => { + const found = isCE ? customElements.get(name) : isRenderableType(resolveDottedPath(window, name)); + if (found) { + polling.delete(name); + onResolved(); + return; + } + if (Date.now() - started >= GLOBAL_POLL_TIMEOUT_MS) { + console.warn( + "[dc-runtime] x-import: global", + JSON.stringify(name), + "never appeared on window after " + GLOBAL_POLL_TIMEOUT_MS + "ms" + ); + return; + } + setTimeout(tick, GLOBAL_POLL_INTERVAL_MS); + }; + setTimeout(tick, GLOBAL_POLL_INTERVAL_MS); + } + function resolveGlobal(url, name) { + const isCE = isCustomElementName(name); + if (!url) { + if (isCE) { + if (customElements.get(name)) return name; + waitForGlobal(name); + return null; + } + const g2 = resolveDottedPath(window, name); + if (isRenderableType(g2)) return g2; + waitForGlobal(name); + return null; + } + const entry = cache.get(url); + if (!entry) return null; + if (isCE && customElements.get(name)) return name; + const g = entry.globals[name] ?? resolveDottedPath(window, name); + if (isRenderableType(g)) return g; + if (name.includes(".")) return null; + const key = url + "\0global\0" + name; + if (!reportedMissing.has(key)) { + reportedMissing.set(key, null); + if (isCE && !customElements.get(name)) { + console.warn( + "[dc-runtime] x-import:", + url, + "loaded but no custom element", + JSON.stringify(name), + "is registered and window." + name + " is not a function \u2014 rendering <" + name + "> as an unknown element." + ); + } + } + return name; + } + function getError(url, name) { + const entry = cache.get(url); + if (entry?.error) return entry.error; + return reportedMissing.get(url + "\0" + name) || null; + } + return { load, resolve: resolve2, resolveGlobal, getError }; + } + function isElementClass(g) { + try { + return typeof g === "function" && typeof HTMLElement !== "undefined" && g.prototype instanceof HTMLElement; + } catch { + return false; + } + } + + // src/atomics.ts + var ATOMIC_CSS = ( + // layout + ".fx{display:flex}.col{display:flex;flex-direction:column}.grid{display:grid}.ac{align-items:center}.jc{justify-content:center}.jb{justify-content:space-between}.f1{flex:1}.noshrink{flex-shrink:0}.wrap{flex-wrap:wrap}.fw5{font-weight:500}.fw6{font-weight:600}.fw7{font-weight:700}.fw8{font-weight:800}.fs11{font-size:11px}.fs12{font-size:12px}.fs13{font-size:13px}.fs14{font-size:14px}.fs15{font-size:15px}.fs16{font-size:16px}.fs20{font-size:20px}.fs22{font-size:22px}.upper{text-transform:uppercase}.tc{text-align:center}.nowrap{white-space:nowrap}.gap8{gap:8px}.gap10{gap:10px}.gap12{gap:12px}.gap16{gap:16px}.gap24{gap:24px}.m0{margin:0}.mt8{margin-top:8px}.mt12{margin-top:12px}.mt16{margin-top:16px}.mb8{margin-bottom:8px}.mb12{margin-bottom:12px}.mb16{margin-bottom:16px}.posrel{position:relative}.posabs{position:absolute}.round{border-radius:50%}.ohide{overflow:hidden}.bbox{box-sizing:border-box}.pointer{cursor:pointer}.w100{width:100%}.b0{border:none}" + ); + + // src/helmet.ts + var DESIGN_DOC_MODE_RE = /]*\bname\s*=\s*["']design_doc_mode["'][^>]*\b(?:content|value)\s*=\s*["'](\w+)["']/i; + var CANVAS_BG_LIGHT = "#f0eee6"; + var CANVAS_BG_DARK = "#2e2c26"; + function createHelmetManager(doc, isStreaming) { + const mounted = /* @__PURE__ */ new Set(); + const live = /* @__PURE__ */ new Map(); + let designDocMode = null; + let canvasStyleEl = null; + let appTheme = "light"; + try { + const ds = doc.documentElement.dataset.theme; + appTheme = ds === "dark" || ds === "light" ? ds : new URLSearchParams(doc.defaultView?.location.search ?? "").get( + "theme" + ) === "dark" ? "dark" : "light"; + } catch { + } + function applyCanvasBg() { + if (!canvasStyleEl) return; + const bg = appTheme === "dark" ? CANVAS_BG_DARK : CANVAS_BG_LIGHT; + canvasStyleEl.textContent = `html,body{background:${bg}}#dc-root>.sc-host{position:relative}`; + } + function postDesignMode(mode) { + if (window.parent === window) return; + try { + window.parent.postMessage({ type: "__dc_design_mode", mode }, "*"); + } catch { + } + } + function setDesignDocMode(mode) { + if (mode === designDocMode) return; + designDocMode = mode; + postDesignMode(mode); + if (mode === "canvas") { + doc.documentElement.setAttribute("data-dc-canvas", ""); + canvasStyleEl = doc.createElement("style"); + canvasStyleEl.setAttribute("data-dc-canvas", ""); + applyCanvasBg(); + doc.head.appendChild(canvasStyleEl); + } else { + doc.documentElement.removeAttribute("data-dc-canvas"); + canvasStyleEl?.remove(); + canvasStyleEl = null; + } + } + window.addEventListener("message", (e) => { + const type = e.data && e.data.type; + if (type === "__dc_theme") { + const t = e.data.theme; + if (t === "light" || t === "dark") { + appTheme = t; + applyCanvasBg(); + } + return; + } + if (!designDocMode || type !== "__dc_probe") return; + postDesignMode(designDocMode); + }); + function compile(node) { + const raw = [...node.children]; + const helmetClosed = node.nextSibling != null || node.parentNode?.nextSibling != null; + if (node.hasAttribute("data-dc-atomics") && !mounted.has("__dc-atomics")) { + mounted.add("__dc-atomics"); + const el = doc.createElement("style"); + el.id = "__dc-atomics"; + el.textContent = ATOMIC_CSS; + doc.head.appendChild(el); + } + return (_vals, ctx) => { + const name = ctx && ctx.__name || ""; + const streaming = !!(name && isStreaming(name)); + for (let i = 0; i < raw.length; i++) { + const child = raw[i]; + const tag = child.tagName; + const mayBePartial = streaming && !helmetClosed && i === raw.length - 1; + if (tag === "SCRIPT") { + if (mayBePartial) continue; + const key = "SCRIPT|" + (child.getAttribute("src") || child.textContent || ""); + if (mounted.has(key)) continue; + mounted.add(key); + const el = doc.createElement("script"); + for (const { name: an, value } of [...child.attributes]) + el.setAttribute(an, value); + if (child.textContent) el.textContent = child.textContent; + doc.head.appendChild(el); + } else if (tag === "LINK" || tag === "META") { + if (mayBePartial) continue; + const key = tag + "|" + (child.getAttribute("href") || child.getAttribute("src") || child.outerHTML); + if (mounted.has(key)) continue; + mounted.add(key); + if (tag === "LINK") { + const rel = (child.getAttribute("rel") || "").toLowerCase().split(/\s+/); + const href = (child.getAttribute("href") || "").trim(); + const res = window.__resources; + const pre = res && rel.includes("stylesheet") && !rel.includes("alternate") ? res[href] : void 0; + const blob = typeof pre === "string" && pre ? bundledBlob(pre) : null; + if (blob) { + const el = doc.createElement("style"); + if (child.hasAttribute("disabled")) { + el.setAttribute("media", "not all"); + } else if (child.getAttribute("media")) { + el.setAttribute("media", child.getAttribute("media")); + } + if (child.getAttribute("title")) + el.setAttribute("title", child.getAttribute("title")); + void blob.text().then((css) => { + el.textContent = css; + }); + doc.head.appendChild(el); + continue; + } + } + doc.head.appendChild(child.cloneNode(true)); + } else { + const key = name + "|" + i; + let el = live.get(key); + if (!el || el.tagName !== tag) { + if (el) el.remove(); + el = doc.createElement(tag.toLowerCase()); + live.set(key, el); + doc.head.appendChild(el); + } + for (const { name: an, value } of [...child.attributes]) { + if (el.getAttribute(an) !== value) el.setAttribute(an, value); + } + if (el.textContent !== child.textContent) + el.textContent = child.textContent; + } + } + return null; + }; + } + return { compile, setDesignDocMode }; + } + + // src/pseudo.ts + function scanUnquotedUrl(css, i) { + if (css[i] !== "u" && css[i] !== "U" || css.slice(i, i + 4).toLowerCase() !== "url(" || /[a-z0-9_-]/i.test(css[i - 1] ?? "")) { + return -1; + } + let j = i + 4; + while (j < css.length && /\s/.test(css[j])) j++; + if (css[j] === '"' || css[j] === "'") return -1; + while (j < css.length && css[j] !== ")") { + if (css[j] === "\\") j++; + j++; + } + return j < css.length ? j + 1 : css.length; + } + function stripComments(css) { + let out = ""; + let quote = ""; + for (let i = 0; i < css.length; i++) { + const c = css[i]; + if (quote) { + if (c === "\\") { + out += c + (css[i + 1] ?? ""); + i++; + continue; + } + if (c === quote) quote = ""; + out += c; + } else if (c === "'" || c === '"') { + quote = c; + out += c; + } else if (c === "/" && css[i + 1] === "*") { + const end = css.indexOf("*/", i + 2); + i = end === -1 ? css.length : end + 1; + out += " "; + } else { + const end = scanUnquotedUrl(css, i); + if (end === -1) out += c; + else { + out += css.slice(i, end); + i = end - 1; + } + } + } + return out; + } + function importantify(css) { + css = stripComments(css); + const decls = []; + let start = 0; + let depth = 0; + let quote = ""; + for (let i = 0; i < css.length; i++) { + const c = css[i]; + if (quote) { + if (c === "\\") i++; + else if (c === quote) quote = ""; + } else if (c === "'" || c === '"') quote = c; + else if (c === "(") depth++; + else if (c === ")") depth = Math.max(0, depth - 1); + else if (c === ";" && depth === 0) { + decls.push(css.slice(start, i)); + start = i + 1; + } else { + const end = scanUnquotedUrl(css, i); + if (end !== -1) i = end - 1; + } + } + decls.push(css.slice(start)); + return decls.map((d) => d.trim()).filter(Boolean).map((d) => /!\s*important$/i.test(d) ? d : d + " !important").join(";"); + } + function createPseudoSheet(doc) { + let el = null; + const cache = /* @__PURE__ */ new Map(); + let n = 0; + return (pseudo, css) => { + const k = pseudo + "|" + css; + const hit = cache.get(k); + if (hit) return hit; + if (!el) { + el = doc.createElement("style"); + doc.head.appendChild(el); + } + const cls = "scp" + (n++).toString(36); + const isPseudoElement = pseudo === "before" || pseudo === "after"; + const sel = isPseudoElement ? "." + cls + "::" + pseudo : "." + cls + ":" + pseudo; + el.sheet.insertRule( + sel + "{" + (isPseudoElement ? css : importantify(css)) + "}", + el.sheet.cssRules.length + ); + cache.set(k, cls); + return cls; + }; + } + + // src/registry.ts + function createRegistry() { + const entries = /* @__PURE__ */ Object.create(null); + function get(name) { + return entries[name] || (entries[name] = { + html: "", + tpl: null, + Logic: null, + jsStreaming: false, + htmlStreaming: false, + ver: 0, + subs: /* @__PURE__ */ new Set(), + fetched: false + }); + } + function bump(name) { + const r = get(name); + r.ver++; + for (const fn of r.subs) fn(); + } + return { + entries, + get, + bump, + bumpAll() { + for (const n in entries) bump(n); + } + }; + } + + // src/runtime.ts + var COMPONENT_DIR = "."; + function createRuntime(doc = document) { + const registry = createRegistry(); + const pseudoClass = createPseudoSheet(doc); + const helmet = createHelmetManager( + doc, + (name) => registry.get(name).htmlStreaming + ); + const external = createExternalModules(() => registry.bumpAll()); + const factory = createComponentFactory(registry, ensureFetched); + const host = { + component: (name) => factory.getDC(name), + placeholder: (props) => h(Placeholder, props), + helmet: (node) => helmet.compile(node), + loadExternal: (kind, url, after) => external.load(kind, url, after), + resolveExternal: (url, name) => external.resolve(url, name), + resolveExternalGlobal: (url, name) => external.resolveGlobal(url, name), + resolveExternalError: (url, name) => external.getError(url, name), + pseudoClass + }; + function ensureFetched(name) { + const r = registry.get(name); + if (r.fetched) return; + r.fetched = true; + const url = COMPONENT_DIR + "/" + encodeURIComponent(name) + ".dc.html"; + const res = window.__resources; + const pre = res ? res[url] : void 0; + const target = typeof pre === "string" && pre ? pre : url; + const blob = bundledBlob(target); + (blob ? blob.text() : fetch(target).then((res2) => { + if (!res2.ok) { + console.error( + '[dc-runtime] sibling fetch for "' + name + '" failed:', + url, + "returned", + res2.status, + "\u2014 the reference renders as an empty placeholder." + ); + return ""; + } + return res2.text(); + })).then((t) => { + if (!t) return; + const parsed = parseDcText(t); + if (!parsed) { + console.error( + '[dc-runtime] sibling fetch for "' + name + '":', + url, + "has no block \u2014 not a Design Component." + ); + return; + } + if (parsed.props) r.propsMeta = parsed.props; + if (parsed.preview) r.preview = parsed.preview; + if (parsed.template && !r.html) updateHtml(name, parsed.template); + if (parsed.js && !r.Logic) updateJs(name, parsed.js); + }).catch( + (e) => console.error( + '[dc-runtime] sibling fetch for "' + name + '" threw:', + url, + e + ) + ); + } + let rootName = null; + function updateHtml(name, html) { + const r = registry.get(name); + r.html = html; + if (name === rootName) { + const mode = DESIGN_DOC_MODE_RE.exec(html)?.[1] ?? null; + if (mode || !r.htmlStreaming) helmet.setDesignDocMode(mode); + } + try { + r.tpl = compileTemplate(html, host); + } catch (e) { + console.error("[dc-runtime] template compile FAILED for", name, e); + } + registry.bump(name); + } + function updateJs(name, src) { + const r = registry.get(name); + const seq = r.jsSeq = (r.jsSeq || 0) + 1; + try { + const Cls = evalDcLogic(src); + if (r.jsSeq !== seq) return; + if (typeof Cls !== "function") { + r.logicError = name + ".dc.html: + + +``` + +- [ ] **Step 5: Page script** + +`core/public/inbox.js`: +```js (() => { const csrf = document.querySelector('meta[name=csrf-token]').content; const call = (method, url, body) => fetch(url, { method, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf }, body: body ? JSON.stringify(body) : undefined, }); + const showErr = async (el, r) => { + const d = await r.json().catch(() => ({})); + el.textContent = d.message || Object.values(d.errors || {}).flat().join(' ') || 'Ошибка'; + el.hidden = false; + }; - // Кнопки «Помню» / «Сделано» - document.querySelectorAll('.event button[data-action]').forEach(btn => btn.addEventListener('click', async () => { - const card = btn.closest('.event'); - btn.disabled = true; + // Звёзды: 90 по небу, 170 в полосе (дуга −14°) + const star = (color, size, bright, x, y, dur, delay) => { + const s = document.createElement('div'); + s.style.cssText = `position:absolute;border-radius:50%;left:${x}%;top:${y}%;width:${size}px;height:${size}px;background:${color};${bright ? `box-shadow:0 0 6px ${color};` : ''}animation:skTwinkle ${dur}s ease-in-out ${delay}s infinite`; + return s; + }; + const sky = document.getElementById('stars'), band = document.getElementById('band'); + for (let i = 0; i < 90; i++) sky.appendChild(star(Math.random() < .2 ? '#8FD6DC' : '#F2ECE0', Math.random() < .85 ? 1.5 : 2.5, false, (Math.random() * 100).toFixed(2), (Math.random() * 100).toFixed(2), (3 + Math.random() * 5).toFixed(1), (-Math.random() * 8).toFixed(1))); + for (let j = 0; j < 170; j++) { + const bright = Math.random() < .08, r = Math.random(); + const color = r < .68 ? '#F2ECE0' : (r < .88 ? '#F7CEDC' : '#8FD6DC'); + const g = (Math.random() + Math.random() + Math.random()) / 3, x = Math.random() * 100; + const arc = 28 * Math.pow((x - 50) / 50, 2) + Math.max(0, 35 - x) * .35; + band.appendChild(star(color, bright ? 2.2 : (0.8 + Math.random() * 1.1).toFixed(1), bright, x.toFixed(2), (6 + g * 55 + arc).toFixed(2), (2.5 + Math.random() * 5).toFixed(1), (-Math.random() * 8).toFixed(1))); + } + + // Панели архив/настройки + document.querySelectorAll('.panel .head').forEach(h => h.addEventListener('click', () => { + const body = h.nextElementSibling; body.hidden = !body.hidden; + h.querySelector('.chev').textContent = body.hidden ? '▼' : '▲'; + })); + + // Форма добавления + const addform = document.getElementById('addform'); + const toggleAdd = () => { addform.hidden = !addform.hidden; document.getElementById('add-err').hidden = true; }; + document.getElementById('toggle-add').addEventListener('click', toggleAdd); + document.getElementById('cancel-add').addEventListener('click', toggleAdd); + document.getElementById('add').addEventListener('submit', async e => { + e.preventDefault(); + const f = new FormData(e.target); + const r = await call('POST', '/me/events', { title: f.get('title'), subtitle: f.get('subtitle') || null, due_date: f.get('due_date'), due_time: f.get('due_time') || null }); + if (r.ok) location.reload(); else showErr(document.getElementById('add-err'), r); + }); + + // «Помню» / «Сделано» + document.querySelectorAll('.card button[data-action]').forEach(btn => btn.addEventListener('click', async () => { + const card = btn.closest('.card'); + card.querySelectorAll('button').forEach(b => b.disabled = true); const r = await call('POST', `/me/events/${card.dataset.id}/${btn.dataset.action}`); - if (r.ok) location.reload(); else btn.disabled = false; + if (r.ok) location.reload(); else card.querySelectorAll('button').forEach(b => b.disabled = false); })); // Настройки @@ -4998,27 +5457,28 @@ class InboxController extends Controller e.preventDefault(); const f = new FormData(e.target); const r = await call('PATCH', '/me', { tz: f.get('tz'), quiet_start: f.get('quiet_start'), quiet_end: f.get('quiet_end') }); - if (r.ok) location.reload(); else alert((await r.json()).message || 'Ошибка'); + if (r.ok) location.reload(); else showErr(document.getElementById('profile-err'), r); }); document.getElementById('webhook').addEventListener('submit', async e => { e.preventDefault(); const f = new FormData(e.target); const r = await call('POST', '/me/channels', { type: 'webhook', config: { deliver_url: f.get('deliver_url'), presence_url: f.get('presence_url') } }); - if (r.ok) location.reload(); else alert((await r.json()).message || 'Ошибка'); - }); - document.getElementById('telegram').addEventListener('submit', async e => { - e.preventDefault(); - const r = await call('POST', '/me/channels/telegram/link'); - const d = await r.json(); - document.getElementById('tg-result').innerHTML = `Отправь боту /start ${d.code} или открой`; + if (r.ok) location.reload(); else showErr(document.getElementById('webhook-err'), r); }); document.querySelectorAll('[data-delete-channel]').forEach(btn => btn.addEventListener('click', async () => { const r = await call('DELETE', `/me/channels/${btn.dataset.deleteChannel}`); if (r.ok) location.reload(); })); + document.getElementById('tg-connect').addEventListener('click', async e => { + const r = await call('POST', '/me/channels/telegram/link'); + if (!r.ok) return; + const d = await r.json(); + document.getElementById('tg-code').textContent = `/start ${d.code}`; + document.getElementById('tg-link').href = d.bot_url; + e.target.hidden = true; document.getElementById('tg-box').hidden = false; + }); - // Присутствие: heartbeat только если вкладка видима и была активность за 3 минуты. - // Забытая фоновая вкладка не должна отвечать «пользователь тут» и глотать доставки. + // Присутствие: heartbeat только при видимой вкладке и активности за 3 минуты. let lastActivity = Date.now(); ['pointerdown', 'pointermove', 'keydown', 'scroll'].forEach(ev => addEventListener(ev, () => { lastActivity = Date.now(); }, { passive: true })); const heartbeat = () => { @@ -5030,35 +5490,28 @@ class InboxController extends Controller setInterval(heartbeat, 30 * 1000); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { lastActivity = Date.now(); heartbeat(); } }); })(); - - - ``` - Add to the `remote.user` group in `core/routes/web.php`: ```php Route::get('/', \App\Http\Controllers\InboxController::class); ``` -and delete `core/resources/views/welcome.blade.php`. +Delete `core/resources/views/welcome.blade.php`. -- [ ] **Step 4: Run tests** +- [ ] **Step 6: Run tests, Pint, whole suite** ```bash -cd core && php artisan test --filter InboxPageTest +cd core && php artisan test --filter InboxPageTest && php artisan test && vendor/bin/pint --test ``` -Expected: 2 tests PASS. +Expected: all green. In `test_renders_groups_cards_archive_and_settings` the relative strings depend on `setTestNow` (2026-09-04): «сегодня» for 09-04, «3 дня назад» for 09-01, «через 26 дней» for 09-30. -- [ ] **Step 5: Run the whole suite and Pint** +- [ ] **Step 7: Visual check against the prototype** + +Open `docs/design/handoff/hado-inbox.dc.html` in a browser (keep `support.js` next to it) and `http://localhost:8080/` with an `X-Remote-User` header (Task 13 compose). Compare: header, counter pill, group headings, card plaque, buttons, archive rows, settings. Fix spacing or token mismatches in `inbox.blade.php` only; do not change behavior. + +- [ ] **Step 8: Commit** ```bash -cd core && php artisan test && vendor/bin/pint --test -``` -Expected: all green; if Pint reports style issues run `vendor/bin/pint` and re-run tests. - -- [ ] **Step 6: Commit** - -```bash -cd /d/ai-projects/hado && git add -A && git commit -m "feat: web inbox with presence heartbeat +cd /d/ai-projects/hado && git add -A && git commit -m "feat: web inbox per Sekai design handoff Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw" @@ -5066,7 +5519,7 @@ Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw" --- -### Task 12: Docker Compose, Dockerfiles, Caddy snippet, README +### Task 13: Docker Compose, Dockerfiles, Caddy snippet, README **Files:** - Create: `docker-compose.yml`, `core/Dockerfile`, `core/Dockerfile.dev`, `deploy/Caddyfile.snippet`, `README.md`, `.env.example` (root, for compose) @@ -5254,10 +5707,10 @@ Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw" | §6 states, transitions, eve rule, recompute on upsert | 3, 4, 5, 9 | | §7 cascade | 3 | | §8 windows, truncated window fallback, quiet rule, ack/done paths | 4, 7, 10 | -| §9 drivers, presence table, web heartbeat rule, tick algorithm, pending row, retries | 8, 9, 11 | -| §10 `/me` API, inbox, tz/quiet hours, channels, telegram link | 7, 10, 11 | -| §11 three auth mechanisms, Caddy bypass paths | 6, 7, 10, 12 | -| §12 compose, scheduler, worker, env | 12 | +| §9 drivers, presence table, web heartbeat rule, tick algorithm, pending row, retries | 8, 9, 12 | +| §10 `/me` API, inbox, tz/quiet hours, channels, telegram link, manual events, archive | 7, 10, 11, 12 | +| §11 three auth mechanisms, Caddy bypass paths | 6, 7, 10, 13 | +| §12 compose, scheduler, worker, env | 13 | | §13 tests | every task | Known simplification vs spec: presence probes run sequentially per user (each cached 60 s) instead of in parallel; only `webhook` does network I/O, so the difference is at most one 2-second timeout per user per minute. Note it in the spec §9 if it ever matters. diff --git a/docs/superpowers/specs/2026-09-03-hado-core-design.md b/docs/superpowers/specs/2026-09-03-hado-core-design.md index 6956024..1620822 100644 --- a/docs/superpowers/specs/2026-09-03-hado-core-design.md +++ b/docs/superpowers/specs/2026-09-03-hado-core-design.md @@ -414,9 +414,23 @@ POST /me/channels/telegram/link → { code, bot_url } // затем /start < `HADO_DEFAULT_TZ`. Смена `tz` — руками через `PATCH /me` или из HA; позже iOS будет обновлять сама. -Веб-инбокс — одна Blade-страница под SSO: список событий по группам `today`, -`overdue`, `preparing`, `scheduled`, у каждого кнопки «Помню» / «Сделано», -`deep_link` ведёт в клиент. Блок настроек: пояс, тихие часы, каналы, привязка +Два дополнения по дизайн-хендоффу от 2026-09-04 (`docs/design/handoff/`): + +``` +POST /me/events { title, subtitle?, due_date, due_time? } + → ручное событие. Источник `manual` зарезервирован, токена у него нет, + через /api он недоступен. fire_at = срок − 30 дней, after_due = keep, + done_label «Сделано». Так ручное событие само попадает в «Грядёт» + за месяц, до этого лежит в «Запланировано». +GET /me/archive → закрытые события (done, expired), новые сверху, + до 100 штук, с подписью закрытия: done_label или «Истекло». + withdrawn в архиве не показывается. Глубина архива = retention. +``` + +Веб-инбокс — одна Blade-страница под SSO по дизайну Sekai (dark only): список +событий по группам `today`, `overdue`, `preparing`, `scheduled`, у каждого кнопки +«Помню» / «Сделано», `deep_link` ведёт в клиент; форма «+ Добавить» для ручного +события; сворачиваемый архив; блок настроек: пояс, тихие часы, каналы, привязка Telegram. Страница держит heartbeat. Никакого SPA. ## 11. Доступ