From c005954882cee0739df4e0eca789c838021ab727 Mon Sep 17 00:00:00 2001 From: nstarikov Date: Mon, 24 Aug 2026 12:05:21 +0300 Subject: [PATCH] feat: derive unique slugs from article titles --- admin/src/App.tsx | 41 +++++++++++++++++++++-------------------- app/routes.py | 22 +++++++++++++++------- 2 files changed, 36 insertions(+), 27 deletions(-) diff --git a/admin/src/App.tsx b/admin/src/App.tsx index 579a196..23c7eb9 100644 --- a/admin/src/App.tsx +++ b/admin/src/App.tsx @@ -389,6 +389,24 @@ async function api(path: string, init?: RequestInit): Promise { return response.json() as Promise } +const slugTransliteration: Record = { + а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "y", + к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u", ф: "f", + х: "h", ц: "ts", ч: "ch", ш: "sh", щ: "shch", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya", +} + +function slugFromTitle(title: string) { + return title + .toLowerCase() + .split("") + .map((character) => slugTransliteration[character] ?? character) + .join("") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 240) + .replace(/-+$/g, "") +} + type VkIdSdk = { Config: { init: (config: Record) => void } ConfigResponseMode?: { Callback?: unknown } @@ -2879,25 +2897,6 @@ export default function App() {

Редактирование статьи

{editorDirty ? "Есть правки" : "Сохранено"} -

Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.

@@ -3123,7 +3122,9 @@ export default function App() { className="mx-auto h-auto min-h-0 max-w-3xl resize-none overflow-hidden border-0 bg-transparent px-0 py-0 text-3xl font-bold leading-tight tracking-normal text-zinc-950 shadow-none focus-visible:ring-0 sm:text-4xl" value={editorTitle} onChange={(event) => { - setEditorTitle(event.target.value) + const title = event.target.value + setEditorTitle(title) + setEditorSlug(slugFromTitle(title)) setEditorDirty(true) }} /> diff --git a/app/routes.py b/app/routes.py index 5cb9dc3..7d2e50a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -74,6 +74,18 @@ def normalize_article_slug(value: str) -> str: return slug +def unique_article_slug(session: Session, value: str, article_id: int | None = None) -> str: + base = normalize_article_slug(value) + if not session.scalar(select(Article.id).where(Article.slug == base, Article.id != article_id)): + return base + for _ in range(10): + suffix = secrets.token_hex(3) + candidate = f"{base[: ARTICLE_SLUG_MAX_LENGTH - len(suffix) - 1].rstrip('-')}-{suffix}" + if not session.scalar(select(Article.id).where(Article.slug == candidate, Article.id != article_id)): + return candidate + raise HTTPException(status_code=409, detail="Не удалось подобрать уникальный slug.") + + class SourceIn(BaseModel): name: str url: str @@ -1253,15 +1265,11 @@ def update_article(article_id: int, payload: ArticleUpdateIn, session: Session = if not article: raise HTTPException(status_code=404, detail="Article not found") title = payload.title.strip() - next_slug = normalize_article_slug(payload.slug) if payload.slug is not None else article.slug - if next_slug != article.slug: - conflict = session.scalar(select(Article).where(Article.slug == next_slug, Article.id != article.id)) - if conflict: - raise HTTPException(status_code=409, detail="Этот slug уже используется другой статьёй.") - body = sanitize_article_editor_html(payload.editableHtml) - body = strip_leading_duplicate_title(body, title) if not title: raise HTTPException(status_code=422, detail="Title is required") + next_slug = unique_article_slug(session, payload.slug, article.id) if payload.slug is not None else article.slug + body = sanitize_article_editor_html(payload.editableHtml) + body = strip_leading_duplicate_title(body, title) signature_html = sanitize_article_editor_html(article.cta_html) if signature_html and signature_html in body: body = body.replace(signature_html, "").rstrip()