feat: derive unique slugs from article titles
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 27s
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 27s
This commit is contained in:
parent
df82280121
commit
c005954882
2 changed files with 36 additions and 27 deletions
|
|
@ -389,6 +389,24 @@ async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
|||
return response.json() as Promise<T>
|
||||
}
|
||||
|
||||
const slugTransliteration: Record<string, string> = {
|
||||
а: "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<string, unknown>) => void }
|
||||
ConfigResponseMode?: { Callback?: unknown }
|
||||
|
|
@ -2879,25 +2897,6 @@ export default function App() {
|
|||
<h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2>
|
||||
<Badge variant="secondary" className="article-save-state">{editorDirty ? "Есть правки" : "Сохранено"}</Badge>
|
||||
</div>
|
||||
<label className="mt-3 block max-w-3xl">
|
||||
<span className="mb-1 block text-xs font-medium text-muted-foreground">Slug публикации</span>
|
||||
<span className="flex min-w-0 items-center rounded-md border bg-background px-3 shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-1">
|
||||
<span className="shrink-0 text-sm text-muted-foreground">/posts/</span>
|
||||
<input
|
||||
className="min-w-0 flex-1 bg-transparent px-1 py-2 text-sm text-foreground outline-none"
|
||||
value={editorSlug}
|
||||
maxLength={240}
|
||||
spellCheck={false}
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
onChange={(event) => {
|
||||
setEditorSlug(event.target.value)
|
||||
setEditorDirty(true)
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">Строчные латинские буквы, цифры и дефисы.</span>
|
||||
</label>
|
||||
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.</p>
|
||||
</div>
|
||||
<div className="article-modal-actions hidden shrink-0 flex-wrap justify-end gap-2 sm:flex">
|
||||
|
|
@ -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)
|
||||
}}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
Loading…
Reference in a new issue