Skip to content

Build your personal knowledge base with Trilium Notes

feat(bulk_actions): name the note count on the execute button

Elian Doran21b73add159f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 83ca273c30..62bb709a08 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -93,7 +93,10 @@
"add_action": "Add action",
"chosen_actions": "Chosen actions",
"remove_action": "Remove this action",
- "execute_bulk_actions": "Execute bulk actions",
+ "execute_bulk_actions_one": "Apply to {{count}} note",
+ "execute_bulk_actions_other": "Apply to {{count}} notes",
+ "no_actions_to_execute": "Add an action first.",
+ "no_notes_to_execute_on": "None of the selected notes exist any more.",
"bulk_actions_executed": "Bulk actions have been executed successfully.",
"none_yet": "No actions yet. Use Add action below to choose one.",
"labels": "Labels",
diff --git a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx
index 3ee87aaef0..3448f07605 100644
--- a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx
+++ b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx
@@ -132,6 +132,49 @@ describe("BulkActionsDialog", () => {
}
});
+ it("names the note count on the execute button and enables it only with actions and notes to run on", async () => {
+ function executeButton() {
+ const button = container.querySelector<HTMLButtonElement>(".modal-footer button[name='execute-bulk-actions']");
+ if (!button) throw new Error("No execute button.");
+ return button;
+ }
+
+ server.post.mockResolvedValue({ affectedNoteCount: 3 });
+ await open([ "n1", "n2" ]);
+ expect(executeButton().textContent).toContain("bulk_actions.execute_bulk_actions:3");
+ expect(executeButton().disabled).toBe(true);
+
+ buildNote({ id: "_bulkAction", title: "Bulk action", "#action": JSON.stringify({ name: "deleteRevisions" }) });
+ await open([ "n1", "n2" ]);
+ expect(executeButton().disabled).toBe(false);
+
+ server.post.mockResolvedValue({ affectedNoteCount: 0 });
+ await open([ "gone" ]);
+ expect(executeButton().textContent).toContain("bulk_actions.execute_bulk_actions:0");
+ expect(executeButton().disabled).toBe(true);
+ });
+
+ it("runs the actions once, however often the execute button is pressed", async () => {
+ buildNote({ id: "_bulkAction", title: "Bulk action", "#action": JSON.stringify({ name: "deleteRevisions" }) });
+ server.post.mockResolvedValue({ affectedNoteCount: 1 });
+ await open([ "n1" ]);
+
+ let finish = () => {};
+ server.post.mockImplementation((url: string) => (url === "bulk-action/execute"
+ ? new Promise<void>((resolve) => { finish = resolve; })
+ : Promise.resolve({ affectedNoteCount: 1 })));
+ const form = container.querySelector("form");
+ if (!form) throw new Error("The dialog has no form.");
+ await act(async () => {
+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+
+ expect(server.post.mock.calls.filter(([ url ]) => url === "bulk-action/execute")).toHaveLength(1);
+ expect(container.querySelector<HTMLButtonElement>("button[name='execute-bulk-actions']")?.disabled).toBe(true);
+ await act(async () => finish());
+ });
+
it("drops a removed chip from the notes the actions apply to, keeping the last one", async () => {
await open([ "n1", "n2" ]);
expect(lastAffectedNotesRequest()).toStrictEqual({ noteIds: [ "n1", "n2" ], includeDescendants: false });
diff --git a/apps/client/src/widgets/dialogs/bulk_actions.tsx b/apps/client/src/widgets/dialogs/bulk_actions.tsx
index 2f20bec14c..2c972ea32e 100644
--- a/apps/client/src/widgets/dialogs/bulk_actions.tsx
+++ b/apps/client/src/widgets/dialogs/bulk_actions.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, useCallback } from "preact/hooks";
+import { useEffect, useState, useCallback, useRef } from "preact/hooks";
import { t } from "../../services/i18n";
import Modal from "../react/Modal";
import "./bulk_actions.css";
@@ -27,23 +27,31 @@ export default function BulkActionsDialog() {
const [ selectedOrActiveNoteIds, setSelectedOrActiveNoteIds ] = useState<string[]>();
const [ bulkActionNote, setBulkActionNote ] = useState<FNote | null>();
const [ includeDescendants, setIncludeDescendants ] = useState(false);
- const [ affectedNoteCount, setAffectedNoteCount ] = useState(0);
+ const [ affectedNoteCount, setAffectedNoteCount ] = useState<number>();
const [ existingActions, setExistingActions ] = useState<AbstractBulkAction[]>([]);
+ const [ executing, setExecuting ] = useState(false);
+ // Read by `onSubmit`, which a second submit reaches before the re-render that `executing` needs.
+ const executingRef = useRef(false);
const [ shown, setShown ] = useState(false);
useTriliumEvent("openBulkActionsDialog", async ({ selectedOrActiveNoteIds }) => {
setSelectedOrActiveNoteIds(selectedOrActiveNoteIds);
+ setAffectedNoteCount(undefined);
setBulkActionNote(await froca.getNote("_bulkAction"));
setShown(true);
});
useEffect(() => {
if (!selectedOrActiveNoteIds || !bulkActionNote) return;
-
+
+ let stale = false;
server.post<BulkActionAffectedNotes>("bulk-action/affected-notes", {
noteIds: selectedOrActiveNoteIds,
includeDescendants
- }).then(({ affectedNoteCount }) => setAffectedNoteCount(affectedNoteCount));
+ }).then(({ affectedNoteCount }) => {
+ if (!stale) setAffectedNoteCount(affectedNoteCount);
+ });
+ return () => { stale = true; };
}, [ selectedOrActiveNoteIds, includeDescendants, bulkActionNote ]);
const refreshExistingActions = useCallback(() => {
@@ -62,6 +70,11 @@ export default function BulkActionsDialog() {
}
});
+ const disabledReason = !existingActions.length
+ ? t("bulk_actions.no_actions_to_execute")
+ : affectedNoteCount === 0 ? t("bulk_actions.no_notes_to_execute_on") : undefined;
+ const canExecute = !disabledReason && affectedNoteCount !== undefined && !executing;
+
return (
<Modal
className="bulk-actions-dialog"
@@ -69,34 +82,52 @@ export default function BulkActionsDialog() {
title={t("bulk_actions.bulk_actions")}
footer={<>
<Button text={t("modal.cancel")} onClick={() => setShown(false)} />
- <Button text={t("bulk_actions.execute_bulk_actions")} kind="primary" />
+ <Button
+ name="execute-bulk-actions"
+ kind="primary"
+ // Until the server has counted, the selection is the best estimate: it is exact
+ // unless descendants are included.
+ text={t("bulk_actions.execute_bulk_actions", {
+ count: affectedNoteCount ?? selectedOrActiveNoteIds?.length ?? 0
+ })}
+ disabled={!canExecute}
+ disabledTooltip={disabledReason}
+ />
</>}
show={shown}
onSubmit={async () => {
- // Let actions surface a confirmation prompt (e.g. lossy conversions) before executing.
- const confirmMessages = existingActions
- .map((action) => action.getConfirmationMessage())
- .filter((message): message is string => !!message);
- if (confirmMessages.length && !await dialog.confirm(confirmMessages.join("\n\n"))) {
- return;
- }
+ if (!canExecute || executingRef.current) return;
+ executingRef.current = true;
+ setExecuting(true);
+ try {
+ // Let actions surface a confirmation prompt (e.g. lossy conversions) before executing.
+ const confirmMessages = existingActions
+ .map((action) => action.getConfirmationMessage())
+ .filter((message): message is string => !!message);
+ if (confirmMessages.length && !await dialog.confirm(confirmMessages.join("\n\n"))) {
+ return;
+ }
- // Submit the in-memory action definitions rather than letting the server re-read the
- // stored labels, so a still-in-flight action save can't make the batch run against a
- // stale/empty choice.
- const actions = existingActions.map((action) => ({
- ...action.actionDef,
- name: (action.constructor as typeof AbstractBulkAction).actionName
- }));
-
- await server.post("bulk-action/execute", {
- noteIds: selectedOrActiveNoteIds,
- includeDescendants,
- actions
- });
-
- toast.showMessage(t("bulk_actions.bulk_actions_executed"), 3000);
- setShown(false);
+ // Submit the in-memory action definitions rather than letting the server re-read the
+ // stored labels, so a still-in-flight action save can't make the batch run against a
+ // stale/empty choice.
+ const actions = existingActions.map((action) => ({
+ ...action.actionDef,
+ name: (action.constructor as typeof AbstractBulkAction).actionName
+ }));
+
+ await server.post("bulk-action/execute", {
+ noteIds: selectedOrActiveNoteIds,
+ includeDescendants,
+ actions
+ });
+
+ toast.showMessage(t("bulk_actions.bulk_actions_executed"), 3000);
+ setShown(false);
+ } finally {
+ executingRef.current = false;
+ setExecuting(false);
+ }
}}
onHidden={() => setShown(false)}
>
@@ -110,7 +141,7 @@ export default function BulkActionsDialog() {
<OptionsRowWithToggle
name="include-descendants"
label={t("bulk_actions.include_descendants")}
- description={t("bulk_actions.affected_note_count", { count: affectedNoteCount })}
+ description={t("bulk_actions.affected_note_count", { count: affectedNoteCount ?? 0 })}
currentValue={includeDescendants} onChange={setIncludeDescendants}
/>
</CardSection>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html
index 76cd1de9fe..8c00aee2ea 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html
@@ -43,8 +43,9 @@
multiple types.</li>
</ul>
</li>
- <li>When all the actions are defined, press <em>Execute bulk actions</em> to
- trigger all of them at once.</li>
+ <li>When all the actions are defined, press the <em>Apply to N notes</em> button
+ to trigger all of them at once. The button names the number of notes that
+ will be affected, and stays disabled until at least one action is added.</li>
<li>For convenience, the last bulk action configuration is saved for further
use and will be restored when entering the dialog again.</li>
</ul>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md b/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md
index e63280f086..b733e2f02b 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md
@@ -16,7 +16,7 @@ The _Bulk Actions_ dialog makes it easy to apply changes to multiple notes at on
* Each chosen action appears as an entry in the _Chosen actions_ section, with its own configuration.
* To remove an action, simply press the X button to the right of it.
* It is possible to apply multiple actions of the same type, such as adding multiple types.
-* When all the actions are defined, press _Execute bulk actions_ to trigger all of them at once.
+* When all the actions are defined, press the _Apply to N notes_ button to trigger all of them at once. The button names the number of notes that will be affected, and stays disabled until at least one action is added.
* For convenience, the last bulk action configuration is saved for further use and will be restored when entering the dialog again.
## Actions