Line data Source code
1 : import type { StorageBackend } from '../../storage/storage_backend.js';
2 : import { RENAME_ATTACHMENT, type SessionScripts } from '../scripts/session_scripts.js';
3 : import type { ModifySessionScripts } from '../scripts/session_scripts_registry.js';
4 : import type { RenameDraftReferences } from '../scripts/script_rename.js';
5 : import { scriptDisplayName } from '../scripts/script_types.js';
6 : import { markSessionAttachmentsChanged } from './attachment_mounts.js';
7 : import { attachmentParameterName, renamedAttachmentFileName } from './session_attachments.js';
8 :
9 : /// Rename an attachment like a script: the file moves, the scripts that read its table parameter read the new name
10 : /// (`RENAME_ATTACHMENT`) and so does the draft. The name takes no name of a script or another attachment, `sales`
11 : /// becomes `sales-2` then. Returns the new file name, null if the name is no plain file name or unchanged.
12 1 : export async function renameAttachment(
13 1 : session: SessionScripts,
14 1 : modify: ModifySessionScripts,
15 1 : backend: Pick<StorageBackend, 'renameDataFile'>,
16 1 : fileName: string,
17 1 : requested: string,
18 1 : renameDraft: RenameDraftReferences | null | undefined,
19 1 : ): Promise<string | null> {
20 1 : const attachments = session.attachments ?? [];
21 1 : if (!attachments.some(attachment => attachment.fileName === fileName)) return null;
22 1 : const scriptNames = session.scriptOrder.map(scriptDisplayName);
23 1 : const newFileName = renamedAttachmentFileName(fileName, requested, scriptNames, attachments);
24 1 : if (newFileName == null || newFileName === fileName) return null;
25 : // The scripts read the new name once the file has it
26 1 : await backend.renameDataFile(session.sessionId, fileName, newFileName);
27 1 : markSessionAttachmentsChanged(session.sessionId);
28 1 : await modify({ type: RENAME_ATTACHMENT, value: { fileName, newFileName } });
29 1 : const [from, to] = [attachmentParameterName(fileName), attachmentParameterName(newFileName)];
30 1 : if (from != null && to != null) renameDraft?.(from, to);
31 1 : return newFileName;
32 1 : }
|