|
| 1 | +/* eslint-disable @typescript-eslint/strict-boolean-expressions */ |
| 2 | +import { Tiddler } from 'tiddlywiki'; |
| 3 | +import { joinPaths } from './makePathRelative'; |
| 4 | + |
| 5 | +// Configuration tiddler title |
| 6 | +const MOVE_TO_TRASH_TITLE = '$:/config/ExternalAttachments/MoveToTrash'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Handles the 'th-deleting-tiddler' hook which is triggered when a tiddler is being deleted. |
| 10 | + * If the tiddler references an external file via _canonical_uri, this function can move that file to trash. |
| 11 | + * |
| 12 | + * @param tiddler - The tiddler being deleted |
| 13 | + * @param wikiFolderLocation - The location of the current wiki folder |
| 14 | + * @returns The tiddler (unmodified) |
| 15 | + */ |
| 16 | +export function handleDeletingTiddler(tiddler: Tiddler, wikiFolderLocation: string): Tiddler { |
| 17 | + // Check if we should move external files to trash on tiddler deletion |
| 18 | + const moveToTrash = $tw.wiki.getTiddlerText(MOVE_TO_TRASH_TITLE, '') === 'yes'; |
| 19 | + if (!moveToTrash) return tiddler; |
| 20 | + |
| 21 | + // Check if the tiddler has a canonical URI (reference to external file) |
| 22 | + const canonicalUri = tiddler.fields._canonical_uri; |
| 23 | + if (!canonicalUri || typeof canonicalUri !== 'string') return tiddler; |
| 24 | + let filePath: string; |
| 25 | + // Handle relative vs absolute paths |
| 26 | + if ( |
| 27 | + canonicalUri.startsWith('/') || |
| 28 | + (canonicalUri.length > 1 && canonicalUri[1] === ':') |
| 29 | + ) { |
| 30 | + // Absolute path |
| 31 | + filePath = canonicalUri; |
| 32 | + } else { |
| 33 | + // Relative path - resolve against wiki folder location |
| 34 | + filePath = joinPaths(wikiFolderLocation, canonicalUri); |
| 35 | + } |
| 36 | + |
| 37 | + // Move the file to trash using TidGi's API |
| 38 | + try { |
| 39 | + void window.service?.native?.moveToTrash?.(filePath); |
| 40 | + |
| 41 | + // Optional: Log operation to console |
| 42 | + console.log(`Moved file to trash: ${filePath}`); |
| 43 | + } catch (error) { |
| 44 | + console.error(`Failed to move file to trash: ${filePath}`, error); |
| 45 | + } |
| 46 | + |
| 47 | + return tiddler; |
| 48 | +} |
0 commit comments