@real1ty-obsidian-plugins/utils 2.2.3 → 2.4.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 (152) hide show
  1. package/README.md +29 -9
  2. package/dist/{async-utils.d.ts → async/async.d.ts} +1 -1
  3. package/dist/async/async.d.ts.map +1 -0
  4. package/dist/{async-utils.js → async/async.js} +1 -1
  5. package/dist/async/async.js.map +1 -0
  6. package/dist/async/batch-operations.d.ts.map +1 -0
  7. package/dist/async/batch-operations.js.map +1 -0
  8. package/dist/async/index.d.ts +3 -0
  9. package/dist/async/index.d.ts.map +1 -0
  10. package/dist/async/index.js +3 -0
  11. package/dist/async/index.js.map +1 -0
  12. package/dist/core/evaluator-base.d.ts.map +1 -0
  13. package/dist/core/evaluator-base.js.map +1 -0
  14. package/dist/core/generate.d.ts.map +1 -0
  15. package/dist/core/generate.js.map +1 -0
  16. package/dist/core/index.d.ts +3 -0
  17. package/dist/core/index.d.ts.map +1 -0
  18. package/dist/core/index.js +3 -0
  19. package/dist/core/index.js.map +1 -0
  20. package/dist/{date-recurrence-utils.d.ts → date/date-recurrence.d.ts} +1 -1
  21. package/dist/date/date-recurrence.d.ts.map +1 -0
  22. package/dist/{date-recurrence-utils.js → date/date-recurrence.js} +1 -1
  23. package/dist/date/date-recurrence.js.map +1 -0
  24. package/dist/{date-utils.d.ts → date/date.d.ts} +1 -1
  25. package/dist/date/date.d.ts.map +1 -0
  26. package/dist/{date-utils.js → date/date.js} +1 -1
  27. package/dist/date/date.js.map +1 -0
  28. package/dist/date/index.d.ts +3 -0
  29. package/dist/date/index.d.ts.map +1 -0
  30. package/dist/date/index.js +3 -0
  31. package/dist/date/index.js.map +1 -0
  32. package/dist/{child-reference-utils.d.ts → file/child-reference.d.ts} +1 -1
  33. package/dist/file/child-reference.d.ts.map +1 -0
  34. package/dist/{child-reference-utils.js → file/child-reference.js} +1 -1
  35. package/dist/file/child-reference.js.map +1 -0
  36. package/dist/file/file-operations.d.ts.map +1 -0
  37. package/dist/{file-operations.js → file/file-operations.js} +2 -2
  38. package/dist/file/file-operations.js.map +1 -0
  39. package/dist/file/file.d.ts +263 -0
  40. package/dist/file/file.d.ts.map +1 -0
  41. package/dist/file/file.js +466 -0
  42. package/dist/file/file.js.map +1 -0
  43. package/dist/{frontmatter-utils.d.ts → file/frontmatter.d.ts} +1 -1
  44. package/dist/file/frontmatter.d.ts.map +1 -0
  45. package/dist/{frontmatter-utils.js → file/frontmatter.js} +1 -1
  46. package/dist/file/frontmatter.js.map +1 -0
  47. package/dist/file/index.d.ts +7 -0
  48. package/dist/file/index.d.ts.map +1 -0
  49. package/dist/file/index.js +7 -0
  50. package/dist/file/index.js.map +1 -0
  51. package/dist/file/link-parser.d.ts.map +1 -0
  52. package/dist/file/link-parser.js.map +1 -0
  53. package/dist/{templater-utils.d.ts → file/templater.d.ts} +1 -1
  54. package/dist/file/templater.d.ts.map +1 -0
  55. package/dist/{templater-utils.js → file/templater.js} +1 -1
  56. package/dist/file/templater.js.map +1 -0
  57. package/dist/index.d.ts +6 -15
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +12 -15
  60. package/dist/index.js.map +1 -1
  61. package/dist/settings/index.d.ts +3 -0
  62. package/dist/settings/index.d.ts.map +1 -0
  63. package/dist/settings/index.js +3 -0
  64. package/dist/settings/index.js.map +1 -0
  65. package/dist/settings/settings-store.d.ts.map +1 -0
  66. package/dist/settings/settings-store.js.map +1 -0
  67. package/dist/settings/settings-ui-builder.d.ts.map +1 -0
  68. package/dist/settings/settings-ui-builder.js.map +1 -0
  69. package/dist/string/index.d.ts +2 -0
  70. package/dist/string/index.d.ts.map +1 -0
  71. package/dist/string/index.js +2 -0
  72. package/dist/string/index.js.map +1 -0
  73. package/dist/{string-utils.d.ts → string/string.d.ts} +1 -1
  74. package/dist/string/string.d.ts.map +1 -0
  75. package/dist/{string-utils.js → string/string.js} +1 -1
  76. package/dist/string/string.js.map +1 -0
  77. package/dist/testing/mocks/obsidian.d.ts +1 -0
  78. package/dist/testing/mocks/obsidian.d.ts.map +1 -1
  79. package/dist/testing/mocks/obsidian.js +6 -0
  80. package/dist/testing/mocks/obsidian.js.map +1 -1
  81. package/package.json +3 -5
  82. package/src/async/async.ts +117 -0
  83. package/src/async/batch-operations.ts +53 -0
  84. package/src/async/index.ts +2 -0
  85. package/src/core/evaluator-base.ts +118 -0
  86. package/src/core/generate.ts +22 -0
  87. package/src/core/index.ts +2 -0
  88. package/src/date/date-recurrence.ts +244 -0
  89. package/src/date/date.ts +111 -0
  90. package/src/date/index.ts +2 -0
  91. package/src/file/child-reference.ts +76 -0
  92. package/src/file/file-operations.ts +197 -0
  93. package/src/file/file.ts +570 -0
  94. package/src/file/frontmatter.ts +80 -0
  95. package/src/file/index.ts +6 -0
  96. package/src/file/link-parser.ts +18 -0
  97. package/src/file/templater.ts +75 -0
  98. package/src/index.ts +14 -0
  99. package/src/settings/index.ts +2 -0
  100. package/src/settings/settings-store.ts +88 -0
  101. package/src/settings/settings-ui-builder.ts +507 -0
  102. package/src/string/index.ts +1 -0
  103. package/src/string/string.ts +26 -0
  104. package/src/testing/index.ts +23 -0
  105. package/src/testing/mocks/obsidian.ts +331 -0
  106. package/src/testing/mocks/utils.ts +113 -0
  107. package/src/testing/setup.ts +19 -0
  108. package/dist/async-utils.d.ts.map +0 -1
  109. package/dist/async-utils.js.map +0 -1
  110. package/dist/batch-operations.d.ts.map +0 -1
  111. package/dist/batch-operations.js.map +0 -1
  112. package/dist/child-reference-utils.d.ts.map +0 -1
  113. package/dist/child-reference-utils.js.map +0 -1
  114. package/dist/date-recurrence-utils.d.ts.map +0 -1
  115. package/dist/date-recurrence-utils.js.map +0 -1
  116. package/dist/date-utils.d.ts.map +0 -1
  117. package/dist/date-utils.js.map +0 -1
  118. package/dist/evaluator-base.d.ts.map +0 -1
  119. package/dist/evaluator-base.js.map +0 -1
  120. package/dist/file-operations.d.ts.map +0 -1
  121. package/dist/file-operations.js.map +0 -1
  122. package/dist/file-utils.d.ts +0 -6
  123. package/dist/file-utils.d.ts.map +0 -1
  124. package/dist/file-utils.js +0 -25
  125. package/dist/file-utils.js.map +0 -1
  126. package/dist/frontmatter-utils.d.ts.map +0 -1
  127. package/dist/frontmatter-utils.js.map +0 -1
  128. package/dist/generate.d.ts.map +0 -1
  129. package/dist/generate.js.map +0 -1
  130. package/dist/link-parser.d.ts.map +0 -1
  131. package/dist/link-parser.js.map +0 -1
  132. package/dist/settings-store.d.ts.map +0 -1
  133. package/dist/settings-store.js.map +0 -1
  134. package/dist/settings-ui-builder.d.ts.map +0 -1
  135. package/dist/settings-ui-builder.js.map +0 -1
  136. package/dist/string-utils.d.ts.map +0 -1
  137. package/dist/string-utils.js.map +0 -1
  138. package/dist/templater-utils.d.ts.map +0 -1
  139. package/dist/templater-utils.js.map +0 -1
  140. /package/dist/{batch-operations.d.ts → async/batch-operations.d.ts} +0 -0
  141. /package/dist/{batch-operations.js → async/batch-operations.js} +0 -0
  142. /package/dist/{evaluator-base.d.ts → core/evaluator-base.d.ts} +0 -0
  143. /package/dist/{evaluator-base.js → core/evaluator-base.js} +0 -0
  144. /package/dist/{generate.d.ts → core/generate.d.ts} +0 -0
  145. /package/dist/{generate.js → core/generate.js} +0 -0
  146. /package/dist/{file-operations.d.ts → file/file-operations.d.ts} +0 -0
  147. /package/dist/{link-parser.d.ts → file/link-parser.d.ts} +0 -0
  148. /package/dist/{link-parser.js → file/link-parser.js} +0 -0
  149. /package/dist/{settings-store.d.ts → settings/settings-store.d.ts} +0 -0
  150. /package/dist/{settings-store.js → settings/settings-store.js} +0 -0
  151. /package/dist/{settings-ui-builder.d.ts → settings/settings-ui-builder.d.ts} +0 -0
  152. /package/dist/{settings-ui-builder.js → settings/settings-ui-builder.js} +0 -0
@@ -0,0 +1,118 @@
1
+ import type { BehaviorSubject, Subscription } from "rxjs";
2
+
3
+ export interface BaseRule {
4
+ id: string;
5
+ expression: string;
6
+ enabled: boolean;
7
+ }
8
+
9
+ /**
10
+ * Generic base class for evaluating JavaScript expressions against frontmatter objects.
11
+ * Provides reactive compilation of rules via RxJS subscription and safe evaluation.
12
+ */
13
+ export abstract class BaseEvaluator<TRule extends BaseRule, TSettings> {
14
+ protected compiledRules: Array<
15
+ TRule & { fn: (frontmatter: Record<string, unknown>) => boolean }
16
+ > = [];
17
+ private settingsSubscription: Subscription | null = null;
18
+
19
+ constructor(settingsStore: BehaviorSubject<TSettings>) {
20
+ const initialRules = this.extractRules(settingsStore.value);
21
+ this.compileRules(initialRules);
22
+
23
+ this.settingsSubscription = settingsStore.subscribe((settings) => {
24
+ const newRules = this.extractRules(settings);
25
+ this.compileRules(newRules);
26
+ });
27
+ }
28
+
29
+ /**
30
+ * Extract rules from settings object. Must be implemented by subclasses.
31
+ */
32
+ protected abstract extractRules(settings: TSettings): TRule[];
33
+
34
+ /**
35
+ * Compile rules into executable functions with error handling.
36
+ */
37
+ private compileRules(rules: TRule[]): void {
38
+ this.compiledRules = [];
39
+
40
+ for (const rule of rules) {
41
+ if (!rule.enabled || !rule.expression.trim()) continue;
42
+
43
+ try {
44
+ const cleanExpression = rule.expression.trim();
45
+
46
+ // Create a function that takes 'fm' (frontmatter) as parameter
47
+ // and evaluates the expression in that context
48
+ const fn = new Function("fm", `return (${cleanExpression});`) as (
49
+ frontmatter: Record<string, unknown>
50
+ ) => boolean;
51
+
52
+ // Test the function with a dummy object to catch syntax errors early
53
+ fn({});
54
+
55
+ this.compiledRules.push({
56
+ ...rule,
57
+ expression: cleanExpression,
58
+ fn,
59
+ });
60
+ } catch (error) {
61
+ console.warn(`Invalid rule expression "${rule.expression}":`, error);
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Evaluate a single rule against frontmatter. Returns the result or undefined if error.
68
+ */
69
+ protected evaluateRule(
70
+ rule: TRule & { fn: (frontmatter: Record<string, unknown>) => boolean },
71
+ frontmatter: Record<string, unknown>
72
+ ): boolean | undefined {
73
+ try {
74
+ return rule.fn(frontmatter);
75
+ } catch (error) {
76
+ console.warn(`Error evaluating rule "${rule.expression}":`, error);
77
+ return undefined;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Convert evaluation result to boolean - only explicit true is considered truthy.
83
+ */
84
+ protected isTruthy(result: boolean | undefined): boolean {
85
+ return result === true;
86
+ }
87
+
88
+ /**
89
+ * Clean up subscriptions and compiled rules.
90
+ */
91
+ destroy(): void {
92
+ if (this.settingsSubscription) {
93
+ this.settingsSubscription.unsubscribe();
94
+ this.settingsSubscription = null;
95
+ }
96
+ this.compiledRules = [];
97
+ }
98
+
99
+ /**
100
+ * Get the number of active (compiled) rules.
101
+ */
102
+ getActiveRuleCount(): number {
103
+ return this.compiledRules.length;
104
+ }
105
+
106
+ /**
107
+ * Get information about all rules including their validity.
108
+ */
109
+ getRuleInfo(): Array<{ expression: string; isValid: boolean; enabled: boolean }> {
110
+ const validExpressions = new Set(this.compiledRules.map((r) => r.expression));
111
+
112
+ return this.compiledRules.map((rule) => ({
113
+ expression: rule.expression,
114
+ isValid: validExpressions.has(rule.expression),
115
+ enabled: rule.enabled,
116
+ }));
117
+ }
118
+ }
@@ -0,0 +1,22 @@
1
+ export interface TimestampData {
2
+ startDate: string;
3
+ zettelId: number;
4
+ }
5
+
6
+ export const generateZettelId = (): number => {
7
+ const currentTimestamp = new Date();
8
+ const padWithZero = (number: number) => String(number).padStart(2, "0");
9
+ return Number(
10
+ `${currentTimestamp.getFullYear()}${padWithZero(currentTimestamp.getMonth() + 1)}${padWithZero(currentTimestamp.getDate())}${padWithZero(currentTimestamp.getHours())}${padWithZero(currentTimestamp.getMinutes())}${padWithZero(currentTimestamp.getSeconds())}`
11
+ );
12
+ };
13
+
14
+ export const generateTimestamps = (): TimestampData => {
15
+ const padWithZero = (number: number): string => String(number).padStart(2, "0");
16
+ const currentDate = new Date();
17
+
18
+ const formattedStartDate: string = `${currentDate.getFullYear()}-${padWithZero(currentDate.getMonth() + 1)}-${padWithZero(currentDate.getDate())}`;
19
+ const uniqueZettelId: number = generateZettelId();
20
+
21
+ return { startDate: formattedStartDate, zettelId: uniqueZettelId };
22
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./evaluator-base";
2
+ export * from "./generate";
@@ -0,0 +1,244 @@
1
+ import type { DateTime } from "luxon";
2
+
3
+ export type RecurrenceType = "daily" | "weekly" | "bi-weekly" | "monthly" | "bi-monthly" | "yearly";
4
+
5
+ export type Weekday =
6
+ | "sunday"
7
+ | "monday"
8
+ | "tuesday"
9
+ | "wednesday"
10
+ | "thursday"
11
+ | "friday"
12
+ | "saturday";
13
+
14
+ export const WEEKDAY_TO_NUMBER: Record<Weekday, number> = {
15
+ sunday: 0,
16
+ monday: 1,
17
+ tuesday: 2,
18
+ wednesday: 3,
19
+ thursday: 4,
20
+ friday: 5,
21
+ saturday: 6,
22
+ };
23
+
24
+ /**
25
+ * Calculates the next occurrence date based on recurrence type and optional weekdays
26
+ */
27
+ export function getNextOccurrence(
28
+ currentDate: DateTime,
29
+ recurrenceType: RecurrenceType,
30
+ weekdays?: Weekday[]
31
+ ): DateTime {
32
+ switch (recurrenceType) {
33
+ case "daily":
34
+ return currentDate.plus({ days: 1 });
35
+ case "weekly":
36
+ if (weekdays && weekdays.length > 0) {
37
+ return getNextWeekdayOccurrence(currentDate, weekdays);
38
+ }
39
+ return currentDate.plus({ weeks: 1 });
40
+ case "bi-weekly":
41
+ if (weekdays && weekdays.length > 0) {
42
+ return getNextBiWeeklyOccurrence(currentDate, weekdays);
43
+ }
44
+ return currentDate.plus({ weeks: 2 });
45
+ case "monthly":
46
+ return currentDate.plus({ months: 1 });
47
+ case "bi-monthly":
48
+ return currentDate.plus({ months: 2 });
49
+ case "yearly":
50
+ return currentDate.plus({ years: 1 });
51
+ default:
52
+ return currentDate.plus({ days: 1 });
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Checks if a given date matches any of the specified weekdays
58
+ */
59
+ export function isDateOnWeekdays(date: DateTime, weekdays: Weekday[]): boolean {
60
+ const dateWeekday = date.weekday;
61
+ const luxonWeekdays = weekdays.map((day) => {
62
+ const dayNumber = WEEKDAY_TO_NUMBER[day];
63
+ return dayNumber === 0 ? 7 : dayNumber; // Convert Sunday from 0 to 7 for Luxon
64
+ });
65
+
66
+ return luxonWeekdays.includes(dateWeekday);
67
+ }
68
+
69
+ /**
70
+ * Finds the next occurrence on specified weekdays
71
+ */
72
+ export function getNextWeekdayOccurrence(currentDate: DateTime, weekdays: Weekday[]): DateTime {
73
+ const currentWeekday = currentDate.weekday;
74
+ const luxonWeekdays = weekdays.map((day) => {
75
+ const dayNumber = WEEKDAY_TO_NUMBER[day];
76
+ return dayNumber === 0 ? 7 : dayNumber; // Convert Sunday from 0 to 7 for Luxon
77
+ });
78
+
79
+ // Find next weekday in the current week (after today)
80
+ const nextWeekday = luxonWeekdays.find((day) => day > currentWeekday);
81
+ if (nextWeekday) {
82
+ return currentDate.set({ weekday: nextWeekday as 1 | 2 | 3 | 4 | 5 | 6 | 7 });
83
+ }
84
+
85
+ // No more weekdays this week, go to first weekday of next week
86
+ const firstWeekday = Math.min(...luxonWeekdays);
87
+ return currentDate.plus({ weeks: 1 }).set({ weekday: firstWeekday as 1 | 2 | 3 | 4 | 5 | 6 | 7 });
88
+ }
89
+
90
+ /**
91
+ * Finds the next bi-weekly occurrence on specified weekdays
92
+ */
93
+ export function getNextBiWeeklyOccurrence(currentDate: DateTime, weekdays: Weekday[]): DateTime {
94
+ const nextWeekly = getNextWeekdayOccurrence(currentDate, weekdays);
95
+ // Add one more week to make it bi-weekly
96
+ return nextWeekly.plus({ weeks: 1 });
97
+ }
98
+
99
+ export function* iterateOccurrencesInRange(
100
+ startDate: DateTime,
101
+ rrules: { type: RecurrenceType; weekdays?: Weekday[] },
102
+ rangeStart: DateTime,
103
+ rangeEnd: DateTime
104
+ ): Generator<DateTime, void, unknown> {
105
+ // Normalize to start of day for comparison
106
+ const normalizedStart = startDate.startOf("day");
107
+ const normalizedRangeStart = rangeStart.startOf("day");
108
+ const normalizedRangeEnd = rangeEnd.startOf("day");
109
+
110
+ // Start from the later of startDate or rangeStart
111
+ let currentDate =
112
+ normalizedStart >= normalizedRangeStart ? normalizedStart : normalizedRangeStart;
113
+
114
+ // For weekly/bi-weekly with weekdays, we need to track which week we're in
115
+ if (
116
+ (rrules.type === "weekly" || rrules.type === "bi-weekly") &&
117
+ rrules.weekdays &&
118
+ rrules.weekdays.length > 0
119
+ ) {
120
+ // Calculate week offset from start date
121
+ const weeksFromStart = Math.floor(currentDate.diff(normalizedStart, "weeks").weeks);
122
+
123
+ // For bi-weekly, we only want even weeks (0, 2, 4...) from the start date
124
+ const weekInterval = rrules.type === "bi-weekly" ? 2 : 1;
125
+
126
+ // Adjust to the correct week if we're in an off-week
127
+ const weekOffset = weeksFromStart % weekInterval;
128
+ if (weekOffset !== 0) {
129
+ currentDate = currentDate.plus({ weeks: weekInterval - weekOffset });
130
+ }
131
+
132
+ // Now iterate through weeks, checking each day
133
+ while (currentDate <= normalizedRangeEnd) {
134
+ // Check all 7 days of the current week
135
+ for (let dayOffset = 0; dayOffset < 7; dayOffset++) {
136
+ const checkDate = currentDate.plus({ days: dayOffset });
137
+
138
+ // Only yield if within range and matches a target weekday
139
+ if (
140
+ checkDate >= normalizedRangeStart &&
141
+ checkDate <= normalizedRangeEnd &&
142
+ isDateOnWeekdays(checkDate, rrules.weekdays)
143
+ ) {
144
+ yield checkDate;
145
+ }
146
+ }
147
+
148
+ // Move to next occurrence week (1 week for weekly, 2 weeks for bi-weekly)
149
+ currentDate = currentDate.plus({ weeks: weekInterval });
150
+ }
151
+ } else {
152
+ // For other recurrence types (daily, monthly, yearly, or weekly without weekdays)
153
+ while (currentDate <= normalizedRangeEnd) {
154
+ if (currentDate >= normalizedRangeStart) {
155
+ yield currentDate;
156
+ }
157
+
158
+ const nextDate = getNextOccurrence(currentDate, rrules.type, rrules.weekdays);
159
+
160
+ if (nextDate <= normalizedRangeEnd) {
161
+ currentDate = nextDate;
162
+ } else {
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Calculates a DateTime for a specific date with optional time
171
+ */
172
+ export function calculateInstanceDateTime(instanceDate: DateTime, timeString?: string): DateTime {
173
+ if (!timeString) {
174
+ return instanceDate.startOf("day");
175
+ }
176
+
177
+ const [hours, minutes] = timeString.split(":").map(Number);
178
+ return instanceDate.set({ hour: hours, minute: minutes, second: 0, millisecond: 0 });
179
+ }
180
+
181
+ export function calculateRecurringInstanceDateTime(
182
+ nextInstanceDateTime: DateTime,
183
+ nodeRecuringEventDateTime: DateTime,
184
+ recurrenceType: RecurrenceType,
185
+ allDay?: boolean
186
+ ): DateTime {
187
+ // Convert the original event time to the target timezone once to preserve local time
188
+ const originalInTargetZone = nodeRecuringEventDateTime.setZone(nextInstanceDateTime.zone);
189
+
190
+ switch (recurrenceType) {
191
+ case "daily":
192
+ case "weekly":
193
+ case "bi-weekly": {
194
+ if (allDay) {
195
+ return nextInstanceDateTime.startOf("day");
196
+ }
197
+
198
+ return nextInstanceDateTime.set({
199
+ hour: originalInTargetZone.hour,
200
+ minute: originalInTargetZone.minute,
201
+ second: 0,
202
+ millisecond: 0,
203
+ });
204
+ }
205
+
206
+ case "monthly":
207
+ case "bi-monthly": {
208
+ if (allDay) {
209
+ return nextInstanceDateTime.set({ day: originalInTargetZone.day }).startOf("day");
210
+ }
211
+
212
+ return nextInstanceDateTime.set({
213
+ day: originalInTargetZone.day,
214
+ hour: originalInTargetZone.hour,
215
+ minute: originalInTargetZone.minute,
216
+ second: 0,
217
+ millisecond: 0,
218
+ });
219
+ }
220
+
221
+ case "yearly": {
222
+ if (allDay) {
223
+ return nextInstanceDateTime
224
+ .set({
225
+ month: originalInTargetZone.month,
226
+ day: originalInTargetZone.day,
227
+ })
228
+ .startOf("day");
229
+ }
230
+
231
+ return nextInstanceDateTime.set({
232
+ month: originalInTargetZone.month,
233
+ day: originalInTargetZone.day,
234
+ hour: originalInTargetZone.hour,
235
+ minute: originalInTargetZone.minute,
236
+ second: 0,
237
+ millisecond: 0,
238
+ });
239
+ }
240
+
241
+ default:
242
+ return nextInstanceDateTime.startOf("day");
243
+ }
244
+ }
@@ -0,0 +1,111 @@
1
+ import { DateTime } from "luxon";
2
+
3
+ export const formatDateTimeForInput = (dateString: string): string => {
4
+ if (!dateString) return "";
5
+
6
+ try {
7
+ const date = new Date(dateString);
8
+ // Format for datetime-local input (YYYY-MM-DDTHH:mm)
9
+ const year = date.getFullYear();
10
+ const month = String(date.getMonth() + 1).padStart(2, "0");
11
+ const day = String(date.getDate()).padStart(2, "0");
12
+ const hours = String(date.getHours()).padStart(2, "0");
13
+ const minutes = String(date.getMinutes()).padStart(2, "0");
14
+
15
+ return `${year}-${month}-${day}T${hours}:${minutes}`;
16
+ } catch {
17
+ return "";
18
+ }
19
+ };
20
+
21
+ export const formatDateForInput = (dateString: string): string => {
22
+ if (!dateString) return "";
23
+
24
+ try {
25
+ const date = new Date(dateString);
26
+ const year = date.getFullYear();
27
+ const month = String(date.getMonth() + 1).padStart(2, "0");
28
+ const day = String(date.getDate()).padStart(2, "0");
29
+
30
+ return `${year}-${month}-${day}`;
31
+ } catch {
32
+ return "";
33
+ }
34
+ };
35
+
36
+ /**
37
+ * Converts input value to ISO string, handling edge cases where
38
+ * browser datetime-local inputs behave differently across platforms.
39
+ * Returns null for invalid dates to prevent silent failures.
40
+ */
41
+ export const inputValueToISOString = (inputValue: string): string | null => {
42
+ try {
43
+ return new Date(inputValue).toISOString();
44
+ } catch {
45
+ return null;
46
+ }
47
+ };
48
+
49
+ export const formatDuration = (minutes: number): string => {
50
+ const hours = Math.floor(minutes / 60);
51
+ const mins = minutes % 60;
52
+ return `${String(hours).padStart(2, "0")}:${String(mins).padStart(2, "0")}:00`;
53
+ };
54
+
55
+ /**
56
+ * Parse time string from datetime value - returns DateTime object
57
+ * Rejects plain HH:mm format, requires full datetime
58
+ */
59
+ export const parseTimeString = (value: string | null): DateTime | undefined => {
60
+ if (value === null) return undefined;
61
+
62
+ const v = value.trim();
63
+
64
+ // Reject plain HH:mm format - require full datetime
65
+ if (/^\d{2}:\d{2}$/.test(v)) {
66
+ return undefined; // Reject plain time format
67
+ }
68
+
69
+ // Try ISO format first (most common) - EXACT same logic as recurring events
70
+ let dt = DateTime.fromISO(v, { setZone: true }); // ISO: with/without seconds, Z/offset, T
71
+ if (!dt.isValid) dt = DateTime.fromSQL(v, { setZone: true }); // "YYYY-MM-DD HH:mm[:ss]" etc.
72
+ if (!dt.isValid) dt = DateTime.fromFormat(v, "yyyy-MM-dd HH:mm", { setZone: true });
73
+
74
+ return dt.isValid ? dt : undefined;
75
+ };
76
+
77
+ /**
78
+ * Parse and validate datetime strings for event parsing
79
+ * Supports multiple formats including date-only and datetime formats
80
+ */
81
+ export const parseDateTimeString = (value: string | null): DateTime | undefined => {
82
+ if (value === null) return undefined;
83
+
84
+ const v = value.trim();
85
+ if (!v) return undefined;
86
+
87
+ // Try multiple datetime formats in order of preference
88
+ let dt: DateTime;
89
+
90
+ // 1. Try ISO format first (most common)
91
+ dt = DateTime.fromISO(v, { setZone: true });
92
+ if (dt.isValid) return dt;
93
+
94
+ // 2. Try SQL format (YYYY-MM-DD HH:mm:ss)
95
+ dt = DateTime.fromSQL(v, { setZone: true });
96
+ if (dt.isValid) return dt;
97
+
98
+ // 3. Try common format with space (YYYY-MM-DD HH:mm)
99
+ dt = DateTime.fromFormat(v, "yyyy-MM-dd HH:mm", { setZone: true });
100
+ if (dt.isValid) return dt;
101
+
102
+ // 4. Try date-only format (YYYY-MM-DD) - treat as start of day
103
+ dt = DateTime.fromFormat(v, "yyyy-MM-dd", { setZone: true });
104
+ if (dt.isValid) return dt;
105
+
106
+ // 5. Try ISO date format (YYYY-MM-DD)
107
+ dt = DateTime.fromISO(v, { setZone: true });
108
+ if (dt.isValid) return dt;
109
+
110
+ return undefined;
111
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./date";
2
+ export * from "./date-recurrence";
@@ -0,0 +1,76 @@
1
+ import { TFile } from "obsidian";
2
+ import { createFileLink } from "./file-operations";
3
+ import { extractFilePathFromLink } from "./link-parser";
4
+
5
+ export interface VaultAdapter {
6
+ getAbstractFileByPath(path: string): TFile | null;
7
+ }
8
+
9
+ export function extractDirectoryPath(filePath: string): string {
10
+ const lastSlashIndex = filePath.lastIndexOf("/");
11
+ if (lastSlashIndex === -1) {
12
+ return "";
13
+ }
14
+ return filePath.substring(0, lastSlashIndex);
15
+ }
16
+
17
+ export function isRelativeChildReference(childRef: string): boolean {
18
+ const filePath = extractFilePathFromLink(childRef);
19
+ if (!filePath) {
20
+ return !childRef.includes("/");
21
+ }
22
+ return !filePath.includes("/");
23
+ }
24
+
25
+ export function normalizeChildReference(
26
+ childRef: string,
27
+ vault: VaultAdapter,
28
+ currentFileDirectory?: string
29
+ ): string {
30
+ const filePath = extractFilePathFromLink(childRef);
31
+
32
+ // Handle plain text references (not wrapped in [[]])
33
+ if (!filePath) {
34
+ // If it's not a link format, check if it should be converted to a link
35
+ if (!childRef.includes("/") && currentFileDirectory !== undefined) {
36
+ // This is a plain text reference that might need to be converted to a link
37
+ const potentialPath = currentFileDirectory
38
+ ? `${currentFileDirectory}/${childRef.endsWith(".md") ? childRef : `${childRef}.md`}`
39
+ : childRef.endsWith(".md")
40
+ ? childRef
41
+ : `${childRef}.md`;
42
+ const file = vault.getAbstractFileByPath(potentialPath);
43
+ if (file instanceof TFile) {
44
+ return createFileLink(file);
45
+ }
46
+ }
47
+ return childRef;
48
+ }
49
+
50
+ // Handle relative references by making them absolute
51
+ if (isRelativeChildReference(childRef) && currentFileDirectory) {
52
+ const absolutePath = `${currentFileDirectory}/${filePath}`;
53
+ const file = vault.getAbstractFileByPath(absolutePath);
54
+ if (file instanceof TFile) {
55
+ return createFileLink(file);
56
+ }
57
+ }
58
+
59
+ // For absolute references or when no directory context, try to find the file as-is
60
+ const file = vault.getAbstractFileByPath(filePath);
61
+ if (file instanceof TFile) {
62
+ return createFileLink(file);
63
+ }
64
+
65
+ return childRef;
66
+ }
67
+
68
+ export function normalizeChildReferences(
69
+ childRefs: string[],
70
+ vault: VaultAdapter,
71
+ currentFileDirectory?: string
72
+ ): string[] {
73
+ return childRefs.map((childRef) => {
74
+ return normalizeChildReference(childRef, vault, currentFileDirectory);
75
+ });
76
+ }