@real1ty-obsidian-plugins/utils 2.10.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/core/color-utils.d.ts +17 -0
  2. package/dist/core/color-utils.d.ts.map +1 -0
  3. package/dist/core/color-utils.js +29 -0
  4. package/dist/core/color-utils.js.map +1 -0
  5. package/dist/core/css-utils.d.ts +39 -0
  6. package/dist/core/css-utils.d.ts.map +1 -0
  7. package/dist/core/css-utils.js +60 -0
  8. package/dist/core/css-utils.js.map +1 -0
  9. package/dist/core/index.d.ts +3 -0
  10. package/dist/core/index.d.ts.map +1 -1
  11. package/dist/core/index.js +3 -0
  12. package/dist/core/index.js.map +1 -1
  13. package/dist/core/property-renderer.d.ts +9 -0
  14. package/dist/core/property-renderer.d.ts.map +1 -0
  15. package/dist/core/property-renderer.js +42 -0
  16. package/dist/core/property-renderer.js.map +1 -0
  17. package/dist/file/file-utils.d.ts +28 -0
  18. package/dist/file/file-utils.d.ts.map +1 -0
  19. package/dist/file/file-utils.js +55 -0
  20. package/dist/file/file-utils.js.map +1 -0
  21. package/dist/file/file.d.ts +51 -1
  22. package/dist/file/file.d.ts.map +1 -1
  23. package/dist/file/file.js +69 -10
  24. package/dist/file/file.js.map +1 -1
  25. package/dist/file/index.d.ts +1 -0
  26. package/dist/file/index.d.ts.map +1 -1
  27. package/dist/file/index.js +1 -0
  28. package/dist/file/index.js.map +1 -1
  29. package/dist/file/link-parser.d.ts +28 -0
  30. package/dist/file/link-parser.d.ts.map +1 -1
  31. package/dist/file/link-parser.js +59 -0
  32. package/dist/file/link-parser.js.map +1 -1
  33. package/dist/string/filename-utils.d.ts +46 -0
  34. package/dist/string/filename-utils.d.ts.map +1 -0
  35. package/dist/string/filename-utils.js +65 -0
  36. package/dist/string/filename-utils.js.map +1 -0
  37. package/dist/string/index.d.ts +1 -0
  38. package/dist/string/index.d.ts.map +1 -1
  39. package/dist/string/index.js +1 -0
  40. package/dist/string/index.js.map +1 -1
  41. package/package.json +2 -1
  42. package/src/core/color-utils.ts +29 -0
  43. package/src/core/css-utils.ts +64 -0
  44. package/src/core/index.ts +3 -0
  45. package/src/core/property-renderer.ts +62 -0
  46. package/src/file/file-utils.ts +67 -0
  47. package/src/file/file.ts +90 -8
  48. package/src/file/index.ts +1 -0
  49. package/src/file/link-parser.ts +71 -0
  50. package/src/string/filename-utils.ts +77 -0
  51. package/src/string/index.ts +1 -0
@@ -0,0 +1,62 @@
1
+ import { getObsidianLinkAlias, getObsidianLinkPath, isObsidianLink } from "../file/link-parser";
2
+
3
+ export interface PropertyRendererConfig {
4
+ createLink: (text: string, path: string, isObsidianLink: boolean) => HTMLElement;
5
+ createText: (text: string) => HTMLElement | Text;
6
+ createSeparator?: () => HTMLElement | Text;
7
+ }
8
+
9
+ export function renderPropertyValue(
10
+ container: HTMLElement,
11
+ value: any,
12
+ config: PropertyRendererConfig
13
+ ): void {
14
+ // Handle arrays - render each item separately
15
+ if (Array.isArray(value)) {
16
+ const hasClickableLinks = value.some(isObsidianLink);
17
+
18
+ if (hasClickableLinks) {
19
+ for (let index = 0; index < value.length; index++) {
20
+ if (index > 0 && config.createSeparator) {
21
+ container.appendChild(config.createSeparator());
22
+ }
23
+ renderSingleValue(container, value[index], config);
24
+ }
25
+ } else {
26
+ // Plain array - just join with commas
27
+ const textNode = config.createText(value.join(", "));
28
+ container.appendChild(textNode);
29
+ }
30
+ return;
31
+ }
32
+
33
+ renderSingleValue(container, value, config);
34
+ }
35
+
36
+ function renderSingleValue(
37
+ container: HTMLElement,
38
+ value: any,
39
+ config: PropertyRendererConfig
40
+ ): void {
41
+ const stringValue = String(value).trim();
42
+
43
+ if (isObsidianLink(stringValue)) {
44
+ const displayText = getObsidianLinkAlias(stringValue);
45
+ const linkPath = getObsidianLinkPath(stringValue);
46
+ const link = config.createLink(displayText, linkPath, true);
47
+ container.appendChild(link);
48
+ return;
49
+ }
50
+
51
+ // Regular text
52
+ const textNode = config.createText(stringValue);
53
+ container.appendChild(textNode);
54
+ }
55
+
56
+ export function createTextNode(text: string): Text {
57
+ return document.createTextNode(text);
58
+ }
59
+
60
+ export function createDefaultSeparator(): Text {
61
+ return document.createTextNode(", ");
62
+ }
@@ -0,0 +1,67 @@
1
+ import type { App } from "obsidian";
2
+ import { TFile } from "obsidian";
3
+
4
+ /**
5
+ * Gets a TFile by path or throws an error if not found.
6
+ * Useful when you need to ensure a file exists before proceeding.
7
+ */
8
+ export const getTFileOrThrow = (app: App, path: string): TFile => {
9
+ const f = app.vault.getAbstractFileByPath(path);
10
+ if (!(f instanceof TFile)) throw new Error(`File not found: ${path}`);
11
+ return f;
12
+ };
13
+
14
+ /**
15
+ * Executes an operation on a file's frontmatter.
16
+ * Wrapper around Obsidian's processFrontMatter for more concise usage.
17
+ */
18
+ export const withFrontmatter = async (
19
+ app: App,
20
+ file: TFile,
21
+ update: (fm: Record<string, unknown>) => void
22
+ ) => app.fileManager.processFrontMatter(file, update);
23
+
24
+ /**
25
+ * Creates a backup copy of a file's frontmatter.
26
+ * Useful for undo/redo operations or temporary modifications.
27
+ */
28
+ export const backupFrontmatter = async (app: App, file: TFile) => {
29
+ let copy: Record<string, unknown> = {};
30
+ await withFrontmatter(app, file, (fm) => {
31
+ copy = { ...fm };
32
+ });
33
+ return copy;
34
+ };
35
+
36
+ /**
37
+ * Restores a file's frontmatter from a backup.
38
+ * Clears existing frontmatter and replaces with the backup.
39
+ */
40
+ export const restoreFrontmatter = async (
41
+ app: App,
42
+ file: TFile,
43
+ original: Record<string, unknown>
44
+ ) =>
45
+ withFrontmatter(app, file, (fm) => {
46
+ for (const k of Object.keys(fm)) {
47
+ delete fm[k];
48
+ }
49
+ Object.assign(fm, original);
50
+ });
51
+
52
+ /**
53
+ * Extracts the content that appears after the frontmatter section.
54
+ * Returns the entire content if no frontmatter is found.
55
+ */
56
+ export const extractContentAfterFrontmatter = (fullContent: string): string => {
57
+ const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n/;
58
+ const match = fullContent.match(frontmatterRegex);
59
+
60
+ if (match) {
61
+ // Return content after frontmatter
62
+ return fullContent.substring(match.index! + match[0].length);
63
+ }
64
+
65
+ // If no frontmatter found, return the entire content
66
+ return fullContent;
67
+ };
package/src/file/file.ts CHANGED
@@ -548,16 +548,98 @@ export function findRootNodesInFolder(app: App, folderPath: string): string[] {
548
548
  }
549
549
 
550
550
  // ============================================================================
551
- // Legacy Utility Functions (kept for backwards compatibility)
551
+ // Filename Sanitization
552
552
  // ============================================================================
553
553
 
554
- export const sanitizeForFilename = (input: string): string => {
555
- return input
556
- .replace(/[<>:"/\\|?*]/g, "") // Remove invalid filename characters
557
- .replace(/\s+/g, "-") // Replace spaces with hyphens
558
- .replace(/-+/g, "-") // Replace multiple hyphens with single
559
- .replace(/^-|-$/g, "") // Remove leading/trailing hyphens
560
- .toLowerCase();
554
+ export interface SanitizeFilenameOptions {
555
+ /**
556
+ * Style of sanitization to apply.
557
+ * - "kebab": Convert to lowercase, replace spaces with hyphens (default, backwards compatible)
558
+ * - "preserve": Preserve spaces and case, only remove invalid characters
559
+ */
560
+ style?: "kebab" | "preserve";
561
+ }
562
+
563
+ /**
564
+ * Sanitizes a string for use as a filename.
565
+ * Defaults to kebab-case style for backwards compatibility.
566
+ *
567
+ * @param input - String to sanitize
568
+ * @param options - Sanitization options
569
+ * @returns Sanitized filename string
570
+ *
571
+ * @example
572
+ * // Default kebab-case style (backwards compatible)
573
+ * sanitizeForFilename("My File Name") // "my-file-name"
574
+ *
575
+ * // Preserve spaces and case
576
+ * sanitizeForFilename("My File Name", { style: "preserve" }) // "My File Name"
577
+ */
578
+ export const sanitizeForFilename = (
579
+ input: string,
580
+ options: SanitizeFilenameOptions = {}
581
+ ): string => {
582
+ const { style = "kebab" } = options;
583
+
584
+ if (style === "preserve") {
585
+ return sanitizeFilenamePreserveSpaces(input);
586
+ }
587
+
588
+ // Default: kebab-case style (legacy behavior)
589
+ return sanitizeFilenameKebabCase(input);
590
+ };
591
+
592
+ /**
593
+ * Sanitizes filename using kebab-case style.
594
+ * - Removes invalid characters
595
+ * - Converts to lowercase
596
+ * - Replaces spaces with hyphens
597
+ *
598
+ * Best for: CLI tools, URLs, slugs, technical files
599
+ *
600
+ * @example
601
+ * sanitizeFilenameKebabCase("My File Name") // "my-file-name"
602
+ * sanitizeFilenameKebabCase("Travel Around The World") // "travel-around-the-world"
603
+ */
604
+ export const sanitizeFilenameKebabCase = (input: string): string => {
605
+ return (
606
+ input
607
+ // Remove invalid filename characters
608
+ .replace(/[<>:"/\\|?*]/g, "")
609
+ // Replace spaces with hyphens
610
+ .replace(/\s+/g, "-")
611
+ // Replace multiple hyphens with single
612
+ .replace(/-+/g, "-")
613
+ // Remove leading/trailing hyphens
614
+ .replace(/^-|-$/g, "")
615
+ // Convert to lowercase
616
+ .toLowerCase()
617
+ );
618
+ };
619
+
620
+ /**
621
+ * Sanitizes filename while preserving spaces and case.
622
+ * - Removes invalid characters only
623
+ * - Preserves spaces and original casing
624
+ * - Removes trailing dots (Windows compatibility)
625
+ *
626
+ * Best for: Note titles, human-readable filenames, Obsidian notes
627
+ *
628
+ * @example
629
+ * sanitizeFilenamePreserveSpaces("My File Name") // "My File Name"
630
+ * sanitizeFilenamePreserveSpaces("Travel Around The World") // "Travel Around The World"
631
+ * sanitizeFilenamePreserveSpaces("File<Invalid>Chars") // "FileInvalidChars"
632
+ */
633
+ export const sanitizeFilenamePreserveSpaces = (input: string): string => {
634
+ return (
635
+ input
636
+ // Remove invalid filename characters (cross-platform compatibility)
637
+ .replace(/[<>:"/\\|?*]/g, "")
638
+ // Remove trailing dots (invalid on Windows)
639
+ .replace(/\.+$/g, "")
640
+ // Remove leading/trailing whitespace
641
+ .trim()
642
+ );
561
643
  };
562
644
 
563
645
  export const getFilenameFromPath = (filePath: string): string => {
package/src/file/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./child-reference";
2
2
  export * from "./file";
3
3
  export * from "./file-operations";
4
+ export * from "./file-utils";
4
5
  export * from "./frontmatter";
5
6
  export * from "./link-parser";
6
7
  export * from "./property-utils";
@@ -89,3 +89,74 @@ export function formatWikiLink(filePath: string): string {
89
89
 
90
90
  return `[[${trimmed}|${displayName}]]`;
91
91
  }
92
+
93
+ /**
94
+ * Represents a parsed Obsidian link with its components
95
+ */
96
+ export interface ObsidianLink {
97
+ raw: string;
98
+ path: string;
99
+ alias: string;
100
+ }
101
+
102
+ /**
103
+ * Checks if a value is an Obsidian internal link in the format [[...]]
104
+ */
105
+ export function isObsidianLink(value: unknown): boolean {
106
+ if (typeof value !== "string") return false;
107
+ const trimmed = value.trim();
108
+ return /^\[\[.+\]\]$/.test(trimmed);
109
+ }
110
+
111
+ /**
112
+ * Parses an Obsidian internal link and extracts its components
113
+ *
114
+ * Supports both formats:
115
+ * - Simple: [[Page Name]]
116
+ * - With alias: [[Path/To/Page|Display Name]]
117
+ */
118
+ export function parseObsidianLink(linkString: string): ObsidianLink | null {
119
+ if (!isObsidianLink(linkString)) return null;
120
+
121
+ const trimmed = linkString.trim();
122
+ const linkContent = trimmed.match(/^\[\[(.+?)\]\]$/)?.[1];
123
+
124
+ if (!linkContent) return null;
125
+
126
+ // Handle pipe syntax: [[path|display]]
127
+ if (linkContent.includes("|")) {
128
+ const parts = linkContent.split("|");
129
+ const path = parts[0].trim();
130
+ const alias = parts.slice(1).join("|").trim(); // Handle multiple pipes
131
+
132
+ return {
133
+ raw: trimmed,
134
+ path,
135
+ alias,
136
+ };
137
+ }
138
+
139
+ // Simple format: [[path]]
140
+ const path = linkContent.trim();
141
+ return {
142
+ raw: trimmed,
143
+ path,
144
+ alias: path,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Gets the display alias from an Obsidian link
150
+ */
151
+ export function getObsidianLinkAlias(linkString: string): string {
152
+ const parsed = parseObsidianLink(linkString);
153
+ return parsed?.alias ?? linkString;
154
+ }
155
+
156
+ /**
157
+ * Gets the file path from an Obsidian link
158
+ */
159
+ export function getObsidianLinkPath(linkString: string): string {
160
+ const parsed = parseObsidianLink(linkString);
161
+ return parsed?.path ?? linkString;
162
+ }
@@ -0,0 +1,77 @@
1
+ import { sanitizeFilenamePreserveSpaces } from "../file/file";
2
+
3
+ /**
4
+ * Normalizes a directory path for consistent comparison.
5
+ *
6
+ * - Trims whitespace
7
+ * - Removes leading and trailing slashes
8
+ * - Converts empty/whitespace-only strings to empty string
9
+ *
10
+ * Examples:
11
+ * - "tasks/" → "tasks"
12
+ * - "/tasks" → "tasks"
13
+ * - "/tasks/" → "tasks"
14
+ * - " tasks " → "tasks"
15
+ * - "" → ""
16
+ * - " " → ""
17
+ * - "tasks/homework" → "tasks/homework"
18
+ */
19
+ export const normalizeDirectoryPath = (directory: string): string => {
20
+ return directory.trim().replace(/^\/+|\/+$/g, "");
21
+ };
22
+
23
+ /**
24
+ * Extracts the date and suffix (everything after the date) from a physical instance filename.
25
+ * Physical instance format: "[title] [date]-[ZETTELID]"
26
+ *
27
+ * @param basename - The filename without extension
28
+ * @returns Object with dateStr and suffix, or null if no date found
29
+ *
30
+ * @example
31
+ * extractDateAndSuffix("My Event 2025-01-15-ABC123") // { dateStr: "2025-01-15", suffix: "-ABC123" }
32
+ * extractDateAndSuffix("Invalid filename") // null
33
+ */
34
+ export const extractDateAndSuffix = (
35
+ basename: string
36
+ ): { dateStr: string; suffix: string } | null => {
37
+ const dateMatch = basename.match(/(\d{4}-\d{2}-\d{2})/);
38
+ if (!dateMatch) {
39
+ return null;
40
+ }
41
+
42
+ const dateStr = dateMatch[1];
43
+ const dateIndex = basename.indexOf(dateStr);
44
+ const suffix = basename.substring(dateIndex + dateStr.length);
45
+
46
+ return { dateStr, suffix };
47
+ };
48
+
49
+ /**
50
+ * Rebuilds a physical instance filename with a new title while preserving the date and zettel ID.
51
+ * Physical instance format: "[title] [date]-[ZETTELID]"
52
+ *
53
+ * @param currentBasename - Current filename without extension
54
+ * @param newTitle - New title (with or without zettel ID - will be stripped)
55
+ * @returns New filename, or null if current filename format is invalid
56
+ *
57
+ * @example
58
+ * rebuildPhysicalInstanceFilename("Old Title 2025-01-15-ABC123", "New Title-XYZ789")
59
+ * // Returns: "New Title 2025-01-15-ABC123"
60
+ */
61
+ export const rebuildPhysicalInstanceFilename = (
62
+ currentBasename: string,
63
+ newTitle: string
64
+ ): string | null => {
65
+ const dateAndSuffix = extractDateAndSuffix(currentBasename);
66
+ if (!dateAndSuffix) {
67
+ return null;
68
+ }
69
+
70
+ const { dateStr, suffix } = dateAndSuffix;
71
+
72
+ // Remove any zettel ID from the new title (just in case)
73
+ const newTitleClean = newTitle.replace(/-[A-Z0-9]{6}$/, "");
74
+ const newTitleSanitized = sanitizeFilenamePreserveSpaces(newTitleClean);
75
+
76
+ return `${newTitleSanitized} ${dateStr}${suffix}`;
77
+ };
@@ -1 +1,2 @@
1
+ export * from "./filename-utils";
1
2
  export * from "./string";