Move and delete chapters by hand in the chapter list

The merge cannot always tell where new chapters go. For example, a site
can list an announcement before the chapters of an old book. You can now
select chapters and move them, in their order, to after another chapter
or to the start. You can also delete them with their revisions. A story
keeps at least one chapter. The book is then rebuilt. A deleted chapter
that the site still lists comes back with the next download.

The Move… and Delete… buttons open a dialog that names the selected
chapters before anything changes. A shift-click selects a range of
chapters.

The Select all checkbox moves into the first heading of the chapter
list. On a phone, that heading shows with the text "Select all".
This commit is contained in:
tim
2026-09-27 23:38:28 +02:00
parent ee611cd283
commit 8faab2463b
9 changed files with 306 additions and 15 deletions
+28
View File
@@ -482,6 +482,34 @@ def set_chapters_included(story_id: int, chapter_ids: list[int], included: bool)
return queue_story(story_id, DownloadMode.REBUILD.value)
def move_chapters(story_id: int, chapter_ids: list[int], after_id: int | None) -> dict[str, Any]:
"""Move chapters, in their current order, to directly after the chapter `after_id`, or to the start with None."""
order = [c["id"] for c in store.list_chapters(story_id)]
moving = [cid for cid in order if cid in set(chapter_ids)]
if not moving:
raise ValueError("Select the chapters to move")
if after_id is not None and after_id not in order:
raise KeyError(f"No chapter {after_id} in this story")
if after_id in moving:
raise ValueError("The chapters cannot go after a chapter that moves with them")
rest = [cid for cid in order if cid not in moving]
at = rest.index(after_id) + 1 if after_id is not None else 0
store.set_positions(story_id, rest[:at] + moving + rest[at:])
return queue_story(story_id, DownloadMode.REBUILD.value)
def delete_chapters(story_id: int, chapter_ids: list[int]) -> dict[str, Any]:
"""Delete chapters and their revisions. A chapter that the site still lists comes back with the next download."""
order = [c["id"] for c in store.list_chapters(story_id)]
deleting = [cid for cid in order if cid in set(chapter_ids)]
if not deleting:
raise ValueError("Select the chapters to delete")
if len(deleting) == len(order):
raise ValueError("A story must keep at least one chapter. To remove the story, stop tracking it")
store.delete_chapters(story_id, deleting)
return queue_story(story_id, DownloadMode.REBUILD.value)
def link_story(story_id: int, book_uuid: str | None) -> None:
"""Link a story to a library book by its uuid, or unlink it with None."""
story = _require_story(story_id)
+83 -6
View File
@@ -87,7 +87,12 @@ export function storyPage(main, { storyId }, config) {
const metadata = h('div', { class: 'metadata' });
const updates = h('div');
const chapters = h('div');
const selectAll = h('span', { class: 'chapter-select-all' });
// One dialog for Move… and Delete…. It names the selected chapters before anything changes.
const dialog = h('dialog', { class: 'chapter-dialog', 'aria-labelledby': 'chapter-dialog-title' });
let moveAfterId = null;
// A shift-click on a chapter checkbox sets every chapter from the last one clicked.
let anchor = null;
let shift = false;
const jobs = jobPanel({ hours: config.story_jobs_hours, count: config.story_jobs_count });
const linked = h('div');
const searchResults = h('div');
@@ -381,8 +386,17 @@ export function storyPage(main, { storyId }, config) {
function renderChapters() {
const list = details.chapters;
const ids = list.map((c) => c.id);
const pick = (i, on) => {
const from = shift ? ids.indexOf(anchor) : -1;
const range = from < 0 ? [ids[i]] : ids.slice(Math.min(from, i), Math.max(from, i) + 1);
for (const cid of range) on ? selected.add(cid) : selected.delete(cid);
anchor = ids[i];
shift = false;
if (range.length > 1) renderChapters();
};
let number = 0;
const rows = list.map((c) => {
const rows = list.map((c, i) => {
if (c.included) number += 1;
const route = `/story/${id}/chapter/${c.id}`;
return h(
@@ -391,8 +405,10 @@ export function storyPage(main, { storyId }, config) {
h(
'td',
{},
checkbox(selected.has(c.id), (on) => (on ? selected.add(c.id) : selected.delete(c.id)), {
checkbox(selected.has(c.id), (on) => pick(i, on), {
'aria-label': `Select ${chapterTitle(c.title)}`,
title: 'Shift-click to select all chapters from the last one you clicked',
onclick: (e) => (shift = e.shiftKey),
}),
),
h('td', { 'data-label': '#' }, c.included ? String(number) : ''),
@@ -412,11 +428,12 @@ export function storyPage(main, { storyId }, config) {
selected = new Set(on ? list.map((c) => c.id) : []);
renderChapters();
}, { 'aria-label': 'Select all chapters' });
fill(selectAll, h('label', {}, all, ' Select all'));
// A phone hides the other headings, so the text shows only there.
const selectAll = h('label', {}, all, h('span', { class: 'select-all-text' }, ' Select all'));
fill(
chapters,
table(
['', '#', 'Title', 'State', 'Revisions', 'Added'],
[selectAll, '#', 'Title', 'State', 'Revisions', 'Added'],
rows.length ? rows : h('tr', {}, h('td', { colspan: 6, class: 'empty' }, 'No chapters stored yet.')),
'chapters-table',
),
@@ -462,6 +479,64 @@ export function storyPage(main, { storyId }, config) {
await load();
};
const finish = async (message) => {
dialog.close();
toast(message);
refreshJobs();
await load();
};
const moveForm = (picked, chapterIds) => {
const others = details.chapters.filter((c) => !selected.has(c.id));
const after = h(
'select',
{ id: 'move-after' },
h('option', { value: '' }, 'The start'),
others.map((c) => h('option', { value: String(c.id) }, chapterTitle(c.title))),
);
after.value = others.some((c) => c.id === moveAfterId) ? String(moveAfterId) : '';
return [
h('div', { class: 'controls' }, h('label', { for: 'move-after' }, picked.length === 1 ? 'Put it after' : 'Put them after'), after),
button('Move', async () => {
moveAfterId = after.value === '' ? null : Number(after.value);
await api(`stories/${id}/chapters/move`, 'POST', { chapter_ids: chapterIds, after: moveAfterId });
await finish('Chapters moved. The book is being rebuilt.');
}, { class: 'primary' }),
];
};
const deleteForm = (picked, chapterIds) => [
h(
'p',
{},
`Bindery deletes ${picked.length === 1 ? 'this chapter and its' : 'these chapters and their'} revisions. `,
'You cannot undo this.',
picked.some((c) => c.on_site) ? ' A chapter that the site still lists comes back with the next download of new chapters.' : '',
),
button('Delete', async () => {
await api(`stories/${id}/chapters/delete`, 'POST', { chapter_ids: chapterIds });
await finish('Chapters deleted. The book is being rebuilt.');
}, { class: 'danger' }),
];
const openDialog = (verb) => {
if (!selected.size) {
toast('Select chapters first', true);
return;
}
const picked = details.chapters.filter((c) => selected.has(c.id));
const chapterIds = picked.map((c) => c.id);
const [body, action] = (verb === 'Move' ? moveForm : deleteForm)(picked, chapterIds);
fill(
dialog,
h('h3', { id: 'chapter-dialog-title' }, `${verb} ${plural(picked.length, 'chapter')}`),
h('ol', { class: 'dialog-chapters' }, picked.map((c) => h('li', {}, chapterTitle(c.title)))),
body,
h('div', { class: 'dialog-actions' }, h('button', { type: 'button', onclick: () => dialog.close() }, 'Cancel'), action),
);
dialog.showModal();
};
const modeHint = h('p', { class: 'hint' }, MODE_HINTS[mode]);
const modes = SITE_MODES.map((m) =>
h(
@@ -601,7 +676,6 @@ export function storyPage(main, { storyId }, config) {
'details',
{ class: 'card', open: true },
h('summary', {}, h('h2', {}, 'Chapters')),
selectAll,
h(
'div',
{ class: 'controls chapter-actions' },
@@ -610,8 +684,11 @@ export function storyPage(main, { storyId }, config) {
),
button('Take out of book', () => setIncluded(false)),
button('Put back in book', () => setIncluded(true)),
button('Move…', () => openDialog('Move')),
button('Delete…', () => openDialog('Delete'), { class: 'danger' }),
),
chapters,
dialog,
),
epubImport(id, 'Import chapters from an ePub'),
h('details', { class: 'card', open: true }, h('summary', {}, h('h2', {}, 'Recent jobs')), jobs.el),
+54 -5
View File
@@ -390,9 +390,8 @@ details.card[open] > summary .summary-action {
justify-content: space-between;
}
.chapter-select-all {
display: block;
margin-top: 8px;
.select-all-text {
display: none;
}
/* Stays visible while the chapter list scrolls, so the buttons need no scrolling back up to
@@ -768,8 +767,7 @@ textarea {
display: block;
}
.stories-table thead,
.chapters-table thead {
.stories-table thead {
position: absolute;
width: 1px;
height: 1px;
@@ -823,6 +821,57 @@ textarea {
flex-basis: 100%;
font-weight: 600;
}
/* Of the chapter list headings, only the Select all checkbox shows. */
/* The left padding is the 1px border and 12px padding of a row card, so the checkboxes line up. */
.chapters-table th {
border-bottom: 0;
padding: 0 0 8px 13px;
}
.chapters-table th:not(:first-child) {
display: none;
}
.select-all-text {
display: inline;
}
}
/* The Move… and Delete… dialog of the chapter list. */
.chapter-dialog {
width: min(32rem, calc(100vw - 32px));
max-height: calc(100dvh - 32px);
padding: 16px 20px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
color: var(--text);
}
.chapter-dialog::backdrop {
background: rgb(0 0 0 / 0.4);
}
.chapter-dialog h3 {
margin: 0 0 8px;
}
.dialog-chapters {
max-height: 40dvh;
overflow-y: auto;
margin: 0 0 12px;
padding: 8px 8px 8px 32px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--card-bg);
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
/* Jobs */
+7
View File
@@ -345,6 +345,13 @@ class Store:
[(i, cid, story_id) for i, cid in enumerate(chapter_ids)],
)
def delete_chapters(self, story_id: int, chapter_ids: list[int]) -> None:
"""Delete chapters of the story and their revisions."""
with self._connect() as conn:
conn.executemany(
"DELETE FROM chapters WHERE id = ? AND story_id = ?", [(cid, story_id) for cid in chapter_ids]
)
def list_revisions(self, chapter_id: int) -> list[dict[str, Any]]:
with self._connect() as conn:
rows = conn.execute(
+14
View File
@@ -332,6 +332,20 @@ def chapters_included(story_id: int) -> Any:
)
@app.post("/api/stories/<int:story_id>/chapters/move")
def move_chapters(story_id: int) -> Any:
data = _json()
after = data.get("after")
return orchestrator.move_chapters(
story_id, [int(c) for c in data.get("chapter_ids", [])], None if after is None else int(after)
)
@app.post("/api/stories/<int:story_id>/chapters/delete")
def delete_chapters(story_id: int) -> Any:
return orchestrator.delete_chapters(story_id, [int(c) for c in _json().get("chapter_ids", [])])
@app.get("/api/stories/<int:story_id>/epub")
def story_epub(story_id: int) -> Any:
path, title = orchestrator.build_for_download(story_id)