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,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}}/>;}