Implement ProgCode identity and real shared reading UI kit
Build and deploy / deploy (push) Successful in 2m39s

This commit is contained in:
huncode committed 2026-10-27 15:19:49 +03:00
1 parent 99c848189e
commit 12562baeb5
2040 files changed
+184656 -181

No files matched your search

@@ -0,0 +1,5 @@
export {getArticles,getArticleBySlug,getArticleSummaries} from './model/articles';
export {formatDate} from '../../shared/lib';
export {ArticleMeta} from './ui/ArticleMeta';
export {ArticleListItem} from './ui/ArticleListItem';
export {ArticleFigure} from './ui/ArticleFigure';
@@ -0,0 +1,4 @@
import articles from '../../../../data/articles.json';
export function getArticles(){return articles;}
export function getArticleBySlug(slug){return articles.find(article=>article.slug===slug);}
export function getArticleSummaries(){return articles.map(({slug,title,date,excerpt,categories,readingMinutes})=>({slug,title,date,excerpt,categories,readingMinutes}));}
@@ -0,0 +1,3 @@
export function ArticleFigure({src,alt,caption,className='',loading='lazy',width,height,...props}){
return <figure className={['article-figure',className].filter(Boolean).join(' ')}><img {...props} src={src} alt={alt} width={width} height={height} loading={loading} decoding="async"/>{caption&&<figcaption>{caption}</figcaption>}</figure>;
}
@@ -0,0 +1,6 @@
import Link from 'next/link';
import {Tag} from '../../../shared/ui';
import {formatDate} from '../../../shared/lib';
export function ArticleListItem({article,onSelect,shortDate=true}){
return <article className="index-entry"><div className="index-date"><time dateTime={article.date}>{formatDate(article.date,shortDate?{month:'short',day:'numeric'}:undefined)}</time><Tag>{article.categories.join(' · ')}</Tag></div><Link onClick={onSelect} href={'/articles/'+encodeURIComponent(article.slug)+'/'}><h3>{article.title}</h3><p>{article.excerpt}</p></Link>{Number.isFinite(article.readingMinutes)&&article.readingMinutes>0&&<span className="index-duration">{article.readingMinutes} мин <b aria-hidden="true">↗</b></span>}</article>;
}
@@ -0,0 +1,4 @@
import {formatDate} from '../../../shared/lib';
export function ArticleMeta({article,short=false,showAuthor=true,className=''}){
return <div className={['article-meta',className].filter(Boolean).join(' ')}><time dateTime={article.date}>{formatDate(article.date,short?{month:'short',day:'numeric'}:undefined)}</time>{Number.isFinite(article.readingMinutes)&&article.readingMinutes>0&&<span>{article.readingMinutes} мин чтения</span>}{showAuthor&&article.author&&<span>{article.author}</span>}</div>;
}
@@ -0,0 +1,2 @@
export {Metrika} from './ui/Metrika';
export {COUNTER_ID,allowedHost,trackGoal,observePage} from './model/metrika.mjs';
@@ -0,0 +1,93 @@
// Existing counter; custom events never include queries, URLs or personal metadata.
export const COUNTER_ID = 109268613;
const goals = new Set(['engaged_read', 'search_used', 'download_click', 'related_content_click', 'search_zero_results', 'content_problem']);
export function allowedHost() {
return typeof window !== 'undefined' && window.location.protocol === 'https:' &&
(window.location.hostname === 'progcode.ru' || window.location.hostname.endsWith('.progcode.ru'));
}
export function trackGoal(name, reason) {
if (!allowedHost() || !goals.has(name) || typeof window.ym !== 'function') return;
const reasons = ['not_found', 'image_failed', 'fragment_missing'];
if (name === 'content_problem' && reasons.includes(reason)) window.ym(COUNTER_ID, 'reachGoal', name, {reason});
else if (name !== 'content_problem') window.ym(COUNTER_ID, 'reachGoal', name);
}
let started = false;
let previousURL;
let previousPath;
export function observePage() {
if (!allowedHost()) return () => {};
if (!started) {
started = true;
window.ym = window.ym || function () {(window.ym.a = window.ym.a || []).push(arguments);};
window.ym.l = Date.now();
const script = document.createElement('script');
script.async = true;
script.src = 'https://mc.yandex.ru/metrika/tag.js';
document.head.append(script);
window.ym(COUNTER_ID, 'init', {defer: true, clickmap: true, trackLinks: true, accurateTrackBounce: true, webvisor: false, trackHash: false});
}
const missing = !!document.querySelector('main.missing');
const url = missing ? window.location.origin + '/404/' : window.location.href.split('#')[0];
if (window.location.pathname !== previousPath) {
window.ym(COUNTER_ID, 'hit', url, {title: document.title, referer: previousURL || document.referrer});
previousURL = url;
previousPath = window.location.pathname;
}
const problems = new Set();
function problem(reason) {
if (!problems.has(reason)) {problems.add(reason); trackGoal('content_problem', reason);}
}
if (missing) problem('not_found');
const body = document.querySelector('main.article-shell .article-content');
function imageError(event) {
if (event.target instanceof HTMLImageElement && event.target.closest('main.article-shell .article-content') && event.target.getAttribute('src')) problem('image_failed');
}
document.addEventListener('error', imageError, true);
for (const img of body?.querySelectorAll('img') || []) {
if (img.complete && img.naturalWidth === 0 && img.getAttribute('src')) problem('image_failed');
}
function fragment() {
if (!window.location.hash || window.location.hash === '#') return;
let id;
try {id = decodeURIComponent(window.location.hash.slice(1));} catch {problem('fragment_missing'); return;}
if (!document.getElementById(id) && ![...document.getElementsByName(id)].length) problem('fragment_missing');
}
fragment();
window.addEventListener('hashchange', fragment);
function click(event) {
if (!event.isTrusted || event.defaultPrevented || event.button !== 0) return;
const link = event.target.closest?.('a[href]');
if (!link || link.getAttribute('aria-disabled') === 'true') return;
if (link.closest('.related')) trackGoal('related_content_click');
if (link.hasAttribute('download')) trackGoal('download_click');
}
document.addEventListener('click', click, true);
let elapsed = 0, last = performance.now(), active = document.visibilityState === 'visible' && document.hasFocus(), sent = false;
function tick() {
const now = performance.now();
if (active) elapsed += now - last;
last = now;
active = document.visibilityState === 'visible' && document.hasFocus();
if (!body || sent || !active || elapsed < 60000) return;
const rect = body.getBoundingClientRect();
if (rect.height > 0 && (window.innerHeight - rect.top) / rect.height >= 0.75) {
sent = true;
trackGoal('engaged_read');
}
}
const interval = body ? window.setInterval(tick, 1000) : null;
window.addEventListener('scroll', tick, {passive: true});
window.addEventListener('focus', tick);
window.addEventListener('blur', tick);
document.addEventListener('visibilitychange', tick);
return () => {
if (interval !== null) window.clearInterval(interval);
window.removeEventListener('scroll', tick);
window.removeEventListener('focus', tick);
window.removeEventListener('blur', tick);
document.removeEventListener('visibilitychange', tick);
window.removeEventListener('hashchange', fragment);
document.removeEventListener('error', imageError, true);
document.removeEventListener('click', click, true);
};
}
@@ -0,0 +1,5 @@
"use client";
import {useEffect} from 'react';
import {usePathname} from 'next/navigation';
import {observePage} from '../model/metrika.mjs';
export function Metrika(){const pathname=usePathname();useEffect(observePage,[pathname]);return null;}
@@ -0,0 +1 @@
export {ContentAccess} from './ui/ContentAccess';
@@ -0,0 +1,33 @@
"use client";
import {useEffect} from 'react';
import {usePathname} from 'next/navigation';
export function ContentAccess({selector='main.article-shell .article-content, .demo-prose'}){
const pathname=usePathname();
useEffect(()=>{
let alive=true;const regions=new Set();
for(const root of document.querySelectorAll(selector)){
for(const pre of root.querySelectorAll('pre')){
pre.tabIndex=0;pre.setAttribute('role','region');
if(!pre.getAttribute('aria-label'))pre.setAttribute('aria-label','Пример кода, прокрутка клавишами со стрелками');
regions.add(pre);
}
for(const table of root.querySelectorAll('table')){
let region=table.parentElement;
if(!region?.matches('.table-scroll,.scroll-region')){
region=document.createElement('div');region.className='table-scroll scroll-region';table.before(region);region.append(table);
}
region.tabIndex=0;region.setAttribute('role','region');
if(!region.getAttribute('aria-label'))region.setAttribute('aria-label','Таблица, прокрутка клавишами со стрелками');
regions.add(region);
}
}
const measure=()=>{if(alive)for(const region of regions)region.dataset.overflow=String(region.scrollWidth>region.clientWidth+1);};
const observer=typeof ResizeObserver==='function'?new ResizeObserver(measure):null;
for(const region of regions)observer?.observe(region);
measure();window.addEventListener('resize',measure);
document.addEventListener('load',measure,true);
document.fonts?.ready.then(measure);
return()=>{alive=false;observer?.disconnect();window.removeEventListener('resize',measure);document.removeEventListener('load',measure,true);};
},[pathname,selector]);
return null;
}
@@ -0,0 +1 @@
export {JournalSearch} from './ui/JournalSearch';
@@ -0,0 +1,16 @@
"use client";
import {useEffect,useState} from 'react';
import {Button,Field,StatusMessage} from '../../../shared/ui';
import {ArticleListItem} from '../../../entities/article';
export function JournalSearch({articles,onResultSelect,onZeroResults}){
const [q,setQ]=useState(''),[topic,setTopic]=useState('Все');
const topics=['Все',...new Set(articles.flatMap(article=>article.categories))];
const shown=articles.filter(article=>(topic==='Все'||article.categories.includes(topic))&&(article.title+' '+article.excerpt+' '+article.categories.join(' ')).toLocaleLowerCase('ru').includes(q.toLocaleLowerCase('ru')));
useEffect(()=>{
if(!q.trim()||shown.length)return;
const timer=setTimeout(()=>onZeroResults?.(),500);
return()=>clearTimeout(timer);
},[q,shown.length,onZeroResults]);
function reset(){setQ('');setTopic('Все');}
return <section id="journal" className="journal"><div className="journal-heading"><div><p className="kicker">ПОЛНЫЙ ИНДЕКС</p><h2>Статьи и заметки</h2></div><span>{articles.length} материалов</span></div><div className="catalog-controls"><Field id="search" label="Найти в журнале" type="search" value={q} onChange={event=>setQ(event.target.value)} placeholder="Тема, язык или задача"/><div className="topic-tabs" aria-label="Темы">{topics.map(value=><Button variant="secondary" aria-pressed={topic===value} key={value} onClick={()=>setTopic(value)}>{value}</Button>)}</div></div><StatusMessage className="search-status">{shown.length?`Найдено материалов: ${shown.length}`:'По этому запросу ничего нет. Попробуйте другое слово или сбросьте тему.'}</StatusMessage><div className="journal-list">{shown.map(article=><ArticleListItem key={article.slug} article={article} onSelect={event=>{if(event.isTrusted&&q.trim())onResultSelect?.();}}/>)}</div>{!shown.length&&<Button variant="secondary" onClick={reset}>Сбросить поиск</Button>}</section>;
}
@@ -0,0 +1 @@
export {JsonEditor} from './ui/JsonEditor';
@@ -0,0 +1,25 @@
"use client";
import {useRef,useState} from 'react';
import {Button,TextArea,StatusMessage,ScrollRegion} from '../../../shared/ui';
const MAX_INPUT_LENGTH=1000000;
export function JsonEditor({id='json',initialValue='{"project":"ProgCode","ready":true}'}){
const [text,setText]=useState(initialValue),[result,setResult]=useState(''),[state,setState]=useState('empty'),[message,setMessage]=useState(''),[copy,setCopy]=useState('');
const revision=useRef(0);
const statusId=`${id}-status`;
function resetResult(){revision.current+=1;setResult('');setState('empty');setMessage('');setCopy('');}
function change(event){setText(event.target.value);resetResult();}
function run(compact){
revision.current+=1;setCopy('');
if(!text.trim()){setResult('');setState('empty');setMessage('Введите JSON для проверки.');return;}
if(text.length>MAX_INPUT_LENGTH){setResult('');setState('error');setMessage('Слишком длинный фрагмент. Сократите текст перед проверкой.');return;}
try{setResult(JSON.stringify(JSON.parse(text),null,compact?0:2));setState('success');setMessage('JSON корректен');}
catch(error){setResult('');setState('error');setMessage(`Ошибка синтаксиса: ${error.message}`);}
}
async function copyResult(){
if(state!=='success')return;
const version=revision.current;
try{await navigator.clipboard.writeText(result);if(revision.current===version)setCopy('Скопировано');}
catch{if(revision.current===version)setCopy('Не удалось скопировать. Выделите текст результата вручную.');}
}
return <div className="workbench"><section><TextArea id={id} label="01 / Исходный JSON" hint="Проверяйте небольшие JSON-фрагменты. Текст обрабатывается в браузере." value={text} maxLength={MAX_INPUT_LENGTH} spellCheck={false} onChange={change} aria-invalid={state==='error'} aria-describedby={statusId}/><div className="tool-actions"><Button onClick={()=>run(false)}>Форматировать</Button><Button variant="secondary" onClick={()=>run(true)}>Сжать</Button><Button variant="secondary" onClick={()=>{setText('');resetResult();}}>Очистить</Button></div></section><section className={'result-panel '+state}><div className="result-heading"><span>02 / Результат</span><Button variant="secondary" disabled={state!=='success'} onClick={copyResult}>Копировать</Button></div><StatusMessage id={statusId} tone={state==='error'?'error':state==='success'?'success':'neutral'} className="result-label">{message||'Ожидает проверки'}</StatusMessage><ScrollRegion label="Результат JSON, прокрутка клавишами со стрелками"><pre>{result||'Результат появится после проверки.'}</pre></ScrollRegion><StatusMessage className="copy-feedback" tone={copy==='Скопировано'?'success':'neutral'}>{copy}</StatusMessage></section></div>;
}
@@ -0,0 +1 @@
export {Shortlinks} from './ui/Shortlinks';
@@ -0,0 +1,12 @@
"use client";
import {useEffect} from 'react';
import links from '../../../../data/shortlinks.json';
export function Shortlinks(){
useEffect(()=>{
const id=new URLSearchParams(location.search).get('p');
if(!id||!Object.hasOwn(links,id))return;
const target=links[id];
if(typeof target==='string'&&target.startsWith('/articles/'))location.replace(target);
},[]);
return null;
}
@@ -0,0 +1,2 @@
export {ThemeControl} from './ui/ThemeControl';
export {ThemeInit} from './ui/ThemeInit';
@@ -0,0 +1,20 @@
"use client";
import {useEffect,useId,useState} from 'react';
import {THEME_STORAGE_KEY,THEME_CHANGE_EVENT,THEME_OPTIONS,validTheme} from '../../../shared/config';
function readPreference(){try{const value=localStorage.getItem(THEME_STORAGE_KEY);return validTheme(value)?value:'system';}catch{return 'system';}}
export function ThemeControl(){
const id=useId();const [theme,setTheme]=useState('system');
useEffect(()=>{
const sync=event=>{const value=validTheme(event?.detail)?event.detail:readPreference();setTheme(value);document.documentElement.dataset.theme=value;};
const onStorage=event=>{if(event.key===THEME_STORAGE_KEY||event.key===null)sync();};
sync();window.addEventListener(THEME_CHANGE_EVENT,sync);window.addEventListener('storage',onStorage);
return()=>{window.removeEventListener(THEME_CHANGE_EVENT,sync);window.removeEventListener('storage',onStorage);};
},[]);
function change(event){
const value=event.target.value;if(!validTheme(value))return;
setTheme(value);document.documentElement.dataset.theme=value;
try{localStorage.setItem(THEME_STORAGE_KEY,value);}catch{/* Preference remains usable for this page without storage. */}
window.dispatchEvent(new CustomEvent(THEME_CHANGE_EVENT,{detail:value}));
}
return <div className="theme-control"><label htmlFor={id}>Тема</label><select id={id} value={theme} onChange={change}>{THEME_OPTIONS.map(option=><option value={option.value} key={option.value}>{option.label}</option>)}</select></div>;
}
@@ -0,0 +1,3 @@
import {THEME_STORAGE_KEY} from '../../../shared/config';
// Constant script contains only the storage key and allowlisted preference values.
export function ThemeInit(){const code=`try{var t=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});document.documentElement.dataset.theme=(t==='light'||t==='dark'||t==='system')?t:'system';}catch(e){document.documentElement.dataset.theme='system';}`;return <script id="progcode-theme-init" dangerouslySetInnerHTML={{__html:code}}/>;}
@@ -0,0 +1,2 @@
import {Prose} from '../../shared/ui';
export default function About(){return <main id="main" className="simple-page"><p className="kicker">PROGCODE.RU</p><h1>Блог одного<br/>программиста.</h1><p className="large-text">Здесь разбирают устройство инструментов, пишут небольшие функции и задают вопросы разработчикам.</p><Prose><h2>Что читать</h2><p>Основная коллекция — заметки DarkRiDDeR 2017–2019 годов о D, PHP, Bitrix, JavaScript и рабочем окружении. Среди них есть короткие рецепты, большой разбор сборщика мусора и интервью с создателем Tilix.</p><p>Технические примеры привязаны к контексту своих версий. Там, где старый совет мог привести к ошибке, текст уточнён. Интервью и переводы сохраняют авторство и ссылки на первичные публикации.</p><h2>Как ориентироваться</h2><p>Начните с <a href="/#journal">индекса статей</a>, выберите тему или задайте поиск. Для длинных разборов предусмотрено оглавление. В <a href="/resources/">справочниках</a> собраны первичные источники по темам блога, а <a href="/tools/">JSON-инструмент</a> помогает проверить ответ API.</p><h2>Автор и связь</h2><p>Автор исторических заметок подписывался DarkRiDDeR. Подтверждённый актуальный канал связи не указан; старые формы отправки сообщений больше не используются.</p></Prose></main>}
@@ -0,0 +1,2 @@
import {Prose,TextLink} from '../../shared/ui';
export default function AccessibilityPage(){return <main id="main" className="simple-page service-page"><p className="kicker">ДОСТУП К СОДЕРЖАНИЮ</p><h1>Настроить чтение<br/>под себя.</h1><Prose><h2>Клавиатура и оглавление</h2><p>Первое нажатие Tab открывает ссылку «К содержанию». Ссылки и кнопки имеют видимую рамку фокуса. В длинных статьях оглавление ведёт к настоящим разделам; на узком экране его можно свернуть.</p><h2>Код и широкие таблицы</h2><p>Примеры кода сохраняют отступы, а таблицы — связь строк и столбцов. Если содержимое шире экрана, прокручивается только этот блок. Перейдите к нему клавишей Tab и используйте стрелки влево и вправо либо прокрутите касанием.</p><h2>Размер текста и тема</h2><p>Используйте масштаб браузера, чтобы увеличить текст. В шапке можно выбрать светлую, тёмную или системную тему; выбор сохраняется только в этом браузере. Системная настройка уменьшенного движения отключает плавную прокрутку.</p><h2>Изображения и состояния</h2><p>Схемы сопровождаются описаниями и подписями. Цвет не заменяет текст ошибки или состояние поиска. Если изображение не загрузилось, остальная статья остаётся доступной. Пустой поиск можно сбросить, а неизвестный адрес ведёт к странице 404 с переходом в журнал.</p><p>Это описание предусмотренных способов работы, а не гарантия одинакового поведения каждого браузера или вспомогательной технологии.</p><ul><li><TextLink href="/#journal">Найти материал в журнале</TextLink></li><li><TextLink href="/ui-kit/">Проверить компоненты на реальном содержимом</TextLink></li><li><TextLink href="/privacy/">О теме, локальных инструментах и аналитике</TextLink></li></ul></Prose></main>}
@@ -0,0 +1,5 @@
import Link from 'next/link';
import {ArticleMeta} from '../../entities/article';
import ArticleReader from '../../widgets/article-reader';
import RelatedReading from '../../widgets/related-reading';
export default function ArticlePage({article,related}){return <main id="main" className="article-shell"><nav className="breadcrumbs" aria-label="Путь"><Link href="/#journal">Журнал</Link><span>/</span><span>{article.categories.join(' · ')}</span></nav><header className="article-header"><p className="kicker">{article.categories.join(' / ')}</p><h1>{article.title}</h1><p className="article-deck">{article.excerpt}</p><ArticleMeta article={article}/></header><ArticleReader article={article} related={<RelatedReading articles={related}/>}/></main>}
@@ -0,0 +1,3 @@
import Link from 'next/link';
import {ArticleListItem} from '../../entities/article';
export default function CatalogPage({title,articles}){return <main id="main" className="archive-page"><p className="kicker">ТЕМАТИЧЕСКИЙ ИНДЕКС</p><h1>{title}</h1><p className="large-text">Материалов по этой теме: {articles.length}. <Link href="/#journal">Перейти к поиску по всему журналу</Link>.</p><div className="journal-list">{articles.map(article=><ArticleListItem key={article.slug} article={article} shortDate={false}/>)}</div></main>}
@@ -0,0 +1,5 @@
import Link from 'next/link';
import Catalog from '../../widgets/journal-index';
import {Shortlinks} from '../../features/shortlinks';
import {getArticles,getArticleSummaries,ArticleFigure} from '../../entities/article';
export default function Home(){const all=getArticles(),lead=all.find(a=>a.slug==='новый-движок-ctfe'),recipes=all.filter(a=>a.categories.includes('Bitrix')||a.categories.includes('PHP')).slice(0,4);return <main id="main"><Shortlinks/><section className="intro"><div><p className="kicker">ЗАПИСКИ ПРОГРАММИСТА · 2017–2019</p><h1>Разобраться.<br/><em>Написать.</em> Проверить.</h1></div><p className="intro-deck">Что происходит во время компиляции? <br/>Как связаны товар и предложение? <br/>Здесь — механизмы, примеры и опыт разработки.</p></section><section className="front-grid" aria-label="С чего начать"><Link className="lead-story" href={'/articles/'+encodeURIComponent(lead.slug)+'/'}><div className="story-meta"><span>ВНУТРИ ЯЗЫКА D</span><span>01 / РАЗБОР</span></div><h2>Код, который работает<br/>до запуска программы</h2><p>Как CTFE выполняет функции на этапе компиляции и зачем D понадобился новый движок.</p><ArticleFigure className="lead-visual" loading="eager" width={720} height={260} src="/visuals/v2/ctfe-overview.svg" alt="Компилятор вычисляет square(3) для enum и получает n = 9 ещё до запуска программы"/><span className="text-link">Разобрать CTFE <b>↗</b></span></Link><div className="recipe-column"><div className="section-title"><p className="kicker">ПРАКТИКА</p><h2>Рецепты без лишнего</h2></div>{recipes.map((article,i)=><Link className="recipe" key={article.slug} href={'/articles/'+encodeURIComponent(article.slug)+'/'}><span className="recipe-number">0{i+1}</span><div><span className="tiny-topic">{article.categories.join(' / ')}</span><h3>{article.title}</h3></div><b aria-hidden="true">↗</b></Link>)}</div></section><section className="reading-routes" aria-label="Маршруты чтения"><p className="kicker">ВЫБЕРИТЕ ЗАДАЧУ</p><div><Link href="/category/dlang/"><span>01</span><strong>Понять язык D</strong><small>CTFE, память, диапазоны и интерфейсы →</small></Link><Link href="/category/bitix/"><span>02</span><strong>Собрать интеграцию Bitrix</strong><small>Товар, предложение, символьный код →</small></Link><Link href="/articles/ошибка-php-ssl-certificate-error-unable-to-get-local-issuer-certificate/"><span>03</span><strong>Разобраться с TLS</strong><small>Проверка сертификата без обхода защиты →</small></Link></div></section><Catalog articles={getArticleSummaries()}/><section className="utility-promo"><div><p className="kicker">НА РАБОЧЕМ СТОЛЕ</p><h2>Сначала проверьте JSON.</h2><p>Форматирование, поиск синтаксических ошибок и компактная запись — прямо в браузере.</p></div><Link className="button" href="/tools/">Открыть инструмент ↗</Link></section></main>}
@@ -0,0 +1,2 @@
import JsonWorkbench from '../../widgets/json-workbench';
export default function JsonToolPage(){return <main id="main" className="tool-page"><header className="tool-heading"><p className="kicker">ИНСТРУМЕНТ РАЗРАБОТЧИКА</p><h1>Привести JSON<br/>в порядок.</h1><p>Проверьте синтаксис, расставьте отступы или уберите пробелы.<br/>Текст обрабатывается локально в вашем браузере.</p></header><JsonWorkbench/><section className="tool-notes"><h2>Синтаксис — только первый шаг.</h2><p>Ключи и строки требуют двойных кавычек. Комментарии и завершающие запятые не поддерживаются. Проверка не подтверждает соответствие схеме API. Большие целые числа могут терять точность в JavaScript: такие идентификаторы лучше хранить строками.</p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">Правила JSON.parse в MDN ↗</a></section></main>}
@@ -0,0 +1,2 @@
import {ActionLink,TextLink} from '../../shared/ui';
export default function NotFoundPage(){return <main id="main" className="missing"><p className="kicker">ОШИБКА 404</p><div className="missing-code" aria-hidden="true">&#123; ? &#125;</div><h1>Такой страницы нет.</h1><p>Возможно, в адресе опечатка или ссылка больше не существует.<br/>Попробуйте найти нужную тему в журнале.</p><ActionLink href="/#journal">Перейти к поиску →</ActionLink><TextLink href="/resources/">Открыть справочники</TextLink></main>}
@@ -0,0 +1,2 @@
import {Prose,TextLink} from '../../shared/ui';
export default function PrivacyPage(){return <main id="main" className="simple-page service-page"><p className="kicker">О РАБОТЕ САЙТА</p><h1>Приватность<br/>и аналитика.</h1><Prose><h2>Чтение и локальные инструменты</h2><p>Для чтения не нужна регистрация. Поиск по журналу и обработка JSON выполняются в браузере: отдельный поисковый запрос или исходный JSON не отправляются в событиях сайта. Выбранная цветовая тема сохраняется в локальном хранилище браузера; её можно поменять в шапке.</p><h2>Что помогает улучшать журнал</h2><p>На ProgCode подключена Яндекс Метрика — счётчик 109268613. Она помогает понять, откуда приходят читатели, какие материалы читают и где возникают трудности. Сервис получает сведения о просмотрах, адресах и заголовках страниц, источниках перехода, браузере и устройстве; может использовать cookie. Это внешняя аналитика, даже когда сам JSON-инструмент работает локально.</p><p>Включены карта кликов и учёт переходов по внешним ссылкам. Вебвизор — запись сеансов — выключен. Стандартный показатель отказов не подменяется искусственными просмотрами или событиями.</p><h2>Какие действия учитывает сайт</h2><p>Отдельные события отмечают чтение статьи не менее минуты в видимом окне с фокусом и достижение 75% текста, выбор результата поиска, отсутствие результатов, переход к связанному материалу и подтверждённую проблему контента. В этих событиях нет текста поискового запроса, введённого JSON, содержимого отсутствующего якоря или полного сообщения ошибки. Скачивания учитывались бы только при клике на настоящую ссылку скачивания; в текущей коллекции таких файлов нет.</p><h2>Ваш браузер и выбор</h2><p>Настройки cookie и локального хранилища управляются в браузере. Яндекс также описывает способы отключить сбор Метрики. Отключение счётчика не мешает чтению статей, поиску и работе JSON-инструмента.</p><ul><li><TextLink href="https://yandex.ru/support/metrica/ru/code/data-collected">Какие сведения собирает Метрика</TextLink></li><li><TextLink href="https://yandex.ru/support/metrica/ru/general/user-opt-out">Как отключить сбор Метрики</TextLink></li><li><TextLink href="https://yandex.ru/legal/confidential/">Политика конфиденциальности Яндекса</TextLink></li></ul><p>Описание относится к функциям этого сайта. Условия обработки данных внешним сервисом изложены в его документах.</p></Prose></main>}
@@ -0,0 +1,3 @@
const sources=[['D','Язык, стандартная библиотека и инструменты',[['Спецификация D','https://dlang.org/spec/spec.html','Синтаксис, семантика и правила языка.'],['Стандартная библиотека Phobos','https://dlang.org/phobos/index.html','Контракты функций, модули и примеры.'],['DUB','https://dub.pm/','Сборка проектов и управление зависимостями.']]],['PHP','Функции и интеграции',[['Справочник PHP','https://www.php.net/manual/ru/','Функции, расширения и примеры использования.'],['API Bitrix','https://dev.1c-bitrix.ru/api_help/','Описание API и ограничений конкретных методов.']]],['Web','Сборка и безопасность',[['webpack: ProvidePlugin','https://webpack.js.org/plugins/provide-plugin/','Как автоматически подключать модуль для свободного идентификатора.'],['MDN: JSON.parse','https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse','Синтаксис JSON, ошибки разбора и точность чисел.'],['curl: проверка TLS','https://curl.se/docs/sslcerts.html','Цепочка доверия и безопасная диагностика сертификатов.']]]];
export default function Resources(){return <main id="main" className="simple-page"><p className="kicker">ДЕРЖАТЬ ПОД РУКОЙ</p><h1>Сначала —<br/>первоисточник.</h1><p className="large-text">Справочники по темам журнала: для проверки версии API, поведения функции и границ примера.</p><div className="resource-groups">{sources.map(([topic,title,links])=><section key={topic}><p className="kicker">{topic}</p><h2>{title}</h2>{links.map(([name,href,text])=><a key={href} href={href}><h3>{name}<span>↗</span></h3><p>{text}</p></a>)}</section>)}</div></main>}
@@ -0,0 +1,2 @@
import {Prose,TextLink} from '../../shared/ui';
export default function SourcesPage(){return <main id="main" className="simple-page service-page"><p className="kicker">ИСТОЧНИКИ И РЕДАКТУРА</p><h1>Сохранить смысл.<br/>Уточнить контекст.</h1><Prose><h2>Что входит в журнал</h2><p>Здесь собрана известная коллекция из четырнадцати публикаций ProgCode 2017–2019 годов: заметки о D, PHP, Bitrix, JavaScript и рабочем окружении. Это исторические материалы, а не обещание актуальности всех описанных версий или полноты прежнего сайта.</p><h2>Как восстанавливаются материалы</h2><p>Основой служат общедоступные архивные снимки старых страниц. Сохранены полные известные тексты, авторство и переводческая атрибуция, примеры кода и исторические даты. Старые адреса известных материалов ведут к соответствующим статьям.</p><p>Архивная оболочка, рекламные вставки и комментарии не переносятся автоматически. Ссылки остаются там, где они помогают проверить техническое утверждение или источник перевода. Неподтверждённые пропуски не заменяются выдуманными публикациями.</p><h2>Что добавляет редактура</h2><p>Оглавления и поясняющие схемы помогают читать большие разборы. Новые схемы объясняют устройство механизмов и не выдаются за исторические снимки интерфейса. В заметке о FileInput сохранён подлинный небольшой пример контрола Bitrix.</p><p>Уточнения раскрывают ограничения версий и последствия старых советов: например, замена шаблона Diet в описанном статически компилируемом варианте требует пересборки использующего его кода. Уточнения не превращают старую статью в руководство по всем современным версиям инструмента.</p><h2>Как проверить и продолжить чтение</h2><ul><li><TextLink href="https://web.archive.org/web/*/http://progcode.ru/">Архивные снимки ProgCode в Wayback Machine</TextLink></li><li><TextLink href="/resources/">Первичные справочники по темам журнала</TextLink></li><li><TextLink href="/#journal">Индекс известных статей</TextLink></li><li><TextLink href="/about/">О блоге и историческом авторстве</TextLink></li></ul><p>Актуальный подтверждённый канал связи автора не указан. На сайте нет формы, которая обещает отправить сообщение без работающего получателя.</p></Prose></main>}
@@ -0,0 +1,8 @@
import Link from 'next/link';
import {Brand,Button,ActionLink,Prose,StatusMessage,ScrollRegion} from '../../shared/ui';
import {getArticles,ArticleMeta} from '../../entities/article';
import {ContentAccess} from '../../features/content-access';
import JournalIndex from '../../widgets/journal-index';
import JsonWorkbench from '../../widgets/json-workbench';
function Label({article}){return <header className="specimen-label"><p>Реальный материал: <Link href={'/articles/'+encodeURIComponent(article.slug)+'/'}>{article.title}</Link></p><ArticleMeta article={article}/></header>}
export default function UIKitPage(){const all=getArticles();const article=prefix=>all.find(item=>item.slug.startsWith(prefix));const ctfe=article('новый-движок'),code=article('пишем-аналог'),bitrix=article('bitrix-api-add'),gc=article('dconf'),tls=article('ошибка-php'),windows=article('вирус-'),hello=article('привет-');const block=(value,pattern)=>value.contentHtml.match(pattern)?.[0]||'';const moduleCode=[...code.contentHtml.matchAll(/<pre[\s\S]*?<\/pre>/g)].map(match=>match[0]).sort((a,b)=>b.length-a.length)[0];const table=block(ctfe,/<table[\s\S]*?<\/table>/);const figures=[...gc.contentHtml.matchAll(/<figure[\s\S]*?<\/figure>/g)].map(match=>match[0]);return <main id="main" className="uikit-page"><header><p className="kicker">ИНЖЕНЕРНАЯ ЗАМЕТКА</p><h1>Компоненты ProgCode.</h1><p className="large-text">Те же элементы, которые помогают читать журнал, находить материал и проверять код. Примеры взяты из настоящих статей.</p></header><section className="uikit-section"><h2>Знак и цвет</h2><div className="uikit-grid"><div className="uikit-panel"><Brand/><p>Буква P и курсор связывают знак с названием журнала. Цветовую тему можно выбрать в шапке.</p></div><div className="uikit-native">{[16,32,48].map(size=><figure key={size}><img src={'/brand/favicon-'+size+'.png'} width={size} height={size} alt={'Знак ProgCode, '+size+' пикселей'}/><figcaption>{size} × {size}</figcaption></figure>)}</div></div><div className="uikit-swatches"><div className="uikit-swatch">Основной текст<strong>Текст и фон чтения</strong><code>text.primary / bg.canvas</code></div><div className="uikit-swatch" style={{background:'var(--color-subtle)',color:'var(--color-secondary)'}}>Подписи и даты<strong>Вторичная информация</strong><code>text.secondary / bg.subtle</code></div><div className="uikit-swatch" style={{color:'var(--color-accent)'}}>Ссылки и фокус<strong>Один тёплый акцент</strong><code>link.default / focus.ring</code></div></div></section><section className="uikit-section"><h2>Текст без обрезанных окончаний</h2><div className="uikit-grid">{[tls,windows].map(item=><div className="uikit-panel" key={item.slug}><Label article={item}/><h3>{item.title}</h3><p>{item.excerpt}</p></div>)}</div><div className="uikit-prose"><Label article={hello}/><Prose html={hello.contentHtml} className="demo-prose"/></div></section><section className="uikit-section"><h2>Полный пример кода</h2><Label article={code}/><p>Самый длинный блок этой заметки сохранён целиком, включая модуль и проверки. При необходимости код прокручивается отдельно от страницы.</p><Prose html={moduleCode} className="demo-prose uikit-prose"/></section><section className="uikit-section"><h2>Сравнение по строкам и столбцам</h2><Label article={ctfe}/><div className="article-content demo-prose"><ScrollRegion label="Таблица сравнения CTFE; горизонтальная прокрутка" className="table-scroll" dangerouslySetInnerHTML={{__html:table}}/></div></section><section className="uikit-section"><h2>Изображение и его смысл</h2><div className="uikit-grid"><div><Label article={bitrix}/><Prose className="demo-prose" html={block(bitrix,/<figure[\s\S]*?<\/figure>/)}/></div><div><Label article={gc}/><Prose className="demo-prose" html={figures[1]||figures[0]}/></div></div></section><section className="uikit-section"><h2>Действия и понятные состояния</h2><div className="uikit-actions"><ActionLink href="/#journal">Открыть журнал →</ActionLink><ActionLink href="/resources/">Проверить источник</ActionLink><Button disabled>Недоступное действие</Button></div><StatusMessage>Пустое состояние не подменяется выдуманным результатом. Поиск и JSON ниже можно проверить самостоятельно.</StatusMessage><p>В текущей коллекции нет файлов для скачивания. Копирование JSON не считается скачиванием.</p><p><Link href="/does-not-exist-uikit/">Посмотреть настоящую страницу 404</Link> · <Link href="/privacy/">Приватность</Link> · <Link href="/sources/">Источники и редактура</Link></p></section><JournalIndex articles={all.map(({slug,title,date,excerpt,categories,readingMinutes})=>({slug,title,date,excerpt,categories,readingMinutes}))}/><section className="uikit-section"><h2>JLine truncated
@@ -0,0 +1,4 @@
export const THEME_STORAGE_KEY='progcode-theme';
export const THEME_CHANGE_EVENT='progcode-theme-change';
export const THEME_OPTIONS=[{value:'system',label:'Системная'},{value:'light',label:'Светлая'},{value:'dark',label:'Тёмная'}];
export function validTheme(value){return value==='light'||value==='dark'||value==='system';}
@@ -0,0 +1,5 @@
// Archived publication timestamps are UTC; their UTC calendar days match the
// visible source dates and dated permalinks. Never use the build/browser timezone.
export function formatDate(date, {day = '2-digit', month = 'long'} = {}) {
return new Intl.DateTimeFormat('ru-RU', {day, month, year: 'numeric', timeZone: 'UTC'}).format(new Date(date));
}
@@ -0,0 +1 @@
export {formatDate} from './dates.mjs';
@@ -0,0 +1,27 @@
/* Public component contracts; semantic tokens are shared by real pages and the kit. */
body{font-family:var(--font-ui)}
a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,summary:focus-visible,[tabindex="0"]:focus-visible{outline:3px solid var(--color-accent);outline-offset:3px}
.brand{display:inline-flex;flex-shrink:0;align-items:center;line-height:1;text-decoration:none}.brand img{width:202px;height:auto}.brand .brand-dark{display:none}:root[data-theme=dark] .brand .brand-light{display:none}:root[data-theme=dark] .brand .brand-dark{display:block}
@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .brand .brand-light{display:none}:root:not([data-theme=light]) .brand .brand-dark{display:block}}
.theme-control{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--color-secondary)}.theme-control select{min-height:44px;max-width:128px;padding:8px;border:1px solid var(--color-control);border-radius:3px;background:var(--color-surface);color:var(--color-text);font:inherit}
.masthead nav{gap:22px}.masthead nav a{display:inline-flex;align-items:center;min-height:44px}.footer nav{display:flex;flex-direction:column;gap:10px}.footer nav a{width:fit-content}.footer .brand img{width:176px}.footer>span{line-height:1.6}
.field{display:block;min-width:0}.field>span,.field-label{display:block;font:12px/1.5 var(--font-ui);margin-bottom:8px}.field input,.field textarea{background:var(--color-surface);border:1px solid var(--color-control);color:var(--color-text)}.field-hint,.field-note{font:12px/1.6 var(--font-ui);color:var(--color-secondary)}
.ui-button,.button{min-height:44px;line-height:1.4;padding:11px 16px;border-radius:3px;font:600 14px/1.4 var(--font-ui)}.ui-button{background:var(--color-surface);color:var(--color-text);border:1px solid var(--color-control)}.ui-button.primary,.ui-button[data-variant=primary]{background:var(--color-text);border-color:var(--color-text);color:var(--color-canvas)}.ui-button:hover:not(:disabled){text-decoration:underline;text-underline-offset:4px}.ui-button:disabled,button:disabled{cursor:not-allowed;color:var(--color-secondary);border-style:dashed;background:var(--color-subtle)}
.status-message{font:14px/1.6 var(--font-ui);color:var(--color-secondary)}.status-message.success,.status-message[data-tone=success]{color:var(--color-success-text)}.status-message.error,.status-message[data-tone=error]{color:var(--color-error-text)}.status-message[data-tone=success]{background:var(--color-success-bg);padding:12px}.status-message[data-tone=error]{background:var(--color-error-bg);padding:12px}
.scroll-region{max-width:100%;min-width:0;overflow:auto}.scroll-region pre{margin:0}.scroll-region[data-overflow=true]::before,.table-scroll[data-overflow=true]::before{content:'Прокрутка по горизонтали: касанием или стрелками после фокусировки';display:block;padding:8px 12px;font:12px/1.5 var(--font-ui);color:var(--color-secondary);background:var(--color-subtle)}
.article-header{max-width:740px}.reading-column{font-family:var(--font-reading);font-size:var(--reading-size);max-width:min(var(--reading-measure),740px)}.article-content{font-family:var(--font-reading);font-size:var(--reading-size);line-height:var(--reading-leading);overflow-wrap:anywhere}.article-content p{margin-bottom:1.1em}.article-content h2{margin-top:48px}.article-content a:visited{color:var(--color-visited)}.article-content pre{font:14px/1.65 var(--font-mono);color:var(--color-code-text);background:var(--color-code)}.article-content pre[data-overflow=true]{border-left:3px solid var(--color-control)}.article-content code{background:var(--color-subtle);font-family:var(--font-mono)}.article-content pre code{background:none}
.article-content figure{background:#fffefa;color:#242521;border-color:var(--color-control)}.article-content figcaption{font-size:12px;color:#62665c;border-color:#d8d8cd}.article-content table{font-size:14px}.article-content th,.article-content td{border-color:var(--color-control)}.article-content .table-scroll{border-color:var(--color-control)}
.related,.article-end{font-family:var(--font-ui)}.article-meta,.article-end,.index-date,.index-date span,.index-duration,.story-meta,.tiny-topic,.recipe-number,.kicker,.search-status,.field-note,.copy-feedback,.result-heading,.result-label{font-size:12px;line-height:1.5}.topic-tabs button{min-height:44px}.topic-tabs button[aria-pressed=true]{font-weight:700}.search-status{min-height:20px}.journal-heading>span{font-size:12px}
.utility-promo{background:var(--color-subtle);color:var(--color-text);border:1px solid var(--color-border)}.utility-promo p{color:var(--color-secondary)}.utility-promo .kicker{color:var(--color-accent)}.result-panel.success{background:var(--color-success-bg)}.result-panel.error{background:var(--color-error-bg)}.result-panel.success .result-label,.result-panel.success .result-panel pre{color:var(--color-success-text)}.result-panel.error .result-label,.result-panel.error pre{color:var(--color-error-text)}.result-panel pre{color:var(--color-text)}.result-panel .status-message{margin:16px 0}.workbench textarea{font-size:14px}.tool-actions button{font-size:14px}.workbench .field>span{display:block}.copy-feedback{color:var(--color-accent)}
.service-page .article-content{max-width:min(var(--reading-measure),740px)}.service-page h2{margin-top:40px}.service-page a{overflow-wrap:anywhere}.service-nav{display:flex;gap:16px;flex-wrap:wrap;margin-top:32px}
.uikit-page{padding:48px 0 64px}.uikit-page>header{max-width:820px}.uikit-page>header h1{font-size:clamp(32px,5vw,58px);letter-spacing:-1.5px}.uikit-section{margin:48px 0;padding-top:32px;border-top:1px solid var(--color-control)}.uikit-section>h2{font-size:30px}.uikit-section>p{max-width:70ch;color:var(--color-secondary)}.specimen-label{font:13px/1.6 var(--font-ui);margin-bottom:20px}.specimen-label a{font-weight:700}.uikit-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px}.uikit-panel{min-width:0;padding:24px;background:var(--color-surface);border:1px solid var(--color-control);border-radius:4px}.uikit-panel .brand img{max-width:100%}.uikit-prose{max-width:min(68ch,740px)}.uikit-native{display:flex;flex-wrap:wrap;align-items:center;gap:32px;padding:24px;background:var(--color-surface);border:1px solid var(--color-control)}.uikit-native figure{margin:0}.uikit-native figcaption{font-size:12px;margin-top:10px}.uikit-native img{max-width:none}.uikit-swatches{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}.uikit-swatch{padding:20px;border:1px solid var(--color-control);border-radius:3px}.uikit-swatch strong,.uikit-swatch code{display:block}.uikit-swatch code{margin-top:8px;font-size:12px}.uikit-actions{display:flex;gap:12px;flex-wrap:wrap}.uikit-panel h3{font-size:22px;line-height:1.3}
@media(max-width:950px){.masthead{gap:12px}.brand img{width:178px}.masthead nav{gap:14px}.reading-column{max-width:min(var(--reading-measure),740px)}.article-header{max-width:740px}}
@media(max-width:650px){main{margin-inline:16px}.masthead{margin-inline:16px;padding-block:16px;display:grid;grid-template-columns:1fr auto;gap:8px 12px}.masthead .brand img{width:168px}.masthead nav{grid-column:1/-1;grid-row:2;gap:4px 14px;flex-wrap:wrap;justify-content:space-between;width:100%;font-size:13px}.masthead nav a{white-space:normal;min-height:44px}.theme-control{gap:4px;justify-content:flex-end}.theme-control>label{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip-path:inset(50%)}.theme-control select{max-width:100px;padding:8px 4px;font-size:12px}.footer{margin-inline:16px;grid-template-columns:1fr;gap:20px}.footer .brand img{width:178px}.footer>p,.footer>nav{grid-column:auto;grid-row:auto}.footer>span{display:block;text-align:left}.footer nav{gap:12px}.footer nav a{min-height:32px}.article-header h1{font-size:34px}.reading-column{max-width:100%}.article-content pre{font-size:13px;margin-inline:0;max-width:100%}.article-content figure{margin-inline:0}.contents-rail{font-size:13px}.article-content figcaption{font-size:12px}.index-date,.index-date span,.index-duration{font-size:12px}.index-entry{grid-template-columns:minmax(0,1fr) 58px}.index-entry h3{overflow-wrap:anywhere}.story-meta{font-size:12px;letter-spacing:0}.intro h1{font-size:38px}.simple-page{padding-inline:16px}.workbench textarea,.result-panel pre{font-size:13px}.result-heading button{font-size:12px;min-height:40px}.uikit-page{padding-top:32px}.uikit-grid,.uikit-swatches{grid-template-columns:1fr}.uikit-panel{padding:16px}.uikit-section{margin-block:32px;padding-top:24px}.uikit-native{padding:16px;gap:24px}.uikit-section>h2{font-size:26px}.article-content h2{margin-top:36px}}
@media(forced-colors:active){button,input,textarea,select,.ui-button,.button,.table-scroll{border:1px solid ButtonText}a:focus-visible,button:focus-visible,[tabindex="0"]:focus-visible{outline:3px solid Highlight}.uikit-swatch{border-color:CanvasText}}
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}*,*::before,*::after{animation:none!important;transition:none!important}}
.ui-action-link{display:inline-flex;align-items:center;justify-content:center;text-decoration:none}.ui-text-link{display:inline;text-decoration:underline;text-underline-offset:4px}.ui-tag{font:12px/1.5 var(--font-ui);color:var(--color-accent)}.brand-symbol img{width:32px;height:32px}.field-label{color:var(--color-text)}.result-panel .status-message.success{color:var(--color-success-text)}.result-panel .status-message.error{color:var(--color-error-text)}
@media(max-width:650px){.simple-page h1,.tool-page h1{font-size:34px;line-height:1.13;letter-spacing:-1px;overflow-wrap:anywhere}}
.catalog-controls>.field{flex:1;max-width:390px}@media(max-width:950px){.catalog-controls>.field{max-width:none;width:100%}}
@@ -0,0 +1,7 @@
*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:92px}body{margin:0;color:var(--ink);background:var(--paper);font-family:Arial,Helvetica,sans-serif;line-height:1.6}a{color:inherit;text-underline-offset:4px}button,input,textarea{font:inherit}button,a,input,textarea,summary{touch-action:manipulation}button{cursor:pointer}button:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible,summary:focus-visible,pre:focus-visible{outline:3px solid var(--accent);outline-offset:4px}img{max-width:100%;height:auto;display:block}h1,h2,h3,p{margin-top:0}h1,h2,h3{line-height:1.12}button{border:1px solid var(--line);padding:9px 14px;background:transparent;color:var(--ink);border-radius:3px}.button{display:inline-flex;align-items:center;justify-content:center;background:var(--ink);color:var(--white);padding:12px 20px;border:1px solid var(--ink);text-decoration:none;font-weight:700;border-radius:3px}.button:hover{background:var(--accent);border-color:var(--accent)}.skip-link{position:absolute;left:16px;top:-80px;z-index:30;background:var(--ink);color:var(--color-canvas);padding:12px}.skip-link:focus{top:10px}.masthead{max-width:1264px;margin:auto;min-height:88px;padding:16px 32px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ink);gap:24px}.wordmark{text-decoration:none;font-size:32px;font-weight:900;letter-spacing:-1.8px;line-height:1}.wordmark span{font-weight:400}.wordmark i{font-style:normal;color:var(--accent)}.masthead nav{display:flex;gap:28px;align-items:center;font-size:14px}.masthead nav a{text-decoration:none}.masthead nav a:hover{color:var(--accent)}.edition{font:11px monospace;letter-spacing:1px;color:var(--muted)}main{max-width:1200px;margin:auto}.kicker{font:700 11px/1.5 Arial,sans-serif;letter-spacing:1.5px;color:var(--accent);margin-bottom:16px}.intro{padding:58px 0 42px;display:flex;align-items:flex-end;justify-content:space-between;gap:40px}.intro h1{font-size:clamp(36px,4.2vw,62px);letter-spacing:-2.5px;margin-bottom:0}.intro h1 em{font-style:normal;color:var(--accent)}.intro-deck{font-size:16px;line-height:1.7;color:var(--muted);max-width:350px;margin-bottom:5px}.front-grid{display:grid;grid-template-columns:1.4fr 1fr;gap:40px;border-top:1px solid var(--line);padding-top:28px}.lead-story{text-decoration:none;background:var(--color-subtle);border:1px solid var(--color-border);border-radius:4px;padding:30px 32px;display:flex;flex-direction:column}.story-meta{display:flex;justify-content:space-between;gap:10px;font:10px monospace;letter-spacing:1px;color:var(--color-secondary);margin-bottom:26px}.lead-story h2{font-size:clamp(28px,3vw,42px);letter-spacing:-1.4px;margin-bottom:17px}.lead-story>p{font-size:16px;color:var(--color-secondary);max-width:480px;line-height:1.6}.lead-visual{margin:20px -8px 26px}.lead-visual img{width:100%;max-height:280px;object-fit:contain}.text-link{display:flex;justify-content:space-between;font-size:14px;font-weight:700;margin-top:auto;border-top:1px solid var(--color-border);padding-top:16px}.text-link b{color:var(--accent);font-size:22px}.section-title{border-bottom:2px solid var(--ink);padding-bottom:16px}.section-title .kicker{margin-bottom:8px}.section-title h2{font-size:25px;letter-spacing:-.6px;margin:0}.recipe{display:flex;gap:15px;border-bottom:1px solid var(--line);padding:22px 0;text-decoration:none;align-items:flex-start}.recipe-number{font:12px monospace;color:var(--muted);padding-top:3px}.tiny-topic{font:10px monospace;letter-spacing:.8px;color:var(--accent)}.recipe h3{font-size:19px;line-height:1.3;margin:6px 0 0;font-weight:600}.recipe>b{margin-left:auto;font-size:22px;color:var(--accent)}.recipe:hover h3,.index-entry a:hover h3{color:var(--accent)}.reading-routes{margin-top:58px;border-top:1px solid var(--ink);padding:24px 0 36px}.reading-routes>div{display:grid;grid-template-columns:repeat(3,1fr);gap:30px}.reading-routes a{text-decoration:none;border-right:1px solid var(--line);display:flex;flex-direction:column;gap:9px;padding-right:24px}.reading-routes a:last-child{border:0}.reading-routes a>span{font:11px monospace;color:var(--muted)}.reading-routes strong{font-size:20px;line-height:1.25}.reading-routes small{font-size:13px;color:var(--muted)}.journal{padding:40px 0 56px;border-top:1px solid var(--ink)}.journal-heading{display:flex;align-items:flex-end;justify-content:space-between;margin-bottom:25px}.journal-heading h2{font-size:38px;letter-spacing:-1px;margin:0}.journal-heading>span{font:12px monospace;color:var(--muted)}.catalog-controls{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;background:var(--soft);padding:24px}.catalog-controls label{flex:1;max-width:390px}.catalog-controls label>span{display:block;font-size:12px;margin-bottom:8px}input{width:100%;background:var(--white);border:1px solid var(--color-control);padding:12px;color:var(--ink);border-radius:2px}.topic-tabs{display:flex;flex-wrap:wrap;gap:7px}.topic-tabs button{padding:8px 12px;Line truncated
@media(min-width:1600px){main{max-width:1200px}}@media(max-width:1280px){main{margin:0 32px}.article-header{margin-left:220px}.reading-layout{grid-template-columns:185px minmax(0,1fr);gap:35px}.reading-layout:has(>.reading-column:first-child){margin-left:220px}.simple-page{margin-left:auto;margin-right:auto;padding-left:25px;padding-right:25px}}@media(max-width:950px){.edition{display:none}.front-grid{grid-template-columns:1.2fr 1fr;gap:25px}.lead-story{padding:25px}.recipe h3{font-size:17px}.intro-deck{max-width:280px;font-size:14px}.catalog-controls{flex-direction:column;align-items:stretch;gap:18px}.catalog-controls label{max-width:none}.article-header{margin-left:0;max-width:820px}.reading-layout{display:block}.reading-layout:has(>.reading-column:first-child){margin-left:0}.contents-rail{position:static;max-height:none;max-width:810px;padding:15px 20px;background:var(--soft);margin-bottom:30px}.contents-rail nav{display:grid;grid-template-columns:1fr 1fr;gap:0 25px}.contents-rail details summary{padding-bottom:10px}.footer{grid-template-columns:1fr 1.5fr 1fr}.footer>span{display:none}.workbench{gap:20px}.index-entry{grid-template-columns:140px 1fr 70px;gap:20px}.article-content{font-size:17px}}
@media(max-width:650px){html{scroll-padding-top:20px}.masthead{margin:0 20px;padding:20px 0;gap:20px;flex-wrap:wrap;min-height:108px}.wordmark{font-size:30px}.masthead nav{gap:22px;width:100%;font-size:12px;justify-content:space-between}.masthead nav a{white-space:nowrap}main{margin:0 20px}.intro{padding:35px 0 28px;display:block}.intro h1{font-size:41px;letter-spacing:-1.8px}.intro-deck{max-width:none;font-size:14px;margin:23px 0 0}.intro-deck br{display:none}.kicker{font-size:10px;letter-spacing:1.2px}.front-grid{display:block;padding-top:20px}.lead-story{padding:22px}.story-meta{font-size:8px;margin-bottom:22px;letter-spacing:.8px}.lead-story h2{font-size:29px;letter-spacing:-1px}.lead-story>p{font-size:14px}.lead-visual{margin:15px -12px 20px}.lead-visual img{max-height:none}.text-link{font-size:12px}.recipe-column{margin-top:30px}.section-title h2{font-size:25px}.recipe{padding:18px 0}.recipe h3{font-size:19px}.reading-routes{margin-top:35px;padding-top:20px}.reading-routes>div{display:block}.reading-routes a{border-right:0;border-bottom:1px solid var(--line);padding:17px 0;gap:7px}.reading-routes strong{font-size:20px}.journal{padding-top:28px;padding-bottom:35px}.journal-heading{display:block}.journal-heading h2{font-size:30px;margin-bottom:14px}.journal-heading>span{font-size:11px}.catalog-controls{padding:18px;margin:0 -4px}.topic-tabs{gap:6px}.topic-tabs button{font-size:12px;padding:8px 11px}.index-entry{grid-template-columns:1fr 55px;gap:10px;padding:22px 0}.index-date{grid-column:1/-1;display:flex;justify-content:space-between;gap:15px;font-size:10px;padding:0}.index-date span{display:inline;margin:0;font-size:10px}.index-entry h3{font-size:20px;line-height:1.3;margin:0 0 10px}.index-entry p{font-size:13px;line-height:1.6}.index-duration{font-size:10px;display:block;text-align:right;padding-top:6px}.index-duration b{display:block;font-size:23px;padding-top:15px}.utility-promo{display:block;padding:25px;margin-bottom:35px}.utility-promo h2{font-size:29px}.utility-promo p{font-size:14px}.utility-promo .button{font-size:12px;margin-top:25px}.footer{margin:0 20px;padding:28px 0;grid-template-columns:1fr 1fr;gap:22px}.footer>p{grid-column:1}.footer>div{grid-column:2;grid-row:1/3;font-size:12px}.footer .wordmark{font-size:24px}.breadcrumbs{font-size:10px;padding:22px 0;gap:10px}.article-header{margin:12px 0 26px}.article-header h1{font-size:34px;letter-spacing:-1px;line-height:1.13;margin-bottom:20px}.article-deck{font-size:18px;line-height:1.5;margin-bottom:20px}.article-meta{font-size:10px;gap:8px 15px;padding-top:13px}.contents-rail{padding:13px 16px;margin:0 0 25px}.contents-rail nav{display:flex;gap:0}.contents-rail nav a{padding:7px 0;font-size:12px}.article-content{font-size:17px;line-height:1.75}.article-content h2{font-size:25px;margin:36px 0 18px;line-height:1.25;letter-spacing:-.4px}.article-content h3{font-size:20px;margin-top:28px}.article-content pre{font-size:12px;padding:20px 18px;margin:24px -4px;max-width:calc(100% + 8px)}.article-content figure{margin:25px -4px;padding:10px}.article-content figcaption{font-size:11px;line-height:1.6;padding-top:10px;margin-top:10px}.article-content blockquote{padding-left:18px;margin:20px 0}.article-end{font-size:10px}.related{padding:20px}.related a{font-size:17px}.reading-layout{padding-bottom:35px}.simple-page{margin:0;padding:35px 20px 50px;max-width:none}.simple-page h1,.tool-page h1{font-size:43px;letter-spacing:-1.6px}.large-text{font-size:20px;line-height:1.6;margin-bottom:35px}.tool-page{padding:35px 0 50px}.tool-heading p:not(.kicker){font-size:15px}.workbench{grid-template-columns:1fr;gap:28px}.workbench textarea{min-height:260px;font-size:13px;padding:16px}.result-panel{min-height:280px;padding:0 18px 18px}.result-panel pre{font-size:13px;min-height:150px}.tool-actions{gap:7px}.tool-actions button{font-size:12px;padding:10px 13px}.field-note{font-size:10px;line-height:1.5}.tool-notes{margin-top:30px;font-size:14px}.missing{padding:45px 0 65px}.missing h1{font-size:34px}.missing>p:not(.kicker){font-size:14px}.missing-code{font-size:70px}.archive-page{padding:35px 0}.archive-page h1{font-size:37px}.archive-page>.large-text{font-size:18px}.resource-groups section>h2{font-size:25px}.resource-groups h3{font-size:18px}}
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
.article-content .table-scroll{max-width:100%;overflow:auto;margin:25px 0;border:1px solid var(--line);border-radius:3px}.article-content .table-scroll:focus-visible{outline:3px solid var(--accent);outline-offset:4px}.article-content .table-scroll table{display:table;min-width:620px;max-width:none;width:100%;margin:0;overflow-wrap:normal}.article-content figure img[src$=".jpg"]{width:auto;max-width:100%;margin-inline:auto}
@@ -0,0 +1,4 @@
:root{color-scheme:light;--color-canvas:#f6f4ef;--color-surface:#fffefa;--color-subtle:#eae7de;--color-text:#242521;--color-secondary:#62665c;--color-accent:#a13e20;--color-visited:#715687;--color-border:#d8d8cd;--color-control:#7d8577;--color-code:#202621;--color-code-text:#e0e7d8;--color-code-border:#465249;--color-success-bg:#e6eee6;--color-success-text:#276345;--color-error-bg:#f6e6df;--color-error-text:#942f24;--font-ui:Arial,Helvetica,sans-serif;--font-reading:Georgia,'Times New Roman',serif;--font-mono:'SFMono-Regular',Consolas,monospace;--reading-size:19px;--reading-leading:1.72;--reading-measure:68ch;--space-1:4px;--space-2:8px;--space-3:12px;--space-4:16px;--space-6:24px;--space-8:32px;--space-12:48px;--space-16:64px;--paper:var(--color-canvas);--white:var(--color-surface);--ink:var(--color-text);--muted:var(--color-secondary);--line:var(--color-border);--accent:var(--color-accent);--soft:var(--color-subtle);--code:var(--color-code)}
:root[data-theme=dark]{color-scheme:dark;--color-canvas:#1c211e;--color-surface:#252c27;--color-subtle:#2c342e;--color-text:#eeeee5;--color-secondary:#b2b9ae;--color-accent:#f1a17d;--color-visited:#c5b3ec;--color-border:#465249;--color-control:#829184;--color-code:#141a16;--color-code-text:#e0e7d8;--color-code-border:#465249;--color-success-bg:#223a2b;--color-success-text:#b4dcbd;--color-error-bg:#4b2b25;--color-error-text:#ffd0c1;}
@media(prefers-color-scheme:dark){:root:not([data-theme=light]){color-scheme:dark;--color-canvas:#1c211e;--color-surface:#252c27;--color-subtle:#2c342e;--color-text:#eeeee5;--color-secondary:#b2b9ae;--color-accent:#f1a17d;--color-visited:#c5b3ec;--color-border:#465249;--color-control:#829184;--color-code:#141a16;--color-code-text:#e0e7d8;--color-code-border:#465249;--color-success-bg:#223a2b;--color-success-text:#b4dcbd;--color-error-bg:#4b2b25;--color-error-text:#ffd0c1;}}
@media(max-width:650px){:root{--reading-size:18px}}
@@ -0,0 +1 @@
export {Brand,Button,ActionLink,TextLink,Field,TextArea,StatusMessage,ScrollRegion,Prose,Tag} from './primitives';
@@ -0,0 +1,34 @@
import Link from 'next/link';
const classes=(...names)=>names.filter(Boolean).join(' ');
export function Brand({symbol=false,className='',...props}){
return <Link {...props} href="/" aria-label="ProgCode — главная" className={classes('brand',symbol&&'brand-symbol',className)}>{symbol?<img src="/brand/favicon.svg" width="32" height="32" alt="" aria-hidden="true"/>:<><img className="brand-light" src="/brand/logo-light.svg" width="224" height="44" alt="" aria-hidden="true"/><img className="brand-dark" src="/brand/logo-dark.svg" width="224" height="44" alt="" aria-hidden="true"/></>}</Link>;
}
export function Button({variant='primary',type='button',className='',children,...props}){
const kind=variant==='secondary'?'secondary':'primary';
return <button {...props} type={type} className={classes('ui-button',kind,className)} data-variant={kind}>{children}</button>;
}
export function ActionLink({href,children,variant='primary',className='',...props}){
const kind=variant==='secondary'?'secondary':'primary';
return <Link {...props} href={href} className={classes('ui-button','ui-action-link',kind,className)} data-variant={kind}>{children}</Link>;
}
export function TextLink({href,children,className='',...props}){return <Link {...props} href={href} className={classes('ui-text-link',className)}>{children}</Link>;}
function descriptions(existing,hintId){return [existing,hintId].filter(Boolean).join(' ')||undefined;}
export function Field({id,label,hint,className='',...inputProps}){
const hintId=hint?`${id}-hint`:undefined;
return <div className="field"><label className="field-label" htmlFor={id}>{label}</label><input {...inputProps} id={id} className={classes('field-control',className)} aria-describedby={descriptions(inputProps['aria-describedby'],hintId)}/>{hint&&<p id={hintId} className="field-note">{hint}</p>}</div>;
}
export function TextArea({id,label,hint,className='',...textareaProps}){
const hintId=hint?`${id}-hint`:undefined;
return <div className="field field-textarea"><label className="field-label" htmlFor={id}>{label}</label><textarea {...textareaProps} id={id} className={classes('field-control',className)} aria-describedby={descriptions(textareaProps['aria-describedby'],hintId)}/>{hint&&<p id={hintId} className="field-note">{hint}</p>}</div>;
}
export function StatusMessage({tone='neutral',children,id,className='',...props}){
const kind=['neutral','success','error'].includes(tone)?tone:'neutral';
return <p {...props} id={id} role="status" aria-live="polite" aria-atomic="true" className={classes('status-message',kind,className)} data-tone={kind}>{children}</p>;
}
export function ScrollRegion({label,children,className='',tabIndex=0,...props}){return <div {...props} className={classes('scroll-region',className)} tabIndex={tabIndex} role="region" aria-label={label}>{children}</div>;}
// html must be the reviewed build-generated publication HTML, never an untrusted input.
export function Prose({children,html,className='',...props}){
const attrs={...props,className:classes('prose','article-content',className)};
return typeof html==='string'?<div {...attrs} dangerouslySetInnerHTML={{__html:html}}/>:<div {...attrs}>{children}</div>;
}
export function Tag({children,className='',...props}){return <span {...props} className={classes('ui-tag',className)}>{children}</span>;}
@@ -0,0 +1,3 @@
import {Prose} from '../../shared/ui';
import {ContentAccess} from '../../features/content-access';
export default function ArticleReader({article,related}){return <div className="reading-layout">{article.toc?.length>1&&<aside className="contents-rail"><details open><summary>В этой статье</summary><nav aria-label="Оглавление статьи">{article.toc.map((section,index)=><a key={section.id} href={'#'+section.id}><span>{String(index+1).padStart(2,'0')}</span>{section.title}</a>)}</nav></details></aside>}<div className="reading-column"><Prose html={article.contentHtml}/><ContentAccess/><div className="article-end"><span>КОНЕЦ ЗАМЕТКИ</span><a href="#main">↑ В начало</a></div>{related}</div></div>}
@@ -0,0 +1,4 @@
"use client";
import {JournalSearch} from '../../features/journal-search';
import {trackGoal} from '../../features/analytics';
export default function JournalIndex({articles}){return <JournalSearch articles={articles} onResultSelect={()=>trackGoal('search_used')} onZeroResults={()=>trackGoal('search_zero_results')}/>}
@@ -0,0 +1,2 @@
import {JsonEditor} from '../../features/json-editor';
export default function JsonWorkbench(){return <JsonEditor/>}
@@ -0,0 +1,2 @@
import Link from 'next/link';
export default function RelatedReading({articles}){if(!articles.length)return null;return <section className="related" aria-label="Связанные материалы"><p className="kicker">ПРОДОЛЖИТЬ ЧТЕНИЕ</p>{articles.map(article=><Link key={article.slug} href={'/articles/'+encodeURIComponent(article.slug)+'/'}>{article.title}<span aria-hidden="true">↗</span></Link>)}</section>}
@@ -0,0 +1,5 @@
import Link from 'next/link';
import {Brand} from '../../shared/ui';
import {ThemeControl} from '../../features/theme-selection';
export function SiteHeader(){return <header className="masthead"><Brand/><nav aria-label="Главная навигация"><Link href="/#journal">Статьи</Link><Link href="/resources/">Справочники</Link><Link href="/tools/">JSON</Link><Link href="/about/">О блоге</Link></nav><ThemeControl/></header>}
export function SiteFooter(){return <footer className="footer"><Brand/><p>Заметки о том, как устроен код.<br/>D, PHP, Bitrix и веб-разработка.</p><nav aria-label="Информация о проекте"><Link href="/#journal">Все статьи</Link><Link href="/sources/">Источники и редактура</Link><Link href="/privacy/">Приватность</Link><Link href="/accessibility/">Доступность и чтение</Link><Link href="/ui-kit/">Компоненты ProgCode</Link></nav><span>Материалы 2017–2019</span></footer>}