diff --git a/docs/docs/Advanced/onePageInputs.md b/docs/docs/Advanced/onePageInputs.md index 9c0d3f52..27bfb76c 100644 --- a/docs/docs/Advanced/onePageInputs.md +++ b/docs/docs/Advanced/onePageInputs.md @@ -18,6 +18,7 @@ This feature is currently in Beta. - Format variables in filenames, templates, and capture content: - `{{VALUE}}`, `{{VALUE:name}}`, `{{VDATE:name, YYYY-MM-DD}}`, `{{FIELD:name|...}}` - Nested `{{TEMPLATE:path}}` are scanned recursively. +- `{{VALUE|type:multiline}}` and `{{VALUE:name|type:multiline}}` render as textareas in the one-page modal. - Capture target file when capturing to a folder or tag. - Script-declared inputs (from user scripts inside macros), if provided. diff --git a/docs/docs/FormatSyntax.md b/docs/docs/FormatSyntax.md index 2f77b4dd..f594b53f 100644 --- a/docs/docs/FormatSyntax.md +++ b/docs/docs/FormatSyntax.md @@ -13,6 +13,7 @@ title: Format syntax | `{{VALUE:\|label:}}` | Adds helper text to the prompt for a single-value input. The helper appears below the header and is useful for reminders or instructions. For multi-value lists, use the same syntax to label the suggester (e.g., `{{VALUE:Red,Green,Blue\|label:Pick a color}}`). | | `{{VALUE:\|}}` | Same as above, but with a default value. For single-value prompts (e.g., `{{VALUE:name\|Anonymous}}`), the default is pre-populated in the input field - press Enter to accept or clear/edit it. For multi-value suggesters without `\|custom`, you must select one of the provided options (no default applies). If you combine options like `\|label:...`, use `\|default:` instead of the shorthand (mixing option keys with a bare default is not supported). | | `{{VALUE:\|default:}}` | Option-form default value, required when combining with other options like `\|label:`. Example: `{{VALUE:title\|label:Snake case\|default:My_Title}}`. | +| `{{VALUE\|type:multiline}}` / `{{VALUE:\|type:multiline}}` | Forces a multi-line input prompt/textarea for that VALUE token. Only supported for single-value prompts (no comma options / `\|custom`). Overrides the global "Use Multi-line Input Prompt" setting. If `\|type:` is present, shorthand defaults like `\|Some value` are ignored; use `\|default:` instead. | | `{{VALUE:\|custom}}` | Allows you to type custom values in addition to selecting from the provided options. Example: `{{VALUE:Red,Green,Blue\|custom}}` will suggest Red, Green, and Blue, but also allows you to type any other value like "Purple". This is useful when you have common options but want flexibility for edge cases. **Note:** You cannot combine `\|custom` with a shorthand default value - use `\|default:` if you need both. | | `{{LINKCURRENT}}` | A link to the file from which the template or capture was triggered (`[[link]]` format). When the append-link setting is set to **Enabled (skip if no active file)**, this token resolves to an empty string instead of throwing an error if no note is focused. | | `{{FILENAMECURRENT}}` | The basename (without extension) of the file from which the template or capture was triggered. Honors the same **required/optional** behavior as `{{LINKCURRENT}}` - when optional and no active file exists, resolves to an empty string. | @@ -26,3 +27,12 @@ title: Format syntax | `{{CLIPBOARD}}` | The current clipboard content. Will be empty if clipboard access fails due to permissions or security restrictions. | | `{{RANDOM:}}` | Generates a random alphanumeric string of the specified length (1-100). Useful for creating unique identifiers, block references, or temporary codes. Example: `{{RANDOM:6}}` generates something like `3YusT5`. | | `{{TITLE}}` | The final rendered filename (without extension) of the note being created or captured to. | + +### Mixed-mode example + +Use single-line for a title and multi-line for a body: + +```markdown +- {{VALUE:Title|label:Title}} +{{VALUE:Body|type:multiline|label:Body}} +``` diff --git a/src/constants.ts b/src/constants.ts index 6b1b4865..f3fc256d 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -77,7 +77,9 @@ export const DATE_REGEX_FORMATTED = new RegExp( ); export const TIME_REGEX = new RegExp(/{{TIME}}/i); export const TIME_REGEX_FORMATTED = new RegExp(/{{TIME:([^}\n\r+]*)}}/i); -export const NAME_VALUE_REGEX = new RegExp(/{{NAME}}|{{VALUE}}/i); +export const NAME_VALUE_REGEX = new RegExp( + /{{(?:NAME|VALUE)(?!:)(?:\|[^\n\r}]*)?}}/i, +); export const VARIABLE_REGEX = new RegExp(/{{VALUE:([^\n\r}]*)}}/i); export const FIELD_VAR_REGEX = new RegExp(/{{FIELD:([^\n\r}]*)}}/i); export const FIELD_VAR_REGEX_WITH_FILTERS = new RegExp( diff --git a/src/formatters/completeFormatter.ts b/src/formatters/completeFormatter.ts index 13f918fa..49e4f694 100644 --- a/src/formatters/completeFormatter.ts +++ b/src/formatters/completeFormatter.ts @@ -174,20 +174,28 @@ export class CompleteFormatter extends Formatter { } try { const linkSourcePath = this.getLinkSourcePath(); + const promptFactory = new InputPrompt().factory( + this.valuePromptContext?.inputTypeOverride, + ); + const defaultValue = this.valuePromptContext?.defaultValue; + const description = this.valuePromptContext?.description; if (linkSourcePath) { - this.value = await new InputPrompt() - .factory() - .PromptWithContext( - this.app, - this.valueHeader ?? `Enter value`, - undefined, - undefined, - linkSourcePath - ); + this.value = await promptFactory.PromptWithContext( + this.app, + this.valueHeader ?? `Enter value`, + undefined, + defaultValue, + linkSourcePath, + description, + ); } else { - this.value = await new InputPrompt() - .factory() - .Prompt(this.app, this.valueHeader ?? `Enter value`); + this.value = await promptFactory.Prompt( + this.app, + this.valueHeader ?? `Enter value`, + undefined, + defaultValue, + description, + ); } } catch (error) { if (isCancellationError(error)) { @@ -217,7 +225,7 @@ export class CompleteFormatter extends Formatter { } // Use default prompt for other variables - return await new InputPrompt().factory().Prompt( + return await new InputPrompt().factory(context?.inputTypeOverride).Prompt( this.app, header ?? context?.label ?? "Enter value", context?.placeholder ?? diff --git a/src/formatters/formatter.ts b/src/formatters/formatter.ts index 013683c4..8df68dba 100644 --- a/src/formatters/formatter.ts +++ b/src/formatters/formatter.ts @@ -27,8 +27,10 @@ import { TemplatePropertyCollector } from "../utils/TemplatePropertyCollector"; import { settingsStore } from "../settingsStore"; import { normalizeDateInput } from "../utils/dateAliases"; import { + parseAnonymousValueOptions, parseValueToken, resolveExistingVariableKey, + type ValueInputType, } from "../utils/valueSyntax"; import { parseMacroToken } from "../utils/macroSyntax"; @@ -42,6 +44,7 @@ export interface PromptContext { description?: string; placeholder?: string; variableKey?: string; + inputTypeOverride?: ValueInputType; // Undefined means use global input prompt setting. } export abstract class Formatter { @@ -50,6 +53,7 @@ export abstract class Formatter { protected dateParser: IDateParser | undefined; private linkToCurrentFileBehavior: LinkToCurrentFileBehavior = "required"; private static readonly FIELD_VARIABLE_PREFIX = "FIELD:"; + protected valuePromptContext?: PromptContext; // Tracks variables collected for YAML property post-processing private readonly propertyCollector: TemplatePropertyCollector; @@ -149,6 +153,8 @@ export abstract class Formatter { // Fast path: nothing to do. if (!NAME_VALUE_REGEX.test(output)) return output; + this.valuePromptContext = this.getValuePromptContext(output); + // Preserve programmatic VALUE injection via reserved variable name `value`. if (this.hasConcreteVariable("value")) { const existingValue = this.variables.get("value"); @@ -168,6 +174,35 @@ export abstract class Formatter { return output; } + private getValuePromptContext(input: string): PromptContext | undefined { + const regex = new RegExp(NAME_VALUE_REGEX.source, "gi"); + let match: RegExpExecArray | null; + let context: PromptContext | undefined; + + while ((match = regex.exec(input)) !== null) { + const token = match[0]; + const inner = token.slice(2, -2); + const optionsIndex = inner.indexOf("|"); + if (optionsIndex === -1) continue; + const rawOptions = inner.slice(optionsIndex); + + const parsed = parseAnonymousValueOptions(rawOptions); + if (!context) context = {}; + + if (!context.description && parsed.label) { + context.description = parsed.label; + } + if (!context.defaultValue && parsed.defaultValue) { + context.defaultValue = parsed.defaultValue; + } + if (parsed.inputTypeOverride === "multiline") { + context.inputTypeOverride = "multiline"; + } + } + + return context; + } + protected async replaceSelectedInString(input: string): Promise { let output: string = input; @@ -308,6 +343,7 @@ export abstract class Formatter { variableValue = await this.promptForVariable(variableName, { defaultValue, description: helperText, + inputTypeOverride: parsed.inputTypeOverride, variableKey, }); } else { diff --git a/src/gui/InputPrompt.test.ts b/src/gui/InputPrompt.test.ts new file mode 100644 index 00000000..2f31bc74 --- /dev/null +++ b/src/gui/InputPrompt.test.ts @@ -0,0 +1,39 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../main", () => ({ + __esModule: true, + default: class QuickAddMock { + static instance = { settings: { inputPrompt: "single-line" } }; + }, +})); + +import InputPrompt from "./InputPrompt"; +import GenericInputPrompt from "./GenericInputPrompt/GenericInputPrompt"; +import GenericWideInputPrompt from "./GenericWideInputPrompt/GenericWideInputPrompt"; +import QuickAdd from "../main"; + +describe("InputPrompt factory", () => { + beforeEach(() => { + QuickAdd.instance = { + settings: { inputPrompt: "single-line" }, + } as any; + }); + + it("prefers multiline override over global single-line", () => { + const prompt = new InputPrompt(); + expect(prompt.factory("multiline")).toBe(GenericWideInputPrompt); + }); + + it("uses global multiline when no override provided", () => { + QuickAdd.instance = { + settings: { inputPrompt: "multi-line" }, + } as any; + const prompt = new InputPrompt(); + expect(prompt.factory()).toBe(GenericWideInputPrompt); + }); + + it("uses single-line when no override and global single-line", () => { + const prompt = new InputPrompt(); + expect(prompt.factory()).toBe(GenericInputPrompt); + }); +}); diff --git a/src/gui/InputPrompt.ts b/src/gui/InputPrompt.ts index 88e0f19a..a8173a33 100644 --- a/src/gui/InputPrompt.ts +++ b/src/gui/InputPrompt.ts @@ -1,9 +1,13 @@ import GenericWideInputPrompt from "./GenericWideInputPrompt/GenericWideInputPrompt"; import GenericInputPrompt from "./GenericInputPrompt/GenericInputPrompt"; import QuickAdd from "../main"; +import type { ValueInputType } from "../utils/valueSyntax"; export default class InputPrompt { - public factory() { + public factory(inputTypeOverride?: ValueInputType) { + if (inputTypeOverride === "multiline") { + return GenericWideInputPrompt; + } if (QuickAdd.instance.settings.inputPrompt === "multi-line") { return GenericWideInputPrompt; } else { diff --git a/src/preflight/OnePageInputModal.ts b/src/preflight/OnePageInputModal.ts index b0cee937..5e774efb 100644 --- a/src/preflight/OnePageInputModal.ts +++ b/src/preflight/OnePageInputModal.ts @@ -404,11 +404,24 @@ export class OnePageInputModal extends Modal { private submit() { const out: Record = {}; - this.result.forEach((v, k) => (out[k] = v)); + const requirementsById = new Map( + this.requirements.map((req) => [req.id, req]), + ); + this.result.forEach((v, k) => { + const requirement = requirementsById.get(k); + out[k] = + requirement?.type === "textarea" + ? this.escapeBackslashes(v) + : v; + }); this.close(); this.resolvePromise(out); } + private escapeBackslashes(input: string): string { + return input.replace(/\\/g, "\\\\"); + } + private cancel() { this.close(); this.rejectPromise("cancelled"); diff --git a/src/preflight/RequirementCollector.test.ts b/src/preflight/RequirementCollector.test.ts index d1a1e801..f5979aed 100644 --- a/src/preflight/RequirementCollector.test.ts +++ b/src/preflight/RequirementCollector.test.ts @@ -7,7 +7,14 @@ const makeApp = () => ({ workspace: { getActiveFile: () => null }, vault: { getAbstractFileByPath: () => null, cachedRead: async () => "" }, } as any); -const makePlugin = () => ({ } as any); +const makePlugin = (overrides: Record = {}) => + ({ + settings: { + inputPrompt: "single-line", + globalVariables: {}, + ...overrides, + }, + } as any); describe("RequirementCollector", () => { it("collects VALUE with default and options", async () => { @@ -66,4 +73,35 @@ describe("RequirementCollector", () => { expect(rc.templatesToScan.size === 0 || rc.templatesToScan.has("Templates/Note")).toBe(true); }); + + it("uses textarea for VALUE tokens with type:multiline", async () => { + const app = makeApp(); + const plugin = makePlugin({ inputPrompt: "single-line" }); + const rc = new RequirementCollector(app, plugin); + await rc.scanString("{{VALUE:Body|type:multiline}}" ); + + const requirement = rc.requirements.get("Body"); + expect(requirement?.type).toBe("textarea"); + }); + + it("uses textarea for unnamed VALUE with type:multiline", async () => { + const app = makeApp(); + const plugin = makePlugin({ inputPrompt: "single-line" }); + const rc = new RequirementCollector(app, plugin); + await rc.scanString("{{VALUE|type:multiline|label:Notes}}" ); + + const requirement = rc.requirements.get("value"); + expect(requirement?.type).toBe("textarea"); + expect(requirement?.description).toBe("Notes"); + }); + + it("respects global multiline setting for named VALUE tokens", async () => { + const app = makeApp(); + const plugin = makePlugin({ inputPrompt: "multi-line" }); + const rc = new RequirementCollector(app, plugin); + await rc.scanString("{{VALUE:title}}" ); + + const requirement = rc.requirements.get("title"); + expect(requirement?.type).toBe("textarea"); + }); }); diff --git a/src/preflight/RequirementCollector.ts b/src/preflight/RequirementCollector.ts index 585c47cf..5d4a4cfa 100644 --- a/src/preflight/RequirementCollector.ts +++ b/src/preflight/RequirementCollector.ts @@ -156,6 +156,11 @@ export class RequirementCollector extends Formatter { 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, @@ -163,7 +168,7 @@ export class RequirementCollector extends Formatter { ? allowCustomInput ? "suggester" : "dropdown" - : "text", + : baseInputType, description, }; if (hasOptions) { @@ -194,9 +199,12 @@ export class RequirementCollector extends Formatter { 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", }); } @@ -230,10 +238,15 @@ export class RequirementCollector extends Formatter { 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" : "text", + type: hasOptions ? "dropdown" : baseInputType, description: context?.description, source: "collected", }; diff --git a/src/utils/valueSyntax.test.ts b/src/utils/valueSyntax.test.ts index 6e4ec512..9e6aa682 100644 --- a/src/utils/valueSyntax.test.ts +++ b/src/utils/valueSyntax.test.ts @@ -1,11 +1,16 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi, afterEach } from "vitest"; import { buildValueVariableKey, + parseAnonymousValueOptions, parseValueToken, resolveExistingVariableKey, } from "./valueSyntax"; describe("parseValueToken", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + it("ignores empty label values", () => { const parsed = parseValueToken("title|label:"); expect(parsed).not.toBeNull(); @@ -42,6 +47,58 @@ describe("parseValueToken", () => { expect(parsed?.allowCustomInput).toBe(true); expect(parsed?.defaultValue).toBe("High"); }); + + it("parses multiline type with label and default", () => { + const parsed = parseValueToken( + "Body|type:multiline|label:Notes|default:Hello", + ); + expect(parsed?.variableName).toBe("Body"); + expect(parsed?.inputTypeOverride).toBe("multiline"); + expect(parsed?.label).toBe("Notes"); + expect(parsed?.defaultValue).toBe("Hello"); + }); + + it("ignores shorthand default when type is present", () => { + const parsed = parseValueToken("Body|Hello|type:multiline"); + expect(parsed?.defaultValue).toBe(""); + expect(parsed?.inputTypeOverride).toBe("multiline"); + }); + + it("warns and ignores unknown type values", () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + const parsed = parseValueToken("Body|type:wide"); + expect(parsed?.inputTypeOverride).toBeUndefined(); + expect(warnSpy).toHaveBeenCalled(); + }); + + it("warns and ignores type for option lists", () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + const parsed = parseValueToken("Red,Green|type:multiline"); + expect(parsed?.inputTypeOverride).toBeUndefined(); + expect(warnSpy).toHaveBeenCalled(); + }); +}); + +describe("parseAnonymousValueOptions", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("parses multiline type for unnamed VALUE tokens", () => { + const parsed = parseAnonymousValueOptions( + "|type:multiline|label:Notes|default:Hello", + ); + expect(parsed.inputTypeOverride).toBe("multiline"); + expect(parsed.label).toBe("Notes"); + expect(parsed.defaultValue).toBe("Hello"); + }); + + it("warns and ignores unknown type for unnamed VALUE tokens", () => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + const parsed = parseAnonymousValueOptions("|type:wide"); + expect(parsed.inputTypeOverride).toBeUndefined(); + expect(warnSpy).toHaveBeenCalled(); + }); }); describe("resolveExistingVariableKey", () => { diff --git a/src/utils/valueSyntax.ts b/src/utils/valueSyntax.ts index 0af124c9..451265be 100644 --- a/src/utils/valueSyntax.ts +++ b/src/utils/valueSyntax.ts @@ -1,7 +1,9 @@ // Internal-only delimiter for scoping labeled VALUE lists. Unlikely to appear in user input. export const VALUE_LABEL_KEY_DELIMITER = "\u001F"; -const VALUE_OPTION_KEYS = new Set(["label", "default", "custom"]); +export type ValueInputType = "multiline"; + +const VALUE_OPTION_KEYS = new Set(["label", "default", "custom", "type"]); export type ParsedValueToken = { raw: string; @@ -12,6 +14,7 @@ export type ParsedValueToken = { allowCustomInput: boolean; suggestedValues: string[]; hasOptions: boolean; + inputTypeOverride?: ValueInputType; }; export function buildValueVariableKey( @@ -74,6 +77,7 @@ type ParsedOptions = { defaultValue: string; allowCustomInput: boolean; usesOptions: boolean; + inputTypeOverride?: string; }; function parseBoolean(value?: string): boolean { @@ -119,6 +123,7 @@ function parseOptions(optionParts: string[], hasOptions: boolean): ParsedOptions let label: string | undefined; let defaultValue = ""; let allowCustomInput = false; + let inputTypeOverride: string | undefined; for (const part of optionParts) { const trimmed = part.trim(); @@ -145,6 +150,9 @@ function parseOptions(optionParts: string[], hasOptions: boolean): ParsedOptions case "custom": allowCustomInput = parseBoolean(value); break; + case "type": + if (value) inputTypeOverride = value; + break; default: break; } @@ -155,9 +163,35 @@ function parseOptions(optionParts: string[], hasOptions: boolean): ParsedOptions defaultValue, allowCustomInput, usesOptions: true, + inputTypeOverride, }; } +function resolveInputType( + rawType: string | undefined, + { + tokenDisplay, + hasOptions, + allowCustomInput, + }: { tokenDisplay: string; hasOptions: boolean; allowCustomInput: boolean }, +): ValueInputType | undefined { + if (!rawType) return undefined; + const normalized = rawType.trim().toLowerCase(); + if (normalized !== "multiline") { + console.warn( + `QuickAdd: Unsupported VALUE type "${rawType}" in token "${tokenDisplay}". Supported types: multiline.`, + ); + return undefined; + } + if (hasOptions || allowCustomInput) { + console.warn( + `QuickAdd: Ignoring type:multiline for option-list VALUE token "${tokenDisplay}".`, + ); + return undefined; + } + return "multiline"; +} + export function parseValueToken(raw: string): ParsedValueToken | null { if (!raw) return null; @@ -180,6 +214,13 @@ export function parseValueToken(raw: string): ParsedValueToken | null { defaultValue = allowCustomInput ? "" : legacyDefault; } + const tokenDisplay = `{{VALUE:${raw}}}`; + const inputTypeOverride = resolveInputType(options.inputTypeOverride, { + tokenDisplay, + hasOptions, + allowCustomInput, + }); + const variableKey = buildValueVariableKey(variablePart, label, hasOptions); return { @@ -191,5 +232,45 @@ export function parseValueToken(raw: string): ParsedValueToken | null { allowCustomInput, suggestedValues, hasOptions, + inputTypeOverride, + }; +} + +export function parseAnonymousValueOptions( + rawOptions: string, +): { + label?: string; + defaultValue: string; + inputTypeOverride?: ValueInputType; +} { + const normalized = rawOptions.startsWith("|") + ? rawOptions.slice(1) + : rawOptions; + const parts = normalized + .split("|") + .map((part) => part.trim()) + .filter(Boolean); + + if (parts.length === 0) { + return { defaultValue: "" }; + } + + const options = parseOptions(parts, false); + let { label, defaultValue } = options; + if (!options.usesOptions) { + defaultValue = defaultValue.trim(); + } + + const tokenDisplay = `{{VALUE${rawOptions}}}`; + const inputTypeOverride = resolveInputType(options.inputTypeOverride, { + tokenDisplay, + hasOptions: false, + allowCustomInput: options.allowCustomInput, + }); + + return { + label, + defaultValue, + inputTypeOverride, }; }