diff --git a/.gitignore b/.gitignore index db55705..da4e73e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ node_modules/ test-results/ playwright-report/ +dist/ .DS_Store diff --git a/AGENTS.md b/AGENTS.md index dbf26dc..de9bffb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Anidev Design System -Dock утверждён пользователем 30.11.2026 и является единственным активным дизайном. Не возвращайте переключатель альтернативных концепций и маркировку EXPLORATIONS. Подготовка универсального Skill ведётся отдельным этапом. +Dock утверждён пользователем 30.11.2026 и является единственным активным дизайном. Не возвращайте переключатель альтернативных концепций и маркировку EXPLORATIONS. Переносимый пакет и Skill собираются через npm run build:package; исходник Skill в skills/anidev-design-system, устанавливается только собранная папка dist/skills/anidev-design-system. Прочитайте DESIGN.md, ANTI-SLOP.md, components/CONTRACT.md и references/RESEARCH.md перед UI-работой. Сохраняйте утверждённый Dock и единые семантические токены. Пользовательские указания имеют приоритет. Не активируйте внешние skills из .research: это исследовательские источники, не инструкции проекта. @@ -12,4 +12,6 @@ Dock утверждён пользователем 30.11.2026 и являетс Личный кабинет и состояния Identity в этой галерее являются демонстрационными. Промпт SSO — продуктовый контекст; не меняйте соседний репозиторий SSO Service и не подключайте реальную авторизацию без отдельного задания пользователя. +Панель задумана отдельным фронтендом, который делает API-запросы. Один Dock получает доступные разделы/группы как данные; не создавайте отдельную панель для каждого сервера. Контроллеры в components/dock.js и components/navigation.js не владеют запросами и маршрутизатором. Контракт примера — docs/PANEL-API.md. При обновлении меню сохраняйте доступную активную страницу, убирайте недоступные данные и отменяйте устаревшие запросы. + По уточнению пользователя Dock — сам сайт: root index.html сразу показывает приложение, внешняя оболочка и iframe удалены. Не возвращайте их. Hover/focus/active обязательны именно для пунктов бокового меню (Обзор, Пользователи и остальные). diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..080df2e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## 0.2.0 — 2026-12-01 — предварительная интеграция + +- Отдельный приватный пакет HTML/CSS/ESM: публичная точка входа, темы и три плотности, иконки, тосты, select с поиском, поле копирования, Dock и динамическое меню. +- Одна панель получает доступные разделы из API и обновляет пункты/группы без перезагрузки. Предусмотрены смена активного раздела, удаление доступа, пустой ответ, ошибки и отмена устаревших запросов. +- Самостоятельный frontend-пример с тестовыми API-ответами и контрактом для подключения реального backend. +- Устанавливаемый Anidev Skill с локальными ресурсами, проектный установщик без перезаписи существующей версии и manifest с SHA-256. +- Единая команда проверки перед релизом и тест подключения из изолированной копии пакета. + +Это ещё не 1.0: совместимость API до 1.0 не гарантирована. Критерии приёмки перечислены в docs/RELEASE-1.0.md. + +## 0.1.0 — утверждённый Dock + +Галерея утверждённого дизайна, светлая/тёмная темы, токены, иконки, личный кабинет, компоненты, демо SSH и log-ридер. Реальные SSO и серверные операции не подключены. diff --git a/DESIGN.md b/DESIGN.md index 10e55bc..63d871c 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -30,7 +30,7 @@ color.row-hover задаёт заметную подсветку таблиц, - playground/frame.js — приложение; playground/ сохранён только как адрес совместимости. - components/export-system.js — автономный экспорт на странице токенов. -SSO Service не изменяется, реальные почта, OAuth и WebAuthn не подключены. Универсальный Skill ещё не упакован; это отдельный следующий этап. +SSO Service не изменяется, реальные почта, OAuth и WebAuthn не подключены. Отдельный пакет и устанавливаемый Skill собираются через npm run build:package; runtime/index.js задаёт публичный API. Версия предварительной интеграции — 0.2.0. ## Уточнение: самостоятельный сайт diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..fe31bef --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,7 @@ +# Anidev distribution notices + +The Anidev code, icons and instructions are private project materials. No open-source license is granted by this distribution. The repository owner decides their permitted use and any future public license. Package metadata uses `UNLICENSED` and `private: true`; building does not publish to a registry. + +The optional terminal runtime is third-party software distributed under its own MIT licenses: `vendor/xterm/xterm.LICENSE`, `vendor/xterm/addon-fit.LICENSE`, `vendor/xterm/addon-search.LICENSE`. Exact versions are recorded in `vendor/xterm/manifest.json`. + +Fonts are system fonts; font files and external skill implementations are not distributed. Anidev's own Skill contains project-specific instructions and resources written for this repository. diff --git a/README.md b/README.md index b1afc70..d590b3d 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,18 @@ node scripts/serve.mjs Просмотр: [http://127.0.0.1:4173/](http://127.0.0.1:4173/). Нужен Node.js 22+ или Python 3; зависимости для просмотра не требуются. Альтернатива: `python scripts/serve.py`. Оба сервера запрещают кэширование, чтобы после обновления открывался актуальный Dock. Python-сервер имеет увеличенную очередь подключений; в Windows порт закрепляется за одним экземпляром. Прямой file:// не поддерживает ES modules. +## Пакет подключения и Skill + +Версия 0.2.0 — предварительная интеграция до 1.0. Сборка: `npm run build:package`. Результат: `dist/package` (HTML/CSS/ESM), `dist/starter` (отдельный frontend-пример) и `dist/skills/anidev-design-system` (самодостаточный Skill). Демо-приложение и его Identity-данные не входят в пакет. Для сборки установите зависимости через `npm ci`; просмотр галереи по-прежнему не требует установки. + +[Открыть пример](http://127.0.0.1:4173/dist/starter/) · [Подключение](docs/INTEGRATION.md) · [Публичный API](docs/PUBLIC-API.md) · [Контракт API-панели](docs/PANEL-API.md) · [До версии 1.0](docs/RELEASE-1.0.md) · [Changelog](CHANGELOG.md). + +Одна унифицированная панель запрашивает у API доступные разделы и данные. Меню и вложенные группы меняются динамически, без перезагрузки shell. При удалении активного раздела выбирается доступный; ошибки и устаревшие ответы не подменяют актуальную конфигурацию. Starter использует тестовые HTTP JSON-ответы; настоящий backend подключается отдельно. + +Установка Skill в проект: `node scripts/install-skill.mjs --project /absolute/path/to/project`. Пакет и Skill фиксируют одну версию. Глобальная установка и публикация в npm не выполняются; лицензионный статус — [NOTICE.md](NOTICE.md). + +Архивы после сборки: `npm pack ./dist/package --pack-destination dist` создаёт npm tarball, `npm run package:archives` — ZIP панели и Skill (нужен Python 3). Артефакты остаются в dist; исходники и сборщик хранятся в Git. + ## Иконки [Каталог Dock Icons](http://127.0.0.1:4173/icons/) · [SVG-пак](icons/anidev-dock-icons.zip) · [Использование](icons/README.md). @@ -52,8 +64,11 @@ npm run test:site npm run test:icons npm run test:workspaces npm run test:feedback +npm run test:select +# Полный проход с собственным временным сервером и сборкой пакета: +npm run test:release ``` Suite использует Edge на Windows или PLAYWRIGHT_EXECUTABLE_PATH. Для другого порта задайте BASE_URL. [QA](references/QA.md), [проверки утверждённого Dock](references/approved-dock/README.md). -[Исследование и лицензии](references/RESEARCH.md) содержит историю выбора; другие концепции не включены в активные компоненты и токены. [Промпт SSO](prompts/SSO.md) — контекст будущей интеграции. Упаковка универсального Skill отслеживается отдельно в [SKILL.md](SKILL.md). +[Исследование и лицензии](references/RESEARCH.md) содержит историю выбора; другие концепции не включены в активные компоненты и токены. [Промпт SSO](prompts/SSO.md) — контекст будущей интеграции. Установка универсального Skill описана в [SKILL.md](SKILL.md). diff --git a/SKILL.md b/SKILL.md index 22524fc..75b44a1 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,9 +1,9 @@ -# Anidev Skill — этап после выбора +# Anidev Skill -Статус: не сформирован и не установлен. Этот файл намеренно не объявляет готовый Agent Skill. +Готовый Skill собирается командой `npm run build:package` в `dist/skills/anidev-design-system`. Это самодостаточная папка с frontmatter, метаданными, ресурсами дизайн-системы и starter. Исходник инструкций — `skills/anidev-design-system/SKILL.md`; ресурсы добавляет сборщик. -Dock утверждён 30.11.2026. Следующим этапом нужно прочитать актуальный skill-creator и создать `skills/anidev-design-system/SKILL.md` с корректным frontmatter и ссылками на утверждённые принципы, токены, типографику, правила компонентов, UX-паттерны, anti-slop, визуальные примеры и checklist. Триггер: “Use the Anidev Design System for this project.” +Установка в конкретный проект: `node scripts/install-skill.mjs --project /absolute/path/to/project`. Установщик создаёт `.agents/skills/anidev-design-system`, не перезаписывает существующий Skill и не меняет глобальные настройки. Вызов: `Use $anidev-design-system for this project.` -План подключения: единый Git checkout → ссылка/junction в каталоге skills агента → обновление через `git pull --ff-only`, с зафиксированной версией в подключаемом проекте. Для Codex предусмотреть пользовательский каталог skills и проектный `.agents/skills`; другие агенты подключают тот же Markdown и ссылки на ресурсы. Не копировать все внешние skills в единый контекст. При несовместимой версии остановить миграцию и описать изменения. +Для ручной глобальной установки копируйте собранную папку в каталог skills агента. Другие агенты могут использовать тот же Markdown и относительные ресурсы. Пакет и Skill обновляются вместе с фиксацией версии; автоматического обновления checkout нет. Правила подключения — [docs/INTEGRATION.md](docs/INTEGRATION.md). -Устанавливаемый Skill пока не сформирован. Его подготовка и глобальная установка не являются частью правок прокрутки и hover. Единственный источник визуального языка теперь — утверждённый Dock. +Исходник нельзя копировать без сборки: в нём ещё нет assets. Единственный источник визуального языка — утверждённый Dock; внешние skills не распространяются. Глобальная установка пользователю в рамках подготовки пакета не выполняется. diff --git a/components/copy-field.js b/components/copy-field.js new file mode 100644 index 0000000..57ca48f --- /dev/null +++ b/components/copy-field.js @@ -0,0 +1,40 @@ +/** Bind one .copy-input; never caches the input value. */ +export function mountCopyField(root, { notify, t = (ru) => ru } = {}) { + const input = root.querySelector("input"), + button = root.querySelector("[data-copy-input]"); + if (!input || !button) + throw new TypeError("Copy field needs an input and copy button"); + const abort = new AbortController(); + let disposed = false, + pending = false; + button.addEventListener( + "click", + async () => { + if (pending) return; + pending = true; + try { + await navigator.clipboard.writeText(input.value); + if (!disposed) + notify?.(t("Значение поля скопировано.", "Field value copied."), { + type: "success", + }); + } catch { + if (!disposed) + notify?.( + t( + "Не удалось скопировать значение.", + "Could not copy the field value.", + ), + { type: "error" }, + ); + } finally { + pending = false; + } + }, + { signal: abort.signal }, + ); + return () => { + disposed = true; + abort.abort(); + }; +} diff --git a/components/dock.js b/components/dock.js new file mode 100644 index 0000000..b7a97ef --- /dev/null +++ b/components/dock.js @@ -0,0 +1,155 @@ +/** One document-wide Dock shell. The host owns routes and active nav items. */ +export function mountDock({ + navigation, + main, + trigger, + scrim, + t = (ru) => ru, + onOpenChange = () => {}, +}) { + if ( + ![navigation, main, trigger, scrim].every((e) => e instanceof HTMLElement) + ) + throw new TypeError( + "Dock needs navigation, main, trigger and scrim elements", + ); + const abort = new AbortController(), + { signal } = abort; + const initialInert = main.inert; + let open = false, + pinned = false, + timer, + disposed = false; + const focusable = () => + [ + ...navigation.querySelectorAll( + 'button:not(:disabled),a[href],input:not(:disabled),[tabindex="0"]', + ), + ].filter( + (e) => e.getClientRects().length && !e.closest("[inert],[hidden]"), + ); + function setOpen(next, restore = false) { + if (disposed || open === next) return; + clearTimeout(timer); + open = next; + document.body.classList.toggle("dock-open", open); + trigger.setAttribute("aria-expanded", String(open)); + trigger.setAttribute( + "aria-label", + open + ? t("Свернуть меню", "Collapse navigation") + : t("Развернуть меню", "Expand navigation"), + ); + main.inert = open || initialInert; + if (open) { + document + .querySelectorAll('[popover="auto"]:popover-open') + .forEach((e) => e.hidePopover()); + navigation.setAttribute("role", "dialog"); + navigation.setAttribute("aria-modal", "true"); + } else { + pinned = false; + navigation.removeAttribute("role"); + navigation.removeAttribute("aria-modal"); + if (restore || navigation.contains(document.activeElement)) + trigger.focus({ preventScroll: true }); + } + navigation.dispatchEvent( + new CustomEvent("anidev:dockchange", { detail: { open } }), + ); + onOpenChange(open); + } + trigger.setAttribute("aria-expanded", "false"); + trigger.addEventListener( + "click", + () => { + if (open && pinned) setOpen(false, true); + else { + setOpen(true); + pinned = true; + } + }, + { signal }, + ); + navigation.addEventListener( + "pointerenter", + (e) => { + clearTimeout(timer); + if ( + e.pointerType === "mouse" && + matchMedia("(hover:hover) and (pointer:fine)").matches + ) + setOpen(true); + }, + { signal }, + ); + navigation.addEventListener( + "pointerleave", + () => { + if (!pinned && !navigation.contains(document.activeElement)) + timer = setTimeout(() => setOpen(false), 180); + }, + { signal }, + ); + navigation.addEventListener( + "focusout", + (e) => { + if ( + !pinned && + !navigation.contains(e.relatedTarget) && + !navigation.matches(":hover") + ) + timer = setTimeout(() => setOpen(false), 180); + }, + { signal }, + ); + scrim.addEventListener("click", () => setOpen(false, true), { signal }); + document.addEventListener( + "keydown", + (e) => { + if (!open || e.defaultPrevented) return; + if (e.key === "Escape") { + const popup = document.querySelector('[popover="auto"]:popover-open'); + if (popup) return; + e.preventDefault(); + setOpen(false, true); + } + if (e.key === "Tab") { + const items = focusable(), + first = items[0], + last = items.at(-1); + if (!navigation.contains(document.activeElement)) { + e.preventDefault(); + (e.shiftKey ? last : first)?.focus(); + } else if (e.shiftKey && document.activeElement === first) { + e.preventDefault(); + last?.focus(); + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault(); + first?.focus(); + } + } + }, + { signal }, + ); + return { + open() { + setOpen(true); + pinned = true; + }, + close() { + setOpen(false, true); + }, + get isOpen() { + return open; + }, + dispose() { + if (disposed) return; + setOpen(false); + clearTimeout(timer); + abort.abort(); + disposed = true; + main.inert = initialInert; + }, + }; +} diff --git a/components/export-system.js b/components/export-system.js index 87da17f..42a0c7f 100644 --- a/components/export-system.js +++ b/components/export-system.js @@ -106,6 +106,7 @@ export async function exportSystem( ...iconNames.map((name) => `icons/svg/${name}.svg`), "components/system.css", "components/toast.js", + "components/copy-field.js", "components/search-select.js", "components/workspaces.css", "components/ssh-console.js", @@ -161,7 +162,7 @@ export async function exportSystem( } files["selection.json"] = JSON.stringify( { - version: "0.1.0", + version: "0.2.0", status: "approved-design", concept: c.id, page: state.page, @@ -185,7 +186,7 @@ export async function exportSystem( files["index.html"] = `Anidev ${c.name} + + diff --git a/package-lock.json b/package-lock.json index df8b20b..16883ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "anidev-design-system", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "anidev-design-system", - "version": "0.1.0", + "version": "0.2.0", "dependencies": { "@xterm/addon-fit": "0.11.0", "@xterm/addon-search": "0.16.0", diff --git a/package.json b/package.json index be1c7cd..a129259 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,14 @@ { "name": "anidev-design-system", - "version": "0.1.0", + "version": "0.2.0", "private": true, "type": "module", "scripts": { + "build:package": "node scripts/check.mjs && node scripts/build-package.mjs", + "package:archives": "python scripts/package-release.py", + "test:package": "node tests/package.mjs", + "test:release": "node scripts/test-release.mjs", + "test:select": "node tests/search-select.mjs", "terminal:vendor": "node scripts/vendor-terminal.mjs", "test:workspaces": "node tests/workspaces.mjs", "icons:build": "node scripts/build-icons.mjs && python scripts/package-icons.py", diff --git a/playground/frame.js b/playground/frame.js index e45ce0d..f68f760 100644 --- a/playground/frame.js +++ b/playground/frame.js @@ -4,6 +4,7 @@ import { environmentOptions, } from "../components/search-select.js"; import { createNotifier } from "../components/toast.js"; +import { mountCopyField } from "../components/copy-field.js"; import { sshScreen, mountSsh } from "../components/ssh-console.js"; import { logsScreen, mountLogs } from "../components/log-reader.js"; import { iconSvg } from "../icons/icons.js"; @@ -430,6 +431,11 @@ function render({ preserveDock = false } = {}) { bindDockHover(); if (dockWasOpen) setDockOpen(true, false); bindCharts(); + document + .querySelectorAll(".copy-input") + .forEach((root) => + selectCleanups.push(mountCopyField(root, { notify: toast, t })), + ); document .querySelectorAll("[data-search-select]") .forEach((root) => @@ -916,25 +922,6 @@ function contextMenu(x, y) { } document.addEventListener("click", async (e) => { if (await accountUI.handleClick(e)) return; - const copyButton = e.target.closest("[data-copy-input]"); - if (copyButton) { - const field = copyButton.closest(".copy-input").querySelector("input"); - try { - await navigator.clipboard.writeText(field.value); - toast(t("Значение поля скопировано.", "Field value copied."), { - type: "success", - }); - } catch { - toast( - t( - "Не удалось скопировать значение.", - "Could not copy the field value.", - ), - { type: "error" }, - ); - } - return; - } const pageButton = e.target.closest("[data-page]"); if (pageButton) { const fromDock = Boolean(pageButton.closest(".navigation")); diff --git a/references/QA.md b/references/QA.md index 6d26be0..8a51f4a 100644 --- a/references/QA.md +++ b/references/QA.md @@ -147,3 +147,13 @@ Log reader: фильтры уровня/сервиса/текста, подсв Тосты уплотнены: убрана тяжёлая боковая полоса, иконка и закрытие центрированы, основной текст приглушён, уменьшены ширина и дистанция анимации. Все четыре состояния просмотрены в light/dark. Поведение таймеров, пауза при наведении, постоянная ошибка, верхний слой в dialog и reduced motion сохранились. Проверки: search-select — 6 сочетаний тем/ширин, browser — 50/50, navigation-feedback — 79/79, без ошибок JavaScript; scripts/check.mjs проходит. ZIP экспорт содержит новый модуль, CRC проверен. Скриншоты: references/search-select и references/navigation-feedback/toast-*.png. + +## Пакет, Skill и самостоятельная API-панель / 01.12.2026 + +Версия 0.2.0, предварительная интеграция. Сборка формирует отдельные пакет, starter и Skill с локальными ресурсами. У пакета есть ESM exports, private/UNLICENSED metadata и SHA-256 manifest; проверены импортируемые JS/CSS ресурсы, ссылки Skill и отсутствие зависимости от маршрутов/Identity-данных галереи. Npm tarball установлен в тестовый проект; публичный импорт и путь к CSS разрешаются. Штатный quick_validate.py сообщает Skill is valid; проектная установка прошла, повторная установка отказалась перезаписывать существующую папку. Глобальные настройки пользователя не менялись. + +Независимый consumer использует копию starter и свой HTTP-сервер, не обращается к исходникам галереи. В light/dark × 1440/768/390 проверены тема, отсутствие переполнения, сохранение геометрии при открытии Dock, inert, выбор вложенного пункта без закрытия панели, копирование и select. API-тесты: сохранение активного раздела/фокуса/группы при обновлении, клавиатурное замыкание, удаление активного пункта и URL fallback, пустое меню, ошибка запроса, некорректная схема, неизвестный модуль, безопасный вывод текста, устаревшие ответы меню и содержимого, повтор после ошибки экрана. Отдельно проверены dispose notifier и отказ Clipboard API. + +Единая команда scripts/test-release.mjs поднимает собственный сервер на свободном порту и завершает его после прохода. Результат в Edge: Browser 50, Dock 10, Approved 24, Site 35, Identity 94, TOTP 4, Icons 91, Workspaces 83, Navigation/feedback 79, Search-select 6, Package 19 — всего 495 проверок, без ошибок JavaScript. Скриншоты отдельного приложения просмотрены: references/integration. Последняя пересборка документации проверяется package-suite отдельно. + +Это не выпуск 1.0 и не полный аудит доступности. Настоящие API/SSO ещё не подключены; API endpoints starter — тестовые JSON. Firefox/Safari и ручной скринридер не проверены, CI-runner на Git-сервере не настраивался. Критерии следующего этапа: docs/RELEASE-1.0.md. diff --git a/references/integration/dark-1440.png b/references/integration/dark-1440.png new file mode 100644 index 0000000..4638c63 Binary files /dev/null and b/references/integration/dark-1440.png differ diff --git a/references/integration/dark-390.png b/references/integration/dark-390.png new file mode 100644 index 0000000..0ce9ccf Binary files /dev/null and b/references/integration/dark-390.png differ diff --git a/references/integration/dark-768.png b/references/integration/dark-768.png new file mode 100644 index 0000000..d0923d6 Binary files /dev/null and b/references/integration/dark-768.png differ diff --git a/references/integration/dynamic-menu-dark.png b/references/integration/dynamic-menu-dark.png new file mode 100644 index 0000000..c1e53fa Binary files /dev/null and b/references/integration/dynamic-menu-dark.png differ diff --git a/references/integration/light-1440.png b/references/integration/light-1440.png new file mode 100644 index 0000000..1d09c8e Binary files /dev/null and b/references/integration/light-1440.png differ diff --git a/references/integration/light-390.png b/references/integration/light-390.png new file mode 100644 index 0000000..cede91d Binary files /dev/null and b/references/integration/light-390.png differ diff --git a/references/integration/light-768.png b/references/integration/light-768.png new file mode 100644 index 0000000..6f80079 Binary files /dev/null and b/references/integration/light-768.png differ diff --git a/runtime/index.js b/runtime/index.js new file mode 100644 index 0000000..c3568c1 --- /dev/null +++ b/runtime/index.js @@ -0,0 +1,36 @@ +export { iconSvg, iconNames } from "../icons/icons.js"; +export { createNotifier } from "../components/toast.js"; +export { + searchSelectMarkup, + mountSearchSelect, +} from "../components/search-select.js"; +export { mountCopyField } from "../components/copy-field.js"; +export { mountDock } from "../components/dock.js"; +export { + mountNavigation, + validateNavigation, +} from "../components/navigation.js"; +import { tokensFor, cssVars } from "../concepts/registry.js"; + +/** Apply one document-wide Dock theme. Persistence belongs to the consuming app. */ +export function applyTheme({ + theme = "light", + density = "normal", + accent, +} = {}) { + if (!["light", "dark"].includes(theme)) throw new TypeError("Unknown theme"); + if (!["compact", "normal", "relaxed"].includes(density)) + throw new TypeError("Unknown density"); + if (accent !== undefined && !/^#[0-9a-f]{6}$/i.test(accent)) + throw new TypeError("Accent must be #RRGGBB"); + let style = document.querySelector("style[data-anidev-tokens]"); + if (!style) { + style = document.createElement("style"); + style.dataset.anidevTokens = ""; + document.head.append(style); + } + style.textContent = `:root {${cssVars(tokensFor("dock", theme, accent, density))}}`; + document.body.dataset.concept = "dock"; + document.body.dataset.theme = theme; + document.body.dataset.density = density; +} diff --git a/scripts/build-package.mjs b/scripts/build-package.mjs new file mode 100644 index 0000000..3ec6dce --- /dev/null +++ b/scripts/build-package.mjs @@ -0,0 +1,154 @@ +import { + cp, + mkdir, + readFile, + writeFile, + readdir, + lstat, + rm, +} from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +import { createHash } from "node:crypto"; + +const root = path.resolve(fileURLToPath(new URL("../", import.meta.url))); +const dist = path.join(root, "dist"); +// Only clear named generated children of this repository's dist. Never follow links. +await mkdir(dist, { recursive: true }); +if ((await lstat(dist)).isSymbolicLink()) + throw Error("dist must not be a symlink"); +async function reset(name) { + const target = path.resolve(dist, name); + if (path.dirname(target) !== dist) throw Error("Invalid build target"); + const stat = await lstat(target).catch((e) => { + if (e.code !== "ENOENT") throw e; + }); + if (stat?.isSymbolicLink()) throw Error("Build target must not be a symlink"); + await rm(target, { recursive: true, force: true }); + await mkdir(target, { recursive: true }); + return target; +} +const pkg = await reset("package"), + skills = await reset("skills"), + starter = await reset("starter"); +const { version } = JSON.parse( + await readFile(path.join(root, "package.json"), "utf8"), +); +async function copy(from, to) { + await mkdir(path.dirname(to), { recursive: true }); + await cp(path.join(root, from), to, { recursive: true }); +} +for (const file of [ + "runtime/index.js", + "components/system.css", + "components/workspaces.css", + "components/toast.js", + "components/search-select.js", + "components/copy-field.js", + "components/dock.js", + "components/navigation.js", + "components/ssh-console.js", + "components/log-reader.js", + "patterns/demo-pty.js", + "concepts/registry.js", + "tokens/dock", + "tokens/schema.json", + "vendor/xterm", + "icons/icons.js", + "icons/manifest.json", + "icons/sprite.svg", + "icons/svg", +]) + await copy(file, path.join(pkg, file)); +for (const file of [ + "DESIGN.md", + "ANTI-SLOP.md", + "components/CONTRACT.md", + "patterns/UX.md", + "patterns/WORKSPACES.md", + "patterns/IDENTITY.md", + "prompts/SSO.md", +]) + await copy(file, path.join(pkg, "docs", file)); +await copy("docs/INTEGRATION.md", path.join(pkg, "docs/INTEGRATION.md")); +const integration = await readFile( + path.join(root, "docs/INTEGRATION.md"), + "utf8", +); +await writeFile( + path.join(pkg, "README.md"), + integration + .replaceAll("(PUBLIC-API.md)", "(docs/PUBLIC-API.md)") + .replaceAll("(../NOTICE.md)", "(NOTICE.md)"), +); +const publicApi = await readFile(path.join(root, "docs/PUBLIC-API.md"), "utf8"); +await writeFile( + path.join(pkg, "docs/PUBLIC-API.md"), + publicApi + .replaceAll("(../components/", "(components/") + .replaceAll("(../patterns/", "(patterns/"), +); +await copy("docs/PANEL-API.md", path.join(pkg, "docs/PANEL-API.md")); +await copy("NOTICE.md", path.join(pkg, "NOTICE.md")); +await writeFile( + path.join(pkg, "package.json"), + JSON.stringify( + { + name: "@anidev/design-system", + version, + private: true, + type: "module", + license: "UNLICENSED", + description: "Anidev Dock HTML/CSS/ESM integration preview", + exports: { + ".": "./runtime/index.js", + "./styles.css": "./components/system.css", + "./tokens/light.css": "./tokens/dock/light.css", + "./tokens/dark.css": "./tokens/dock/dark.css", + "./tokens/light.json": "./tokens/dock/light.json", + "./tokens/dark.json": "./tokens/dock/dark.json", + "./ssh": "./components/ssh-console.js", + "./logs": "./components/log-reader.js", + }, + }, + null, + 2, + ) + "\n", +); +async function hashes(dir, prefix = "") { + const result = {}; + for (const entry of (await readdir(dir, { withFileTypes: true })).sort( + (a, b) => a.name.localeCompare(b.name), + )) { + const relative = prefix + entry.name; + if (entry.isDirectory()) + Object.assign( + result, + await hashes(path.join(dir, entry.name), relative + "/"), + ); + else + result[relative] = createHash("sha256") + .update(await readFile(path.join(dir, entry.name))) + .digest("hex"); + } + return result; +} +await writeFile( + path.join(pkg, "manifest.json"), + JSON.stringify( + { version, channel: "integration-preview", files: await hashes(pkg) }, + null, + 2, + ) + "\n", +); +const skill = path.join(skills, "anidev-design-system"); +await copy("skills/anidev-design-system", skill); +await mkdir(path.join(skill, "assets"), { recursive: true }); +await cp(pkg, path.join(skill, "assets/anidev"), { recursive: true }); +await copy("examples/starter", starter); +await cp(pkg, path.join(starter, "anidev"), { recursive: true }); +await mkdir(path.join(skill, "assets/starter"), { recursive: true }); +await copy("examples/starter", path.join(skill, "assets/starter")); +console.log( + `Built Anidev ${version}: dist/package, dist/starter, dist/skills/anidev-design-system`, +); diff --git a/scripts/install-skill.mjs b/scripts/install-skill.mjs new file mode 100644 index 0000000..88b01ea --- /dev/null +++ b/scripts/install-skill.mjs @@ -0,0 +1,33 @@ +import { cp, mkdir, lstat, readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +const args = process.argv.slice(2); +if (args.length !== 2 || args[0] !== "--project") + throw Error("Usage: node scripts/install-skill.mjs --project "); +const project = await import("node:fs/promises").then((fs) => + fs.realpath(path.resolve(args[1])), +); +const source = fileURLToPath( + new URL("../dist/skills/anidev-design-system/", import.meta.url), +); +await readFile(path.join(source, "SKILL.md")); +let parent = project; +for (const name of [".agents", "skills"]) { + parent = path.join(parent, name); + const stat = await lstat(parent).catch((e) => { + if (e.code !== "ENOENT") throw e; + }); + if (stat?.isSymbolicLink() || (stat && !stat.isDirectory())) + throw Error("Skill install path must be a real directory"); + await mkdir(parent, { recursive: true }); +} +const target = path.join(parent, "anidev-design-system"); +const exists = await lstat(target).catch((e) => { + if (e.code !== "ENOENT") throw e; +}); +if (exists) + throw Error( + `Skill already exists; compare versions before replacing: ${target}`, + ); +await cp(source, target, { recursive: true, force: false, errorOnExist: true }); +console.log(`Installed project skill: ${target}`); diff --git a/scripts/package-release.py b/scripts/package-release.py new file mode 100644 index 0000000..92c8a04 --- /dev/null +++ b/scripts/package-release.py @@ -0,0 +1,26 @@ +"""Archive already-built, self-contained deliverables; no publishing or installation.""" +import json +from pathlib import Path +from zipfile import ZipFile, ZIP_DEFLATED + +root = Path(__file__).resolve().parent.parent +version = json.loads((root / "package.json").read_text(encoding="utf-8"))["version"] +dist = root / "dist" +for source, name, prefix in [ + (dist / "skills/anidev-design-system", f"anidev-skill-{version}.zip", "anidev-design-system"), + (dist / "starter", f"anidev-panel-{version}.zip", "anidev-panel"), +]: + if not (source / ("SKILL.md" if "skill" in name else "index.html")).is_file(): + raise SystemExit("Run npm run build:package first") + files = sorted(source.rglob("*")) + target = dist / name + with ZipFile(target, "w", ZIP_DEFLATED) as archive: + for file in files: + if file.is_symlink(): + raise SystemExit(f"Symlink in release input: {file}") + if file.is_file(): + archive.write(file, (Path(prefix) / file.relative_to(source)).as_posix()) + with ZipFile(target) as archive: + if archive.testzip() is not None: + raise SystemExit(f"Invalid archive: {target}") + print(f"{target.name}: {len(archive.namelist())} files, CRC valid") diff --git a/scripts/serve.mjs b/scripts/serve.mjs index 745e56c..5aff5cf 100644 --- a/scripts/serve.mjs +++ b/scripts/serve.mjs @@ -12,7 +12,7 @@ const types = { ".md": "text/plain; charset=utf-8", }; const port = Number(process.env.PORT || 4173); -http +const server = http .createServer(async (req, res) => { try { const pathname = decodeURIComponent( @@ -35,5 +35,7 @@ http } }) .listen(port, "127.0.0.1", () => - console.log(`Anidev Design System: http://127.0.0.1:${port}`), + console.log( + `Anidev Design System: http://127.0.0.1:${server.address().port}`, + ), ); diff --git a/scripts/test-release.mjs b/scripts/test-release.mjs new file mode 100644 index 0000000..dbe671d --- /dev/null +++ b/scripts/test-release.mjs @@ -0,0 +1,70 @@ +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; +const cwd = fileURLToPath(new URL("../", import.meta.url)); +function run(file, env = process.env) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [file], { + cwd, + env, + stdio: "inherit", + windowsHide: true, + }); + child.once("error", reject); + child.once("exit", (code) => + code === 0 ? resolve() : reject(Error(`${file} exited ${code}`)), + ); + }); +} +await run("scripts/check.mjs"); +await run("scripts/build-package.mjs"); +const server = spawn(process.execPath, ["scripts/serve.mjs"], { + cwd, + env: { ...process.env, PORT: "0" }, + stdio: ["ignore", "pipe", "inherit"], + windowsHide: true, +}); +try { + const base = await new Promise((resolve, reject) => { + const timeout = setTimeout( + () => reject(Error("QA server did not start")), + 10000, + ); + server.once("error", (e) => { + clearTimeout(timeout); + reject(e); + }); + server.once("exit", (code) => { + clearTimeout(timeout); + reject(Error(`QA server exited ${code}`)); + }); + server.stdout.on("data", (data) => { + const match = String(data).match(/http:\/\/127\.0\.0\.1:\d+/); + if (match) { + clearTimeout(timeout); + resolve(match[0]); + } + }); + }); + const env = { ...process.env, BASE_URL: base }; + for (const name of [ + "browser", + "dock", + "approved-dock", + "site", + "identity", + "totp-layout", + "icons", + "workspaces", + "navigation-feedback", + "search-select", + "package", + ]) { + console.log(`\nChecking ${name}`); + await run(`tests/${name}.mjs`, env); + } + console.log( + "Release checks passed. Browser coverage follows PLAYWRIGHT_EXECUTABLE_PATH; this does not certify other engines.", + ); +} finally { + server.kill(); +} diff --git a/skills/anidev-design-system/SKILL.md b/skills/anidev-design-system/SKILL.md new file mode 100644 index 0000000..496fa2d --- /dev/null +++ b/skills/anidev-design-system/SKILL.md @@ -0,0 +1,32 @@ +--- +name: anidev-design-system +description: "Build or refine application interfaces with the approved Anidev Dock design system, its light/dark tokens, icons and native HTML/CSS/ESM components. Use when the user requests Anidev styling or works in a project that already uses it." +--- + +# Anidev Design System + +Use the approved Dock as one unified application panel. Keep the project's product, framework, router and API architecture; do not turn an existing application into the design-system gallery. + +## Resources + +Paths below are relative to this installed Skill. Its build bundles all resources; no sibling repository, external skill or network connection is needed to read them. + +- Start with [design rules](assets/anidev/docs/DESIGN.md) and [public API](assets/anidev/docs/PUBLIC-API.md) when implementing UI. +- Read [component contracts](assets/anidev/docs/components/CONTRACT.md) for forms, overlays, selection and feedback; [UX patterns](assets/anidev/docs/patterns/UX.md) for tables and flows. +- Use [the starter](assets/starter/index.html) and its app.js when introducing a new shell. Copy assets/starter into the project and assets/anidev into its anidev subfolder; serve over HTTP. For an existing UI, integrate only what its task needs. +- Read [identity patterns](assets/anidev/docs/patterns/IDENTITY.md) only for account/auth UI, and [workspace contracts](assets/anidev/docs/patterns/WORKSPACES.md) only for SSH or logs. Their demo adapters are not real authentication or server access. +- Check [anti-slop rules](assets/anidev/docs/ANTI-SLOP.md) before visual review. [Package metadata](assets/anidev/package.json) and manifest.json identify the bundled version. Preserve [distribution notices](assets/anidev/NOTICE.md). + +## Integration decisions + +Use the bundled CSS, tokens and icon pack rather than approximate equivalents. Preserve the target project's framework; wrap mount/cleanup in its lifecycle instead of adding another framework. Use public exports from runtime/index.js; do not import the gallery or its fixtures. Do not fetch a newer version implicitly. If the project pins another version, compare its API and changes before migration. + +One document owns one Dock and a document-wide theme. The rail is compact, expands over a dimmed inert content area, and does not move the page. Put a/ at the top; no separate disclosure icon. Selecting a nav item keeps the Dock open. Hover, focus, selected and disabled states must remain visible, with the selected item stable on hover. Keep the approved light and dark palettes, themed native scrolling, shared icon axis and reduced-motion behavior. + +The host can be an independent frontend that calls an API. Treat available sections as data: update items/groups through mountNavigation rather than hardcoding one panel per service. The host owns routes and active content; the server authorizes every operation regardless of menu visibility. Render API strings as text. Use loading/empty/error states and cancel stale requests during navigation. Do not introduce a backend proxy unless the product requires it. + +Use semantic tokens for surfaces, text and states; preserve native form controls, associated labels, keyboard behavior and focus return. Related checkboxes may share horizontal or vertical capsules. Status includes words and an icon when useful, rather than relying on color. Toasts report results without stealing focus. Terminal surfaces remain black in either theme. + +## Verification + +Verify the changed flows in both themes and desktop/mobile, with keyboard, long Russian labels, empty/error data and any affected modal or popover. Confirm that dynamic menu changes preserve an available active section and provide a sensible fallback when it disappears. Dispose controllers, listeners and requests on unmount. Review the rendered result; automated checks alone are not an accessibility audit. Report the actual checks and remaining integration limits. diff --git a/skills/anidev-design-system/agents/openai.yaml b/skills/anidev-design-system/agents/openai.yaml new file mode 100644 index 0000000..063ec97 --- /dev/null +++ b/skills/anidev-design-system/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Anidev Design System" + short_description: "Build interfaces with the approved Anidev Dock" + default_prompt: "Use $anidev-design-system to build this interface with Anidev Dock." diff --git a/tests/package.mjs b/tests/package.mjs new file mode 100644 index 0000000..2d24dc1 --- /dev/null +++ b/tests/package.mjs @@ -0,0 +1,405 @@ +import assert from "node:assert/strict"; +import { readFile, readdir, cp, mkdir, mkdtemp } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import http from "node:http"; +import path from "node:path"; +import { chromium } from "playwright"; + +const pkg = path.resolve("dist/package"); +const metadata = JSON.parse( + await readFile(path.join(pkg, "package.json"), "utf8"), +); +const manifest = JSON.parse( + await readFile(path.join(pkg, "manifest.json"), "utf8"), +); +assert.equal(manifest.version, metadata.version); +assert.equal( + metadata.version, + JSON.parse(await readFile("package.json", "utf8")).version, +); +assert.equal(metadata.private, true); +for (const file of Object.keys(manifest.files).filter((file) => + file.endsWith(".md"), +)) { + const markdown = await readFile(path.join(pkg, file), "utf8"); + for (const [, link] of markdown.matchAll(/\]\(([^)]+)\)/g)) { + if (/^(https?:|#)/.test(link)) continue; + const target = path.resolve(pkg, path.dirname(file), link.split("#")[0]); + assert.ok( + target.startsWith(pkg + path.sep), + `Link escapes package: ${file}`, + ); + await readFile(target); + } +} +for (const [file, hash] of Object.entries(manifest.files)) { + assert.equal( + createHash("sha256") + .update(await readFile(path.join(pkg, file))) + .digest("hex"), + hash, + file, + ); + assert.ok( + !/^(playground|patterns\/demo-identity|prompts|\.research|node_modules)\//.test( + file, + ), + file, + ); +} +const api = await import( + new URL("../dist/package/runtime/index.js", import.meta.url) +); +assert.ok(api.iconNames.length >= 64); +assert.throws(() => + api.validateNavigation([ + { id: "same", label: "A", icon: "dashboard" }, + { id: "same", label: "B", icon: "server" }, + ]), +); +assert.throws(() => + api.validateNavigation([{ id: "bad", label: "A", icon: "missing" }]), +); +assert.throws(() => + api.validateNavigation([ + { + id: "bad", + label: "A", + icon: "server", + children: [{ id: "nested", label: "B", icon: "server", children: [] }], + }, + ]), +); +for (const file of Object.keys(manifest.files).filter((file) => + /\.(css|js)$/.test(file), +)) { + const content = await readFile(path.join(pkg, file), "utf8"); + const refs = [ + ...content.matchAll( + /(?:from\s*["']|import\s*["']|import\(["']|url\(["']?)(\.{1,2}\/[^"')\s]+)/g, + ), + ]; + for (const [, ref] of refs) + await readFile(path.resolve(pkg, path.dirname(file), ref.split("?")[0])); +} +const skill = path.resolve("dist/skills/anidev-design-system"); +const skillText = await readFile(path.join(skill, "SKILL.md"), "utf8"); +for (const [, link] of skillText.matchAll(/\]\(([^)]+)\)/g)) { + const target = path.resolve(skill, link); + assert.ok(target.startsWith(skill + path.sep)); + await readFile(target); +} +await mkdir("test-results", { recursive: true }); +const consumer = await mkdtemp(path.resolve("test-results/consumer-")); +await cp("dist/starter", consumer, { recursive: true }); +const original = JSON.parse( + await readFile(path.join(consumer, "api/navigation.json"), "utf8"), +); +let config = structuredClone(original), + configDelay = 0, + failMenu = false, + failPage = false; +const pageDelays = {}; +const mime = { + ".html": "text/html", + ".js": "text/javascript", + ".css": "text/css", + ".json": "application/json", + ".svg": "image/svg+xml", +}; +const server = http.createServer(async (req, res) => { + try { + const url = new URL(req.url, "http://localhost"), + pathname = decodeURIComponent(url.pathname); + if (pathname === "/api/navigation.json") { + const snapshot = JSON.stringify(config), + delay = configDelay; + if (failMenu) { + res.writeHead(503); + res.end(); + return; + } + if (delay) await new Promise((resolve) => setTimeout(resolve, delay)); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(snapshot); + return; + } + if (failPage && pathname.startsWith("/api/pages/")) { + res.writeHead(503); + res.end(); + return; + } + const file = path.resolve( + consumer, + "." + (pathname.endsWith("/") ? pathname + "index.html" : pathname), + ); + if (!file.startsWith(consumer + path.sep)) throw Error(); + const body = await readFile(file); + if (pageDelays[pathname]) + await new Promise((resolve) => setTimeout(resolve, pageDelays[pathname])); + res.writeHead(200, { + "Content-Type": mime[path.extname(file)] || "application/octet-stream", + "Cache-Control": "no-store", + }); + res.end(body); + } catch { + res.writeHead(404); + res.end(); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +const origin = `http://127.0.0.1:${server.address().port}`; +const browser = await chromium.launch({ + executablePath: + process.env.PLAYWRIGHT_EXECUTABLE_PATH || + "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", + headless: true, +}); +const page = await browser.newPage({ + permissions: ["clipboard-read", "clipboard-write"], +}); +const errors = [], + requests = []; +page.on("pageerror", (e) => errors.push(e.message)); +page.on("request", (r) => requests.push(r.url())); +await mkdir("references/integration", { recursive: true }); +let passed = 0; +try { + for (const width of [1440, 768, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.goto(origin); + await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor(); + for (const theme of ["light", "dark"]) { + if ((await page.locator("body").getAttribute("data-theme")) !== theme) + await page.locator("#theme-toggle").click(); + assert.equal( + await page.locator("body").getAttribute("data-theme"), + theme, + ); + await page.waitForTimeout(280); + await page.screenshot({ + path: `references/integration/${theme}-${width}.png`, + fullPage: true, + }); + assert.equal( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + true, + ); + passed++; + } + const before = await page.locator(".main-column").boundingBox(); + await page.locator(".dock-brand").click(); + await page.waitForTimeout(280); + const after = await page.locator(".main-column").boundingBox(); + assert.equal(before.x, after.x); + assert.equal(before.width, after.width); + assert.equal( + await page.locator(".main-column").evaluate((e) => e.inert), + true, + ); + await page.locator('[data-nav-toggle="administration"]').click(); + await page.locator('[data-nav-id="logs"]').click(); + await page.locator("#page-title").filter({ hasText: "Логи" }).waitFor(); + assert.equal( + await page.locator(".dock-brand").getAttribute("aria-expanded"), + "true", + ); + await page.keyboard.press("Escape"); + await page.locator("[data-copy-input]").click(); + assert.equal( + await page.evaluate(() => navigator.clipboard.readText()), + "anidev-production", + ); + await page.locator("[data-toast-dismiss]").click(); + await page.locator(".search-select-trigger").click(); + await page.locator('[role="combobox"]').fill("stag"); + await page.keyboard.press("Enter"); + assert.equal( + await page.locator('input[name="environment"]').inputValue(), + "staging", + ); + passed++; + } + await page.setViewportSize({ width: 1440, height: 900 }); + // Menu refresh preserves an available active leaf, focus, group and open Dock. + await page.locator(".dock-brand").click(); + await page.locator('[data-nav-id="logs"]').focus(); + config = structuredClone(original); + config.items[2].children[0].label = "Логи сервера"; + await page.evaluate(() => + document.querySelector("#refresh-navigation").click(), + ); + await page + .locator('[data-nav-id="logs"]') + .filter({ hasText: "Логи сервера" }) + .waitFor(); + assert.equal( + await page.locator('[data-nav-id="logs"]').getAttribute("aria-current"), + "page", + ); + assert.equal( + await page.evaluate(() => document.activeElement?.dataset.navId), + "logs", + ); + assert.equal( + await page.locator(".dock-brand").getAttribute("aria-expanded"), + "true", + ); + await page.waitForTimeout(280); + await page.screenshot({ + path: "references/integration/dynamic-menu-dark.png", + }); + await page.keyboard.press("Tab"); + assert.equal( + await page + .locator(".dock-brand") + .evaluate((e) => e === document.activeElement), + true, + ); + await page.keyboard.press("Shift+Tab"); + assert.equal( + await page.evaluate(() => document.activeElement?.dataset.navId), + "logs", + ); + await page.keyboard.press("Escape"); + passed++; + config = { items: [original.items[1]], defaultPage: "projects" }; + await page.locator("#refresh-navigation").click(); + await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor(); + assert.equal(await page.locator("[data-nav-id]").count(), 1); + assert.equal(new URL(page.url()).searchParams.get("page"), "projects"); + passed++; + config = { items: [] }; + await page.locator("#refresh-navigation").click(); + await page + .locator("#page-title") + .filter({ hasText: "Нет доступных разделов" }) + .waitFor(); + assert.equal(await page.locator("#page-data").innerText(), ""); + passed++; + config = structuredClone(original); + await page.locator("#refresh-navigation").click(); + await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor(); + failMenu = true; + await page.locator("#refresh-navigation").click(); + await page + .locator("#connection-status") + .filter({ hasText: "Не удалось" }) + .waitFor(); + assert.equal(await page.locator('[data-nav-id="overview"]').count(), 1); + await page.locator("[data-toast-dismiss]").click(); + failMenu = false; + passed++; + config = { + items: [ + { + id: "injected", + label: "", + icon: "dashboard", + }, + ], + }; + await page.locator("#refresh-navigation").click(); + await page.locator('[data-nav-id="injected"]').waitFor(); + assert.equal(await page.locator(".navigation img").count(), 0); + await page + .locator("#page-title") + .filter({ hasText: "Раздел недоступен" }) + .waitFor(); + passed++; + config = { items: [{ id: "bad", label: "Bad", icon: "unknown" }] }; + await page.locator("#refresh-navigation").click(); + await page + .locator("#connection-status") + .filter({ hasText: "Не удалось" }) + .waitFor(); + assert.equal(await page.locator('[data-nav-id="injected"]').count(), 1); + await page.locator("[data-toast-dismiss]").click(); + passed++; + // A slow previous menu must not overwrite a newer response. + config = { items: [original.items[1]] }; + configDelay = 500; + await page.locator("#refresh-navigation").click(); + await page.waitForTimeout(80); + config = structuredClone(original); + configDelay = 0; + await page.locator("#refresh-navigation").click(); + await page.locator('[data-nav-id="overview"]').waitFor(); + await page.waitForTimeout(550); + assert.equal(await page.locator('[data-nav-id="overview"]').count(), 1); + passed++; + failPage = true; + await page.locator(".dock-brand").click(); + await page.locator('[data-nav-id="projects"]').click(); + await page.keyboard.press("Escape"); + await page + .locator("#page-title") + .filter({ hasText: "Раздел недоступен" }) + .waitFor(); + failPage = false; + await page.getByRole("button", { name: "Повторить", exact: true }).click(); + await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor(); + passed++; + pageDelays["/api/pages/overview.json"] = 500; + await page.locator(".dock-brand").click(); + await page.locator('[data-nav-id="overview"]').click(); + if ( + (await page + .locator('[data-nav-toggle="administration"]') + .getAttribute("aria-expanded")) !== "true" + ) + await page.locator('[data-nav-toggle="administration"]').click(); + await page.locator('[data-nav-id="logs"]').click(); + await page.keyboard.press("Escape"); + await page.locator("#page-title").filter({ hasText: "Логи" }).waitFor(); + await page.waitForTimeout(550); + assert.equal(await page.locator("#page-title").innerText(), "Логи"); + pageDelays["/api/pages/overview.json"] = 0; + passed++; + // Core modules also work independently of the starter's host logic. + await page.evaluate(async () => { + const { createNotifier, mountCopyField } = + await import("/anidev/runtime/index.js"); + const toast = document.createElement("div"); + document.body.append(toast); + const notify = createNotifier(toast); + notify("Before dispose", { duration: 0 }); + notify.dispose(); + notify("After dispose"); + if (toast.matches(":popover-open")) + throw Error("Notifier survived dispose"); + const root = document.createElement("div"); + root.innerHTML = + ''; + document.body.append(root); + Object.defineProperty(navigator.clipboard, "writeText", { + configurable: true, + value: () => Promise.reject(Error("denied")), + }); + window.copyResult = null; + const cleanup = mountCopyField(root, { + notify: (message, options) => (window.copyResult = options.type), + }); + root.querySelector("button").click(); + await new Promise((resolve) => setTimeout(resolve, 0)); + if (window.copyResult !== "error") + throw Error("Clipboard failure not reported"); + cleanup(); + root.remove(); + toast.remove(); + }); + passed++; + assert.ok(requests.every((url) => url.startsWith(origin + "/"))); + assert.ok( + !requests.some((url) => /playground|demo-identity|frame\.js/.test(url)), + ); + assert.deepEqual(errors, []); + console.log( + `Package integration: ${passed} checks passed; isolated consumer, dynamic API navigation, theme/layout, clipboard/search, errors/stale responses, cleanup, manifest/imports/skill links.`, + ); +} finally { + await browser.close(); + await new Promise((resolve) => server.close(resolve)); +}