Integrate existing Metrika counter with private behavioral goals
Build and deploy / deploy (push) Successful in 38s
Build and deploy / deploy (push) Successful in 38s
This commit is contained in:
1 parent
8c58a54f5b
commit
0458a99d3a
19 files changed
+355
-3
No files matched your search
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
import {useState,useEffect} from 'react';
|
||||
import Link from 'next/link';
|
||||
import {trackGoal} from '../lib/metrika.mjs';
|
||||
import {formatDate} from '../lib/dates.mjs';
|
||||
export default function Catalog({articles}){const [q,setQ]=useState(''),[topic,setTopic]=useState('Все');const topics=['Все',...new Set(articles.flatMap(a=>a.categories))];const shown=articles.filter(a=>(topic==='Все'||a.categories.includes(topic))&&(a.title+' '+a.excerpt+' '+a.categories.join(' ')).toLocaleLowerCase('ru').includes(q.toLocaleLowerCase('ru')));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"><label htmlFor="search"><span>Найти в журнале</span><input id="search" type="search" value={q} onChange={e=>setQ(e.target.value)} placeholder="Тема, язык или задача"/></label><div className="topic-tabs" aria-label="Темы">{topics.map(t=><button aria-pressed={topic===t} key={t} onClick={()=>setTopic(t)}>{t}</button>)}</div></div><p role="status" className="search-status">{shown.length?`Найдено материалов: ${shown.length}`:'По этому запросу ничего нет. Попробуйте другое слово или сбросьте тему.'}</p><div className="journal-list">{shown.map(a=><article key={a.slug} className="index-entry"><div className="index-date"><time dateTime={a.date}>{formatDate(a.date,{month:'short',day:'numeric'})}</time><span>{a.categories.join(' · ')}</span></div><Link href={'/articles/'+encodeURIComponent(a.slug)+'/'}><h3>{a.title}</h3><p>{a.excerpt}</p></Link><span className="index-duration">{a.readingMinutes} мин <b aria-hidden="true">↗</b></span></article>)}</div>{!shown.length&&<button onClick={()=>{setQ('');setTopic('Все');}}>Сбросить поиск</button>}</section>}
|
||||
export default function Catalog({articles}){const [q,setQ]=useState(''),[topic,setTopic]=useState('Все');const topics=['Все',...new Set(articles.flatMap(a=>a.categories))];const shown=articles.filter(a=>(topic==='Все'||a.categories.includes(topic))&&(a.title+' '+a.excerpt+' '+a.categories.join(' ')).toLocaleLowerCase('ru').includes(q.toLocaleLowerCase('ru')));useEffect(()=>{if(!q.trim()||shown.length)return;const timer=setTimeout(()=>trackGoal('search_zero_results'),500);return()=>clearTimeout(timer);},[q,shown.length]);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"><label htmlFor="search"><span>Найти в журнале</span><input id="search" type="search" value={q} onChange={e=>setQ(e.target.value)} placeholder="Тема, язык или задача"/></label><div className="topic-tabs" aria-label="Темы">{topics.map(t=><button aria-pressed={topic===t} key={t} onClick={()=>setTopic(t)}>{t}</button>)}</div></div><p role="status" className="search-status">{shown.length?`Найдено материалов: ${shown.length}`:'По этому запросу ничего нет. Попробуйте другое слово или сбросьте тему.'}</p><div className="journal-list">{shown.map(a=><article key={a.slug} className="index-entry"><div className="index-date"><time dateTime={a.date}>{formatDate(a.date,{month:'short',day:'numeric'})}</time><span>{a.categories.join(' · ')}</span></div><Link onClick={e=>{if(e.isTrusted&&q.trim())trackGoal('search_used');}} href={'/articles/'+encodeURIComponent(a.slug)+'/'}><h3>{a.title}</h3><p>{a.excerpt}</p></Link><span className="index-duration">{a.readingMinutes} мин <b aria-hidden="true">↗</b></span></article>)}</div>{!shown.length&&<button onClick={()=>{setQ('');setTopic('Все');}}>Сбросить поиск</button>}</section>}
|
||||
@@ -0,0 +1,9 @@
|
||||
"use client";
|
||||
import {useEffect} from 'react';
|
||||
import {usePathname} from 'next/navigation';
|
||||
import {observePage} from '../lib/metrika.mjs';
|
||||
export default function Metrika() {
|
||||
const pathname = usePathname();
|
||||
useEffect(observePage, [pathname]);
|
||||
return null;
|
||||
}
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
import './globals.css';
|
||||
import Link from 'next/link';
|
||||
import Metrika from './Metrika';
|
||||
export const metadata={metadataBase:new URL('https://progcode.ru'),icons:{icon:'/icon.svg'},title:'ProgCode — записки о программировании',description:'D, PHP, Bitrix и JavaScript: разборы механизмов, рабочие рецепты и разговоры с разработчиками.'};
|
||||
export default function RootLayout({children}){return <html lang="ru"><body><a className="skip-link" href="#main">К содержанию</a><header className="masthead"><Link className="wordmark" href="/" aria-label="ProgCode — главная">prog<span>code</span><i>_</i></Link><nav aria-label="Главная навигация"><Link href="/#journal">Статьи</Link><Link href="/resources/">Справочники</Link><Link href="/tools/">JSON</Link><Link href="/about/">О блоге</Link></nav><span className="edition">D / PHP / WEB</span></header>{children}<footer className="footer"><Link className="wordmark" href="/">prog<span>code</span><i>_</i></Link><p>Заметки о том, как устроен код.<br/>D, PHP, Bitrix и веб-разработка.</p><div><Link href="/#journal">Все статьи</Link><Link href="/resources/">Полезные ссылки</Link><Link href="/tools/">JSON-инструмент</Link></div><span>Материалы 2017–2019</span></footer></body></html>}
|
||||
export default function RootLayout({children}){return <html lang="ru"><body><Metrika/><a className="skip-link" href="#main">К содержанию</a><header className="masthead"><Link className="wordmark" href="/" aria-label="ProgCode — главная">prog<span>code</span><i>_</i></Link><nav aria-label="Главная навигация"><Link href="/#journal">Статьи</Link><Link href="/resources/">Справочники</Link><Link href="/tools/">JSON</Link><Link href="/about/">О блоге</Link></nav><span className="edition">D / PHP / WEB</span></header>{children}<footer className="footer"><Link className="wordmark" href="/">prog<span>code</span><i>_</i></Link><p>Заметки о том, как устроен код.<br/>D, PHP, Bitrix и веб-разработка.</p><div><Link href="/#journal">Все статьи</Link><Link href="/resources/">Полезные ссылки</Link><Link href="/tools/">JSON-инструмент</Link></div><span>Материалы 2017–2019</span></footer></body></html>}
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"sourceHash": "53f217e5370ecafe41a0afcfe51fe80f2e443f04637adbe0d4f7476babe9beeb",
|
||||
"sourceHash": "527ea7bf774eca2b18d9dcd2f1ab0ac0341fa87e50a160ad75aefb3e30ad31a2",
|
||||
"articles": 14
|
||||
}
|
||||
Reference in new issue
Block a user