Compare commits

...

3 commits

5 changed files with 412 additions and 29 deletions

View file

@ -8,6 +8,8 @@ import {
AlertTriangle, AlertTriangle,
ArrowLeft, ArrowLeft,
CheckCircle2, CheckCircle2,
ChevronDown,
ChevronLeft,
Clock3, Clock3,
Copy, Copy,
ExternalLink, ExternalLink,
@ -1210,6 +1212,8 @@ export default function App() {
const [publishAt, setPublishAt] = useState("") const [publishAt, setPublishAt] = useState("")
const [editorDirty, setEditorDirty] = useState(false) const [editorDirty, setEditorDirty] = useState(false)
const [editorBusy, setEditorBusy] = useState(false) const [editorBusy, setEditorBusy] = useState(false)
const [articleCloseConfirmOpen, setArticleCloseConfirmOpen] = useState(false)
const [articleMoreOpen, setArticleMoreOpen] = useState(false)
const [featureImageBusy, setFeatureImageBusy] = useState(false) const [featureImageBusy, setFeatureImageBusy] = useState(false)
const [featureImageDragActive, setFeatureImageDragActive] = useState(false) const [featureImageDragActive, setFeatureImageDragActive] = useState(false)
const [featureImageHoverActive, setFeatureImageHoverActive] = useState(false) const [featureImageHoverActive, setFeatureImageHoverActive] = useState(false)
@ -1237,6 +1241,8 @@ export default function App() {
const selectedArticleRef = useRef<ArticleDetail | null>(null) const selectedArticleRef = useRef<ArticleDetail | null>(null)
const editorTitleRef = useRef("") const editorTitleRef = useRef("")
const titleTextareaRef = useRef<HTMLTextAreaElement | null>(null) const titleTextareaRef = useRef<HTMLTextAreaElement | null>(null)
const articleBackButtonRef = useRef<HTMLButtonElement | null>(null)
const articleMoreRef = useRef<HTMLDetailsElement | null>(null)
const articlesOffsetRef = useRef(0) const articlesOffsetRef = useRef(0)
const articlesLoadingRef = useRef(false) const articlesLoadingRef = useRef(false)
const articlesHasMoreRef = useRef(false) const articlesHasMoreRef = useRef(false)
@ -1627,6 +1633,8 @@ export default function App() {
setEditorTitle(result.title) setEditorTitle(result.title)
setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue()) setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue())
setEditorDirty(false) setEditorDirty(false)
setArticleCloseConfirmOpen(false)
setArticleMoreOpen(false)
appliedImageGenerationJobsRef.current = new Set() appliedImageGenerationJobsRef.current = new Set()
try { try {
const active = await fetch(`/api/articles/${id}/image-generations/active`) const active = await fetch(`/api/articles/${id}/image-generations/active`)
@ -1840,6 +1848,28 @@ export default function App() {
} }
}, [selectedArticle?.id, selectedArticle?.videoSourceUrl]) }, [selectedArticle?.id, selectedArticle?.videoSourceUrl])
useEffect(() => {
if (!selectedArticle) return
function handleArticleKeyDown(event: KeyboardEvent) {
if (event.key !== "Escape") return
if (articleMoreOpen) {
event.preventDefault()
articleMoreRef.current?.removeAttribute("open")
setArticleMoreOpen(false)
return
}
if (articleCloseConfirmOpen) {
event.preventDefault()
stayInArticle()
return
}
event.preventDefault()
requestArticleClose()
}
window.addEventListener("keydown", handleArticleKeyDown)
return () => window.removeEventListener("keydown", handleArticleKeyDown)
}, [selectedArticle, articleCloseConfirmOpen, articleMoreOpen, editorDirty])
function findImageBlockFromElement(target: EventTarget | null) { function findImageBlockFromElement(target: EventTarget | null) {
const editor = editorInstanceRef.current const editor = editorInstanceRef.current
if (!editor || !(target instanceof Element)) return null if (!editor || !(target instanceof Element)) return null
@ -2114,6 +2144,31 @@ export default function App() {
setSelectedArticle(null) setSelectedArticle(null)
} }
function requestArticleClose() {
if (!editorDirty) {
setSelectedArticle(null)
return
}
setArticleCloseConfirmOpen(true)
}
function stayInArticle() {
setArticleCloseConfirmOpen(false)
window.requestAnimationFrame(() => articleBackButtonRef.current?.focus())
}
function discardArticleChanges() {
setArticleCloseConfirmOpen(false)
setSelectedArticle(null)
}
async function saveAndCloseArticle() {
const saved = await saveArticle(false)
if (!saved) return
setArticleCloseConfirmOpen(false)
setSelectedArticle(null)
}
async function copyArticleText() { async function copyArticleText() {
if (!selectedArticle) return if (!selectedArticle) return
let text = "" let text = ""
@ -2698,6 +2753,10 @@ export default function App() {
<div className="article-modal-header flex min-w-0 items-start justify-between gap-4 border-b p-5"> <div className="article-modal-header flex min-w-0 items-start justify-between gap-4 border-b p-5">
<div className="article-modal-intro min-w-0 flex-1"> <div className="article-modal-intro min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Button ref={articleBackButtonRef} variant="ghost" size="default" className="article-back-button h-11 shrink-0 px-2" onClick={requestArticleClose}>
<ChevronLeft className="size-5" />
К черновикам
</Button>
{isScheduledForFuture(selectedArticle.publishedAt) ? ( {isScheduledForFuture(selectedArticle.publishedAt) ? (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline"> <Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<Clock3 className="size-3.5" /> <Clock3 className="size-3.5" />
@ -2707,13 +2766,14 @@ export default function App() {
<StatusBadge status={selectedArticle.status} /> <StatusBadge status={selectedArticle.status} />
)} )}
<h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2> <h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2>
{editorDirty ? <Badge variant="secondary">есть правки</Badge> : null} <Badge variant="secondary" className="article-save-state">{editorDirty ? "Есть правки" : "Сохранено"}</Badge>
</div> </div>
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.</p> <p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.</p>
</div> </div>
<div className="article-modal-actions flex shrink-0 flex-wrap justify-end gap-2"> <div className="article-modal-actions hidden shrink-0 flex-wrap justify-end gap-2 sm:flex">
<input <input
ref={featureImageInputRef} ref={featureImageInputRef}
id="article-feature-image-upload"
className="hidden" className="hidden"
type="file" type="file"
accept="image/*" accept="image/*"
@ -2767,25 +2827,63 @@ export default function App() {
<Button size="icon" variant="outline" disabled={editorBusy} title="Удалить" aria-label="Удалить" onClick={() => deleteArticle(selectedArticle.id)}> <Button size="icon" variant="outline" disabled={editorBusy} title="Удалить" aria-label="Удалить" onClick={() => deleteArticle(selectedArticle.id)}>
<Trash2 className="size-4" /> <Trash2 className="size-4" />
</Button> </Button>
<Button variant="outline" size="icon" title="Закрыть" aria-label="Закрыть" onClick={() => setSelectedArticle(null)}> </div>
<X className="size-4" /> <details
ref={articleMoreRef}
className="article-more-actions w-full sm:hidden"
onToggle={(event) => setArticleMoreOpen(event.currentTarget.open)}
>
<summary aria-expanded={articleMoreOpen} className="flex h-11 cursor-pointer list-none items-center justify-between rounded-md border bg-background px-3 text-sm font-medium shadow-sm">
Ещё
<ChevronDown className="size-4" aria-hidden="true" />
</summary>
<div className="mt-2 grid gap-2 rounded-md border bg-muted/30 p-2">
<Button variant="outline" className="h-11 justify-start" disabled={editorBusy} onClick={copyArticleText}>
<Copy data-icon="inline-start" />
Скопировать текст
</Button>
<Button
variant="outline"
className="h-11 justify-start whitespace-normal text-left"
disabled={editorBusy || imageGenerationStarting || Boolean(imageGenerationBatch && !["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status))}
onClick={() => startImageGeneration("all")}
>
{imageGenerationStarting ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <ImagePlus data-icon="inline-start" />}
Сгенерировать изображения
</Button>
{selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? (
<label className="article-publish-time flex h-11 items-center gap-2 rounded-md border bg-background px-3 text-xs text-muted-foreground" title="Время выхода в RSS">
<Clock3 className="size-4" />
<input
type="datetime-local"
className="min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none"
value={publishAt}
onChange={(event) => setPublishAt(event.target.value)}
/>
</label>
) : (
<Button variant="outline" className="h-11 justify-start" onClick={() => window.open(selectedArticle.url, "_blank")}>
<ExternalLink data-icon="inline-start" />
Открыть на сайте
</Button>
)}
<Button variant="outline" className="h-11 justify-start text-destructive hover:text-destructive" disabled={editorBusy} onClick={() => deleteArticle(selectedArticle.id)}>
<Trash2 data-icon="inline-start" />
Удалить
</Button> </Button>
</div> </div>
</details>
</div> </div>
<div className="article-modal-body overflow-y-auto bg-zinc-50 p-4 sm:p-6"> <div className="article-modal-body overflow-y-auto bg-zinc-50 p-4 sm:p-6">
<article className="article-modal-content mx-auto w-full max-w-[1024px] rounded-lg border bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10"> <article className="article-modal-content mx-auto w-full max-w-[1024px] rounded-lg border bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10">
<div className="mb-6"> <div className="mb-6">
<div className="mb-2 flex items-center justify-between gap-3"> <div className="article-feature-image-heading mb-2 flex items-center justify-between gap-3">
<div> <div className="min-w-0">
<p className="text-sm font-semibold text-zinc-950">Feature Image</p> <p className="text-sm font-semibold text-zinc-950">Feature Image</p>
<p className="text-xs text-muted-foreground">Главная обложка публикации для RSS и Дзена.</p> <p className="text-xs text-muted-foreground">Главная обложка публикации для RSS и Дзена.</p>
</div> </div>
<Button <div className="article-feature-image-controls flex flex-wrap gap-2">
size="sm" <Button size="sm" variant="outline" disabled={featureImageBusy} onClick={() => featureImageInputRef.current?.click()}>
variant="outline"
disabled={featureImageBusy}
onClick={() => featureImageInputRef.current?.click()}
>
<ImagePlus data-icon="inline-start" className={featureImageBusy ? "animate-pulse" : ""} /> <ImagePlus data-icon="inline-start" className={featureImageBusy ? "animate-pulse" : ""} />
Выбрать Выбрать
</Button> </Button>
@ -2799,10 +2897,13 @@ export default function App() {
Перегенерировать обложку Перегенерировать обложку
</Button> </Button>
</div> </div>
<div </div>
className={`relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed transition ${ <button
type="button"
className={`relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed text-left transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${
featureImageDragActive ? "border-primary bg-primary/5" : "border-zinc-300 bg-zinc-50 hover:bg-zinc-100" featureImageDragActive ? "border-primary bg-primary/5" : "border-zinc-300 bg-zinc-50 hover:bg-zinc-100"
}`} }`}
aria-label="Выбрать обложку статьи"
onClick={() => featureImageInputRef.current?.click()} onClick={() => featureImageInputRef.current?.click()}
onMouseEnter={() => { onMouseEnter={() => {
clearEditorImageHover() clearEditorImageHover()
@ -2856,7 +2957,7 @@ export default function App() {
</div> </div>
</div> </div>
) : null} ) : null}
</div> </button>
</div> </div>
{imageGenerationBatch ? ( {imageGenerationBatch ? (
<section className="image-generation-status mb-6 rounded-md border bg-zinc-50 p-3" aria-live="polite"> <section className="image-generation-status mb-6 rounded-md border bg-zinc-50 p-3" aria-live="polite">
@ -2903,8 +3004,36 @@ export default function App() {
/> />
</article> </article>
</div> </div>
<div className="article-mobile-actions grid gap-2 border-t bg-background p-3 sm:hidden">
<Button className="h-11 w-full" variant="outline" disabled={editorBusy || !editorDirty} onClick={() => saveArticle()}>
{editorBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Save data-icon="inline-start" />}
Сохранить
</Button>
{selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? (
<Button className="h-11 w-full" disabled={editorBusy} onClick={saveAndPublishArticle}>
{editorBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Radio data-icon="inline-start" />}
{isScheduledForFuture(publishAt) ? "Запланировать" : "Опубликовать"}
</Button>
) : null}
</div> </div>
</div> </div>
{articleCloseConfirmOpen ? (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm" role="presentation">
<section className="w-full max-w-sm rounded-lg border bg-background p-5 shadow-lg" role="dialog" aria-modal="true" aria-labelledby="article-close-confirm-title" aria-describedby="article-close-confirm-description">
<h3 id="article-close-confirm-title" className="text-lg font-semibold">Сохранить изменения?</h3>
<p id="article-close-confirm-description" className="mt-2 text-sm text-muted-foreground">Несохранённые правки останутся только в этом браузере и будут потеряны при выходе.</p>
<div className="mt-5 grid gap-2 sm:flex sm:justify-end">
<Button variant="outline" className="h-11" onClick={stayInArticle}>Остаться</Button>
<Button variant="outline" className="h-11" disabled={editorBusy} onClick={discardArticleChanges}>Не сохранять</Button>
<Button className="h-11" disabled={editorBusy} onClick={() => void saveAndCloseArticle()}>
{editorBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : null}
Сохранить и выйти
</Button>
</div>
</section>
</div>
) : null}
</div>
) : null} ) : null}
</main> </main>
) )

View file

@ -19,6 +19,7 @@ const buttonVariants = cva(
sm: "h-8 rounded-md px-3 text-xs", sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8", lg: "h-10 rounded-md px-8",
icon: "size-9", icon: "size-9",
touchIcon: "size-11",
}, },
}, },
defaultVariants: { defaultVariants: {
@ -40,4 +41,3 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
Button.displayName = "Button" Button.displayName = "Button"
export { Button, buttonVariants } export { Button, buttonVariants }

View file

@ -466,6 +466,10 @@
border-right: 0; border-right: 0;
} }
.modal-panel:has(.article-modal-body) {
min-width: 0;
}
.article-modal-header { .article-modal-header {
flex-direction: column; flex-direction: column;
gap: 0.75rem; gap: 0.75rem;
@ -481,6 +485,11 @@
line-height: 1.35; line-height: 1.35;
} }
.article-save-state {
max-width: 100%;
overflow-wrap: anywhere;
}
.article-modal-actions { .article-modal-actions {
width: 100%; width: 100%;
justify-content: flex-start; justify-content: flex-start;
@ -497,13 +506,39 @@
} }
.article-modal-body { .article-modal-body {
min-height: 0;
flex: 1 1 auto;
padding: 0.75rem; padding: 0.75rem;
} }
.article-modal-content { .article-modal-content {
min-width: 0;
padding: 1rem; padding: 1rem;
} }
.article-feature-image-heading {
align-items: flex-start;
flex-direction: column;
}
.article-feature-image-controls {
width: 100%;
}
.article-feature-image-controls > button {
min-height: 2.75rem;
flex: 1 1 100%;
white-space: normal;
overflow-wrap: anywhere;
}
.article-mobile-actions {
position: sticky;
bottom: 0;
z-index: 2;
padding-bottom: max(0.75rem, env(safe-area-inset-bottom));
}
.article-modal-content .article-editorjs .ce-block__content, .article-modal-content .article-editorjs .ce-block__content,
.article-modal-content .article-editorjs .ce-toolbar__content { .article-modal-content .article-editorjs .ce-toolbar__content {
max-width: calc(100vw - 4rem); max-width: calc(100vw - 4rem);

View file

@ -0,0 +1,173 @@
# Mobile Article Editor Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make the existing article editor usable on a 320–430 px phone, with an explicit safe return to drafts and no horizontal overflow.
**Architecture:** Keep the current `selectedArticle` overlay and Editor.js instance. Add a small, local editor-navigation state machine in `App.tsx` for close confirmation and a mobile-only command hierarchy: persistent back/status top bar, main save/publish bottom bar, and a native disclosure for secondary actions. Use scoped CSS in `index.css` so desktop controls preserve their current layout.
**Tech Stack:** React 19, TypeScript, Tailwind CSS, shadcn-style `Button`, Editor.js, Vite.
---
## File structure
- Modify: `admin/src/App.tsx` — editor return guard, responsive action groups, semantic feature-image trigger and keyboard handling.
- Modify: `admin/src/index.css` — 640 px task-view layout, safe-area bottom actions, touch sizes and no-overflow rules.
- Modify: `admin/src/components/ui/button.tsx` — add a reusable 44 px `touch-icon` button size without changing existing compact desktop sizes.
### Task 1: Safe return from the editor
**Files:**
- Modify: `admin/src/App.tsx:1211-1235,1624-1640,2108-2115,2695-2773`
- [ ] **Step 1: Reproduce the loss-of-context path**
Run the Vite app, open a draft, make a title change, then use the current close icon.
Expected: the modal closes immediately, with no explicit return label or save/discard decision.
- [ ] **Step 2: Add local close-confirmation state and a single `requestArticleClose` function**
Add `articleCloseConfirmOpen` beside the existing editor state. Implement `requestArticleClose` so it calls `setSelectedArticle(null)` immediately only when `editorDirty` is false; otherwise it opens a confirmation panel. Implement explicit handlers: `stayInArticle`, `discardArticleChanges`, and `saveAndCloseArticle` (await `saveArticle(false)` first; only close after it resolves).
```ts
function requestArticleClose() {
if (!editorDirty) {
setSelectedArticle(null)
return
}
setArticleCloseConfirmOpen(true)
}
async function saveAndCloseArticle() {
const saved = await saveArticle(false)
if (saved) setSelectedArticle(null)
}
```
- [ ] **Step 3: Route all editor exits through the guard**
Replace the header close callback with `requestArticleClose`. In `saveAndPublishArticle`, retain closing only after the successful publish request. Add a `keydown` effect active while `selectedArticle` is set: Escape closes the secondary-actions disclosure if open, otherwise calls `requestArticleClose`.
- [ ] **Step 4: Render an accessible confirmation panel**
Render a labelled modal/panel only while `articleCloseConfirmOpen` is true. It must contain: title «Сохранить изменения?», text explaining that unsaved edits stay only in this browser, and buttons «Остаться», «Не сохранять», «Сохранить и выйти». Disable the save button while `editorBusy` is true. Return focus to the «К черновикам» trigger when the panel closes.
- [ ] **Step 5: Manually verify return behavior**
Check each branch: clean back closes; dirty → stay remains; dirty → discard closes; dirty → save waits for the PATCH, then closes; publish still refreshes the list and closes only on success.
- [ ] **Step 6: Commit**
```bash
git add admin/src/App.tsx
git commit -m "feat: guard article editor return"
```
### Task 2: Establish the mobile command hierarchy
**Files:**
- Modify: `admin/src/App.tsx:2695-2776`
- Modify: `admin/src/components/ui/button.tsx:5-30`
- [ ] **Step 1: Establish the expected mobile arrangement**
At 390 px, inspect the editor header. Expected failure before the change: the primary navigation competes with a copy button, a long generate button, save, date input, publish, delete, and close.
- [ ] **Step 2: Add a 44 px icon-button size**
Extend the `size` variants in `button.tsx` with `touch-icon: "size-11"`. Keep `icon` at 36 px so lists and desktop controls do not shift.
```ts
touchIcon: "size-11",
```
Use the TypeScript-compatible variant key actually chosen in the component (`touchIcon`), not a hyphenated prop.
- [ ] **Step 3: Split editor actions into persistent and secondary groups**
In the selected-article header, add a labelled back button containing `ChevronLeft` and visible text «К черновикам» that calls `requestArticleClose`. Keep the current article status and save state in the top section. Put copy, image generation, schedule input and deletion into a `<details>` / `<summary>` labelled «Ещё» on mobile; desktop keeps the existing direct controls through responsive utility classes. Leave the current save and publish callbacks unchanged.
- [ ] **Step 4: Add a mobile action footer**
Render a `.article-mobile-actions` group after the scrollable editor body. It has a full-width «Сохранить» button (disabled if clean or busy) and a full-width «Опубликовать»/«Запланировать» button based on the existing `isScheduledForFuture` and `publishAt` state. Both reuse `saveArticle` and `saveAndPublishArticle`; no duplicate request code.
- [ ] **Step 5: Preserve keyboard semantics**
Use real `<button>` controls for back, save, publish and the secondary disclosure. Set `aria-expanded` on the disclosure trigger and make Escape close it before requesting return. Ensure the newly introduced buttons use `touchIcon` or `h-11` at mobile widths.
- [ ] **Step 6: Verify the 390 px primary flow**
Open a draft at 390 px. Confirm «К черновикам», save state, save and publish are visible without horizontal scroll; copy/generate/date/delete are reachable through «Ещё»; desktop still shows direct actions.
- [ ] **Step 7: Commit**
```bash
git add admin/src/App.tsx admin/src/components/ui/button.tsx
git commit -m "feat: prioritize mobile article editor actions"
```
### Task 3: Make feature-image controls and layout responsive and accessible
**Files:**
- Modify: `admin/src/App.tsx:2775-2859`
- Modify: `admin/src/index.css:454-511`
- [ ] **Step 1: Capture the current responsive failure**
At 390 px inspect `.article-modal-content`. Expected failure: its feature-image title, description, «Выбрать» and «Перегенерировать обложку» share one non-wrapping flex row; the document becomes wider than the viewport.
- [ ] **Step 2: Make feature-image actions reflow**
Give the descriptive feature-image group `min-w-0`; give its control container `flex flex-wrap gap-2`; at max-width 640 px make its buttons grow to available width and allow their labels to wrap. Do not use horizontal scrolling or clipped text as the fix.
- [ ] **Step 3: Replace the clickable upload `div` with a semantic trigger**
Keep the hidden file input, but make the visual upload area a `<label htmlFor={...}>` or a `button type="button"` with an accessible name such as «Выбрать обложку статьи». Retain drag/drop and paste enhancement handlers. If a button is used, preserve keyboard Enter/Space through native button behavior and prevent nested interactive controls.
- [ ] **Step 4: Add mobile safe-area and no-overflow CSS**
At `@media (max-width: 640px)`, ensure the article modal is a column with the editor body as its only scrolling region. Add bottom padding equal to the footer height plus `env(safe-area-inset-bottom)`. Give `.article-mobile-actions` a sticky bottom position, `padding-bottom: max(0.75rem, env(safe-area-inset-bottom))`, opaque background and top border. Add `min-width: 0` at flex boundaries and `overflow-wrap: anywhere` only to long control labels/status text.
- [ ] **Step 5: Build and inspect the bounded responsive matrix**
Run:
```bash
npm run build --prefix admin
```
Expected: TypeScript and Vite build complete successfully.
Inspect at 320, 375, 390 and 430 px, plus desktop. At each phone width execute in DevTools:
```js
document.documentElement.scrollWidth <= window.innerWidth
```
Expected: `true`. Check title at 200% text zoom, the feature-image picker by Tab/Enter, all close-confirmation paths, Escape and the iOS safe-area visual result.
- [ ] **Step 6: Run Impeccable detector and final diff checks**
Run:
```bash
node /Users/dima/.agents/skills/impeccable/scripts/detect.mjs --json admin/src/App.tsx admin/src/index.css admin/src/components/ui/button.tsx
git diff --check
```
Expected: detector findings reviewed in context and `git diff --check` has no output.
- [ ] **Step 7: Commit**
```bash
git add admin/src/App.tsx admin/src/index.css
git commit -m "fix: adapt article editor for mobile"
```
## Plan review
- Spec coverage: task 1 covers explicit return and unsaved-edit protection; task 2 covers persistent primary controls and secondary command disclosure; task 3 covers feature-image overflow, semantic upload, touch/safe-area rules, and responsive/a11y verification.
- No API or database changes are required; all actions reuse existing callbacks and article state.
- The project has no configured unit-test runner, so each behavior is verified through deterministic build output and the stated mobile interaction matrix instead of adding a test framework solely for this focused UI repair.

View file

@ -0,0 +1,46 @@
# Мобильный редактор статьи
## Цель
Сделать редактор статьи выполнимой мобильной задачей: редактор всегда даёт понятный путь обратно к исходным черновикам, не создаёт горизонтальную прокрутку и оставляет публикацию доступным действием.
## Границы
Изменяется только мобильная оболочка существующего редактора статьи и её адаптивные стили. Существующие данные статьи, Editor.js, генерация изображений, сохранение и RSS-публикация не меняют контрактов.
## Сценарий
1. Администратор открывает черновик из карточки ролика.
2. На экранах до 640 px редактор занимает весь viewport. В верхней панели всегда видны кнопка «К черновикам» и состояние сохранения.
3. При возврате с несохранёнными изменениями интерфейс предлагает сохранить их, отбросить или остаться в редакторе. После подтверждённого сохранения, отмены или публикации пользователь возвращается к исходному списку черновиков.
4. Внизу редактора расположены крупные действия: «Сохранить» и «Опубликовать» (либо «Запланировать» для будущей даты). Второстепенные действия открываются по кнопке «Ещё».
5. Блок Feature Image становится одноколоночным: описание, кнопки «Выбрать» и «Перегенерировать обложку», затем зона изображения. Ни строка, ни кнопки не должны выходить за viewport.
## Структура интерфейса
- Верхняя панель: `← К черновикам`, статус «Сохранено» или «Есть правки» и меню «Ещё».
- Содержимое: статус черновика, название, редактор и блок обложки в естественном порядке.
- Нижняя закреплённая панель: явное сохранение и публикация; область учитывает безопасную зону iOS.
- Меню «Ещё»: копирование текста, генерация изображений, изменение времени публикации, удаление и закрытие на больших экранах. Опасное удаление визуально отделено.
## Доступность и отзывчивость
- Все основные touch-цели на мобильном экране имеют размер не меньше 44 x 44 px.
- Обложка остаётся нативным доступным `input`/`label` либо семантической кнопкой с доступным именем; drag-and-drop и вставка из буфера — только дополнительный способ.
- У контролов есть понятные aria-label; Escape закрывает второстепенное меню или запускает тот же безопасный сценарий возврата.
- На ширинах 320, 375, 390 и 430 px `document.documentElement.scrollWidth` не больше `window.innerWidth`; текст и увеличенный размер шрифта не обрезают действия.
## Состояния и ошибки
- Во время сохранения или публикации кнопки блокируются и показывают состояние операции.
- Ошибка сохранения не закрывает редактор и оставляет текст на месте.
- Если пользователь открывает возврат с правками, он не теряет их без явного выбора.
- После публикации редактор закрывается, как и сейчас, но возврат ведёт к исходному черновику/ролику.
## Проверка
1. Открыть черновик и вернуться без правок: виден исходный список черновиков.
2. Внести правки, проверить все три варианта диалога возврата.
3. Сохранить, запланировать и опубликовать черновик; убедиться, что сохранение не теряется и список корректно обновлён.
4. Проверить обложку, меню и нижнюю панель на 320, 375, 390 и 430 px, включая iOS safe area и масштаб текста 200%.
5. Выполнить клавиатурную проверку: Tab, Enter/Space для загрузки обложки и Escape.