Deploy implemented Videoreg interface and persistent theme cycle

This commit is contained in:
huncode committed 2026-10-27 15:49:46 +03:00
1 parent 6405a8d101
commit a12eefa1de
98 files changed
+4094 -2319

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { analytics, designTokens } from '@/fsd/shared/config';
import { SiteShell } from '@/fsd/widgets/site-shell';
import { UiKitPage } from '@/fsd/pages/ui-kit';
import { PrivacyPage } from '@/fsd/pages/services';
const luminance = (hex: string) => hex.slice(1).match(/../g)!.map(v => parseInt(v,16)/255).map(v => v <= .04045 ? v/12.92 : ((v+.055)/1.055)**2.4).reduce((n,v,i) => n + v * [.2126,.7152,.0722][i],0);
const contrast = (a: string,b: string) => { const [lo,hi]=[luminance(a),luminance(b)].sort((x,y)=>x-y);return (hi+.05)/(lo+.05); };
describe('used reading system and explicit analytics boundary', () => {
it('keeps design-only shell free of rejected analytics and privacy consistent', () => {
expect(analytics.enabled).toBe(false);
const shell=renderToStaticMarkup(createElement(SiteShell,{children:createElement('main',null,'текст')}));
expect(shell).not.toContain('/metrika.js');expect(shell).not.toContain('mc.yandex');
expect(renderToStaticMarkup(createElement(PrivacyPage))).toContain('счётчик Яндекс Метрики не подключён');
});
it('uses one prefixed working search/calculator demo and no reading-eligible article', () => {
const html=renderToStaticMarkup(createElement(UiKitPage));
expect(html).toContain('id="demo-search-query"');expect(html).not.toContain('id="library-query"');
expect(html).toContain('name="demo-recording-mode"');expect(html).not.toContain('<article');
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);expect(new Set(ids).size).toBe(ids.length);
expect(html).toContain('Logitech QuickCam for notebooks Pro Carl Zeiss optics');
expect(html).toContain('USB.BIN');expect(html).not.toContain('href="#"');
});
it('binds documented semantic palette to used CSS and real readable contrast', () => {
const css=readFileSync('web-front/src/fsd/shared/styles/tokens.css','utf8');
for(const [name,value] of Object.entries(designTokens.palette))expect(css).toContain(`--color-${name}: ${value};`);
const p=designTokens.palette;
for(const name of ['text-primary','text-secondary','link'] as const)for(const bg of ['surface-paper','surface-sheet'] as const)expect(contrast(p[name],p[bg])).toBeGreaterThanOrEqual(4.5);
expect(contrast(p['text-inverse-muted'],p['surface-inverse'])).toBeGreaterThanOrEqual(4.5);
expect(contrast(p['accent-inverse'],p['surface-inverse'])).toBeGreaterThanOrEqual(4.5);
expect(contrast(p['focus'],p['surface-paper'])).toBeGreaterThanOrEqual(3);
expect(contrast(p['border-control'],p['surface-sheet'])).toBeGreaterThanOrEqual(3);
for(const theme of Object.values(designTokens.themes)) {
for(const name of ['text-primary','text-secondary','link'] as const)for(const bg of ['surface-paper','surface-sheet'] as const)expect(contrast(theme[name],theme[bg])).toBeGreaterThanOrEqual(4.5);
expect(contrast(theme['text-note'],theme['surface-note'])).toBeGreaterThanOrEqual(4.5);
expect(contrast(theme['text-action'],theme['accent-inverse'])).toBeGreaterThanOrEqual(4.5);
expect(contrast(theme['focus'],theme['surface-sheet'])).toBeGreaterThanOrEqual(3);
}
});
});
@@ -0,0 +1,2 @@
export { articles, findArticle, articleText, searchIndex } from "./model";
export type { LibraryArticle } from "./model";
+100
View File
@@ -0,0 +1,100 @@
import { z } from "zod";
import recovered from "@/content/v2-articles.json";
import community from "@/content/v2-community.json";
import externalApprovals from "@/content/v2-link-approvals.json";
const localPath = z.string().regex(/^\/(?!\/)[a-zA-Z0-9/_.-]*$/);
const approvedHref = z.string().refine(value => localPath.safeParse(value).success || externalApprovals.some(item => item.destination === value), "Unreviewed outbound URL");
const sectionSchema = z.object({
gallery: z
.array(
z.object({
src: localPath,
filename: z.string(),
width: z.number().positive(),
height: z.number().positive(),
}),
)
.optional(),
heading: z.string().min(1),
paragraphs: z.array(z.string().min(1)),
list: z.array(z.string()).optional(),
note: z.string().optional(),
code: z.string().optional(),
links: z.array(z.object({ href: approvedHref, label: z.string() })).optional(),
figure: z
.object({
src: localPath,
alt: z.string().min(12),
caption: z.string(),
diagram: z.boolean().optional(),
small: z.boolean().optional(),
})
.optional(),
table: z
.object({
caption: z.string(),
head: z.array(z.string()).min(2),
rows: z.array(z.array(z.string())),
})
.optional(),
});
const articleSchema = z.object({
path: localPath,
title: z.string().min(3),
category: z.string(),
summary: z.string(),
date: z.string(),
kind: z.enum(["recovered", "linked-source", "recovered-media"]),
sourcePaths: z.array(z.string()),
rawFiles: z.array(z.string()),
sections: z.array(sectionSchema).min(1),
related: z.array(localPath),
});
export const articles = z
.array(articleSchema)
.parse([...recovered, ...community]);
export type LibraryArticle = z.infer<typeof articleSchema>;
export function findArticle(path: string) {
return articles.find((article) => article.path === path);
}
export function articleText(article: LibraryArticle) {
return article.sections
.map((s) =>
[
s.heading,
...s.paragraphs,
...(s.list ?? []),
s.note ?? "",
s.code ?? "",
...(s.links ?? []).map((link) => link.label),
s.table?.head.join(" ") ?? "",
s.table?.rows.flat().join(" ") ?? "",
].join(" "),
)
.join(" ");
}
export const searchIndex = articles.map((article) => ({
path: article.path,
title: article.title,
summary: article.summary,
category: article.category,
date: article.date,
text: articleText(article),
}));
if (new Set(articles.map((x) => x.path)).size !== articles.length)
throw new Error("Duplicate article path");
for (const article of articles) {
for (const section of article.sections) {
for (const link of section.links ?? []) {
if (link.href.startsWith("http") && !externalApprovals.some(item => item.sourcePage === article.path && item.destination === link.href && item.anchor === link.label && item.reviewed)) throw new Error("Unreviewed page/link context: " + article.path);
}
}
for (const section of article.sections) {
if (
section.table?.rows.some(
(row) => row.length !== section.table!.head.length,
)
)
throw new Error("Invalid table: " + article.path);
}
}
@@ -0,0 +1,2 @@
import { analytics } from "@/fsd/shared/config";
export function AnalyticsTag() { return analytics.enabled ? <script src="/metrika.js" defer /> : null; }
@@ -0,0 +1 @@
export { default as FrameGallery } from "./ui";
@@ -0,0 +1,38 @@
"use client";
import { useState } from "react";
import { Button } from "@/fsd/shared/ui";
type Frame = { src: string; filename: string; width: number; height: number };
export default function FrameGallery({ frames }: { frames: Frame[] }) {
const [all, setAll] = useState(false);
const visible = all ? frames : frames.slice(0, 6);
return (
<div className="frame-gallery">
<p className="frame-count" role="status">
Показано доступных кадров: {visible.length} из {frames.length}
</p>
<div className="frame-grid">
{visible.map((f, i) => (
<figure key={f.src}>
<a href={f.src} aria-label={"Открыть исходный кадр " + f.filename}>
<img
src={f.src}
width={f.width}
height={f.height}
alt={"Кадр дорожной последовательности " + f.filename}
loading={i < 2 ? "eager" : "lazy"}
/>
</a>
<figcaption>
{f.filename} · {f.width}×{f.height}
</figcaption>
</figure>
))}
</div>
{frames.length > 6 && (
<Button type="button" onClick={() => setAll((v) => !v)}>
{all ? "Свернуть серию" : "Показать доступные " + frames.length + " кадров"}
</Button>
)}
</div>
);
}
@@ -0,0 +1 @@
export { default as Search } from "./ui";
@@ -0,0 +1,96 @@
"use client";
import { useEffect, useState } from "react";
import { Button, Input, Select, ContentCard, StateMessage } from "@/fsd/shared/ui";
import { analytics } from "@/fsd/shared/config";
type Entry = {
path: string;
title: string;
summary: string;
category: string;
date: string;
text: string;
};
const normalized = (value: string) =>
value
.toLocaleLowerCase("ru")
.replaceAll("ё", "е")
.replace(/\s+/g, " ")
.trim();
export default function Search({ entries, idPrefix = "library", emitAnalytics = true }: { entries: Entry[]; idPrefix?: string; emitAnalytics?: boolean }) {
const [query, setQuery] = useState("");
const [category, setCategory] = useState("Все темы");
const categories = ["Все темы", ...new Set(entries.map((a) => a.category))];
const words = normalized(query).split(" ").filter(Boolean);
const found = entries.filter(
(a) =>
(category === "Все темы" || a.category === category) &&
words.every((word) =>
normalized(a.title + " " + a.summary + " " + a.text).includes(word),
),
);
useEffect(() => {
if (!analytics.enabled || !emitAnalytics || !query.trim() || found.length !== 0) return;
// Wait until the live filtered zero state is displayed, not an initial page state.
const timer = setTimeout(() => document.dispatchEvent(new Event("videoreg:search-zero-results")), 500);
return () => clearTimeout(timer);
}, [query, category, found.length, emitAnalytics]);
return (
<>
<div className="search-panel">
<label htmlFor={idPrefix + "-query"}>Найти в материалах</label>
<div className="query-row">
<Input
id={idPrefix + "-query"}
type="search"
placeholder="Например: GPS, USB или резервная копия"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<Button
type="button"
onClick={() => {
setQuery("");
setCategory("Все темы");
}}
>
Сбросить
</Button>
</div>
<label htmlFor={idPrefix + "-category"}>Раздел</label>
<Select
id={idPrefix + "-category"}
value={category}
onChange={(e) => setCategory(e.target.value)}
>
{categories.map((c) => (
<option key={c}>{c}</option>
))}
</Select>
</div>
<p className="result-count" role="status">
Найдено материалов: {found.length}
</p>
<div className="search-results">
{found.map((a) => (
<ContentCard key={a.path} href={a.path} title={a.title} summary={a.summary} eyebrow={a.category + " · " + a.date} />
))}
</div>
{found.length === 0 && (
<StateMessage className="empty" title="Такого сочетания пока нет">
<p>
Попробуйте название модели, «карта», «кадры» или уберите фильтр
раздела.
</p>
<Button
onClick={() => {
setQuery("");
setCategory("Все темы");
}}
>
Показать все материалы
</Button>
</StateMessage>
)}
</>
);
}
@@ -0,0 +1,9 @@
"use client";
import { useState } from "react";
import { Select } from "@/fsd/shared/ui";
export type PreviewEntry={path:string;title:string;source:string;components:string};
export function PagePreview({ entries }: { entries: PreviewEntry[] }) {
const [selected,setSelected]=useState(entries[0].path),[width,setWidth]=useState("100%");
const entry=entries.find(e=>e.path===selected)!;
return <div><div className="page-preview-controls"><label htmlFor="kit-real-page">Полная страница<Select id="kit-real-page" value={selected} onChange={e=>setSelected(e.target.value)}>{entries.map(e=><option key={e.path} value={e.path}>{e.title}</option>)}</Select></label><label htmlFor="kit-page-width">Ширина просмотра<Select id="kit-page-width" value={width} onChange={e=>setWidth(e.target.value)}><option value="100%">По контейнеру</option><option value="390px">390 px</option><option value="320px">320 px</option></Select></label><a href={entry.path} target="_blank" rel="noreferrer">Открыть отдельно ↗</a></div><p className="kit-usage"><code>{entry.source}</code><br />{entry.components}</p><p className="review-note">Здесь загружена настоящая страница этой сборки, составленная из тех же компонентов. Тема синхронизируется с выбором в шапке. Это не статический макет.</p><div className="page-preview-shell"><iframe title={"Полная страница: "+entry.title} src={entry.path} style={{width}} loading="lazy" /></div></div>;
}
@@ -0,0 +1 @@
export { default as Calculator } from "./ui";
@@ -0,0 +1,161 @@
"use client";
import { useState } from "react";
import { Input, Field } from "@/fsd/shared/ui";
export default function Calculator({ idPrefix = "recording" }: { idPrefix?: string }) {
const [mode, setMode] = useState("frames");
const [capacity, setCapacity] = useState("1");
const [reserve, setReserve] = useState("10");
const [frameSize, setFrameSize] = useState("64");
const [fps, setFps] = useState("5");
const [cameras, setCameras] = useState("1");
const [bitrate, setBitrate] = useState("40");
const values = [
capacity,
reserve,
...(mode === "frames" ? [frameSize, fps, cameras] : [bitrate]),
];
const [c, s, k, f, n, r] = [
Number(capacity),
Number(reserve),
Number(frameSize),
Number(fps),
Number(cameras),
Number(bitrate),
];
const valid =
values.every((v) => v.trim() !== "" && Number.isFinite(Number(v))) &&
c > 0 &&
c <= 100000 &&
s >= 0 &&
s < 100 &&
(mode === "frames"
? k > 0 &&
k <= 100000 &&
f > 0 &&
f <= 1000 &&
Number.isInteger(n) &&
n >= 1 &&
n <= 16
: r > 0 && r <= 10000);
const seconds = valid
? Math.floor(
mode === "frames"
? (c * 1e6 * (1 - s / 100)) / (k * f * n)
: (c * 8000 * (1 - s / 100)) / r,
)
: 0;
return (
<>
<fieldset className="mode-choice">
<legend>Способ записи</legend>
<label>
<Input
type="radio"
name={idPrefix + "-mode"}
value="frames"
checked={mode === "frames"}
onChange={() => setMode("frames")}
/>{" "}
JPEG-кадры
</label>
<label>
<Input
type="radio"
name={idPrefix + "-mode"}
value="stream"
checked={mode === "stream"}
onChange={() => setMode("stream")}
/>{" "}
Видеопоток
</label>
</fieldset>
<div className="calculation-layout">
<div className="input-fields">
<Field id={idPrefix+"-capacity"} label="Ёмкость носителя, ГБ" hint="Десятичные ГБ; больше нуля, не более 100 000." error={capacity.trim()==="" || !Number.isFinite(c) || c<=0 || c>100000 ? "Введите ёмкость больше нуля и не более 100 000 ГБ." : undefined}>
<Input id={idPrefix+"-capacity"} type="number" min="0.001" max="100000" step="any" value={capacity} aria-invalid={capacity.trim()==="" || !Number.isFinite(c) || c<=0 || c>100000} aria-describedby={idPrefix+"-capacity-hint"+(capacity.trim()==="" || !Number.isFinite(c) || c<=0 || c>100000 ? " "+idPrefix+"-capacity-error":"")} onChange={e=>setCapacity(e.target.value)} />
</Field>
{mode === "frames" ? (
<>
<label>
Средний размер одного JPEG, КБ
<Input
type="number"
min="0.001"
max="100000"
step="any"
value={frameSize}
onChange={(e) => setFrameSize(e.target.value)}
/>
</label>
<div className="input-pair">
<label>
Кадров/с на камеру
<Input
type="number"
min="0.01"
max="1000"
step="any"
value={fps}
onChange={(e) => setFps(e.target.value)}
/>
</label>
<label>
Число камер
<Input
type="number"
min="1"
max="16"
step="1"
value={cameras}
onChange={(e) => setCameras(e.target.value)}
/>
</label>
</div>
</>
) : (
<label>
Суммарный битрейт, Мбит/с
<Input
type="number"
min="0.01"
max="10000"
step="any"
value={bitrate}
onChange={(e) => setBitrate(e.target.value)}
/>
</label>
)}
<label>
Резерв места, %
<Input
type="number"
min="0"
max="99"
step="any"
value={reserve}
onChange={(e) => setReserve(e.target.value)}
/>
</label>
</div>
<div className="time-result" role="status" aria-live="polite">
<span>ОЦЕНКА ВРЕМЕНИ</span>
<strong>
{valid
? `${Math.floor(seconds / 3600)} ч ${Math.floor((seconds % 3600) / 60)} мин ${seconds % 60} с`
: "Проверьте значения"}
</strong>
<p>
{valid
? "До перезаписи старейших файлов при заданных условиях."
: mode === "frames" ? "Нужны положительные размеры и скорость; камеры — целое число от 1 до 16, резерв — от 0 до 99%." : "Нужны положительные ёмкость и суммарный битрейт; резерв — от 0 до 99%."}
</p>
<small>
{mode === "frames"
? "Размер кадра × частота × число камер"
: "Сумма битрейтов всех камер"}
</small>
</div>
</div>
</>
);
}
@@ -0,0 +1,31 @@
'use client';
import { useSyncExternalStore } from 'react';
import { getThemeChoice, setThemeChoice, subscribeThemeChoice, type ThemeChoice } from '@/fsd/shared/lib';
const choices = [
{ value: 'system', label: 'Системная тема' },
{ value: 'light', label: 'Светлая тема' },
{ value: 'dark', label: 'Тёмная тема' },
] as const;
const serverChoice = (): ThemeChoice => 'system';
function ThemeIcon({ choice }: { choice: ThemeChoice }) {
return <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
{choice === 'system' ? <><rect x="2" y="3" width="17" height="12" rx="1"/><path d="M8 19h6M11 15v4M16 22l3-7 3 7M17 20h4"/></>
: choice === 'light' ? <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5 19 19M5 19l1.5-1.5M17.5 6.5 19 5"/></>
: <path d="M20.5 14.3A9 9 0 0 1 9.7 3.5a9 9 0 1 0 10.8 10.8Z"/>}
</svg>;
}
export function ThemeSwitch({ idPrefix }: { idPrefix: string }) {
const choice = useSyncExternalStore(subscribeThemeChoice, getThemeChoice, serverChoice);
const index = choices.findIndex(item => item.value === choice);
const next = choices[(index + 1) % choices.length].value;
const currentNames = { system: 'системная', light: 'светлая', dark: 'тёмная' };
const nextNames = { system: 'системную', light: 'светлую', dark: 'тёмную' };
const label = `Тема: ${currentNames[choice]}. Переключить на ${nextNames[next]}`;
return <button className="theme-cycle" id={`${idPrefix}-theme`} type="button" aria-label={label} title={label} onClick={() => setThemeChoice(next)}>
{choices.map(item => <span key={item.value} className={`theme-cycle-icon theme-cycle-icon-${item.value}`} aria-hidden="true"><ThemeIcon choice={item.value}/></span>)}
</button>;
}
+62
View File
@@ -0,0 +1,62 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { articles, searchIndex } from "@/fsd/entities/article";
import { ArticleReader } from "@/fsd/widgets/article-reader";
import { Search } from "@/fsd/features/library-search";
import { Calculator } from "@/fsd/features/recording-estimate";
const text = (value: string) => renderToStaticMarkup(createElement("span", null, value)).slice(6, -7);
describe("active FSD migration contracts", () => {
it("renders every real section, preserved anchor, paragraph, list, code and table cell", () => {
for (const article of articles) {
const html = renderToStaticMarkup(createElement(ArticleReader, { article }));
expect(html).toContain('class="article-body"');
for (const [i, section] of article.sections.entries()) {
expect(html).toContain(`id="section-${i}"`);
expect(html).toContain(`href="#section-${i}"`);
expect(html).toContain(`<h2>${text(section.heading)}</h2>`);
for (const paragraph of section.paragraphs) expect(html).toContain(`<p>${text(paragraph)}</p>`);
for (const value of section.list ?? []) expect(html).toContain(`<li>${text(value)}</li>`);
if (section.note) expect(html).toContain(text(section.note));
if (section.code) expect(html).toContain(`<code>${text(section.code)}</code>`);
if (section.table) {
expect(html).toContain(`<caption>${text(section.table.caption)}</caption>`);
for (const value of [...section.table.head, ...section.table.rows.flat()]) expect(html).toContain(text(value));
}
if (section.figure) {
expect(html).toContain(`src="${section.figure.src}"`);
expect(html).toContain(`<figcaption>${text(section.figure.caption)}</figcaption>`);
}
for (const link of section.links ?? []) {
expect(html).toContain(`href="${text(link.href)}"`);
expect(html).toContain(text(link.label));
}
for (const frame of (section.gallery ?? []).slice(0, 6)) {
expect(html).toContain(`src="${frame.src}"`);
expect(html).toContain(text(frame.filename));
}
}
for (const path of article.related) expect(html).toContain(`href="${path}"`);
}
});
it("keeps production search IDs and namespaces functional demo IDs", () => {
const live = renderToStaticMarkup(createElement(Search, { entries: searchIndex }));
const demo = renderToStaticMarkup(createElement(Search, { entries: searchIndex, idPrefix: "demo-search", emitAnalytics: false }));
expect(live).toContain('id="library-query"');
expect(live).toContain('for="library-category"');
expect(demo).toContain('id="demo-search-query"');
expect(demo).toContain('for="demo-search-category"');
expect(demo).not.toContain('id="library-query"');
for (const entry of searchIndex) expect(live).toContain(`href="${entry.path}"`);
});
it("isolates calculator radio groups and preserves the numeric default estimate", () => {
const live = renderToStaticMarkup(createElement(Calculator));
const demo = renderToStaticMarkup(createElement(Calculator, { idPrefix: "demo-recording" }));
expect(live).toContain('name="recording-mode"');
expect(demo).toContain('name="demo-recording-mode"');
expect(demo).not.toContain('name="recording-mode"');
expect(live).toContain("0 ч 46 мин 52 с");
expect(demo).toContain("0 ч 46 мин 52 с");
});
});
+1
View File
@@ -0,0 +1 @@
export { AboutPage } from "./ui";
+44
View File
@@ -0,0 +1,44 @@
export function AboutPage() {
return (
<main id="main-content" className="about-page">
<p className="kicker">VIDEOREG</p>
<h1>Библиотека систем СВК</h1>
<p className="lede">
Устройство, эксплуатация и чтение записи — без витрины продаж.
</p>
<p>
Здесь доступны отобранные технические материалы, пять полных PDF-документов
и подборки кадров. Это не полный архив всех прежних страниц и файлов
videoreg.ru. Ограничения неполных подборок и недоступных файлов указаны
непосредственно в соответствующем материале.
</p>
<h2>Для кого эти материалы</h2>
<p>
Для владельца старого блока СВК, которому нужна инструкция своего
поколения, таблица камер или объяснение покадровой записи. Отдельные
материалы помогают понять устройство ранних автомобильных систем
регистрации.
</p>
<h2>Сначала модель и редакция</h2>
<p>
Страницы разных лет относятся к разным аппаратным версиям. Даты у
материалов помогают различать поколения. Указанные там камеры, носители
и параметры не являются универсальной рекомендацией для современного
оборудования.
</p>
<h2>Как пользоваться</h2>
<p>
Начните с устройства системы, затем откройте инструкцию подходящего
блока. Для поиска конкретной ошибки или камеры используйте поиск по
полным текстам. Исходные PDF открываются внутри сайта; программы и
прошивки автоматически не запускаются.
</p>
<div className="about-links">
<a href="/system">Устройство СВК →</a>
<a href="/library">Материалы и поиск →</a>
<a href="/down.shtml">Документы →</a>
</div>
</main>
);
}
+1
View File
@@ -0,0 +1 @@
export { ArticlePage } from "./ui";
+3
View File
@@ -0,0 +1,3 @@
import { ArticleReader } from "@/fsd/widgets/article-reader";
import type { LibraryArticle } from "@/fsd/entities/article";
export function ArticlePage({ article }: { article: LibraryArticle }) { return <ArticleReader article={article} />; }
@@ -0,0 +1 @@
export { CommunityPage } from "./ui";
+28
View File
@@ -0,0 +1,28 @@
import { ContentCard } from "@/fsd/shared/ui";
import { articles } from "@/fsd/entities/article";
export function CommunityPage() {
return (
<main id="main-content" className="library-page">
<p className="kicker">ЭКСПЛУАТАЦИЯ / РАЗБОРЫ</p>
<h1>
Проблема и условия,
<br />в которых она возникла.
</h1>
<p className="lede">
Два разбора из обсуждений владельцев СВК. Частный опыт не превращён в
обещание совместимости любого оборудования.
</p>
<div className="search-results">
{articles
.filter((a) => a.path.startsWith("/community/"))
.map((a) => (
<ContentCard key={a.path} href={a.path} title={a.title} summary={a.summary} eyebrow={"Обсуждение · " + a.date} />
))}
</div>
<p style={{ marginTop: 32 }}>
<a href="/faq.shtml">Также: ответы по конструкции и настройке →</a>
</p>
</main>
);
}
+1
View File
@@ -0,0 +1 @@
export { HomePage } from "./ui";
+11
View File
@@ -0,0 +1,11 @@
import { ActionLink, ContentCard, ImageFigure, Notice } from "@/fsd/shared/ui";
import { articles, findArticle } from "@/fsd/entities/article";
export function HomePage() {
const rain=findArticle("/samples/rain")!; const frames=rain.sections.find(s=>s.gallery)!.gallery!;
const paths=["/system","/manuals/svk007","/support.shtml","/samples.shtml"];
return <main id="main-content"><section className="home-intro"><div className="intro-copy"><p className="kicker">ИСТОРИЧЕСКИЕ СИСТЕМЫ СВК · 2005–2014</p><h1>Сначала — система.<br />Затем — кадр.</h1><p className="lede">Найдите своё поколение СВК, откройте инструкцию и проверьте исходную запись. Камеры отдельно, JPEG — на съёмном носителе.</p><ActionLink href="/system">Как устроена СВК ↗</ActionLink><a className="hero-secondary" href="/down.shtml">Найти инструкцию →</a></div><div className="hero-recording"><ImageFigure src={frames[0].src} alt="Исходный дорожный кадр в сильный дождь с камеры Genius Videocam WEB." caption={frames[0].filename+" · "+frames[0].width+" × "+frames[0].height+" · исходный JPEG"} width={frames[0].width} height={frames[0].height} loading="eager" /><div className="recording-strip">{frames.slice(1,3).map(f=><a href={f.src} key={f.src}><img src={f.src} alt={"Исходный кадр "+f.filename} width={f.width} height={f.height} /></a>)}<p>30 из 36 кадров<br />Серия неполная</p></div></div></section>
<section className="home-path"><div><p className="kicker">ВАША ЗАДАЧА</p><h2>Разобраться<br />по порядку</h2></div><div className="task-index">{paths.map((p,i)=>{const a=findArticle(p)!;return <ContentCard key={p} href={p} title={a.title} summary={a.summary} eyebrow={String(i+1).padStart(2,"0")+" / "+a.category+" · "+a.date} variant="index" headingLevel="h3" />})}</div></section>
<section className="home-library"><div className="section-title"><div><p className="kicker">ПОКОЛЕНИЕ И ДОКУМЕНТ</p><h2>Сверьте свой блок</h2></div><a href="/catalog">Модели и комплекты →</a></div><div className="device-dossier"><ImageFigure src="/archive-media/svk006-front.jpg" alt="Передняя панель СВК-006: USB A и B, слот SD CARD и индикаторы." caption="СВК-006. Фотография конкретного блока; составы разных поколений отличаются." width={800} height={528} /><div><h3>Не переносите параметры между версиями</h3><p>В библиотеке рядом остаются дата документа, название модели и оговорки источника. Частота кадров, число каналов и носитель зависят от исполнения.</p><ActionLink href="/manuals/svk007">Паспорт СВК-007 · 2008 ↗</ActionLink><p><a href="/manuals/quickstart">СВК-006/007: начинаем работу →</a></p></div></div></section>
<section className="home-workbench"><div><p className="kicker">ПРОВЕРИТЬ ЗАПИСЬ</p><h2>Оригинал важнее пересказа</h2><p>Дождь, вечер и GPS: сравнивайте исходные файлы с их реальными ограничениями.</p><Notice>По разрывам неполной серии нельзя подтверждать остановку камеры. Наличие GPSInfo не гарантирует корректность координат.</Notice><p><a href={rain.path}>{rain.title} →</a></p><p><a href="/samples/gps">Четыре исходных JPEG с GPSInfo →</a></p></div><div className="formula-note"><span className="kicker">ОЦЕНКА ВРЕМЕНИ</span><h3>Сколько поместится?</h3><p>Размер JPEG × частота × камеры. Учитывайте резерв и реальные условия.</p><ActionLink href="/tools/recording-time">Рассчитать длительность ↗</ActionLink></div></section>
<section className="home-case"><div><p className="kicker">ИЗ ПРАКТИКИ</p><h2>Конкретный случай.<br />Понятные границы.</h2><p>Обсуждение владельца — наблюдение, а не обещание совместимости любого оборудования.</p></div><div>{articles.filter(a=>a.path.startsWith("/community/")).map(a=><ContentCard key={a.path} href={a.path} title={a.title} summary={a.summary} eyebrow={a.date} variant="index" headingLevel="h3" />)}</div></section></main>;
}
+1
View File
@@ -0,0 +1 @@
export { LibraryPage } from "./ui";
+18
View File
@@ -0,0 +1,18 @@
import { searchIndex } from "@/fsd/entities/article";
import { Search } from "@/fsd/features/library-search";
export function LibraryPage() {
return (
<main className="library-page" id="main-content">
<div className="page-heading">
<p className="kicker">КАТАЛОГ ЗНАНИЙ</p>
<h1>Техническая библиотека</h1>
<p className="lede">
Ищите по полным текстам, названиям камер и моделям блоков. Всё
работает здесь, без запроса к стороннему поиску.
</p>
</div>
<Search entries={searchIndex} />
</main>
);
}
@@ -0,0 +1 @@
export { NotFoundPage } from "./ui";
+9
View File
@@ -0,0 +1,9 @@
import { StateMessage, ActionLink } from "@/fsd/shared/ui";
export function NotFoundPage() {
return <main id="main-content" className="not-found">
<p className="kicker">404 / СТРАНИЦА НЕ НАЙДЕНА</p>
<StateMessage headingLevel="h1" title={<>По этому адресу<br />материала нет.</>} actions={<><ActionLink href="/library">Искать в материалах ↗</ActionLink><a href="/">На главную →</a></>}>
<p>Проверьте адрес или найдите модель, камеру и нужную тему в библиотеке.</p>
</StateMessage>
</main>;
}
@@ -0,0 +1 @@
export { RecordingToolPage } from "./ui";
@@ -0,0 +1,63 @@
import { CodeBlock } from "@/fsd/shared/ui";
import { Calculator } from "@/fsd/features/recording-estimate";
export function RecordingToolPage() {
return (
<main id="main-content" className="calculator-page">
<a className="back-link" href="/library">
← К библиотеке
</a>
<p className="kicker">ПРАКТИЧЕСКИЙ РАСЧЁТ</p>
<h1>
Сколько записи
<br />
поместится на носителе?
</h1>
<p className="lede">
Для покадровой СВК используйте размер JPEG и частоту. Для современного
видеопотока — суммарный битрейт. Расчёт не подтверждает совместимость
карты.
</p>
<Calculator />
<div className="calculation-notes">
<section>
<h2>Как измерить размер JPEG</h2>
<p>
Возьмите несколько исходных кадров из обычной поездки. Разделите их
общий размер в байтах на число кадров и на 1000. Получится средний
размер в десятичных КБ. Разные сцены сжимаются неодинаково, поэтому
один случайный кадр даёт грубую оценку.
</p>
<p>
Частоту задавайте для одной камеры, затем укажите число камер. Если
камеры работают с разной частотой или размером кадра, посчитайте их
скорости отдельно и сложите: КБ/кадр × кадров/с.
</p>
<CodeBlock label="Формула времени записи">{"Время, с = ГБ × 1 000 000 × (1 − резерв/100) ÷ (КБ/кадр × кадров/с × камер)"}</CodeBlock>
</section>
<section>
<h2>Проверочный пример</h2>
<p>
1 ГБ, средний JPEG 100 КБ, 5 кадров/с с каждой из двух камер и
нулевой резерв дают 1000 секунд: 16 минут 40 секунд. Это
арифметический пример, а не измеренная характеристика определённого
СВК.
</p>
<h2>Для видеопотока</h2>
<p>
Сложите битрейты всех камер, включая звук, если он не входит в
указанное значение. Для 128 ГБ, 40 Мбит/с и резерва 10% получится 6
часов 24 минуты. Переменный битрейт, служебные данные и защищённые
файлы изменяют фактический результат.
</p>
<p>
Десятичные ГБ и КБ соответствуют расчёту по размерам файлов в
байтах. Резерв 10% — настраиваемый пример, а не измеренное свойство
носителя.
</p>
<a href="/faq.shtml">Почему старые таблицы времени различаются →</a>
</section>
</div>
</main>
);
}
@@ -0,0 +1,3 @@
import { ResourceLink } from "@/fsd/shared/ui";
export function SourcesPage() { return <main id="main-content" className="service-page"><p className="kicker">ИСТОЧНИКИ И РЕДАКЦИЯ</p><h1>Как читать эти материалы</h1><p className="lede">Модель, дата и исходный документ важнее универсального совета.</p><section><h2>Разные годы — разные устройства</h2><p>Даты рядом с материалами обозначают период исходных сведений. Дата нового оформления сайта не превращает историческую характеристику в актуальное обещание совместимости.</p><p>Мы сохраняем различия между моделями, условия расчётов и замеченные несогласованности. Если старые таблицы противоречат друг другу, это отмечается в тексте; значения не исправляются молча. Калькулятор даёт оценку по введённым условиям и не проверяет совместимость носителя.</p></section><section><h2>Документы, тексты и исходные кадры</h2><p>Там, где полный исходный файл доступен, ссылка ведёт к нему. Если не хватает файлов или кадров, это указано отдельно. Текстовый разбор и внешний видеоролик не заменяют недоступный оригинал. Права на исходные материалы не объявляются переданными проекту без подтверждения.</p><p>В библиотеке доступны пять полных PDF-документов: четыре инструкции и журнальный тест СВК-002. Это отобранная часть материалов, а не полный архив всех прежних страниц и файлов сайта.</p><ul className="document-links"><li><ResourceLink href="/down.shtml" label="Инструкции и документы по поколениям СВК" /></li><li><ResourceLink href="/reviews/svk002-mobile-news" label="Тест СВК-002 — Денис Кирин, «Мобильные новости», январь 2008" /></li><li><ResourceLink href="/samples.shtml" label="Исходные кадры и ограничения подборок" /></li></ul></section><section><h2>Как пользоваться библиотекой</h2><p>Сначала определите название блока и поколение. Сопоставляйте частоты кадров, носители и камеры только в пределах той версии, о которой говорит документ.</p><p><a href="/system">Начать с устройства СВК →</a></p><p><a href="/library">Найти конкретную модель или ошибку →</a></p></section></main>; }
export function PrivacyPage() { return <main id="main-content" className="service-page"><p className="kicker">ПРИВАТНОСТЬ</p><h1>Приватность и аналитика</h1><p className="lede">Поиск по библиотеке и расчёт длительности выполняются в браузере.</p><section><h2>Действия на сайте</h2><p>В проекте нет формы отправки обращений, регистрации и загрузки ваших записей.</p><p>В этой версии библиотеки счётчик Яндекс Метрики не подключён: она не загружает скрипт Метрики и не отправляет события в этот сервис. Это описание данной версии; при изменении аналитики эта страница должна быть обновлена.</p></section><section><h2>Выбранная тема</h2><p>Выбор «Системная», «Светлая» или «Тёмная» сохраняется в localStorage вашего браузера под ключом videoreg-theme. Поисковые запросы и значения калькулятора в этот ключ не записываются. Вы можете изменить тему в шапке или удалить локальные данные сайта в браузере.</p></section><section><h2>Внешние ссылки</h2><p>Ссылки на YouTube и другие внешние источники открывают сторонние сайты с их собственными правилами обработки данных. Внешний ролик не запускается автоматически в библиотеке.</p></section><section><h2>Получение страниц</h2><p>Для получения страниц браузер обращается к серверу сайта. Это отличается от сторонней аналитики. Состав и сроки хранения технических журналов сервера здесь не подтверждены; мы не заявляем, что такие журналы отсутствуют.</p></section><a href="/sources">Источники и редакционный подход →</a></main>; }
+44
View File
@@ -0,0 +1,44 @@
import { articles, findArticle, searchIndex } from "@/fsd/entities/article";
import { Search } from "@/fsd/features/library-search";
import { Calculator } from "@/fsd/features/recording-estimate";
import { ThemeSwitch } from "@/fsd/features/theme-choice";
import { PagePreview, type PreviewEntry } from "@/fsd/features/page-preview";
import { ArticleMeta, ArticleSection } from "@/fsd/widgets/article-reader";
import { Brand, ActionLink, DataTable, CodeBlock, ResourceLink, ContentCard, ImageFigure } from "@/fsd/shared/ui";
import { designTokens } from "@/fsd/shared/config";
import { componentReference } from "./reference";
const pageEntries:PreviewEntry[]=[
{path:"/",title:"Главная: система → кадр",source:"fsd/pages/home/ui.tsx",components:"SiteShell · Brand · ThemeSwitch · ContentCard · ImageFigure · Notice · ActionLink"},
{path:"/library",title:"Библиотека и полный поиск",source:"fsd/pages/library/ui.tsx",components:"SiteShell · Search · Input · Select · Button · ContentCard · StateMessage"},
{path:"/catalog",title:"Каталог поколений",source:"fsd/widgets/article-reader",components:"ArticleMeta · ArticleContents · ArticleSection · DataTable · RelatedReading"},
{path:"/system",title:"Полная техническая статья",source:"fsd/widgets/article-reader",components:"ArticleMeta · ArticleContents · ArticleSection · Notice · ImageFigure · CodeBlock · DataTable"},
{path:"/manuals/svk007",title:"Полная инструкция СВК-007",source:"fsd/widgets/article-reader",components:"ArticleSection · ResourceLink · DataTable · Notice"},
{path:"/community/flash-start",title:"Процедура и предупреждение",source:"fsd/widgets/article-reader",components:"ArticleSection: контекст → предупреждение → список действий"},
{path:"/samples/gps",title:"Четыре JPEG и ограничения GPS",source:"fsd/widgets/article-reader",components:"ArticleSection · FrameGallery · DataTable · исходники и оговорки"},
{path:"/tools/recording-time",title:"Рабочий калькулятор: оба режима",source:"fsd/features/recording-estimate",components:"Field · Input · radio group · live result · CodeBlock"},
{path:"/sources",title:"Источники и редакция",source:"fsd/pages/services",components:"SiteShell · ResourceLink · service prose"},
{path:"/privacy",title:"Приватность и сохранение темы",source:"fsd/pages/services",components:"SiteShell · ThemeSwitch · service prose"},
{path:"/review-ui-kit-missing-20261027",title:"Настоящая 404",source:"fsd/pages/not-found",components:"StateMessage · ActionLink · SiteShell"}
];
export function UiKitPage() {
const system=findArticle("/system")!,support=findArticle("/support.shtml")!,manual=findArticle("/manuals/svk007")!,procedure=findArticle("/community/flash-start")!;
const tableIndex=support.sections.findIndex(s=>s.table);const procedureIndex=procedure.sections.findIndex(s=>s.note&&s.list);
const formula=system.sections.find(s=>s.code)!.code!;
const galleryArticles=articles.filter(a=>a.sections.some(s=>s.gallery));
const pdfs=articles.flatMap(a=>a.sections.flatMap(s=>(s.links??[]).filter(l=>/\.pdf$/i.test(l.href)).map(l=>({...l,article:a}))));
return <main id="main-content" className="ui-kit-page"><p className="kicker">VIDEOREG / UI KIT</p><h1>UI kit Videoreg</h1><p className="lede">Устройство, документ, исходный кадр. Те же рабочие компоненты, что на настоящих страницах библиотеки.</p><p className="review-note">Переключите тему в шапке и откройте нужный рабочий пример. Здесь собраны API, варианты, содержание и полные страницы. <a href="/health/ready">Сведения о сборке →</a></p>
<nav className="kit-index" aria-label="Разделы UI kit">{[["foundations","Основы"],["brand-demo","Знак"],["controls","Управление"],["reading-demo","Текст и процедура"],["table-demo","Таблицы"],["code-demo","Код и формулы"],["resources-demo","Документы и медиа"],["gallery-demo","Галереи"],["search-demo","Поиск"],["calculation-demo","Расчёт"],["page-assemblies","Полные страницы"],["component-api","API и состояния"]].map(([id,label])=><a href={"#"+id} key={id}>{label}</a>)}</nav>
<section id="foundations"><h2>01 / Основы и композиция</h2><p>Холодная рабочая поверхность, приборный синий и янтарная рамка кадра. Документальная фотография не перекрашивается при смене темы. Цвет обозначает поверхность или действие; смысл таблицы остаётся в тексте.</p><div className="token-grid">{Object.entries(designTokens.palette).map(([name,value])=><div className="token-swatch" key={name}><span style={{backgroundColor:"var(--color-"+name+")"}}/><code>{name}</code><p>Светлая: {value}<br />Тёмная: {designTokens.themes.dark[name as keyof typeof designTokens.palette]}</p></div>)}</div><div className="kit-grid"><div><h3>Шрифт и ритм</h3><div className="type-demo"><h2>Заголовок раздела</h2><p>Основной текст 18px/1,75; на телефоне 17px/1,75. Колонка чтения — до 640px. Системный гротеск не требует внешней загрузки.</p><p className="kicker">МЕТАДАННЫЕ / НЕ МЕНЕЕ 12PX</p><CodeBlock label="Файловое имя и единицы">{"USB.BIN · fr000775.jpg · 640 × 480 · КБ/кадр"}</CodeBlock></div></div><div><h3>Сетка и интервалы</h3><p>Контейнер до 1440px. У статьи rail220px +48px + колонка 640px. До 900px — одна колонка, содержание остаётся раскрываемым. До 600px — поля и блоки в один поток. Широкая таблица и код прокручиваются локально.</p><div className="space-scale">{designTokens.spacing.map(n=><div key={n}><span style={{height:n}}/>{n}px</div>)}</div></div></div></section>
<section id="brand-demo"><h2>02 / Айдентика и изображения</h2><div className="kit-grid"><div className="kit-example"><Brand /><div className="icon-examples">{[16,32,48].map(n=><figure key={n}><img src={"/brand/icon-light-"+n+".png"} width={n} height={n} alt={"Знак Videoreg "+n+" px"}/><figcaption>{n}×{n}</figcaption></figure>)}</div><p>Крупная апертура 4:3 и боковые следы последовательности. Это один и тот же нативный знак шапки и вкладки.</p></div><div className="kit-example"><h3>Кадр остаётся оригиналом</h3><p>Проверьте эту же шапку в обеих темах. Исходные фотографии и схемы не перекрашиваются и не инвертируются; у изображения сохраняются пропорции, имя и доступ к оригиналу.</p><ImageFigure src="/recordings/samples/fr000775.jpg" width={640} height={480} alt="Исходный дорожный кадр при сильном дожде с камеры Genius Videocam WEB." caption="fr000775.jpg · 640×480 · тот же исходник, что на главной."/></div></div></section>
<section id="controls"><h2>03 / Выбрать режим. Выполнить действие.</h2><div className="kit-grid"><div className="kit-example"><h3>Одна иконка — три режима</h3><ThemeSwitch idPrefix="kit"/><p>Иконка показывает текущий режим: монитор+A — системный, солнце — светлый, луна — тёмный. Нажатие, Enter или Space выбирает следующий режим. Доступное имя называет текущий и следующий.</p><p>Это тот же переключатель, что в шапке. Выбор сохраняется между страницами и перезагрузками; системный режим следует настройкам ОС.</p></div><div className="kit-example"><h3>Каждое управление — в своей задаче</h3><ul><li><a href="#search-demo">Поиск и фильтр</a>: введите запрос, получите ноль результатов и восстановите список кнопкой.</li><li><a href="#gallery-demo">Галерея</a>: откройте серию, покажите доступные кадры и сверните её.</li><li><a href="#calculation-demo">Расчёт</a>: переключите способ записи и проверьте ошибку реального поля.</li></ul><ActionLink href="/manuals/svk007">Открыть инструкцию СВК-007 ↗</ActionLink><p>Ссылка открывает инструкцию. Кнопки поиска и галереи меняют состояние; недоступность файла объяснена в исходном тексте.</p></div></div><ContentCard href="/system" title={system.title} summary={system.summary} eyebrow="2014 / Устройство" variant="index" headingLevel="h3"/></section>
<section id="reading-demo"><h2>04 / Метаданные, проза и процедура</h2><div className="kit-content-sample"><ArticleMeta article={manual}/><h3>{manual.title}</h3><p className="demo-prose">{manual.sections[0].paragraphs[0]}</p><p>Предупреждение об удалении данных размещается перед действиями. Ни слова инструкции не убираются.</p><ArticleSection section={procedure.sections[procedureIndex]} index={procedureIndex} idPrefix="kit-procedure-" headingLevel="h3"/></div></section>
<section id="table-demo"><h2>05 / Камера, режим и отрицательная ячейка</h2><div className="kit-content-sample">{support.sections.slice(0,tableIndex).flatMap(s=>s.paragraphs).map(p=><p key={p}>{p}</p>)}<ArticleSection section={support.sections[tableIndex]} index={tableIndex} idPrefix="kit-support-" headingLevel="h3"/></div><p>Все 17 строк×6 колонок, подпись, заголовки строк и столбцов. Tab переводит фокус на область; клавиши прокрутки позволяют дойти до последнего примечания.</p><details className="kit-reference"><summary>Вариант: сравнение двух блоков</summary><DataTable {...system.sections.find(s=>s.table)!.table!}/></details></section>
<section id="code-demo"><h2>06 / Код, формула и единицы</h2><CodeBlock label="Число сохраняемых кадров">{formula}</CodeBlock><CodeBlock label="Полная формула времени JPEG-записи">{"Время, с = ГБ × 1 000 000 × (1 − резерв/100) ÷ (КБ/кадр × кадров/с × камер)"}</CodeBlock><p>Полный plaintext сохраняется при копировании. Пример не выдаётся за измеренную характеристику прибора.</p></section>
<section id="resources-demo"><h2>07 / Источник и доступность</h2><ul className="document-links">{pdfs.map(l=><li key={l.href}><ArticleMeta article={l.article}/><ResourceLink href={l.href} label={l.label}/></li>)}</ul><div className="kit-content-sample"><h3>Недоступные программы: текст исходного разбора</h3>{findArticle("/down.shtml")!.sections.filter(s=>s.paragraphs.some(p=>/EXE|USB\.BIN|недоступ/i.test(p))).map((s,i)=><ArticleSection key={s.heading} section={s} index={i} idPrefix="kit-unavailable-" headingLevel="h3"/>)}</div><div className="kit-grid"><ImageFigure src="/archive-media/svk006-front.jpg" width={800} height={528} alt="Передняя панель системного блока СВК-006 со слотом SD CARD и разъёмами USB." caption="Предметная фотография: конкретный блок, не обещание характеристик всех поколений."/><ImageFigure src="/archive-media/certificate.jpg" width={200} height={282} small alt="Исторический скан сертификата соответствия системы СВК." caption="Малый скан 200×282: не увеличиваем его до ложной детализации. Оригинал открывается по ссылке."/><ImageFigure src="/diagrams/svk-signal-chain.svg" width={440} height={870} diagram alt="Схема пути от внешних USB-камер через системный блок СВК к съёмному носителю и компьютеру." caption="Схема пути данных, не инструкция электрического подключения. Оригинал доступен целиком."/><ImageFigure src="/archive-media/installation-block.jpg" width={200} height={150} small alt="Маленькая историческая фотография установленного системного блока СВК." caption="Малая документальная фотография 200×150 сохраняется в исходных пропорциях."/></div></section>
<section id="gallery-demo"><h2>08 / Исходные серии и их ограничения</h2><p>Семь настоящих галерей. Внутри — тот же FrameGallery, что на странице серии. Счётчик относится к доступным файлам, не к недостающей части архива.</p>{galleryArticles.map(a=><details className="kit-gallery-case" key={a.path}><summary>{a.title} · {a.sections.find(s=>s.gallery)!.gallery!.length} доступных кадров</summary><ArticleMeta article={a}/><p><a href={a.path}>Открыть полный разбор →</a></p>{a.sections.map((s,i)=><ArticleSection key={s.heading} section={s} index={i} idPrefix={"kit-gallery-"+a.path.replaceAll("/","-")+"-"} headingLevel="h3"/>)}</details>)}</section>
<section id="search-demo"><h2>09 / Полнотекстовый поиск</h2><p>Все 28 материалов; слова ищутся в полном тексте, таблицах и названиях. Проверьте GPSVersionID, категорию, отсутствующий запрос и сброс. У этого локального поиска нет сетевого loading-состояния.</p><Search entries={searchIndex} idPrefix="demo-search" emitAnalytics={false}/></section>
<section id="calculation-demo"><h2>10 / Расчёт: два режима</h2><p>Рабочий Calculator с теми же полями, единицами и границами. Пустое поле/ноль/дробное число камер — реальные проверки; ошибка сохраняет введённые значения. Режим видеопотока объясняет только его поля.</p><Calculator idPrefix="demo-recording"/></section>
<section id="page-assemblies"><h2>11 / Полные страницы из этого kit</h2><PagePreview entries={pageEntries}/></section>
<section id="component-api"><h2>12 / Анатомия, варианты, API и применение</h2><p>API соответствует используемым компонентам. Ссылки ведут к их настоящим страницам. Наведение и клавиатурный фокус работают на самих элементах.</p>{componentReference.map(c=><details className="kit-reference" key={c.name}><summary>{c.name}</summary><dl><dt>Анатомия</dt><dd>{c.anatomy}</dd><dt>Варианты</dt><dd>{c.variants.join(" · ")}</dd><dt>Состояния</dt><dd>{c.states.join(" · ")}</dd><dt>API</dt><dd><code>{c.api || "Без props"}</code></dd><dt>Исходник</dt><dd><code>{c.source}:{c.line}</code></dd><dt>Адаптив</dt><dd>{c.responsive}</dd><dt>Клавиатура</dt><dd>{c.keyboard}</dd><dt>Реальные страницы</dt><dd>{c.routes.slice(0,8).map(r=><p key={r}>{r.includes("review-ui-kit-missing") ? <code>{r} · пример HTTP404</code> : <a href={r}>{r}</a>}</p>)}</dd></dl></details>)}</section>
</main>;
}
+687
View File
@@ -0,0 +1,687 @@
/** Actual API declarations plus required reference states; visual acceptance is recorded separately. */
export const componentReference = [
{
"name": "Button",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 3,
"api": "{ className, ...props }: ButtonHTMLAttributes<HTMLButtonElement>",
"anatomy": "Нативная кнопка изменения состояния: сброс поиска или раскрытие серии",
"variants": [
"reset",
"expand/collapse"
],
"states": [
"default",
"hover",
"focus-visible",
"activated"
],
"responsive": "Перенос строки; область управления и обтекание в реальном Search/Gallery",
"keyboard": "Tab + Enter/Space, disabled исключён из обычной фокусировки",
"routes": [
"/library",
"/samples/stx",
"/samples/gps",
"/samples/evening-zeiss",
"/samples/day-zeiss",
"/samples/rain",
"/samples/late-evening",
"/samples/roundabout"
]
},
{
"name": "Input",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 6,
"api": "{ className, ...props }: InputHTMLAttributes<HTMLInputElement>",
"anatomy": "native input; label принадлежит потребителю; type/value/onChange и native attributes",
"variants": [
"search",
"number",
"radio"
],
"states": [
"empty",
"filled",
"focus-visible",
"invalid in calculator"
],
"responsive": "query-row/input-pair на320/390, длинное число без общего overflow",
"keyboard": "Tab, нативное редактирование; radio arrows; связь label",
"routes": [
"/library",
"/tools/recording-time"
]
},
{
"name": "Select",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 7,
"api": "{ className, ...props }: SelectHTMLAttributes<HTMLSelectElement>",
"anatomy": "Категории поиска или выбор реальной страницы/ширины reference",
"variants": [
"search category",
"reference page",
"reference width"
],
"states": [
"default",
"focus-visible",
"value changed"
],
"responsive": "Ширина фильтра на мобильном, длинная категория",
"keyboard": "Нативный select; фактическая смена клавишами требует доказательства",
"routes": [
"/library",
"/ui-kit"
]
},
{
"name": "ActionLink",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 8,
"api": "{ className, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>",
"anatomy": "native anchor с class button и href",
"variants": [
"навигационное действие"
],
"states": [
"normal",
"hover",
"focus-visible",
"visited"
],
"responsive": "Длинная надпись на320 без обрезки",
"keyboard": "Tab/Enter; не выдаётся за submit/button",
"routes": [
"/",
"/review-ui-kit-missing-20261027"
]
},
{
"name": "Brand",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 9,
"api": "",
"anatomy": "Один нативный знак и HTML-имя, автоматически в текущей теме",
"variants": [
"site brand"
],
"states": [
"default",
"hover",
"focus-visible",
"16/32/48 native mark"
],
"responsive": "wordmark+подпись на320/390; inverse только на inverse поверхности",
"keyboard": "Одна ссылка с доступным именем; Tab/Enter",
"routes": [
"/",
"/library",
"/community",
"/tools/recording-time",
"/about",
"/sources",
"/privacy",
"/ui-kit",
"/review-ui-kit-missing-20261027",
"/system",
"/auto.shtml",
"/support.shtml",
"/down.shtml",
"/manuals/uvr",
"/manuals/svk007",
"/autopredpr.shtml",
"/samples.shtml",
"/catalog",
"/equipment/svk002-lqcd",
"/equipment/svk002-gps",
"/equipment/svk004",
"/sert.html",
"/predpr.shtml",
"/manuals/two-camera",
"/manuals/quickstart",
"/samples/stx",
"/samples/gps",
"/samples/evening-zeiss",
"/samples/day-zeiss",
"/samples/rain",
"/samples/late-evening",
"/samples/roundabout",
"/demo.shtml",
"/reviews/svk002-mobile-news",
"/faq.shtml",
"/community/flash-start",
"/community/usb-extension"
]
},
{
"name": "Notice",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 15,
"api": "{ children, className }: { children: ReactNode; className?: string }",
"anatomy": "Видимая исходная оговорка; перед действиями, если есть процедура",
"variants": [
"source note"
],
"states": [
"long warning",
"historical limitation"
],
"responsive": "Не убирать критическое предупреждение на мобильном",
"keyboard": "Статическое чтение; ссылки внутри наследуют обычный Tab",
"routes": [
"/faq.shtml",
"/community/flash-start",
"/community/usb-extension"
]
},
{
"name": "CodeBlock",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 18,
"api": "{ children, label = \"Код или формула\" }: { children: string; label?: string }",
"anatomy": "подсказка, pre role region/tabIndex0, code plaintext",
"variants": [
"код",
"формула"
],
"states": [
"fits",
"horizontal overflow",
"keyboard focus"
],
"responsive": "Локальная прокрутка полной строки без изменения символов",
"keyboard": "Tab на region, ArrowRight/Home/End доступ до конца строки",
"routes": [
"/system",
"/tools/recording-time"
]
},
{
"name": "DataTable",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 21,
"api": "{ caption, head, rows }: { caption: string; head: string[]; rows: string[][] }",
"anatomy": "caption, col/row headers, focusable region, scroll hint",
"variants": [
"сравнение",
"состав комплекта",
"камера/режим"
],
"states": [
"normal",
"wide",
"keyboard focus",
"negative cell",
"last column"
],
"responsive": "Локальный scroll, не скрывать отрицательную правую колонку",
"keyboard": "Именованный region, Tab + горизонтальная прокрутка",
"routes": [
"/system",
"/support.shtml",
"/catalog",
"/faq.shtml"
]
},
{
"name": "ResourceLink",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 24,
"api": "{ href, label, className }: { href: string; label: string; className?: string }",
"anatomy": "Доступный реальный документ или источник: href и полная подпись",
"variants": [
"internal original",
"approved external source"
],
"states": [
"default",
"hover",
"focus-visible"
],
"responsive": "Длинное имя файла/PDF/EXE без скрытия",
"keyboard": "Только доступный href фокусируется; недоступный файл не имитирует кнопку",
"routes": [
"/down.shtml",
"/manuals/uvr",
"/manuals/svk007",
"/samples.shtml",
"/manuals/two-camera",
"/manuals/quickstart",
"/demo.shtml",
"/reviews/svk002-mobile-news",
"/sources"
]
},
{
"name": "ContentCard",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 27,
"api": "{ href, title, summary, eyebrow, variant=\"result\", headingLevel=\"h2\" }: { href:string; title:string; summary?:string; eyebrow?:ReactNode; variant?:\"index\"|\"result\"; headingLevel?:\"h2\"|\"h3\" }",
"anatomy": "Ссылка, метаданные, полный заголовок и краткое описание",
"variants": [
"index / h3",
"result / h2"
],
"states": [
"default",
"hover",
"focus-visible",
"long model title"
],
"responsive": "Book/result раскладка и длинное название без clamp",
"keyboard": "Одна ссылка, полный accessible heading",
"routes": [
"/",
"/library",
"/community"
]
},
{
"name": "ImageFigure",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 31,
"api": "{ src, alt, caption, width, height, small = false, diagram = false, loading = \"lazy\", openLabel, className }: { src: string; alt: string; caption: string; width?: number; height?: number; small?: boolean; diagram?: boolean; loading?: \"eager\" | \"lazy\"; openLabel?: string; className?: string }",
"anatomy": "figure, anchor to original, img alt/intrinsic size, figcaption",
"variants": [
"normal",
"small",
"diagram",
"eager/lazy"
],
"states": [
"loaded",
"lazy pending",
"original opened",
"missing resource intent unspecified"
],
"responsive": "Сохранить пропорции/читабельность подписи и схемы",
"keyboard": "Tab/Enter открывает оригинал; alt и подпись имеют разные роли",
"routes": [
"/system",
"/auto.shtml",
"/samples.shtml",
"/sert.html",
"/predpr.shtml"
]
},
{
"name": "StateMessage",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 34,
"api": "{ title, children, actions, headingLevel = \"h2\", className }: { title: ReactNode; children?: ReactNode; actions?: ReactNode; headingLevel?: \"h1\" | \"h2\"; className?: string }",
"anatomy": "h1/h2/h3 title + children + optional actions",
"variants": [
"404 / h1",
"zero results / h2"
],
"states": [
"not found",
"zero results",
"real recovery action"
],
"responsive": "Многострочное сообщение и действия на320",
"keyboard": "Actions доступны; заголовочная иерархия принадлежит странице",
"routes": [
"/library",
"/review-ui-kit-missing-20261027"
]
},
{
"name": "Search",
"source": "web-front/src/fsd/features/library-search/ui.tsx",
"line": 19,
"api": "{ entries, idPrefix = \"library\", emitAnalytics = true }: { entries: Entry[]; idPrefix?: string; emitAnalytics?: boolean }",
"anatomy": "query+category+reset+status+result cards+empty recovery",
"variants": [
"page library",
"isolated UIkit prefix; analytics false"
],
"states": [
"initial28",
"positive",
"zero",
"category",
"combined filter",
"reset",
"long query"
],
"responsive": "Поля/результаты320/390/1440",
"keyboard": "Label, Tab, native select, reset button, role=status",
"routes": [
"/library"
]
},
{
"name": "Calculator",
"source": "web-front/src/fsd/features/recording-estimate/ui.tsx",
"line": 4,
"api": "{ idPrefix = \"recording\" }: { idPrefix?: string }",
"anatomy": "mode fieldset+radio+controlled numeric fields+live estimate+explanation",
"variants": [
"JPEG",
"stream"
],
"states": [
"valid",
"empty",
"zero",
"negative",
"fractional camera invalid",
"limits",
"large number",
"mode switch"
],
"responsive": "Парные поля, длинное значение/формула с локальным overflow",
"keyboard": "Radio group, label/input, live polite result; сохранить ввод при ошибке",
"routes": [
"/tools/recording-time"
]
},
{
"name": "FrameGallery",
"source": "web-front/src/fsd/features/frame-gallery/ui.tsx",
"line": 5,
"api": "{ frames }: { frames: Frame[] }",
"anatomy": "count+original-link frames+filename/dimensions+toggle",
"variants": [
"<=6",
">6 expandable"
],
"states": [
"six shown",
"all shown",
"collapsed",
"partial historical series",
"lazy pending"
],
"responsive": "Сетка/полные размеры/исходник на320/390",
"keyboard": "Tab/Enter original; button Enter/Space expand/collapse",
"routes": [
"/samples/stx",
"/samples/gps",
"/samples/evening-zeiss",
"/samples/day-zeiss",
"/samples/rain",
"/samples/late-evening",
"/samples/roundabout"
]
},
{
"name": "ArticleReader",
"source": "web-front/src/fsd/widgets/article-reader/ui.tsx",
"line": 3,
"api": "{ article:a }: { article: LibraryArticle }",
"anatomy": "heading/meta/back; responsive TOC; ordered source sections; related",
"variants": [
"technical prose",
"catalog table",
"manual",
"community case",
"gallery"
],
"states": [
"long text",
"deep anchor",
"details open/closed",
"table/code/media",
"related"
],
"responsive": "Desktop reading rail; mobile native details and source section-N",
"keyboard": "Skip/TOC/details/scroll regions/related links",
"routes": [
"/system",
"/auto.shtml",
"/support.shtml",
"/down.shtml",
"/manuals/uvr",
"/manuals/svk007",
"/autopredpr.shtml",
"/samples.shtml",
"/catalog",
"/equipment/svk002-lqcd",
"/equipment/svk002-gps",
"/equipment/svk004",
"/sert.html",
"/predpr.shtml",
"/manuals/two-camera",
"/manuals/quickstart",
"/samples/stx",
"/samples/gps",
"/samples/evening-zeiss",
"/samples/day-zeiss",
"/samples/rain",
"/samples/late-evening",
"/samples/roundabout",
"/demo.shtml",
"/reviews/svk002-mobile-news",
"/faq.shtml",
"/community/flash-start",
"/community/usb-extension"
]
},
{
"name": "SiteShell",
"source": "web-front/src/fsd/widgets/site-shell/index.tsx",
"line": 5,
"api": "{ children }: { children: ReactNode }",
"anatomy": "inactive AnalyticsTag; skip; brand; primary nav; main slot; footer",
"variants": [
"one site shell"
],
"states": [
"skip focus",
"nav hover/focus",
"mobile wrap",
"footer"
],
"responsive": "Видимые переносимые ссылки, без fakehamburger",
"keyboard": "Первая skip link, последовательность nav/main/footer",
"routes": [
"/",
"/library",
"/community",
"/tools/recording-time",
"/about",
"/sources",
"/privacy",
"/ui-kit",
"/review-ui-kit-missing-20261027",
"/system",
"/auto.shtml",
"/support.shtml",
"/down.shtml",
"/manuals/uvr",
"/manuals/svk007",
"/autopredpr.shtml",
"/samples.shtml",
"/catalog",
"/equipment/svk002-lqcd",
"/equipment/svk002-gps",
"/equipment/svk004",
"/sert.html",
"/predpr.shtml",
"/manuals/two-camera",
"/manuals/quickstart",
"/samples/stx",
"/samples/gps",
"/samples/evening-zeiss",
"/samples/day-zeiss",
"/samples/rain",
"/samples/late-evening",
"/samples/roundabout",
"/demo.shtml",
"/reviews/svk002-mobile-news",
"/faq.shtml",
"/community/flash-start",
"/community/usb-extension"
]
},
{
"name": "Field",
"source": "web-front/src/fsd/shared/ui/index.tsx",
"line": 12,
"api": "{ id, label, hint, error, children }: { id: string; label: string; hint?: string; error?: string; children: ReactNode }",
"anatomy": "Label → control → hint/error; id connects aria-describedby",
"variants": [
"hint",
"error",
"required control"
],
"states": [
"empty",
"filled",
"invalid",
"disabled"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Нативные элементы, видимый фокус; конкретный сценарий проверяется в этой сборке",
"routes": [
"/tools/recording-time"
]
},
{
"name": "ThemeSwitch",
"source": "web-front/src/fsd/features/theme-choice/index.tsx",
"line": 21,
"api": "{ idPrefix }: { idPrefix: string }",
"anatomy": "Одна компактная кнопка; иконка текущего режима, доступное имя текущего и следующего",
"variants": [
"system icon",
"light icon",
"dark icon"
],
"states": [
"default",
"hover",
"focus-visible",
"Enter/Space/click/tap",
"persisted reload",
"live OS"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Tab на кнопку; Enter или Space выбирает следующий режим: System → Light → Dark",
"routes": [
"/",
"/system",
"/library",
"/privacy"
]
},
{
"name": "ArticleMeta",
"source": "web-front/src/fsd/widgets/article-reader/parts.tsx",
"line": 5,
"api": "{ article }: { article: LibraryArticle }",
"anatomy": "Category/date of the original source",
"variants": [
"manufacturer",
"instruction",
"owner case"
],
"states": [
"long category",
"unknown date"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Нативные элементы, видимый фокус; конкретный сценарий проверяется в этой сборке",
"routes": [
"/system",
"/manuals/svk007",
"/community/flash-start"
]
},
{
"name": "ArticleContents",
"source": "web-front/src/fsd/widgets/article-reader/parts.tsx",
"line": 6,
"api": "{ article }: { article: LibraryArticle }",
"anatomy": "Native details/summary and original section-N anchors",
"variants": [
"desktop rail",
"mobile block"
],
"states": [
"expanded",
"collapsed",
"deep anchor"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Нативные элементы, видимый фокус; конкретный сценарий проверяется в этой сборке",
"routes": [
"/system",
"/catalog"
]
},
{
"name": "ArticleSection",
"source": "web-front/src/fsd/widgets/article-reader/parts.tsx",
"line": 7,
"api": "{ section:s, index, idPrefix=\"section-\", headingLevel=\"h2\" }: { section: LibraryArticle[\"sections\"][number]; index:number; idPrefix?:string; headingLevel?:\"h2\"|\"h3\" }",
"anatomy": "Heading, original paragraphs, notice before list, code/table/figure/gallery/resources",
"variants": [
"prose",
"procedure",
"table",
"diagram",
"gallery"
],
"states": [
"long prose",
"destructive warning",
"last table column",
"original media"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Нативные элементы, видимый фокус; конкретный сценарий проверяется в этой сборке",
"routes": [
"/system",
"/support.shtml",
"/community/flash-start"
]
},
{
"name": "RelatedReading",
"source": "web-front/src/fsd/widgets/article-reader/parts.tsx",
"line": 19,
"api": "{ paths }: { paths: string[] }",
"anatomy": "Full related titles in source order",
"variants": [
"article",
"tool"
],
"states": [
"long title",
"keyboard link"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Нативные элементы, видимый фокус; конкретный сценарий проверяется в этой сборке",
"routes": [
"/system",
"/samples/gps"
]
},
{
"name": "PagePreview",
"source": "web-front/src/fsd/features/page-preview/index.tsx",
"line": 5,
"api": "{ entries }: { entries: PreviewEntry[] }",
"anatomy": "Real same-build route inside iframe; same actual page components",
"variants": [
"fluid",
"390px",
"320px"
],
"states": [
"route change",
"width change",
"theme synchronization"
],
"responsive": "Общие320/390/1440 правила; полные подписи и локальная прокрутка",
"keyboard": "Нативные элементы, видимый фокус; конкретный сценарий проверяется в этой сборке",
"routes": [
"/ui-kit"
]
}
] as const;
@@ -0,0 +1,3 @@
// Explicit source-pinned gate: this design-only candidate MUST NOT activate the
// separately prepared/rejected analytics release. No environment/runtime override.
export const analytics = Object.freeze({ enabled: false, counterId: 109268682, webvisor: false, accurateTrackBounce: true, trackHash: false });
@@ -0,0 +1,88 @@
{
"palette": {
"surface-paper": "#eef3f6",
"surface-sheet": "#f9fbfc",
"text-primary": "#152d40",
"text-secondary": "#435f73",
"link": "#185d82",
"focus": "#a34200",
"border-control": "#56758c",
"border-subtle": "#c4d0d9",
"surface-note": "#fff0df",
"surface-inverse": "#112c43",
"text-inverse": "#ffffff",
"text-inverse-muted": "#d1dee7",
"accent-inverse": "#f3933d",
"text-note": "#703700",
"surface-subtle": "#e3ebf0",
"accent-hover": "#ffb36c",
"text-action": "#112c43"
},
"themes": {
"light": {
"surface-paper": "#eef3f6",
"surface-sheet": "#f9fbfc",
"text-primary": "#152d40",
"text-secondary": "#435f73",
"link": "#185d82",
"focus": "#a34200",
"border-control": "#56758c",
"border-subtle": "#c4d0d9",
"surface-note": "#fff0df",
"surface-inverse": "#112c43",
"text-inverse": "#ffffff",
"text-inverse-muted": "#d1dee7",
"accent-inverse": "#f3933d",
"text-note": "#703700",
"surface-subtle": "#e3ebf0",
"accent-hover": "#ffb36c",
"text-action": "#112c43"
},
"dark": {
"surface-paper": "#07131c",
"surface-sheet": "#102636",
"text-primary": "#e0ebf3",
"text-secondary": "#b1c5d4",
"link": "#86ccef",
"focus": "#ffbb77",
"border-control": "#7896aa",
"border-subtle": "#58758a",
"surface-note": "#382b1c",
"surface-inverse": "#0b2030",
"text-inverse": "#ffffff",
"text-inverse-muted": "#d1dee7",
"accent-inverse": "#f3933d",
"text-note": "#ffd2a0",
"surface-subtle": "#1a3548",
"accent-hover": "#ffb36c",
"text-action": "#112c43"
}
},
"typography": {
"bodyDesktop": "18px / 1.75 system sans",
"bodyMobile": "17px / 1.75 system sans",
"proseMeasure": "40rem",
"heading": "Arial, Helvetica, system sans",
"code": "ui-monospace, SFMono-Regular, Consolas, monospace"
},
"spacing": [
4,
8,
12,
16,
24,
32,
48,
64
],
"grid": {
"container": "1440px",
"reading": "640px",
"rail": "220px",
"gap": "48px",
"breakpoints": [
600,
900
]
}
}
+2
View File
@@ -0,0 +1,2 @@
export { analytics } from "./analytics";
export { default as designTokens } from "./design-tokens.json";
+1
View File
@@ -0,0 +1 @@
export { getThemeChoice, setThemeChoice, subscribeThemeChoice, themeChangeEvent, type ThemeChoice } from './theme';
@@ -0,0 +1,85 @@
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { describe, expect, it } from 'vitest';
import { getThemeChoice, setThemeChoice } from './theme';
const script = readFileSync('web-front/public/theme.js', 'utf8');
function boot({ saved = null, dark = false, blocked = false, mediaAvailable = true, legacy = false }: {
saved?: string | null; dark?: boolean; blocked?: boolean; mediaAvailable?: boolean; legacy?: boolean;
} = {}) {
const values = new Map<string, string>();
if (saved !== null) values.set('videoreg-theme', saved);
const listeners: Record<string, ((event: any) => void)[]> = {};
const osListeners: (() => void)[] = [];
const storage = { getItem(key: string) { if (blocked) throw Error('blocked'); return values.get(key) ?? null; },
setItem(key: string, value: string) { if (blocked) throw Error('blocked'); values.set(key, value); } };
const root = { dataset: {} as Record<string, string>, style: {} as Record<string, string> };
const media = { matches: dark,
...(legacy ? { addListener: (fn: () => void) => osListeners.push(fn) }
: { addEventListener: (_: string, fn: () => void) => osListeners.push(fn) }) };
const window: any = {
addEventListener: (name: string, fn: (event: any) => void) => (listeners[name] ??= []).push(fn),
dispatchEvent: (event: any) => (listeners[event.type] ?? []).forEach(fn => fn(event)),
...(mediaAvailable ? { matchMedia: () => media } : {}),
};
let notifications = 0;
window.addEventListener('videoreg:theme-change', () => notifications++);
const context = { window, document: { documentElement: root }, localStorage: storage,
CustomEvent: class { constructor(public type: string) {} } };
runInNewContext(script, context);
return { root, values, storage, window, choice: () => window.videoregTheme.get(),
set: (choice: string) => window.videoregTheme.set(choice), notifications: () => notifications,
os: (dark: boolean) => { media.matches = dark; osListeners.forEach(fn => fn()); },
storageEvent: (key: string | null = 'videoreg-theme', storageArea: unknown = storage) => window.dispatchEvent({ type: 'storage', key, storageArea }) };
}
describe('blocking theme bootstrap contract', () => {
it('sets all first-paint attributes synchronously from persisted explicit choice', () => {
const app = boot({ saved: 'light', dark: true });
expect(app.root).toEqual({ dataset: { theme: 'light', themeChoice: 'light' }, style: { colorScheme: 'light' } });
expect(app.notifications()).toBe(1);
app.os(false); app.os(true);
expect(app.root.dataset.theme).toBe('light');
expect(app.notifications()).toBe(1);
});
it('follows live OS changes only in system mode, including legacy media listeners', () => {
const app = boot({ dark: true, legacy: true });
expect(app.choice()).toBe('system'); expect(app.root.dataset.theme).toBe('dark');
app.os(false); expect(app.root.dataset.theme).toBe('light');
app.set('dark'); app.os(false); expect(app.root.dataset.theme).toBe('dark');
app.set('system'); expect(app.root.dataset.theme).toBe('light');
app.os(true); expect(app.root.dataset.theme).toBe('dark');
});
it('persists every valid mode across a fresh page bootstrap and rejects invalid input', () => {
const app = boot();
for (const choice of ['light', 'dark', 'system']) {
app.set(choice);
expect(boot({ saved: app.values.get('videoreg-theme') }).choice()).toBe(choice);
}
app.set('invalid'); expect(app.choice()).toBe('system');
expect(app.values.get('videoreg-theme')).toBe('system');
});
it('handles missing/invalid/blocked storage and missing matchMedia without throwing', () => {
for (const saved of [null, '', 'sepia']) expect(boot({ saved, dark: true }).root.dataset.theme).toBe('dark');
const blocked = boot({ blocked: true, dark: true });
blocked.set('light'); expect(blocked.root.dataset.theme).toBe('light');
expect(blocked.choice()).toBe('light');
expect(boot({ mediaAvailable: false }).root.dataset.theme).toBe('light');
});
it('updates other consumers via events and follows same-origin storage updates and removal', () => {
const app = boot(); const before = app.notifications();
app.set('dark'); expect(app.notifications()).toBe(before + 1);
app.values.set('videoreg-theme', 'light'); app.storageEvent();
expect(app.choice()).toBe('light'); expect(app.root.dataset.theme).toBe('light');
app.values.delete('videoreg-theme'); app.storageEvent(null);
expect(app.choice()).toBe('system');
app.values.set('videoreg-theme', 'dark'); app.storageEvent('unrelated');
expect(app.choice()).toBe('system');
app.storageEvent('videoreg-theme', {}); expect(app.choice()).toBe('system');
app.storageEvent(); expect(app.choice()).toBe('dark');
});
it('keeps client API safe during server rendering', () => {
expect(getThemeChoice()).toBe('system');
expect(() => setThemeChoice('dark')).not.toThrow();
});
});
+22
View File
@@ -0,0 +1,22 @@
export type ThemeChoice = 'system' | 'light' | 'dark';
export const themeChangeEvent = 'videoreg:theme-change';
declare global {
interface Window {
videoregTheme?: { get(): ThemeChoice; set(choice: ThemeChoice): void };
}
}
export function getThemeChoice(): ThemeChoice {
return typeof window === 'undefined' ? 'system' : window.videoregTheme?.get() ?? 'system';
}
export function setThemeChoice(choice: ThemeChoice): void {
if (typeof window === 'undefined') return;
window.videoregTheme?.set(choice);
}
export function subscribeThemeChoice(onChange: () => void): () => void {
window.addEventListener(themeChangeEvent, onChange);
return () => window.removeEventListener(themeChangeEvent, onChange);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,81 @@
:root {
color-scheme: light;
--color-surface-paper: #eef3f6;
--color-surface-sheet: #f9fbfc;
--color-text-primary: #152d40;
--color-text-secondary: #435f73;
--color-link: #185d82;
--color-focus: #a34200;
--color-border-control: #56758c;
--color-border-subtle: #c4d0d9;
--color-surface-note: #fff0df;
--color-surface-inverse: #112c43;
--color-text-inverse: #ffffff;
--color-text-inverse-muted: #d1dee7;
--color-accent-inverse: #f3933d;
--color-text-note: #703700;
--color-surface-subtle: #e3ebf0;
--color-accent-hover: #ffb36c;
--color-text-action: #112c43;
--space-4: 4px;
--space-8: 8px;
--space-12: 12px;
--space-16: 16px;
--space-24: 24px;
--space-32: 32px;
--space-48: 48px;
--space-64: 64px;
--font-sans: Arial, Helvetica, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
--font-serif: var(--font-sans);
--font-mono: ui-monospace, SFMono-Regular, Consolas, monospace;
--type-body: 18px;
--leading-body: 1.75;
--type-meta: 12px;
--type-code: 14px;
--type-h1: clamp(32px, 4.5vw, 60px);
--type-h2: clamp(25px, 3vw, 36px);
--measure-reading: 40rem;
--paper: var(--color-surface-paper); --sheet: var(--color-surface-sheet);
--ink: var(--color-text-primary); --muted: var(--color-text-secondary);
--rule: var(--color-border-subtle); --accent: var(--color-link);
--mono: var(--font-mono); --serif: var(--font-sans);
}
html[data-theme="dark"] { color-scheme: dark;
--color-surface-paper: #07131c;
--color-surface-sheet: #102636;
--color-text-primary: #e0ebf3;
--color-text-secondary: #b1c5d4;
--color-link: #86ccef;
--color-focus: #ffbb77;
--color-border-control: #7896aa;
--color-border-subtle: #58758a;
--color-surface-note: #382b1c;
--color-surface-inverse: #0b2030;
--color-text-inverse: #ffffff;
--color-text-inverse-muted: #d1dee7;
--color-accent-inverse: #f3933d;
--color-text-note: #ffd2a0;
--color-surface-subtle: #1a3548;
--color-accent-hover: #ffb36c;
--color-text-action: #112c43;
}
@media (prefers-color-scheme: dark) { html:not([data-theme]) { color-scheme: dark;
--color-surface-paper: #07131c;
--color-surface-sheet: #102636;
--color-text-primary: #e0ebf3;
--color-text-secondary: #b1c5d4;
--color-link: #86ccef;
--color-focus: #ffbb77;
--color-border-control: #7896aa;
--color-border-subtle: #58758a;
--color-surface-note: #382b1c;
--color-surface-inverse: #0b2030;
--color-text-inverse: #ffffff;
--color-text-inverse-muted: #d1dee7;
--color-accent-inverse: #f3933d;
--color-text-note: #ffd2a0;
--color-surface-subtle: #1a3548;
--color-accent-hover: #ffb36c;
--color-text-action: #112c43;
}}
@media (max-width: 600px) { :root { --type-body: 17px; } }
+37
View File
@@ -0,0 +1,37 @@
import type { AnchorHTMLAttributes, ButtonHTMLAttributes, InputHTMLAttributes, SelectHTMLAttributes, ReactNode } from "react";
const cls = (...values: (string | undefined | false)[]) => values.filter(Boolean).join(" ");
export function Button({ className, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {
return <button type="button" {...props} className={cls("ui-button", className)} />;
}
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) { return <input {...props} className={cls("ui-input", className)} />; }
export function Select({ className, ...props }: SelectHTMLAttributes<HTMLSelectElement>) { return <select {...props} className={cls("ui-select", className)} />; }
export function ActionLink({ className, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) { return <a {...props} className={cls("button", className)} />; }
export function Brand() {
return <a className="brand" href="/" aria-label="На главную — videoreg, библиотека систем СВК"><img className="brand-mark" src="/brand/mark.svg" alt="" aria-hidden="true" width="48" height="48" /><span className="brand-words"><strong>videoreg</strong><span className="brand-subtitle">Библиотека систем СВК</span></span></a>;
}
export function Field({ id, label, hint, error, children }: { id: string; label: string; hint?: string; error?: string; children: ReactNode }) {
return <div className={cls("field", !!error && "field-invalid")}><label htmlFor={id}>{label}</label>{children}{hint && <p id={id+"-hint"} className="field-hint">{hint}</p>}{error && <p id={id+"-error"} className="field-error">{error}</p>}</div>;
}
export function Notice({ children, className }: { children: ReactNode; className?: string }) {
return <aside className={cls("reading-note", className)}>{children}</aside>;
}
export function CodeBlock({ children, label = "Код или формула" }: { children: string; label?: string }) {
return <div className="code-block"><p className="scroll-hint">Длинную строку можно прокрутить по горизонтали.</p><pre tabIndex={0} role="region" aria-label={label}><code>{children}</code></pre></div>;
}
export function DataTable({ caption, head, rows }: { caption: string; head: string[]; rows: string[][] }) {
return <div className="table-block"><p className="scroll-hint">Таблицу можно прокручивать по горизонтали.</p><div className="table-region" tabIndex={0} role="region" aria-label={caption}><table><caption>{caption}</caption><thead><tr>{head.map(h => <th scope="col" key={h}>{h}</th>)}</tr></thead><tbody>{rows.map((row,i) => <tr key={i}>{row.map((value,j) => j === 0 ? <th scope="row" key={j}>{value}</th> : <td key={j}>{value}</td>)}</tr>)}</tbody></table></div></div>;
}
export function ResourceLink({ href, label, className }: { href: string; label: string; className?: string }) {
return <a className={cls("resource-link",className)} href={href} rel={href.startsWith("https://")?"noreferrer":undefined}>{label} ↗</a>;
}
export function ContentCard({ href, title, summary, eyebrow, variant="result", headingLevel="h2" }: { href:string; title:string; summary?:string; eyebrow?:ReactNode; variant?:"index"|"result"; headingLevel?:"h2"|"h3" }) {
const Heading=headingLevel;
return <a className={variant==="index"?"index-card":"result-card"} href={href}>{eyebrow&&<span className="search-kind">{eyebrow}</span>}<Heading>{title}</Heading>{summary&&<p>{summary}</p>}<span aria-hidden="true">↗</span></a>;
}
export function ImageFigure({ src, alt, caption, width, height, small = false, diagram = false, loading = "lazy", openLabel, className }: { src: string; alt: string; caption: string; width?: number; height?: number; small?: boolean; diagram?: boolean; loading?: "eager" | "lazy"; openLabel?: string; className?: string }) {
return <figure className={cls("content-figure", small && "small-figure", diagram && "diagram", className)}><a href={src} aria-label={openLabel ?? "Открыть изображение: " + alt}><img src={src} alt={alt} width={width} height={height} loading={loading} /></a><figcaption>{caption}</figcaption></figure>;
}
export function StateMessage({ title, children, actions, headingLevel = "h2", className }: { title: ReactNode; children?: ReactNode; actions?: ReactNode; headingLevel?: "h1" | "h2"; className?: string }) {
const Heading = headingLevel;
return <div className={cls("state-message", className)}><Heading>{title}</Heading>{children}{actions && <div className="state-actions">{actions}</div>}</div>;
}
@@ -0,0 +1,2 @@
export { ArticleReader } from "./ui";
export { ArticleMeta, ArticleContents, ArticleSection, RelatedReading } from "./parts";
@@ -0,0 +1,19 @@
import { FrameGallery } from "@/fsd/features/frame-gallery";
import { findArticle, type LibraryArticle } from "@/fsd/entities/article";
import { Notice, CodeBlock, DataTable, ImageFigure, ResourceLink } from "@/fsd/shared/ui";
const dimensions: Record<string,[number,number]>={"/archive-media/svk006-front.jpg":[800,528],"/archive-media/early-kit.jpg":[640,551],"/archive-media/viewer-map.jpg":[1259,850],"/archive-media/certificate.jpg":[200,282],"/archive-media/installation-interior.jpg":[200,150],"/archive-media/installation-block.jpg":[200,150],"/diagrams/svk-signal-chain.svg":[440,870],"/diagrams/svk-road-guard.svg":[440,815],"/diagrams/svk-fleet-channels.svg":[440,1015]};
export function ArticleMeta({ article }: { article: LibraryArticle }) { return <p className="kicker">{article.category} / {article.date}</p>; }
export function ArticleContents({ article }: { article: LibraryArticle }) { return <aside className="contents"><details open><summary>В этом материале</summary><nav aria-label="Содержание статьи">{article.sections.map((s,i)=><a href={"#section-"+i} key={s.heading}>{s.heading}</a>)}</nav></details><a className="contents-tool" href="/tools/recording-time">Расчёт времени записи ↗</a></aside>; }
export function ArticleSection({ section:s, index, idPrefix="section-", headingLevel="h2" }: { section: LibraryArticle["sections"][number]; index:number; idPrefix?:string; headingLevel?:"h2"|"h3" }) {
const Heading=headingLevel;
return <section className="article-section" id={idPrefix+index}><Heading>{s.heading}</Heading>{s.paragraphs.map(p=><p key={p}>{p}</p>)}
{s.note && <Notice>{s.note}</Notice>}
{s.list && <ol>{s.list.map(v=><li key={v}>{v}</li>)}</ol>}
{s.code && <CodeBlock label={s.heading}>{s.code}</CodeBlock>}
{s.table && <DataTable {...s.table} />}
{s.figure && <ImageFigure {...s.figure} width={dimensions[s.figure.src]?.[0]} height={dimensions[s.figure.src]?.[1]} />}
{s.gallery && <FrameGallery frames={s.gallery} />}
{s.links && <ul className="document-links">{s.links.map(l=><li key={l.href}><ResourceLink href={l.href} label={l.label} /></li>)}</ul>}
</section>;
}
export function RelatedReading({ paths }: { paths: string[] }) { return <nav className="related-reading" aria-label="Связанные материалы"><h2>Продолжить разбор</h2>{paths.map(path=><a key={path} href={path}>{findArticle(path)?.title??"Калькулятор времени записи"}<span>→</span></a>)}</nav>; }
@@ -0,0 +1,5 @@
import type { LibraryArticle } from "@/fsd/entities/article";
import { ArticleMeta, ArticleContents, ArticleSection, RelatedReading } from "./parts";
export function ArticleReader({ article:a }: { article: LibraryArticle }) {
return <main className={"reading-page"+(a.path==="/catalog"?" equipment-page":"")} id="main-content"><div className="article-heading"><a className="back-link" href="/library">← К библиотеке</a><ArticleMeta article={a} /><h1>{a.title}</h1><p className="lede">{a.summary}</p></div><div className="reading-layout"><ArticleContents article={a} /><article className="article-body">{a.sections.map((s,i)=><ArticleSection key={s.heading} section={s} index={i} />)}<RelatedReading paths={a.related} /></article></div></main>;
}
@@ -0,0 +1,9 @@
import type { ReactNode } from "react";
import { Brand } from "@/fsd/shared/ui";
import { AnalyticsTag } from "@/fsd/features/analytics";
import { ThemeSwitch } from "@/fsd/features/theme-choice";
export function SiteShell({ children }: { children: ReactNode }) {
return <><AnalyticsTag /><a className="skip" href="#main-content">Перейти к содержимому</a>
<header className="masthead"><Brand /><nav aria-label="Основная навигация"><a href="/catalog">Системы</a><a href="/down.shtml">Инструкции</a><a href="/support.shtml">Камеры</a><a href="/samples.shtml">Записи</a><a href="/library">Поиск</a></nav><ThemeSwitch idPrefix="site" /></header>
{children}<footer className="footer"><div><Brand /><p>От системы — к исходному кадру.</p></div><nav aria-label="Навигация внизу страницы"><a href="/library">Вся библиотека</a><a href="/tools/recording-time">Расчёт записи</a><a href="/about">О библиотеке</a><a href="/sources">Источники и редакция</a><a href="/privacy">Приватность</a><a href="/ui-kit">UI kit</a></nav><p>Исторические системы СВК.<br />Документ, устройство, запись.</p></footer></>;
}