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

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><rect width="16" height="16" fill="#112c43"/><path d="M0 5h1v5H0zM15 5h1v5h-1z" fill="#f9fbfc"/><path d="M2 3h12v9H2z" fill="#f3933d"/><path d="M4 5h8v5H4z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 262 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" fill="#112c43"/><path d="M0 11h2v10H0zM30 11h2v10h-2z" fill="#f9fbfc"/><path d="M4 7h24v18H4z" fill="#f3933d"/><path d="M8 11h16v10H8z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><rect width="48" height="48" fill="#112c43"/><path d="M0 16h3v15H0zM45 16h3v15h-3z" fill="#f9fbfc"/><path d="M6 10h36v27H6z" fill="#f3933d"/><path d="M12 16h24v15H12z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 273 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><rect width="16" height="16" fill="#112c43"/><path d="M0 5h1v5H0zM15 5h1v5h-1z" fill="#f9fbfc"/><path d="M2 3h12v9H2z" fill="#f3933d"/><path d="M4 5h8v5H4z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 262 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" fill="#112c43"/><path d="M0 11h2v10H0zM30 11h2v10h-2z" fill="#f9fbfc"/><path d="M4 7h24v18H4z" fill="#f3933d"/><path d="M8 11h16v10H8z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><rect width="48" height="48" fill="#112c43"/><path d="M0 16h3v15H0zM45 16h3v15h-3z" fill="#f9fbfc"/><path d="M6 10h36v27H6z" fill="#f3933d"/><path d="M12 16h24v15H12z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 273 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="275" height="64" viewBox="0 0 275 64" role="img" aria-labelledby="title"><title id="title">Videoreg</title><g transform="translate(0 8) scale(1.5)"><rect width="32" height="32" rx="6" fill="#e9eee5"/><path d="M7 7h18v18H7z" fill="none" stroke="#17382f" stroke-width="2"/><path d="M4 12v16h16" fill="none" stroke="#17382f" stroke-width="2"/><circle cx="21" cy="11" r="2" fill="#9d4820"/></g><text x="64" y="44" fill="#f5f2e9" font-family="Georgia,Times New Roman,serif" font-size="43" font-weight="700" letter-spacing="-1.5">videoreg</text></svg>

After

Width:  |  Height:  |  Size: 592 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="275" height="64" viewBox="0 0 275 64" role="img" aria-labelledby="title"><title id="title">Videoreg</title><g transform="translate(0 8) scale(1.5)"><rect width="32" height="32" rx="6" fill="#17382f"/><path d="M7 7h18v18H7z" fill="none" stroke="#fffef9" stroke-width="2"/><path d="M4 12v16h16" fill="none" stroke="#fffef9" stroke-width="2"/><circle cx="21" cy="11" r="2" fill="#efbf78"/></g><text x="64" y="44" fill="#17382f" font-family="Georgia,Times New Roman,serif" font-size="43" font-weight="700" letter-spacing="-1.5">videoreg</text></svg>

After

Width:  |  Height:  |  Size: 592 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" fill="#112c43"/><path d="M0 11h2v10H0zM30 11h2v10h-2z" fill="#f9fbfc"/><path d="M4 7h24v18H4z" fill="#f3933d"/><path d="M8 11h16v10H8z" fill="#112c43"/></svg>

After

Width:  |  Height:  |  Size: 270 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 32 32"><title>Videoreg — кадр СВК</title><rect width="32" height="32" fill="#112c43"/><g transform="translate(4.625 4.625) scale(0.7109375)"><path d="M0 11h2v10H0zM30 11h2v10h-2z" fill="#f9fbfc"/><path d="M4 7h24v18H4z" fill="#f3933d"/><path d="M8 11h16v10H8z" fill="#112c43"/></g></svg>

After

Width:  |  Height:  |  Size: 374 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 32 32"><title>Videoreg — кадр СВК</title><rect width="32" height="32" fill="#112c43"/><g transform="translate(4.625 4.625) scale(0.7109375)"><path d="M0 11h2v10H0zM30 11h2v10h-2z" fill="#f9fbfc"/><path d="M4 7h24v18H4z" fill="#f3933d"/><path d="M8 11h16v10H8z" fill="#112c43"/></g></svg>

After

Width:  |  Height:  |  Size: 374 B

+79
View File
@@ -0,0 +1,79 @@
/* Videoreg analytics: one existing counter, public hosts only, no query payloads. */
(function () {
"use strict";
if (!/^(www\.)?videoreg\.ru$/.test(window.location.hostname) || window.__videoregMetrika) return;
window.__videoregMetrika = true;
var counter = 109268682;
window.ym = window.ym || function () { (window.ym.a = window.ym.a || []).push(arguments); };
window.ym.l = Number(new Date());
var tag = document.createElement("script");
tag.async = true;
tag.src = "https://mc.yandex.ru/metrika/tag.js";
document.head.appendChild(tag);
window.ym(counter, "init", {
webvisor: false, clickmap: true, trackLinks: true,
accurateTrackBounce: true, trackHash: false
});
function goal(name, params) { window.ym(counter, "reachGoal", name, params); }
var problems = new Set();
function problem(kind) {
if (problems.has(kind)) return;
problems.add(kind);
goal("content_problem", { problem: kind });
}
// Only actual, enabled document/ZIP downloads; a click does not imply success.
document.addEventListener("click", function (event) {
var link = event.target instanceof Element ? event.target.closest("a[href]") : null;
if (!link || event.defaultPrevented || link.getAttribute("aria-disabled") === "true") return;
var url = new URL(link.href, window.location.href);
if (url.origin !== window.location.origin) return;
if (/^\/(manuals|download)\//.test(url.pathname) && /\.(pdf|zip)$/i.test(url.pathname)) goal("download_click");
if (link.closest(".related-reading")) goal("related_content_click");
var queryInput = document.querySelector("#library-query");
if (link.closest(".search-results") && queryInput && queryInput.value.trim()) goal("search_used");
});
document.addEventListener("keydown", function (event) {
if (event.key === "Enter" && !event.isComposing && !event.repeat && event.target.id === "library-query" && event.target.value.trim()) goal("search_used");
});
document.addEventListener("videoreg:search-zero-results", function () { goal("search_zero_results"); });
function fragment() {
var id;
try { id = decodeURIComponent(window.location.hash.slice(1).split(":~:")[0]); } catch (_) { return; }
if (id && !document.getElementById(id) && !document.getElementsByName(id).length) problem("missing_fragment");
}
function imageFailed(image) {
if (image instanceof HTMLImageElement && image.closest("main") && image.getAttribute("src")) problem("image_failed");
}
document.addEventListener("error", function (event) { imageFailed(event.target); }, true);
if (document.querySelector("main.not-found")) problem("not_found");
document.querySelectorAll("main img").forEach(function (image) {
if (image.complete && image.naturalWidth === 0) imageFailed(image);
});
if (document.readyState === "complete") fragment();
else window.addEventListener("load", fragment, { once: true });
window.addEventListener("hashchange", fragment);
var article = document.querySelector("article.article-body");
if (!article) return;
var visibleMs = 0, depth = 0, sent = false, last = performance.now();
var active = document.visibilityState === "visible" && document.hasFocus();
function sample() {
var now = performance.now();
var nextActive = document.visibilityState === "visible" && document.hasFocus();
// Conservative cap avoids counting background/throttled gaps as reading.
if (active && nextActive) visibleMs += Math.min(now - last, 1500);
last = now; active = nextActive;
if (nextActive) {
var rect = article.getBoundingClientRect();
if (rect.height > 0) depth = Math.max(depth, Math.min(1, (window.innerHeight - rect.top) / rect.height));
}
if (!sent && visibleMs >= 60000 && depth >= 0.75) {
sent = true; goal("engaged_read"); clearInterval(timer);
}
}
var timer = setInterval(sample, 1000);
window.addEventListener("scroll", sample, { passive: true });
window.addEventListener("focus", sample);
window.addEventListener("blur", sample);
document.addEventListener("visibilitychange", sample);
})();
+39
View File
@@ -0,0 +1,39 @@
/* Blocking, same-origin bootstrap: keep this before body paint. */
(function () {
'use strict';
var key = 'videoreg-theme';
var root = document.documentElement;
var media = typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-color-scheme: dark)') : null;
function valid(value) { return value === 'light' || value === 'dark' || value === 'system'; }
function read() { try { var value = localStorage.getItem(key); return valid(value) ? value : 'system'; } catch (_) { return 'system'; } }
var choice = read();
function apply() {
var resolved = choice === 'system' ? (media && media.matches ? 'dark' : 'light') : choice;
root.dataset.theme = resolved;
root.dataset.themeChoice = choice;
root.style.colorScheme = resolved;
window.dispatchEvent(new CustomEvent('videoreg:theme-change'));
}
window.videoregTheme = {
get: function () { return choice; },
set: function (value) {
if (!valid(value)) return;
choice = value;
try { localStorage.setItem(key, choice); } catch (_) { /* Session choice still works. */ }
apply();
}
};
function osChanged() { if (choice === 'system') apply(); }
if (media) {
if (media.addEventListener) media.addEventListener('change', osChanged);
else if (media.addListener) media.addListener(osChanged);
}
window.addEventListener('storage', function (event) {
if (event.key !== key && event.key !== null) return;
// Ignore sessionStorage events; inaccessible storage must not break rendering.
try { if (event.storageArea && event.storageArea !== localStorage) return; } catch (_) { return; }
choice = read();
apply();
});
apply();
}());
+8 -164
View File
@@ -1,172 +1,16 @@
import { notFound } from "next/navigation";
import FrameGallery from "@/components/FrameGallery";
import { articles, findArticle } from "@/content/library";
import { articles, findArticle } from "@/fsd/entities/article";
import { ArticlePage } from "@/fsd/pages/article";
export const dynamicParams = false;
export function generateStaticParams() {
return articles.map((a) => ({ slug: a.path.slice(1).split("/") }));
}
export async function generateMetadata({
params,
}: {
params: Promise<{ slug: string[] }>;
}) {
export function generateStaticParams() { return articles.map(a => ({ slug: a.path.slice(1).split("/") })); }
export async function generateMetadata({ params }: { params: Promise<{ slug: string[] }> }) {
const { slug } = await params;
const a = findArticle("/" + slug.join("/"));
return { title: a?.title, description: a?.summary };
}
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 default async function Page({
params,
}: {
params: Promise<{ slug: string[] }>;
}) {
export default async function Page({ params }: { params: Promise<{ slug: string[] }> }) {
const { slug } = await params;
const a = findArticle("/" + slug.join("/"));
if (!a) notFound();
return (
<main className="reading-page" id="main-content">
<div className="article-heading">
<a className="back-link" href="/library">
← К библиотеке
</a>
<p className="kicker">
{a.category} / {a.date}
</p>
<h1>{a.title}</h1>
<p className="lede">{a.summary}</p>
</div>
<div className="reading-layout">
<aside className="contents">
<details open>
<summary>В этом материале</summary>
<nav aria-label="Содержание статьи">
{a.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>
<article className="article-body">
{a.sections.map((s, i) => (
<section id={"section-" + i} key={s.heading}>
<h2>{s.heading}</h2>
{s.paragraphs.map((p) => (
<p key={p}>{p}</p>
))}
{s.list && (
<ol>
{s.list.map((v) => (
<li key={v}>{v}</li>
))}
</ol>
)}
{s.note && <aside className="reading-note">{s.note}</aside>}
{s.code && (
<pre tabIndex={0}>
<code>{s.code}</code>
</pre>
)}
{s.table && (
<div
className="table-region"
tabIndex={0}
role="region"
aria-label={s.table.caption}
>
<table>
<caption>{s.table.caption}</caption>
<thead>
<tr>
{s.table.head.map((h) => (
<th scope="col" key={h}>
{h}
</th>
))}
</tr>
</thead>
<tbody>
{s.table.rows.map((row, j) => (
<tr key={j}>
{row.map((value, k) =>
k === 0 ? (
<th scope="row" key={k}>
{value}
</th>
) : (
<td key={k}>{value}</td>
),
)}
</tr>
))}
</tbody>
</table>
</div>
)}
{s.figure && (
<figure
className={
s.figure.diagram
? "content-figure diagram"
: s.figure.small
? "content-figure small-figure"
: "content-figure"
}
>
<a
href={s.figure.src}
aria-label={"Открыть изображение: " + s.figure.alt}
>
<img
src={s.figure.src}
alt={s.figure.alt}
width={dimensions[s.figure.src]?.[0]}
height={dimensions[s.figure.src]?.[1]}
loading="lazy"
/>
</a>
<figcaption>{s.figure.caption}</figcaption>
</figure>
)}
{s.gallery && <FrameGallery frames={s.gallery} />}{" "}
{s.links && (
<ul className="document-links">
{s.links.map((l) => (
<li key={l.href}>
<a href={l.href} rel={l.href.startsWith("https://") ? "noreferrer" : undefined}>{l.label} ↗</a>
</li>
))}
</ul>
)}
</section>
))}
<nav className="related-reading" aria-label="Связанные материалы">
<h2>Продолжить разбор</h2>
{a.related.map((path) => {
const other = findArticle(path);
return (
<a key={path} href={path}>
{other?.title ?? "Калькулятор времени записи"} <span>→</span>
</a>
);
})}
</nav>
</article>
</div>
</main>
);
const article = findArticle("/" + slug.join("/"));
if (!article) notFound();
return <ArticlePage article={article} />;
}
+2 -43
View File
@@ -1,44 +1,3 @@
import { AboutPage } from "@/fsd/pages/about";
export const metadata = { title: "О технической библиотеке" };
export default function About() {
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>
);
}
export default AboutPage;
+2 -31
View File
@@ -1,32 +1,3 @@
import { articles } from "@/content/library";
import { CommunityPage } from "@/fsd/pages/community";
export const metadata = { title: "Технические разборы СВК" };
export default function Page() {
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) => (
<a href={a.path} key={a.path}>
<span className="search-kind">Обсуждение · {a.date}</span>
<h2>{a.title}</h2>
<p>{a.summary}</p>
<span>↗</span>
</a>
))}
</div>
<p style={{ marginTop: 32 }}>
<a href="/faq.shtml">Также: ответы по конструкции и настройке →</a>
</p>
</main>
);
}
export default CommunityPage;
Binary file not shown.

After

Width:  |  Height:  |  Size: 617 B

+1 -1
View File
@@ -1,4 +1,4 @@
import { NextResponse } from 'next/server';
import { articles } from '@/content/library';
import { articles } from '@/fsd/entities/article';
export const dynamic='force-static';
export async function GET(){return NextResponse.json({status:'ok',service:'videoreg-web',edition:'rebuild-v2-limited',restorationComplete:false,articles:articles.length,metadata:{commitSha:process.env.COMMIT_SHA??'local-v2'}})}
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="8" fill="#17382f"/><rect x="9" y="18" width="46" height="30" rx="3" fill="#f5f2e9"/><rect x="16" y="26" width="13" height="6" rx="1" fill="#17382f"/><rect x="16" y="36" width="13" height="6" rx="1" fill="#17382f"/><path d="M37 24v19h13V24z" fill="#d8894b"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><title>Videoreg — покадровая запись СВК</title><rect width="32" height="32" fill="#112c43"/><path d="M0 11h2v10H0zM30 11h2v10h-2z" fill="#f9fbfc"/><path d="M4 7h24v18H4z" fill="#f3933d"/><path d="M8 11h16v10H8z" fill="#112c43"/></svg>

Before

Width:  |  Height:  |  Size: 356 B

After

Width:  |  Height:  |  Size: 338 B

+7 -47
View File
@@ -1,53 +1,13 @@
import type { Metadata } from "next";
import "./library.css";
import { SiteShell } from "@/fsd/widgets/site-shell";
import "@/fsd/shared/styles/tokens.css";
import "@/fsd/shared/styles/library.css";
export const metadata: Metadata = {
metadataBase: new URL("https://videoreg.ru"),
title: {
default: "Videoreg — техническая библиотека СВК",
template: "%s · Videoreg",
},
description:
"Устройство видеорегистраторов СВК, оригинальные инструкции, таблицы камер и работа с покадровой записью JPEG.",
title: { default: "Videoreg — техническая библиотека СВК", template: "%s · Videoreg" },
description: "Устройство видеорегистраторов СВК, оригинальные инструкции, таблицы камер и работа с покадровой записью JPEG.",
icons: { icon: [{ url: "/brand/icon-light-32.png", sizes: "32x32", type: "image/png" }, { url: "/brand/icon-light-512.png", sizes: "512x512", type: "image/png" }], apple: [{ url: "/brand/icon-light-180.png", sizes: "180x180", type: "image/png" }] }
};
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="ru">
<body>
<a className="skip" href="#main-content">
Перейти к содержимому
</a>
<header className="masthead">
<a className="wordmark" href="/">
videoreg<span>ТЕХНИЧЕСКАЯ БИБЛИОТЕКА</span>
</a>
<nav aria-label="Основная навигация">
<a href="/library">Материалы и поиск</a>
<a href="/catalog">Оборудование</a>
<a href="/down.shtml">Инструкции</a>
<a href="/tools/recording-time">Расчёт записи</a>
</nav>
<span className="masthead-index">СВК / JPEG / FLASH</span>
</header>
{children}
<footer className="footer">
<div>
<a className="wordmark" href="/">
videoreg
</a>
<p>Камера → кадр → носитель.</p>
</div>
<nav aria-label="Навигация внизу страницы">
<a href="/library">Вся библиотека</a>
<a href="/about">О библиотеке</a>
<a href="/faq.shtml">Вопросы по СВК</a>
</nav>
<p>
Документация и практика
<br />
работы с записью.
</p>
</footer>
</body>
</html>
);
return <html lang="ru" suppressHydrationWarning><head><script src="/theme.js" /></head><body><SiteShell>{children}</SiteShell></body></html>;
}
File diff suppressed because it is too large. Load diff
+1 -96
View File
@@ -1,96 +1 @@
"use client";
import { useState } from "react";
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 }: { entries: Entry[] }) {
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),
),
);
return (
<>
<div className="search-panel">
<label htmlFor="library-query">Найти в материалах</label>
<div className="query-row">
<input
id="library-query"
type="search"
placeholder="Например: GPS, USB или резервная копия"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button
type="button"
onClick={() => {
setQuery("");
setCategory("Все темы");
}}
>
Сбросить
</button>
</div>
<label htmlFor="library-category">Раздел</label>
<select
id="library-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) => (
<a href={a.path} key={a.path}>
<span className="search-kind">
{a.category} · {a.date}
</span>
<h2>{a.title}</h2>
<p>{a.summary}</p>
<span aria-hidden="true">↗</span>
</a>
))}
</div>
{found.length === 0 && (
<div className="empty">
<h2>Такого сочетания пока нет</h2>
<p>
Попробуйте название модели, «карта», «кадры» или уберите фильтр
раздела.
</p>
<button
onClick={() => {
setQuery("");
setCategory("Все темы");
}}
>
Показать все материалы
</button>
</div>
)}
</>
);
}
export { Search as default } from "@/fsd/features/library-search";
+2 -17
View File
@@ -1,18 +1,3 @@
import { searchIndex } from "@/content/library";
import Search from "./Search";
import { LibraryPage } from "@/fsd/pages/library";
export const metadata = { title: "Все материалы и поиск" };
export default function Page() {
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>
);
}
export default LibraryPage;
+2 -21
View File
@@ -1,21 +1,2 @@
export default function NotFound() {
return (
<main id="main-content" className="not-found">
<p className="kicker">404 / СТРАНИЦА НЕ НАЙДЕНА</p>
<h1>
По этому адресу
<br />
материала нет.
</h1>
<p>
Проверьте адрес или найдите модель, камеру и нужную тему в библиотеке.
</p>
<div>
<a className="button" href="/library">
Искать в материалах ↗
</a>
<a href="/">На главную →</a>
</div>
</main>
);
}
import { NotFoundPage } from "@/fsd/pages/not-found";
export default NotFoundPage;
+2 -143
View File
@@ -1,143 +1,2 @@
import { articles } from "@/content/library";
export default function Home() {
const paths = [
"/system",
"/auto.shtml",
"/faq.shtml",
"/support.shtml",
"/down.shtml",
"/samples.shtml",
];
return (
<main id="main-content">
<section className="home-intro">
<div className="intro-copy">
<p className="kicker">БИБЛИОТЕКА СИСТЕМ ВИДЕОРЕГИСТРАЦИИ</p>
<h1>
Разобраться
<br />в устройстве.
<br />
<em>Сохранить запись.</em>
</h1>
<p className="lede">
СВК — камеры отдельно, кадры на съёмном носителе. Здесь собраны
устройство системы, инструкции, совместимость и разборы работы с
файлами.
</p>
<a className="button" href="/system">
Как устроена система <span>↗</span>
</a>
</div>
<figure className="intro-figure">
<span className="figure-label">ОБОРУДОВАНИЕ / СВК-006</span>
<img
src="/archive-media/svk006-front.jpg"
alt="Передняя панель системного блока СВК-006: USB A и B, слот SD CARD и индикаторы."
width="800"
height="528"
fetchPriority="high"
/>
<figcaption>
<span>01 / Системный блок</span>
<p>
Камеры подключаются по USB.
<br />
Изображения сохраняются на карту.
</p>
</figcaption>
</figure>
</section>
<section className="home-path">
<span className="kicker">С ЧЕГО НАЧАТЬ</span>
<a href="/system">
<b>01</b> Устройство и поколения
</a>
<a href="/auto.shtml">
<b>02</b> Работа в автомобиле
</a>
<a href="/down.shtml">
<b>03</b> Инструкция своего блока
</a>
<a href="/samples.shtml">
<b>04</b> Кадры и просмотр
</a>
</section>
<section className="home-library">
<div className="section-title">
<div>
<p className="kicker">НА ПОЛКЕ</p>
<h2>Документация, которую можно открыть</h2>
</div>
<a href="/library">Все {articles.length} материалов и поиск →</a>
</div>
<div className="book-grid">
{paths.map((path, i) => {
const a = articles.find((a) => a.path === path)!;
return (
<a className="book" href={path} key={path}>
<span className="book-top">
{a.category}
<span>{String(i + 1).padStart(2, "0")}</span>
</span>
<h3>{a.title}</h3>
<p>{a.summary}</p>
<span className="book-bottom">
{a.date}
<span aria-hidden="true">↗</span>
</span>
</a>
);
})}
</div>
</section>
<section className="home-workbench">
<div>
<p className="kicker">РАБОЧИЙ ИНСТРУМЕНТ</p>
<h2>
Вместо обещания
<br />
«карты хватит надолго»
</h2>
<p>
Посчитайте время по реальному размеру JPEG и частоте кадров. Для
видеопотока есть отдельный режим по битрейту.
</p>
<a className="button" href="/tools/recording-time">
Оценить длительность записи ↗
</a>
</div>
<div className="formula-note">
<span>ПОКАДРОВАЯ ЗАПИСЬ</span>
<code>
объём × (1 − резерв/100)
<br />÷<br />
(размер кадра × кадров/с × камер)
</code>
<p>
Число камер и резерв места
<br />
тоже участвуют в расчёте.
</p>
</div>
</section>
<section className="home-case">
<div>
<p className="kicker">ИЗ ПРАКТИКИ</p>
<h2>Не только характеристики</h2>
<p>
Почему прибор долго запускается с FLASH и что известно о
нестабильной камере с удлинителем.
</p>
</div>
<div>
<a href="/community/flash-start">
FLASH не выходит в рабочий режим <span>↗</span>
</a>
<a href="/community/usb-extension">
Камера и USB-удлинитель <span>↗</span>
</a>
</div>
</section>
</main>
);
}
import { HomePage } from "@/fsd/pages/home";
export default HomePage;
+3
View File
@@ -0,0 +1,3 @@
import { PrivacyPage } from "@/fsd/pages/services";
export const metadata = { title: "Приватность и аналитика" };
export default PrivacyPage;
+3
View File
@@ -0,0 +1,3 @@
import { SourcesPage } from "@/fsd/pages/services";
export const metadata = { title: "Источники и редакционный подход" };
export default SourcesPage;
@@ -1,168 +1 @@
"use client";
import { useState } from "react";
export default function Calculator() {
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="recording-mode"
value="frames"
checked={mode === "frames"}
onChange={() => setMode("frames")}
/>{" "}
JPEG-кадры
</label>
<label>
<input
type="radio"
name="recording-mode"
value="stream"
checked={mode === "stream"}
onChange={() => setMode("stream")}
/>{" "}
Видеопоток
</label>
</fieldset>
<div className="calculation-layout">
<div className="input-fields">
<label>
Ёмкость носителя, ГБ
<input
type="number"
min="0.001"
max="100000"
step="any"
value={capacity}
onChange={(e) => setCapacity(e.target.value)}
/>
</label>
{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
? "До перезаписи старейших файлов при заданных условиях."
: "Нужны положительные размеры и скорость; камеры — целое число от 1 до 16, резерв — от 0 до 99%."}
</p>
<small>
{mode === "frames"
? "Размер кадра × частота × число камер"
: "Сумма битрейтов всех камер"}
</small>
</div>
</div>
</>
);
}
export { Calculator as default } from "@/fsd/features/recording-estimate";
@@ -1,69 +1,5 @@
import Calculator from "./Calculator";
import { RecordingToolPage } from "@/fsd/pages/recording-tool";
export const metadata = {
title: "Расчёт длительности записи — JPEG и видеопоток",
};
export default function Page() {
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>
<pre tabIndex={0}>
<code>
Время, с = ГБ × 1 000 000 × (1 − резерв/100) ÷ (КБ/кадр × кадров/с
× камер)
</code>
</pre>
</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>
);
}
export default RecordingToolPage;
+3
View File
@@ -0,0 +1,3 @@
import { UiKitPage } from "@/fsd/pages/ui-kit";
export const metadata = { title: "Элементы интерфейса библиотеки" };
export default UiKitPage;
+1 -37
View File
@@ -1,37 +1 @@
"use client";
import { useState } from "react";
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>
);
}
export { FrameGallery as default } from "@/fsd/features/frame-gallery";
+3 -100
View File
@@ -1,100 +1,3 @@
import { z } from "zod";
import recovered from "./v2-articles.json";
import community from "./v2-community.json";
import externalApprovals from "./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);
}
}
// Compatibility API; active domain ownership is fsd/entities/article.
export { articles, findArticle, articleText, searchIndex } from "@/fsd/entities/article";
export type { LibraryArticle } from "@/fsd/entities/article";
@@ -83,5 +83,22 @@
"playbackWatched": false
},
"reason": "Specific original technical demonstration, not a paid insertion; direct link only, no remote player/script/pixel loaded by this site."
},
{
"sourcePage": "/metrika.js",
"destination": "https://mc.yandex.ru/metrika/tag.js",
"anchor": "nction () { (window.ym.a = window.ym.a || []).push(arguments); };\n window.ym.l = Number(new Date());\n var tag = document.createElement(\"script\");\n tag.async = true;\n tag.src = \"https://mc.yandex.ru/metrika/tag.js\";\n document.head.appendChild(tag);\n window.ym(counter, \"init\", {\n webvisor: false, clickmap: true, trackLinks: true,\n accurateTrackBounce: true, trackHash: false\n });\n fu",
"purpose": "Authorized first-party integration of existing counter109268682; one async official vendor tag on exactpublichosts only",
"decision": "keep",
"reviewed": true,
"verification": {
"method": "ActualofficialYandexinitialization+CSPdocs andsourcehostguard review",
"officialDocs": [
"https://yandex.com/support/metrica/en/code/counter-initialize",
"https://yandex.ru/support/metrica/ru/code/install-counter-csp"
],
"projectContract": "docs/metrika/counters-and-contract.json"
},
"reason": "Authorized analytics infrastructure, not recovered editorial content; webvisorfalse/default15s accuratebounce/noextra hit, no customquery or PII; localhost disabled. Runtime request interception tested separately."
}
]
+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></>;
}
+77
View File
@@ -0,0 +1,77 @@
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
const code = readFileSync('web-front/public/metrika.js', 'utf8');
function browser(options: { host?: string; article?: boolean; notFound?: boolean; hash?: string } = {}) {
const handlers: Record<string, ((event?: any) => void)[]> = {};
let now = 0, focused = true, visibility = 'visible', top = 0;
const tags: any[] = [];
const nodes = new Set<string>();
const article = { getBoundingClientRect: () => ({ top, height: 4000 }) };
const document = {
head: { appendChild: (node: any) => tags.push(node) },
createElement: () => ({}), readyState: 'complete',
get visibilityState() { return visibility; }, hasFocus: () => focused,
querySelector: (selector: string) => selector === 'article.article-body' ? (options.article ? article : null) : selector === 'main.not-found' && options.notFound ? {} : null,
querySelectorAll: () => [], getElementById: (id: string) => nodes.has(id) ? {} : null,
getElementsByName: () => [], addEventListener: (name: string, fn: any) => (handlers[name] ||= []).push(fn),
};
const window: any = { location: { hostname: options.host ?? 'videoreg.ru', href: 'https://videoreg.ru/a', origin: 'https://videoreg.ru', hash: options.hash ?? '' }, innerHeight: 800, addEventListener: document.addEventListener };
let tick: any;
class FakeElement {}
const context = vm.createContext({ window, document, performance: { now: () => now }, setInterval: (fn: any) => { tick = fn; return 1; }, clearInterval: () => {}, Element: FakeElement, HTMLImageElement: class {}, URL, Set, Date });
vm.runInContext(code, context);
const calls = () => Array.from(window.ym?.a ?? [], (args: any) => Array.from(args));
const goals = () => calls().filter((args: any) => args[1] === 'reachGoal');
return { tags, calls, goals, again: () => vm.runInContext(code, context), nodes,
clickResultWithoutQuery: () => {
const link = { href: 'https://videoreg.ru/system', getAttribute: () => null, closest: (selector: string) => selector === '.search-results' ? {} : null };
const target = Object.assign(new FakeElement(), { closest: () => link });
handlers.click?.forEach(fn => fn({ target, defaultPrevented: false }));
},
step: (ms = 1000) => { now += ms; tick?.(); },
focus: (value: boolean) => { focused = value; handlers[value ? 'focus' : 'blur']?.forEach(fn => fn()); },
visible: (value: boolean) => { visibility = value ? 'visible' : 'hidden'; handlers.visibilitychange?.forEach(fn => fn()); },
depth: (value: number) => { top = 800 - value * 4000; handlers.scroll?.forEach(fn => fn()); },
};
}
describe('public-host-only Metrica and honest engagement', () => {
it.each(['localhost', '127.0.0.1', 'preview.videoreg.ru', 'videoreg.ru.attacker.test'])('sends nothing on %s', host => {
const b = browser({ host }); expect(b.tags).toHaveLength(0); expect(b.calls()).toHaveLength(0);
});
it.each(['videoreg.ru', 'www.videoreg.ru'])('initializes exactly once on %s with default bounce and no replay', host => {
const b = browser({ host }); b.again(); expect(b.tags).toHaveLength(1);
expect(b.calls()).toHaveLength(1);
expect(b.calls()[0]).toEqual([109268682, 'init', { accurateTrackBounce: true, webvisor: false, clickmap: true, trackLinks: true, trackHash: false }]);
expect(b.tags[0]).toEqual({ async: true, src: 'https://mc.yandex.ru/metrika/tag.js' });
});
it('does not crash or invent search_used on community/demo result cards without search input', () => {
const b = browser(); expect(() => b.clickResultWithoutQuery()).not.toThrow(); expect(b.goals()).toHaveLength(0);
});
it('requires BOTH 60 visible focused seconds and 75 percent article depth, once', () => {
const b = browser({ article: true });
for (let i = 0; i < 61; i++) b.step(); expect(b.goals()).toHaveLength(0);
b.depth(.74); expect(b.goals()).toHaveLength(0);
b.depth(.75); expect(b.goals()).toEqual([[109268682, 'reachGoal', 'engaged_read', undefined]]);
for (let i = 0; i < 61; i++) b.step(); expect(b.goals()).toHaveLength(1);
});
it('does not count hidden, unfocused or long throttled gaps as full reading time', () => {
const b = browser({ article: true }); b.depth(1); b.visible(false);
for (let i = 0; i < 120; i++) b.step(); b.visible(true); b.focus(false);
for (let i = 0; i < 120; i++) b.step(); b.focus(true); b.step(120000);
expect(b.goals()).toHaveLength(0);
for (let i = 0; i < 58; i++) b.step(); expect(b.goals()).toHaveLength(0);
b.step(); expect(b.goals()).toHaveLength(1);
});
it('does not synthesize reading on non-articles; confirmed404 is diagnostic only', () => {
const b = browser({ notFound: true }); for (let i = 0; i < 100; i++) b.step();
expect(b.goals()).toEqual([[109268682, 'reachGoal', 'content_problem', { problem: 'not_found' }]]);
expect(b.calls().some((args: any) => ['hit', 'notBounce'].includes(args[1]))).toBe(false);
});
it('diagnoses a nonempty missing fragment, excluding browser text fragments and malformed encoding', () => {
expect(browser({ hash: '#absent' }).goals()).toEqual([[109268682, 'reachGoal', 'content_problem', { problem: 'missing_fragment' }]]);
expect(browser({ hash: '#:~:text=hello' }).goals()).toHaveLength(0);
expect(browser({ hash: '#%XX' }).goals()).toHaveLength(0);
expect(browser().goals()).toHaveLength(0);
});
});