-
-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathRequirementCollector.ts
More file actions
341 lines (306 loc) · 9.99 KB
/
RequirementCollector.ts
File metadata and controls
341 lines (306 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import type { App } from "obsidian";
import { GLOBAL_VAR_REGEX, TEMPLATE_REGEX, VARIABLE_REGEX } from "src/constants";
import { Formatter, type PromptContext } from "src/formatters/formatter";
import type { IChoiceExecutor } from "src/IChoiceExecutor";
import type QuickAdd from "src/main";
import { NLDParser } from "src/parsers/NLDParser";
import { parseValueToken } from "src/utils/valueSyntax";
export type FieldType =
| "text"
| "textarea"
| "dropdown"
| "date"
| "field-suggest"
| "file-picker"
| "suggester";
export interface FieldRequirement {
id: string; // variable key or special input id
label: string; // user-facing label
type: FieldType;
description?: string;
placeholder?: string;
defaultValue?: string;
options?: string[]; // for dropdowns and suggesters
displayOptions?: string[]; // visible labels for mapped VALUE lists
// Additional metadata
dateFormat?: string; // for VDATE
filters?: string; // serialized filters for FIELD variables
source?: "collected" | "script"; // provenance for UX badges
suggesterConfig?: {
allowCustomInput?: boolean;
caseSensitive?: boolean;
multiSelect?: boolean;
};
}
/**
* RequirementCollector walks through strings that may contain QuickAdd format
* syntax and records inputs we'd otherwise prompt for at runtime. It never
* executes macros, scripts, or inline JavaScript. It returns inert replacements
* so that formatting can continue to discover further requirements.
*/
export class RequirementCollector extends Formatter {
public readonly requirements = new Map<string, FieldRequirement>();
public readonly templatesToScan = new Set<string>();
constructor(
protected app: App,
private plugin: QuickAdd,
protected choiceExecutor?: IChoiceExecutor,
) {
super(app);
this.dateParser = NLDParser;
if (choiceExecutor) {
// Use a shallow copy to avoid mutating the executor's live variables
// during preflight scanning. This ensures unresolved detection works
// and the One Page Input modal is shown when needed.
this.variables = new Map(choiceExecutor.variables);
}
}
// Entry points -------------------------------------------------------------
public async scanString(input: string): Promise<void> {
// Expand global variables first so we can detect inner requirements
const expanded = await this.replaceGlobalVarInString(input);
// Run a safe formatting pass that collects variables but avoids side-effects
this.scanVariableTokens(expanded);
await this.format(expanded);
}
protected async format(input: string): Promise<string> {
let output = input;
// NOTE: Intentionally skip macros, inline js, templates content resolution
// We will only record the TEMPLATE references for later recursive scanning.
// Expand global variables early (text-only expansion)
output = await this.replaceGlobalVarInString(output);
// Dates/Times
output = this.replaceDateInString(output);
output = this.replaceTimeInString(output);
// VALUE & NAME
output = await this.replaceValueInString(output);
// Clipboard/Selected: keep inert
output = await this.replaceSelectedInString(output);
output = await this.replaceClipboardInString(output);
// VDATE + VALUE variables + FIELD
output = await this.replaceDateVariableInString(output);
output = await this.replaceVariableInString(output);
output = await this.replaceFieldVarInString(output);
// Math value
output = await this.replaceMathValueInString(output);
// Random
output = this.replaceRandomInString(output);
// Record any template inclusions for callers to handle separately
{
const re = new RegExp(TEMPLATE_REGEX.source, "gi");
let m: RegExpExecArray | null;
while ((m = re.exec(output)) !== null) {
const path = m[1];
if (path) this.templatesToScan.add(path);
}
}
return output;
}
protected async replaceGlobalVarInString(input: string): Promise<string> {
let output = input;
let guard = 0;
const re = new RegExp(GLOBAL_VAR_REGEX.source, "gi");
while (re.test(output)) {
if (++guard > 5) break;
output = output.replace(re, (_m, rawName) => {
const name = String(rawName ?? "").trim();
if (!name) return _m;
const snippet = this.plugin?.settings?.globalVariables?.[name];
return typeof snippet === "string" ? snippet : "";
});
}
return output;
}
// Additional scanning for defaults/options in {{VALUE:...}} tokens
private scanVariableTokens(input: string) {
const re = new RegExp(VARIABLE_REGEX.source, "gi");
let match: RegExpExecArray | null;
while ((match = re.exec(input)) !== null) {
const inner = (match[1] ?? "").trim();
if (!inner) continue;
const parsed = parseValueToken(inner);
if (!parsed) continue;
const {
variableName,
variableKey,
label,
defaultValue,
allowCustomInput,
suggestedValues,
displayValues,
hasOptions,
} = parsed;
if (!variableName) continue;
const displayLabel = hasOptions && label ? label : variableName;
const description = !hasOptions && label ? label : undefined;
const requirementId = variableKey;
if (!this.requirements.has(requirementId)) {
const baseInputType =
parsed.inputTypeOverride === "multiline" ||
this.plugin.settings.inputPrompt === "multi-line"
? "textarea"
: "text";
const req: FieldRequirement = {
id: requirementId,
label: displayLabel,
type: hasOptions
? allowCustomInput
? "suggester"
: "dropdown"
: baseInputType,
description,
};
if (hasOptions) {
req.options = suggestedValues;
if (displayValues) req.displayOptions = displayValues;
if (allowCustomInput) {
req.suggesterConfig = {
allowCustomInput: true,
caseSensitive: false,
multiSelect: false,
};
}
}
if (defaultValue) req.defaultValue = defaultValue;
this.requirements.set(requirementId, req);
} else {
const existing = this.requirements.get(requirementId)!;
if (defaultValue && existing.defaultValue === undefined)
existing.defaultValue = defaultValue;
if (!existing.displayOptions && displayValues) {
existing.displayOptions = displayValues;
}
}
}
}
// Formatter hooks ----------------------------------------------------------
protected async promptForValue(header?: string): Promise<string> {
const key = "value";
if (!this.requirements.has(key)) {
this.requirements.set(key, {
id: key,
label: header || "Enter value",
type:
this.valuePromptContext?.inputTypeOverride === "multiline" ||
this.plugin.settings.inputPrompt === "multi-line"
? "textarea"
: "text",
description: this.valuePromptContext?.description,
defaultValue: this.valuePromptContext?.defaultValue,
source: "collected",
});
}
return ""; // return inert value to keep scanning
}
protected async promptForVariable(
variableName?: string,
context?: PromptContext,
): Promise<string> {
if (!variableName) return "";
const key = context?.variableKey ?? variableName;
// VDATE variables
if (context?.type === "VDATE") {
if (!this.requirements.has(key)) {
this.requirements.set(key, {
id: key,
label: variableName,
type: "date",
defaultValue: context.defaultValue,
dateFormat: context.dateFormat ?? "YYYY-MM-DD",
description: context.description,
source: "collected",
});
}
return context.defaultValue ?? "@date:1970-01-01T00:00:00.000Z";
}
// Generic named variables
if (!this.requirements.has(key)) {
// Detect simple comma-separated option lists
const hasOptions = variableName.includes(",");
const baseInputType =
context?.inputTypeOverride === "multiline" ||
this.plugin.settings.inputPrompt === "multi-line"
? "textarea"
: "text";
const req: FieldRequirement = {
id: key,
label: variableName,
type: hasOptions ? "dropdown" : baseInputType,
description: context?.description,
source: "collected",
};
if (hasOptions) {
req.options = variableName
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}
if (context?.defaultValue) req.defaultValue = context.defaultValue;
this.requirements.set(key, req);
}
return context?.defaultValue ?? "";
}
protected async promptForMathValue(): Promise<string> {
const key = "mvalue";
if (!this.requirements.has(key)) {
this.requirements.set(key, {
id: key,
label: "Math expression",
type: "text",
placeholder: "e.g., 2+2*3",
});
}
return "";
}
protected async suggestForField(variableName: string): Promise<string> {
// Store as a field-suggest requirement; actual suggestions are provided by UI
if (!this.requirements.has(variableName)) {
this.requirements.set(variableName, {
id: variableName,
label: variableName,
type: "field-suggest",
source: "collected",
});
}
return "";
}
protected async suggestForValue(
_suggestedValues: string[],
_allowCustomInput?: boolean,
_context?: { placeholder?: string; variableKey?: string },
): Promise<string> {
// No-op here because scanVariableTokens already records a requirement for
// anonymous option lists (e.g., {{VALUE:low,medium,high}}) under the exact
// token content as id, which the runtime formatter will look up.
return "";
}
protected getVariableValue(variableName: string): string {
// During collection, always resolve to empty string to continue scanning
return "";
}
protected async getTemplateContent(_templatePath: string): Promise<string> {
// Never read files here; caller scans template files separately
return "";
}
protected async getSelectedText(): Promise<string> {
return "";
}
protected async getClipboardContent(): Promise<string> {
return "";
}
protected getCurrentFileLink(): string | null {
return null;
}
protected getCurrentFileName(): string | null {
return null;
}
protected async getMacroValue(
_macroName: string,
_context?: { label?: string },
): Promise<string> {
return "";
}
protected isTemplatePropertyTypesEnabled(): boolean {
return false; // Requirement collector doesn't need structured YAML variable handling
}
}