diff --git a/assets/css/custom.css b/assets/css/custom.css index fc12bd663..e2e2003aa 100644 --- a/assets/css/custom.css +++ b/assets/css/custom.css @@ -364,3 +364,24 @@ html:not(.dark) { @media (prefers-reduced-motion: reduce) { .home-button, .home-topic, .home-topic-arrow { transition: none; } } +/* Knowledge graph explorer */ +#kg-root .kg-controls { display: flex; flex-wrap: wrap; gap: .75rem; margin-bottom: 1rem; } +#kg-root .kg-search { min-width: 14rem; flex: 1; border: 1px solid #94a3b8; border-radius: .65rem; padding: .6rem .8rem; color: inherit; background: transparent; } +#kg-root .kg-btn, #kg-root .kg-chip { border: 1px solid #94a3b8; border-radius: 999px; padding: .45rem .8rem; color: inherit; background: transparent; cursor: pointer; } +#kg-root .kg-chips, #kg-root .kg-legend { display: flex; flex-wrap: wrap; gap: .5rem 1rem; margin: 1rem 0; } +#kg-root .kg-chip.kg-active { border-color: var(--chip); box-shadow: inset 0 0 0 1px var(--chip); } +#kg-root .kg-stage { display: grid; grid-template-columns: minmax(0, 1fr) minmax(15rem, 20rem); min-height: 32rem; overflow: hidden; border: 1px solid rgba(148,163,184,.35); border-radius: 1rem; } +#kg-root .kg-svg { min-width: 0; min-height: 32rem; background: radial-gradient(circle at center, rgba(148,163,184,.08), transparent 70%); } +#kg-root .kg-svg-el { width: 100%; height: 100%; min-height: 32rem; } +#kg-root .kg-label { font: 11px system-ui,sans-serif; fill: currentColor; pointer-events: none; } +#kg-root .kg-node { cursor: pointer; } +#kg-root .kg-node.kg-dim, #kg-root .kg-edge.kg-dim { opacity: .12; } +#kg-root .kg-edge-hi { stroke: #f59e0b; stroke-width: 2.5; } +#kg-root .kg-node.kg-selected circle { stroke: #f59e0b; stroke-width: 3; } +#kg-root .kg-panel { padding: 1rem; border-left: 1px solid rgba(148,163,184,.35); background: rgba(148,163,184,.04); } +#kg-root .kg-panel-title { margin: 0 0 .5rem; font-size: 1.1rem; font-weight: 700; } +#kg-root .kg-panel-type, #kg-root .kg-panel-date, #kg-root .kg-panel-sub { font-size: .85rem; color: #64748b; } +#kg-root .kg-panel-rel { padding-left: 1rem; font-size: .9rem; } +#kg-root .kg-leg { display: inline-flex; align-items: center; gap: .4rem; font-size: .8rem; } +#kg-root .kg-leg-dot { width: .55rem; height: .55rem; border-radius: 50%; } +@media (max-width: 760px) { #kg-root .kg-stage { grid-template-columns: 1fr; } #kg-root .kg-panel { border-top: 1px solid rgba(148,163,184,.35); border-left: 0; } } diff --git a/content/archives/_index.md b/content/archives/_index.md new file mode 100644 index 000000000..898c6a84d --- /dev/null +++ b/content/archives/_index.md @@ -0,0 +1,7 @@ +--- +title: Архив публикаций +description: Все публикации блога по годам. +layout: archives +--- + +Все статьи и заметки, собранные по годам. diff --git a/content/awesome/_index.md b/content/awesome/_index.md index 2d30517aa..45c7e89f0 100644 --- a/content/awesome/_index.md +++ b/content/awesome/_index.md @@ -1,5 +1,5 @@ --- -title: Awesome +title: Подборки description: "Курируемые awesome-списки из внешних репозиториев, сгруппированные по темам." layout: awesome # menu defined in config/_default/menus.ru.toml to avoid duplicate diff --git a/content/categories/_index.md b/content/categories/_index.md new file mode 100644 index 000000000..ec987c9aa --- /dev/null +++ b/content/categories/_index.md @@ -0,0 +1,6 @@ +--- +title: Категории +description: Тематические разделы публикаций. +--- + +Публикации сгруппированы по основным областям интереса. diff --git a/content/community/_index.md b/content/community/_index.md new file mode 100644 index 000000000..c34b4a4a9 --- /dev/null +++ b/content/community/_index.md @@ -0,0 +1,18 @@ +--- +title: Сообщество +description: Где следить за проектами, обсуждать материалы и связываться с автором. +--- + +Открытые проекты и публикации живут в GitHub. Вопросы и предложения можно оставить в обсуждениях репозитория сайта; для личной связи доступны Telegram и LinkedIn. + +## Участвовать + +- [Обсуждения сайта на GitHub](https://github.com/dominicusin/dominicusin.github.io/discussions) — идеи, вопросы и предложения по материалам. +- [Задачи и ошибки](https://github.com/dominicusin/dominicusin.github.io/issues) — сообщить о проблеме или предложить улучшение. +- [Репозитории проектов](/repositories/) — код, документация и открытые проекты. +- [Подборки](/awesome/) — рекомендованные инструменты и ресурсы. + +## Связаться + +- [Telegram](https://t.me/dominicusin) +- [LinkedIn](https://www.linkedin.com/in/dominicusin) diff --git a/content/gists/_index.md b/content/gists/_index.md new file mode 100644 index 000000000..9be487df5 --- /dev/null +++ b/content/gists/_index.md @@ -0,0 +1,6 @@ +--- +title: Гисты +description: Короткие скрипты, заметки и фрагменты кода автора на GitHub Gist. +--- + +Кодовые фрагменты и заметки, отсортированные по дате обновления. diff --git a/content/knowledge-graph/_index.md b/content/knowledge-graph/_index.md index c33a7d091..3af4e0bca 100644 --- a/content/knowledge-graph/_index.md +++ b/content/knowledge-graph/_index.md @@ -1,5 +1,5 @@ --- -title: Knowledge Graph +title: Граф знаний date: '2025-12-29T20:01:00.000Z' slug: knowledge-graph image: /images/og-default.png @@ -9,7 +9,7 @@ alt: "Knowledge Graph" Интерактивная карта взаимосвязей между постами, концепциями, людьми и проектами. Визуализирует семантические связи по тегам, категориям и датам. -
+
+ + + ## Как работает Данный раздел генерируется из реестра тегов и категорий. Каждый узел — это пост, @@ -31,6 +34,6 @@ alt: "Knowledge Graph" ## Статистика -- **{{ len .Site.Pages }}** страниц в блоге -- **{{ len .Site.Tags }}** уникальных тегов -- **{{ len .Site.Categories }}** уникальных категорий +- **{{ len (where .Site.RegularPages "Section" "blog") }}** публикаций в блоге +- **{{ len .Site.Taxonomies.tags }}** уникальных тегов +- **{{ len .Site.Taxonomies.categories }}** уникальных категорий diff --git a/content/ontology/_index.md b/content/ontology/_index.md new file mode 100644 index 000000000..bf7e7aab4 --- /dev/null +++ b/content/ontology/_index.md @@ -0,0 +1,7 @@ +--- +title: Онтология сайта +description: "Тематическая модель сайта: категории, теги, статьи, GitHub-репозитории и гисты." +layout: ontology +--- + +Онтология связывает публикации с темами, а темы — с проектами и кодом. Она строится из таксономии сайта и публичных данных GitHub. diff --git a/content/people/_index.md b/content/people/_index.md new file mode 100644 index 000000000..ede429fa5 --- /dev/null +++ b/content/people/_index.md @@ -0,0 +1,6 @@ +--- +title: Люди +description: Авторы и участники, связанные с публикациями и проектами сайта. +--- + +Здесь собраны авторы и участники, чьи профили используются в материалах сайта. diff --git a/content/repositories/_index.md b/content/repositories/_index.md new file mode 100644 index 000000000..26302ef5b --- /dev/null +++ b/content/repositories/_index.md @@ -0,0 +1,6 @@ +--- +title: Репозитории +description: Публичные проекты автора и связанных организаций на GitHub. +--- + +Каталог публичных репозиториев. Откройте карточку, чтобы посмотреть описание проекта, или перейдите прямо к исходному коду на GitHub. diff --git a/content/tags/_index.md b/content/tags/_index.md new file mode 100644 index 000000000..579688cec --- /dev/null +++ b/content/tags/_index.md @@ -0,0 +1,6 @@ +--- +title: Теги +description: Темы, технологии и ключевые понятия публикаций. +--- + +Теги помогают найти материалы по конкретной теме или технологии. diff --git a/layouts/_default/list.html b/layouts/_default/list.html index 15b54ab53..60f0a7cca 100644 --- a/layouts/_default/list.html +++ b/layouts/_default/list.html @@ -63,6 +63,38 @@

{{ end }} {{ end }} + {{/* GitHub indexes use their source names instead of Hugo's page title. */}} + {{ if eq .Section "repositories" }} +
+ {{ range (.Paginate (.Pages.ByTitle)).Pages }} + {{ $name := .Params.repo_name | default .LinkTitle | default .Title }} +
+

{{ $name }}

+ {{ with .Params.description }}

{{ . | plainify | htmlEscape }}

{{ end }} +
+ GitHub ↗ + {{ with .Params.language }}{{ . }}{{ end }} + {{ with .Params.stars }}★ {{ . }}{{ end }} +
+
+ {{ end }} +
+ {{ else if eq .Section "gists" }} +
+ {{ range (.Paginate ((.Pages.ByParam "updated_at").Reverse)).Pages }} + {{ $name := .Params.description | default .Title }} + {{ if eq $name .Params.gist_id }}{{ $name = .Params.gist_name | default $name }}{{ end }} + + {{ end }} +
+ {{ else }} {{/* Articles grid */}} {{ if gt .Pages 0 }} {{ $cardView := .Params.cardView | default (site.Params.list.cardView | default false) }} @@ -112,6 +144,7 @@

+ {{/* Hero */}} + {{ if .Params.showHero | default (site.Params.article.showHero | default false) }} + {{ $heroStyle := .Params.heroStyle }} + {{ if not $heroStyle }}{{ $heroStyle = site.Params.article.heroStyle }}{{ end }} + {{ $heroStyle := print "hero/" $heroStyle ".html" }} + {{ if templates.Exists ( printf "partials/%s" $heroStyle ) }} + {{ partial $heroStyle . }} + {{ else }} + {{ partial "hero/basic.html" . }} + {{ end }} + {{ end }} + + {{/* Header */}} +
+ {{ if .Params.showBreadcrumbs | default (site.Params.article.showBreadcrumbs | default false) }} + {{ partial "breadcrumbs.html" . }} + {{ end }} +

+ {{ .Title | emojify }} +

+ {{ partial "article-taxonomies/categories.html" . }} +
+ {{ partial "article-meta/basic.html" (dict "context" . "scope" "single") }} +
+ {{ if not (.Params.showAuthorBottom | default (site.Params.article.showAuthorBottom | default false)) }} + {{ template "SingleAuthor" . }} + {{ end }} +
+ + {{/* Body */}} +
+ {{ $enableToc := site.Params.article.showTableOfContents | default false }} + {{ $enableToc = .Params.showTableOfContents | default $enableToc }} + {{ $showToc := and $enableToc (in .TableOfContents " +
+ {{ partial "toc.html" . }} +
+

+ {{ end }} + + +
+ {{ partial "series/series.html" . }} +
+ {{ .Content }} + {{ $defaultReplyByEmail := site.Params.replyByEmail }} + {{ $replyByEmail := default $defaultReplyByEmail .Params.replyByEmail }} + {{ if $replyByEmail }} + {{ $replySubject := i18n "article.reply_to" (dict "Title" .Title) | default (printf "Reply to %s" .Title) }} + + + + + {{ end }} +
+ {{ if (.Params.showAuthorBottom | default (site.Params.article.showAuthorBottom | default false)) }} + {{ template "SingleAuthor" . }} + {{ end }} + {{ partial "series/series-closed.html" . }} + {{ partial "sharing-links.html" . }} + {{ partial "related.html" . }} +
+ + + {{/* Footer */}} + + +{{ end }} + +{{ define "SingleAuthor" }} + {{ $authorsData := hugo.Data.authors }} + {{ $taxonomies := site.Taxonomies.authors }} + {{ $baseURL := site.BaseURL }} + {{ $taxonomyLink := 0 }} + {{ $showAuthor := 0 }} + {{ $isAuthorBottom := (.Params.showAuthorBottom | default ( site.Params.article.showAuthorBottom | default false)) }} + + {{ if not (strings.HasSuffix $baseURL "/") }} + {{ $baseURL = delimit (slice $baseURL "/") "" }} + {{ end }} + + {{ if .Page.Params.authors }} + {{ range $author := .Page.Params.authors }} + {{ $authorData := index $authorsData $author }} + {{- if $authorData -}} + {{ range $taxonomyname, $taxonomy := $taxonomies }} + {{ if (eq $taxonomyname $author) }} + {{ $taxonomyLink = delimit (slice $baseURL "authors/" $author "/") "" }} + {{ end }} + {{ end }} + + {{ $finalLink := $taxonomyLink }} + {{ $currentLang := site.Language.Name }} + {{ if eq site.LanguagePrefix "" }} + {{ $finalLink = printf "%sauthors/%s/" $baseURL $author }} + {{ else }} + {{ $finalLink = printf "%s%s/authors/%s/" $baseURL $currentLang $author }} + {{ end }} + {{ partial "author-extra.html" (dict "context" . "data" $authorData "link" $finalLink) }} + {{- end -}} + {{ end }} + {{ else }} + {{ if .Params.showAuthor | default (site.Params.article.showAuthor | default true) }} + {{ $showAuthor = 1 }} + {{ partial "author.html" . }} + {{ end }} + {{ end }} + + {{ if or $taxonomyLink $showAuthor }} +
+ {{ end }} +{{ end }} diff --git a/layouts/archives/list.html b/layouts/archives/list.html new file mode 100644 index 000000000..d7dbfcf55 --- /dev/null +++ b/layouts/archives/list.html @@ -0,0 +1,20 @@ +{{ define "main" }} +
+

{{ .Title }}

+
{{ .Content }}
+
+ {{ $posts := where site.RegularPages "Section" "blog" }} + {{ range $posts.GroupByDate "2006" }} +
+

{{ .Key }} {{ len .Pages }}

+
    + {{ range .Pages }} +
  1. + + {{ .LinkTitle }} +
  2. + {{ end }} +
+
+ {{ end }} +{{ end }} diff --git a/layouts/community/list.html b/layouts/community/list.html new file mode 100644 index 000000000..855eb13cd --- /dev/null +++ b/layouts/community/list.html @@ -0,0 +1,6 @@ +{{ define "main" }} +
+

{{ .Title }}

+
{{ .Content }}
+
+{{ end }} diff --git a/layouts/ontology/list.html b/layouts/ontology/list.html new file mode 100644 index 000000000..b6d7ca8d5 --- /dev/null +++ b/layouts/ontology/list.html @@ -0,0 +1,11 @@ +{{ define "main" }} +
+

{{ .Title }}

+
{{ .Content }}
+
+
+

Загружаю тематический указатель…

+ +
+ +{{ end }} diff --git a/layouts/partials/article-meta/basic.html b/layouts/partials/article-meta/basic.html new file mode 100644 index 000000000..ca0862588 --- /dev/null +++ b/layouts/partials/article-meta/basic.html @@ -0,0 +1,97 @@ +{{/* Determine the correct context and scope */}} +{{/* This allows for different logic depending on where the partial is called */}} +{{ $context := . }} +{{ $scope := default nil }} + +{{ if (reflect.IsMap . ) }} + {{ $context = .context }} + {{ $scope = cond (not .scope) nil .scope }} +{{ end }} + +{{ with $context }} + {{ $meta := newScratch }} + + {{/* Gather partials for this context */}} + {{ $shouldShowDate := false }} + {{ if .Params.showDate | default (.Site.Params.article.showDate | default true) }} + {{ $shouldShowDate = true }} + {{ else }} + {{ $shouldShowDate = false }} + {{ end }} + + {{ if (.Params.showDateOnlyInArticle | default (.Site.Params.article.showDateOnlyInArticle | default false)) }} + {{ if (ne $scope "single") }} + {{/* only takes effect when not called directly in the header of single.html */}} + {{ $shouldShowDate = false }} + {{ end }} + {{ end }} + + {{ if $shouldShowDate }} + {{ $meta.Add "partials" (slice (partial "meta/date.html" .Date)) }} + {{ end }} + + {{ if and (.Params.showDateUpdated | default (.Site.Params.article.showDateUpdated | default false)) (ne (partial + "functions/date.html" .Date) (partial "functions/date.html" .Lastmod)) (gt (.Lastmod | time.Format "2006") 1) + }} + {{ $meta.Add "partials" (slice (partial "meta/date-updated.html" .Lastmod)) }} + {{ end }} + + {{ if and (.Params.showWordCount | default (.Site.Params.article.showWordCount | default false)) (ne .WordCount 0) }} + {{ $meta.Add "partials" (slice (partial "meta/word-count.html" .)) }} + {{ end }} + + {{ if and (.Params.showReadingTime | default (.Site.Params.article.showReadingTime | default true)) (ne .ReadingTime 0) }} + {{ $meta.Add "partials" (slice (partial "meta/reading-time.html" .)) }} + {{ end }} + + {{ if and (not .Params.externalURL) (.Params.showViews | default (.Site.Params.article.showViews | default false)) }} + {{ $meta.Add "partials" (slice (partial "meta/views.html" .)) }} + {{ end }} + + {{ if and (not .Params.externalURL) (.Params.showLikes | default (.Site.Params.article.showLikes | default false)) }} + {{ $meta.Add "partials" (slice (partial "meta/likes.html" .)) }} + {{ end }} + + {{ if and (eq $scope "single") (not .Params.externalURL) (.Params.showLikes | default (.Site.Params.article.showLikes | default false)) }} + {{ $meta.Add "partials" (slice (partial "meta/likes_button.html" .)) }} + {{ end }} + + {{ if and (eq $scope "single") (.Params.showEdit | default (.Site.Params.article.showEdit | default false)) }} + {{ $meta.Add "partials" (slice (partial "meta/edit.html" .)) }} + {{ end }} + + {{ if and (eq $scope "single") (.Params.showZenMode | default (.Site.Params.article.showZenMode | default false)) }} + {{ $meta.Add "partials" (slice (partial "meta/zen-mode.html" .)) }} + {{ end }} + + +
+ {{/* Output partials */}} + {{ with ($meta.Get "partials") }} + {{ delimit . "·" | safeHTML }} + {{ end }} + + {{/* Output draft label */}} + {{ if and (eq $scope "single") (and .Draft .Site.Params.article.showDraftLabel) }} + {{ partial "badge.html" (i18n "article.draft" | emojify) }} + {{ end }} +
+ + {{ if .Params.showAuthorsBadges | default (.Site.Params.article.showAuthorsBadges | default false) }} +
+ {{ range $taxonomy, $terms := .Site.Taxonomies }} + {{ if (eq $taxonomy "authors") }} + {{ if (gt (len ($context.GetTerms $taxonomy)) 0) }} + {{ range $i, $a := $context.GetTerms $taxonomy }} + {{ if not (eq $i 0) }} + ,  + {{ end }} + {{ $a.LinkTitle }} + {{ end }} + {{ end }} + {{ end }} + {{ end }} +
+ {{ end }} + +{{ end }} diff --git a/layouts/partials/article-taxonomies/categories.html b/layouts/partials/article-taxonomies/categories.html new file mode 100644 index 000000000..1d5a55a92 --- /dev/null +++ b/layouts/partials/article-taxonomies/categories.html @@ -0,0 +1,8 @@ +{{ $terms := .GetTerms "categories" }} +{{ if and (gt (len $terms) 0) (.Params.showCategories | default (.Site.Params.article.showCategories | default true)) }} + +{{ end }} diff --git a/layouts/partials/article-taxonomies/tags.html b/layouts/partials/article-taxonomies/tags.html new file mode 100644 index 000000000..da91338ce --- /dev/null +++ b/layouts/partials/article-taxonomies/tags.html @@ -0,0 +1,9 @@ +{{ $terms := .GetTerms "tags" }} +{{ if and (gt (len $terms) 0) (.Params.showTags | default (.Site.Params.article.showTags | default true)) }} + +{{ end }} diff --git a/layouts/people/list.html b/layouts/people/list.html new file mode 100644 index 000000000..b7b18030b --- /dev/null +++ b/layouts/people/list.html @@ -0,0 +1,21 @@ +{{ define "main" }} +
+

{{ .Title }}

+
{{ .Content }}
+
+
+ {{ range $slug, $person := hugo.Data.authors }} +
+

{{ $person.name | default ($slug | humanize) }}

+ {{ with $person.bio }}

{{ . }}

{{ end }} +
+ {{ with $person.social.github }}GitHub ↗{{ end }} + {{ with $person.social.telegram }}Telegram ↗{{ end }} + {{ with $person.social.linkedin }}LinkedIn ↗{{ end }} +
+
+ {{ else }} +

Профили пока не добавлены.

+ {{ end }} +
+{{ end }} diff --git a/scripts/build-awesome.cjs b/scripts/build-awesome.cjs index edbf6458d..4440a827a 100644 --- a/scripts/build-awesome.cjs +++ b/scripts/build-awesome.cjs @@ -176,9 +176,27 @@ function balanceHtmlTags(html) { return html + stack.reverse().map((n) => ``).join(''); } -function writePreviews(entries) { +async function readmeFromGitHub(entry) { + const match = entry.gh.match(/github\.com\/([^/]+)\/([^/]+)$/i); + if (!match) return ''; + const [, owner, repo] = match; + const branches = [entry.defaultBranch, 'main', 'master'].filter((x, i, a) => x && a.indexOf(x) === i); + for (const branch of branches) { + try { + const file = entry.readme.split('/').map(encodeURIComponent).join('/'); + const ref = branch.split('/').map(encodeURIComponent).join('/'); + const response = await fetch(`https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`, { + headers: { 'User-Agent': 'dominicusin-site-build' }, signal: AbortSignal.timeout(12000), + }); + if (response.ok) return await response.text(); + } catch {} + } + return ''; +} + +async function writePreviews(entries) { const keep = new Set(); - for (const e of entries) { + await Promise.all(entries.map(async (e) => { const key = `${e.group}/${e.name}`; keep.add(key); const src = path.join(ROOT, e.path, e.readme); @@ -186,7 +204,10 @@ function writePreviews(entries) { fs.mkdirSync(dir, { recursive: true }); let body = ''; try { - const raw = fs.readFileSync(src, 'utf8'); + let raw; + try { raw = fs.readFileSync(src, 'utf8'); } + catch { raw = await readmeFromGitHub(e); } + if (!raw) throw new Error('README unavailable'); const lines = raw.split('\n'); // Drop a leading "# Title" line (the repo name already is the H1). let start = 0; @@ -201,7 +222,7 @@ function writePreviews(entries) { // that would otherwise break the rendered preview/page layout. body = balanceHtmlTags(body); } catch (err) { - body = `_Не удалось прочитать ${e.readme} субмодуля._`; + body = `Полный README сейчас недоступен для сборки. [Откройте исходный список на GitHub](${e.gh}).`; } const md = [ '---', @@ -217,7 +238,7 @@ function writePreviews(entries) { body, ].join('\n') + '\n'; fs.writeFileSync(path.join(dir, 'index.md'), md); - } + })); clearStalePreviews(keep); } @@ -229,15 +250,15 @@ function saveMetaCache(c) { try { fs.mkdirSync(path.dirname(META_CACHE), { recur async function fetchRepoMeta(gh) { const m = gh.match(/github\.com[/:]([^/]+)\/([^/.]+)(?:\.git)?$/i); if (!m) return null; const full = `${m[1]}/${m[2]}`; const cache = loadMetaCache(); const hit = cache[full]; - if (hit && Date.now() - (hit.ts||0) < META_TTL_MS) return { stars: hit.stars, description: hit.description }; + if (hit && Date.now() - (hit.ts||0) < META_TTL_MS) return { stars: hit.stars, description: hit.description, defaultBranch: hit.defaultBranch || 'main' }; try { const headers = { 'Accept': 'application/vnd.github+json', 'User-Agent': 'build-awesome' }; if (process.env.GITHUB_TOKEN) headers['Authorization'] = `Bearer ${process.env.GITHUB_TOKEN}`; const res = await fetch(`https://api.github.com/repos/${full}`, { headers }); if (!res.ok) return null; const j = await res.json(); - const meta = { stars: j.stargazers_count ?? null, description: j.description ?? null, ts: Date.now() }; - cache[full] = meta; saveMetaCache(cache); return { stars: meta.stars, description: meta.description }; + const meta = { stars: j.stargazers_count ?? null, description: j.description ?? null, defaultBranch: j.default_branch || 'main', ts: Date.now() }; + cache[full] = meta; saveMetaCache(cache); return { stars: meta.stars, description: meta.description, defaultBranch: meta.defaultBranch }; } catch { return null; } } function countCJK(text){const m=(text||'').match(/[\u3400-\u9fff\uf900-\ufaff]/g);return m?m.length:0;} @@ -295,11 +316,11 @@ async function main() { }) .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)); - await Promise.all(entries.map(async (e) => { const meta = await fetchRepoMeta(e.gh); if (meta) { e.stars = meta.stars; e.description = meta.description; } })); + await Promise.all(entries.map(async (e) => { const meta = await fetchRepoMeta(e.gh); if (meta) { e.stars = meta.stars; e.description = meta.description; e.defaultBranch = meta.defaultBranch; } })); for (const g of groups) for (const r of g.repos) { const src = entries.find((x) => x.name === r.name && x.group === r.group); if (src) { r.stars = src.stars; r.description = src.description; } } const total = groups.reduce((n, g) => n + g.repos.length, 0); writeOut({ generatedAt: GENERATED_AT, groups, total }); - writePreviews(entries); + await writePreviews(entries); ensureIndex(); console.log(`[awesome] catalog: ${groups.length} groups, ${total} lists -> ${path.relative(ROOT, OUT)}`); } @@ -331,4 +352,4 @@ function ensureIndex() { console.warn('[awesome] created content/awesome/_index.md'); } -main().catch((err) => { console.error('[awesome] FATAL', err); process.exit(1); }); \ No newline at end of file +main().catch((err) => { console.error('[awesome] FATAL', err); process.exit(1); }); diff --git a/scripts/build-ontology-feed.cjs b/scripts/build-ontology-feed.cjs index 0b6d61d25..cbca33f10 100644 --- a/scripts/build-ontology-feed.cjs +++ b/scripts/build-ontology-feed.cjs @@ -17,6 +17,7 @@ 'use strict'; const fs = require('fs'); const path = require('path'); +const yaml = require('js-yaml'); const ROOT = process.cwd(); const TAXONOMY = path.join(ROOT, 'docs', 'TAXONOMY.md'); @@ -26,29 +27,10 @@ const OUT = path.join(ROOT, 'static', 'data', 'ontology.json'); function readFrontmatter(file) { const raw = fs.readFileSync(file, 'utf8'); - if (!raw.startsWith('---')) return {}; - const end = raw.indexOf('\n---', 3); - if (end === -1) return {}; - const fm = raw.slice(3, end).trim(); - const out = {}; - let key = null, collecting = null, buf = []; - const flush = () => { if (key) out[key] = (collecting ? buf : buf[0] || ''); key = null; collecting = null; buf = []; }; - for (const line of fm.split('\n')) { - const m = line.match(/^([A-Za-z_]+):\s*(.*)$/); - if (m && !line.startsWith(' ')) { - flush(); - key = m[1]; - const val = m[2].trim(); - if (val === '' || val === '[') { collecting = (val === '['); if (!collecting) buf = ['']; } - else buf = [val]; - } else if (line.match(/^\s*-\s+(.*)$/) && collecting) { - buf.push(line.match(/^\s*-\s+(.*)$/)[1].replace(/^["']|["']$/g, '')); - } else if (collecting) { - buf.push(line.trim().replace(/^["']|["']$/g, '')); - } - } - flush(); - return out; + const match = raw.match(/^---\s*\n([\s\S]*?)\n---(?:\s|$)/); + if (!match) return {}; + try { return yaml.load(match[1]) || {}; } + catch (error) { console.warn(`⚠ could not parse frontmatter in ${file}: ${error.message}`); return {}; } } function parseTaxonomyCategories() { @@ -57,10 +39,10 @@ function parseTaxonomyCategories() { // Categories live in the block under "## Categories (domains)" up to the next "## ". const block = (md.match(/## Categories \(domains\)([\s\S]*?)\n## /) || [null, ''])[1]; const cats = []; - const reTable = /\|\s*`([a-z0-9-]+)`\s*\|/g; + const reTable = /\|\s*`([a-z0-9-]+)`\s*\|\s*([^|]+)\s*\|/g; let m; - while ((m = reTable.exec(block))) cats.push(m[1]); - if (cats.length) return cats.map(c => ({ title: c, slug: c })); + while ((m = reTable.exec(block))) cats.push({ slug: m[1], title: m[2].trim() }); + if (cats.length) return cats; // Fallback: ### headings in that block const reHeading = /^###\s+([A-Za-z0-9_ -]+)/gm; while ((m = reHeading.exec(block))) cats.push(m[1].trim()); @@ -88,19 +70,22 @@ function main() { const posts = walk(CONTENT, []).map(readFrontmatter); const tagPostCount = {}; - const catPostCount = {}; + const tagsByCategory = {}; for (const p of posts) { - for (const t of normList(p.tags)) tagPostCount[t] = (tagPostCount[t] || 0) + 1; - for (const c of normList(p.categories)) catPostCount[c] = (catPostCount[c] || 0) + 1; + const tags = normList(p.tags); + const pageCategories = normList(p.categories); + for (const t of tags) tagPostCount[t] = (tagPostCount[t] || 0) + 1; + for (const c of pageCategories) { + const key = String(c).toLowerCase(); + tagsByCategory[key] = tagsByCategory[key] || new Set(); + tags.forEach(t => tagsByCategory[key].add(t)); + } } - // Attach tags to their category where the category name appears in the tag, - // otherwise group under an "uncategorized" bucket derived from tag vocabulary. const lattice = categories.map(c => ({ slug: c.slug, title: c.title, - tags: Object.keys(tagPostCount) - .filter(t => t.toLowerCase().includes(c.slug.replace(/-/g, ' ')) || t.toLowerCase().includes(c.slug)) + tags: [...(tagsByCategory[c.slug.toLowerCase()] || new Set())] .map(t => ({ slug: t, postCount: tagPostCount[t], repoCount: 0, gistCount: 0 })), })); @@ -110,6 +95,7 @@ function main() { categories: lattice, repositories: [], gists: [], + repositoryTopics: [], }; if (fs.existsSync(GH)) { @@ -117,21 +103,19 @@ function main() { const gh = JSON.parse(fs.readFileSync(GH, 'utf8')); feed.repositories = (gh.repos || []).map(r => ({ id: `repo:${r.fullName || r.owner + '/' + r.name}`, - owner: r.owner, name: r.name, topics: r.topics || [], + owner: r.owner, name: r.name, url: r.html_url || `https://github.com/${r.owner}/${r.name}`, topics: r.topics || [], })); feed.gists = (gh.gists || []).map(g => ({ - id: `gist:${g.id}`, description: g.description || '', fileCount: (g.files || []).length, + id: `gist:${g.id}`, description: g.description || '', url: g.html_url || `https://gist.github.com/${g.id}`, fileCount: (g.files || []).length, })); // Facet counts: how many repos/gists reference each tag (by topic overlap). - const topicSet = new Set(); - for (const r of feed.repositories) r.topics.forEach(t => topicSet.add(t)); - for (const t of topicSet) { - const repoCount = feed.repositories.filter(r => r.topics.includes(t)).length; - const gistCount = 0; + const topicCounts = new Map(); + for (const r of feed.repositories) for (const t of r.topics) topicCounts.set(t, (topicCounts.get(t) || 0) + 1); + feed.repositoryTopics = [...topicCounts.entries()].map(([slug, repoCount]) => ({ slug, repoCount })).sort((a, b) => b.repoCount - a.repoCount || a.slug.localeCompare(b.slug)); + for (const { slug: t, repoCount } of feed.repositoryTopics) { for (const cat of feed.categories) { const tag = cat.tags.find(x => x.slug === t); - if (tag) { tag.repoCount = repoCount; tag.gistCount = gistCount; } - else cat.tags.push({ slug: t, postCount: tagPostCount[t] || 0, repoCount, gistCount }); + if (tag) tag.repoCount = repoCount; } } } catch (e) { diff --git a/static/js/knowledge-graph.js b/static/js/knowledge-graph.js index 83edc8a85..211e51781 100644 --- a/static/js/knowledge-graph.js +++ b/static/js/knowledge-graph.js @@ -21,7 +21,7 @@ gist: 'var(--kg-gist, #fbbf24)', org: 'var(--kg-org, #c084fc)' }; - var LABELS = { post: 'Post', concept: 'Concept', person: 'Person', project: 'Project', dao: 'DAO contract', repository: 'Repository', gist: 'Gist', org: 'Organization' }; + var LABELS = { post: 'Публикация', concept: 'Тема', person: 'Человек', project: 'Проект', dao: 'Контракт DAO', repository: 'Репозиторий', gist: 'Gist', org: 'Организация' }; function el(tag, cls, text) { var n = document.createElement(tag); @@ -33,7 +33,7 @@ fetch('/data/knowledge-graph.json', { cache: 'no-cache' }) .then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }) .then(init) - .catch(function (e) { root.innerHTML = ''; root.appendChild(el('p', 'kg-error', 'Could not load knowledge graph data: ' + e.message)); }); + .catch(function () { root.innerHTML = ''; root.appendChild(el('p', 'kg-error', 'Не удалось загрузить данные графа. Попробуйте обновить страницу позже.')); }); function init(data) { var nodes = data.nodes.map(function (n) { return Object.assign({}, n); }); @@ -47,8 +47,8 @@ // Controls var controls = el('div', 'kg-controls'); - var search = el('input', 'kg-search'); search.type = 'search'; search.placeholder = 'Search the graph…'; - var reset = el('button', 'kg-btn', 'Reset view'); + var search = el('input', 'kg-search'); search.type = 'search'; search.placeholder = 'Найти в графе…'; + var reset = el('button', 'kg-btn', 'Сбросить вид'); controls.appendChild(search); controls.appendChild(reset); wrap.appendChild(controls); @@ -73,7 +73,7 @@ var stage = el('div', 'kg-stage'); var svgHost = el('div', 'kg-svg'); var panel = el('div', 'kg-panel'); - panel.appendChild(el('p', 'kg-panel-empty', 'Select a node to see details.')); + panel.appendChild(el('p', 'kg-panel-empty', 'Выберите узел, чтобы увидеть подробности.')); stage.appendChild(svgHost); stage.appendChild(panel); wrap.appendChild(stage); @@ -206,15 +206,15 @@ panel.appendChild(el('span', 'kg-panel-type', LABELS[d.type] || d.type)); if (d.date) panel.appendChild(el('p', 'kg-panel-date', String(d.date).slice(0, 10))); if (d.url && d.url.indexOf('http') === 0) { - var a = el('a', 'kg-panel-link', 'Open ↗'); a.href = d.url; a.target = '_blank'; a.rel = 'noopener'; panel.appendChild(a); + var a = el('a', 'kg-panel-link', 'Открыть ↗'); a.href = d.url; a.target = '_blank'; a.rel = 'noopener'; panel.appendChild(a); } else if (d.url) { - var b = el('a', 'kg-panel-link', 'Open post →'); b.href = d.url; panel.appendChild(b); + var b = el('a', 'kg-panel-link', 'Открыть публикацию →'); b.href = d.url; panel.appendChild(b); } var rel = links.filter(function (l) { return (l.source.id || l.source) === d.id || (l.target.id || l.target) === d.id; }) .map(function (l) { var other = (l.source.id || l.source) === d.id ? (l.target.id || l.target) : (l.source.id || l.source); return byId[other]; }) .filter(Boolean).slice(0, 12); if (rel.length) { - panel.appendChild(el('p', 'kg-panel-sub', 'Connected (' + rel.length + '):')); + panel.appendChild(el('p', 'kg-panel-sub', 'Связи (' + rel.length + '):')); var ul = el('ul', 'kg-panel-rel'); rel.forEach(function (r) { var li = el('li'); var ra = el('a', null, r.label); ra.href = '#'; ra.addEventListener('click', function (e) { e.preventDefault(); focusNode(r.id); }); @@ -253,7 +253,7 @@ fitView(); node.classed('kg-dim', false).classed('kg-selected', false); link.classed('kg-dim', false).classed('kg-edge-hi', false); - panel.innerHTML = ''; panel.appendChild(el('p', 'kg-panel-empty', 'Select a node to see details.')); + panel.innerHTML = ''; panel.appendChild(el('p', 'kg-panel-empty', 'Выберите узел, чтобы увидеть подробности.')); }); window.addEventListener('resize', function () { diff --git a/static/js/ontology.js b/static/js/ontology.js new file mode 100644 index 000000000..494715456 --- /dev/null +++ b/static/js/ontology.js @@ -0,0 +1,68 @@ +(function () { + 'use strict'; + var root = document.getElementById('ontology-root'); + if (!root) return; + function node(tag, className, text) { + var el = document.createElement(tag); + if (className) el.className = className; + if (text !== undefined) el.textContent = text; + return el; + } + fetch('/data/ontology.json') + .then(function (response) { if (!response.ok) throw new Error('data unavailable'); return response.json(); }) + .then(function (data) { + root.innerHTML = ''; + var totalTags = (data.categories || []).reduce(function (sum, category) { return sum + category.tags.length; }, 0); + var summary = node('p', 'text-sm text-neutral-500', (data.categories || []).length + ' категорий · ' + totalTags + ' тем · ' + (data.repositories || []).length + ' репозиториев · ' + (data.gists || []).length + ' гистов'); + root.appendChild(summary); + (data.categories || []).forEach(function (category) { + var section = node('section', 'rounded-xl border border-neutral-200 p-5 dark:border-neutral-700'); + var title = node('h2', 'mt-0 text-xl font-bold'); + var link = node('a', 'hover:text-primary-600', category.title); + link.href = '/categories/' + encodeURIComponent(category.slug) + '/'; + title.appendChild(link); + section.appendChild(title); + if (!category.tags.length) section.appendChild(node('p', 'text-sm text-neutral-500', 'Пока нет связанных тегов.')); + var tags = node('div', 'flex flex-wrap gap-2'); + category.tags.forEach(function (tag) { + var chip = node('a', 'rounded-full bg-neutral-100 px-3 py-1 text-sm dark:bg-neutral-800', tag.slug + ' · ' + tag.postCount); + chip.href = '/tags/' + encodeURIComponent(tag.slug) + '/'; + tags.appendChild(chip); + }); + section.appendChild(tags); + root.appendChild(section); + }); + if (!data.categories || !data.categories.length) root.appendChild(node('p', 'text-neutral-500', 'Онтология пока не содержит категорий.')); + if (data.repositoryTopics && data.repositoryTopics.length) { + var topicsSection = node('section', 'rounded-xl border border-neutral-200 p-5 dark:border-neutral-700'); + topicsSection.appendChild(node('h2', 'mt-0 text-xl font-bold', 'Темы репозиториев')); + var topics = node('div', 'flex flex-wrap gap-2'); + data.repositoryTopics.slice(0, 30).forEach(function (topic) { + var chip = node('a', 'rounded-full border border-neutral-300 px-3 py-1 text-sm dark:border-neutral-600', topic.slug + ' · ' + topic.repoCount); + chip.href = 'https://github.com/topics/' + encodeURIComponent(topic.slug); + chip.target = '_blank'; chip.rel = 'noopener noreferrer'; + topics.appendChild(chip); + }); + topicsSection.appendChild(topics); + root.appendChild(topicsSection); + } + [['repositories', 'Репозитории', 12], ['gists', 'Gists', 12]].forEach(function (config) { + var items = data[config[0]] || []; + if (!items.length) return; + var section = node('section', 'rounded-xl border border-neutral-200 p-5 dark:border-neutral-700'); + section.appendChild(node('h2', 'mt-0 text-xl font-bold', config[1])); + var list = node('ul', 'grid gap-2 sm:grid-cols-2'); + items.slice(0, config[2]).forEach(function (item) { + var li = node('li'); + var link = node('a', 'font-medium hover:text-primary-600', config[0] === 'repositories' ? item.owner + '/' + item.name : item.description || item.id.replace(/^gist:/, 'Gist ')); + link.href = item.url; link.target = '_blank'; link.rel = 'noopener noreferrer'; + li.appendChild(link); + if (config[0] === 'gists') li.appendChild(node('span', 'ms-2 text-xs text-neutral-500', item.fileCount + ' файлов')); + list.appendChild(li); + }); + section.appendChild(list); + root.appendChild(section); + }); + }) + .catch(function () { root.innerHTML = '

Не удалось загрузить тематический указатель. Категории доступны на странице категорий, теги — в списке тегов.

'; }); +}());