Enhance interview functionality and settings; add YAML dependency
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run

- Introduced profile selection modal for creating notes from interview profiles.
- Added settings for interview configuration path, auto-starting interviews, and intercepting unresolved link clicks.
- Updated package files to include YAML dependency for configuration handling.
- Enhanced CSS for profile selection and interview wizard UI elements.
This commit is contained in:
Lars committed 2026-01-16 12:27:44 +01:00
1 parent d577283af6
commit bab84549e2
19 files changed
+2840 -5

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
import type { App } from "obsidian";
import { VocabularyLoader } from "../vocab/VocabularyLoader";
import { parseInterviewConfig, validateConfig } from "./parseInterviewConfig";
import type { InterviewConfig } from "./types";
/**
* Loader for interview config YAML files.
*/
export class InterviewConfigLoader {
/**
* Load and parse interview config from vault.
*/
static async loadConfig(
app: App,
path: string
): Promise<{ config: InterviewConfig; errors: string[] }> {
const yamlText = await VocabularyLoader.loadText(app, path);
return parseInterviewConfig(yamlText);
}
}
+52
View File
@@ -0,0 +1,52 @@
/**
* Extract basename from link target, preserving spaces and case.
* Only removes alias separator (|) and heading separator (#).
* For [[file#sec|alias]] => "file"
* For [[My Note]] => "My Note"
*/
export function extractBasenameFromTarget(target: string): string {
// Split by pipe (alias separator) and take first part
const parts = target.split("|");
const firstPart = parts[0];
if (!firstPart) return target.trim();
// Split by hash (heading separator) and take first part
const baseParts = firstPart.split("#");
const base = baseParts[0];
if (!base) return target.trim();
return base.trim();
}
/**
* Extract target basename from anchor data.
* Pure function that works with strings.
* Preserves spaces and case (Obsidian-style filenames).
*/
export function extractTargetFromData(
dataHref: string | null,
textContent: string | null
): string | null {
// Try data-href first
if (dataHref) {
return extractBasenameFromTarget(dataHref);
}
// Fall back to text content
if (textContent) {
return extractBasenameFromTarget(textContent.trim());
}
return null;
}
/**
* Extract target basename from an anchor element.
* Handles data-href attribute and text content.
* Preserves spaces and case (Obsidian-style filenames).
*/
export function extractTargetFromAnchor(anchor: HTMLElement): string | null {
const dataHref = anchor.getAttribute("data-href");
const textContent = anchor.textContent;
return extractTargetFromData(dataHref, textContent);
}
+363
View File
@@ -0,0 +1,363 @@
import { parse } from "yaml";
import type {
InterviewConfig,
InterviewProfile,
InterviewStep,
} from "./types";
export interface ParseResult {
config: InterviewConfig;
errors: string[];
}
/**
* Parse YAML interview config file.
*/
export function parseInterviewConfig(yamlText: string): ParseResult {
const errors: string[] = [];
try {
const raw = parse(yamlText) as unknown;
if (!raw || typeof raw !== "object") {
return {
config: {
version: "2.0",
frontmatterWhitelist: [],
profiles: [],
},
errors: ["Invalid YAML: root must be an object"],
};
}
const obj = raw as Record<string, unknown>;
// Extract version
const version = typeof obj.version === "string" ? obj.version : "2.0";
// Extract frontmatterWhitelist (accept both camelCase and snake_case)
const frontmatterWhitelist: string[] = [];
const whitelistSource = obj.frontmatterWhitelist || obj.frontmatter_whitelist;
if (Array.isArray(whitelistSource)) {
for (const item of whitelistSource) {
if (typeof item === "string") {
frontmatterWhitelist.push(item);
}
}
}
// Extract profiles
const profiles: InterviewProfile[] = [];
if (Array.isArray(obj.profiles)) {
for (let i = 0; i < obj.profiles.length; i++) {
const profileRaw = obj.profiles[i];
if (!profileRaw || typeof profileRaw !== "object") {
errors.push(`Profile at index ${i} is not an object`);
continue;
}
const profile = parseProfile(profileRaw as Record<string, unknown>, i);
if (profile) {
profiles.push(profile);
} else {
errors.push(`Failed to parse profile at index ${i}`);
}
}
}
const config: InterviewConfig = {
version,
frontmatterWhitelist,
profiles,
};
// Validate
const validationErrors = validateConfig(config);
errors.push(...validationErrors);
return { config, errors };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
return {
config: {
version: "2.0",
frontmatterWhitelist: [],
profiles: [],
},
errors: [`YAML parse error: ${msg}`],
};
}
}
function parseProfile(
raw: Record<string, unknown>,
index: number
): InterviewProfile | null {
if (typeof raw.key !== "string" || !raw.key.trim()) {
return null;
}
if (typeof raw.label !== "string" || !raw.label.trim()) {
return null;
}
if (typeof raw.note_type !== "string" || !raw.note_type.trim()) {
return null;
}
const profile: InterviewProfile = {
key: raw.key.trim(),
label: raw.label.trim(),
note_type: raw.note_type.trim(),
steps: [],
};
if (typeof raw.group === "string" && raw.group.trim()) {
profile.group = raw.group.trim();
}
if (raw.defaults && typeof raw.defaults === "object") {
profile.defaults = raw.defaults as Record<string, unknown>;
}
// Parse steps
if (Array.isArray(raw.steps)) {
for (let i = 0; i < raw.steps.length; i++) {
const stepRaw = raw.steps[i];
if (!stepRaw || typeof stepRaw !== "object") {
continue;
}
const step = parseStep(stepRaw as Record<string, unknown>);
if (step) {
profile.steps.push(step);
}
}
}
return profile;
}
function parseStep(raw: Record<string, unknown>): InterviewStep | null {
// Accept both "type" and "kind" (YAML uses "kind", but we normalize to "type" internally)
const stepType = raw.type || raw.kind;
if (typeof stepType !== "string") {
return null;
}
const type = stepType;
// Helper: get key from "key" or "id" field
const getKey = (): string | null => {
if (typeof raw.key === "string" && raw.key.trim()) {
return raw.key.trim();
}
if (typeof raw.id === "string" && raw.id.trim()) {
return raw.id.trim();
}
return null;
};
if (type === "loop") {
const key = getKey();
if (!key) {
return null;
}
// Accept both "items" and "steps" for loop nested steps
const nestedSteps = raw.items || raw.steps;
if (!Array.isArray(nestedSteps)) {
return null;
}
const step: InterviewStep = {
type: "loop",
key: key,
items: [],
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
for (const itemRaw of nestedSteps) {
if (!itemRaw || typeof itemRaw !== "object") {
continue;
}
const item = parseStep(itemRaw as Record<string, unknown>);
if (item) {
step.items.push(item);
}
}
return step;
}
if (type === "llm_dialog") {
const key = getKey();
if (!key) {
return null;
}
// Accept both "prompt" and "prompt_template"
const promptText = raw.prompt || raw.prompt_template;
if (typeof promptText !== "string" || !promptText.trim()) {
return null;
}
const step: InterviewStep = {
type: "llm_dialog",
key: key,
prompt: promptText.trim(),
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
if (typeof raw.system_prompt === "string" && raw.system_prompt.trim()) {
step.system_prompt = raw.system_prompt.trim();
}
if (typeof raw.model === "string" && raw.model.trim()) {
step.model = raw.model.trim();
}
if (typeof raw.temperature === "number") {
step.temperature = raw.temperature;
}
if (typeof raw.max_tokens === "number") {
step.max_tokens = raw.max_tokens;
}
return step;
}
if (type === "capture_frontmatter") {
const key = getKey();
if (!key) {
return null;
}
if (typeof raw.field !== "string" || !raw.field.trim()) {
return null;
}
const step: InterviewStep = {
type: "capture_frontmatter",
key: key,
field: raw.field.trim(),
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
if (typeof raw.required === "boolean") {
step.required = raw.required;
}
return step;
}
if (type === "capture_text") {
const key = getKey();
if (!key) {
return null;
}
const step: InterviewStep = {
type: "capture_text",
key: key,
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
if (typeof raw.required === "boolean") {
step.required = raw.required;
}
if (typeof raw.section === "string" && raw.section.trim()) {
step.section = raw.section.trim();
}
if (typeof raw.prompt === "string" && raw.prompt.trim()) {
step.prompt = raw.prompt.trim();
}
return step;
}
if (type === "instruction") {
const key = getKey();
if (!key) {
return null;
}
if (typeof raw.content !== "string") {
return null;
}
const step: InterviewStep = {
type: "instruction",
key: key,
content: raw.content,
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
return step;
}
if (type === "review") {
const key = getKey();
if (!key) {
return null;
}
const step: InterviewStep = {
type: "review",
key: key,
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
return step;
}
return null;
}
/**
* Validate parsed config.
*/
export function validateConfig(config: InterviewConfig): string[] {
const errors: string[] = [];
// Check unique profile keys
const profileKeys = new Set<string>();
for (const profile of config.profiles) {
if (profileKeys.has(profile.key)) {
errors.push(`Duplicate profile key: ${profile.key}`);
} else {
profileKeys.add(profile.key);
}
}
// Check capture_frontmatter.field in whitelist
for (const profile of config.profiles) {
validateSteps(profile.steps, config.frontmatterWhitelist, errors);
}
return errors;
}
function validateSteps(
steps: InterviewStep[],
whitelist: string[],
errors: string[]
): void {
for (const step of steps) {
if (step.type === "capture_frontmatter") {
if (!whitelist.includes(step.field)) {
errors.push(
`capture_frontmatter field '${step.field}' not in frontmatterWhitelist`
);
}
} else if (step.type === "loop") {
validateSteps(step.items, whitelist, errors);
}
}
}
+15
View File
@@ -0,0 +1,15 @@
/**
* Convert string to URL-safe slug (a-z0-9_).
* Used for file names.
*/
export function slugify(text: string): string {
if (!text) return "";
return text
.toLowerCase()
.normalize("NFD") // Decompose accented characters
.replace(/[\u0300-\u036f]/g, "") // Remove diacritics
.replace(/[^a-z0-9_]+/g, "_") // Replace non-alphanumeric with underscore
.replace(/^_+|_+$/g, "") // Remove leading/trailing underscores
.replace(/_+/g, "_"); // Collapse multiple underscores
}
+74
View File
@@ -0,0 +1,74 @@
/**
* InterviewConfig v2 types
*/
export interface InterviewConfig {
version: string;
frontmatterWhitelist: string[];
profiles: InterviewProfile[];
}
export interface InterviewProfile {
key: string;
label: string;
note_type: string;
group?: string;
defaults?: Record<string, unknown>;
steps: InterviewStep[];
}
export type InterviewStep =
| LoopStep
| LLMDialogStep
| CaptureFrontmatterStep
| CaptureTextStep
| InstructionStep
| ReviewStep;
export interface LoopStep {
type: "loop";
key: string;
label?: string;
items: InterviewStep[];
}
export interface LLMDialogStep {
type: "llm_dialog";
key: string;
label?: string;
prompt: string;
system_prompt?: string;
model?: string;
temperature?: number;
max_tokens?: number;
}
export interface CaptureFrontmatterStep {
type: "capture_frontmatter";
key: string;
label?: string;
field: string;
required?: boolean;
}
export interface CaptureTextStep {
type: "capture_text";
key: string;
label?: string;
required?: boolean;
section?: string; // Markdown section header (e.g., "## 🧩 Erlebnisse")
prompt?: string; // Optional prompt text
}
export interface InstructionStep {
type: "instruction";
key: string;
label?: string;
content: string;
}
export interface ReviewStep {
type: "review";
key: string;
label?: string;
}
+106
View File
@@ -0,0 +1,106 @@
import type { InterviewProfile, InterviewStep } from "./types";
export interface WizardState {
profile: InterviewProfile;
currentStepIndex: number;
stepHistory: number[]; // Stack for back navigation
collectedData: Map<string, unknown>; // key -> value
loopContexts: Map<string, unknown[]>; // loop key -> array of collected items
patches: Patch[]; // Collected patches to apply
}
export interface Patch {
type: "frontmatter" | "content";
field?: string; // For frontmatter patches
value: unknown;
lineStart?: number;
lineEnd?: number;
}
export function createWizardState(profile: InterviewProfile): WizardState {
// Log flattened steps before creating state
const flat = flattenSteps(profile.steps);
const flatKinds = flat.map(s => s.type);
console.log("Wizard flattened steps", {
count: flat.length,
kinds: flatKinds,
});
return {
profile,
currentStepIndex: 0,
stepHistory: [],
collectedData: new Map(),
loopContexts: new Map(),
patches: [],
};
}
export function getCurrentStep(state: WizardState): InterviewStep | null {
const steps = flattenSteps(state.profile.steps);
// Log flattened steps count
if (state.currentStepIndex === 0) {
console.log("Flattened steps", { count: steps.length });
}
if (steps.length === 0) {
console.warn("No steps available in profile", { profileKey: state.profile.key });
return null;
}
if (state.currentStepIndex >= 0 && state.currentStepIndex < steps.length) {
return steps[state.currentStepIndex] || null;
}
return null;
}
export function getNextStepIndex(state: WizardState): number | null {
const steps = flattenSteps(state.profile.steps);
if (state.currentStepIndex < steps.length - 1) {
return state.currentStepIndex + 1;
}
return null;
}
export function getPreviousStepIndex(state: WizardState): number | null {
if (state.stepHistory.length > 0) {
const prev = state.stepHistory[state.stepHistory.length - 1];
return prev !== undefined ? prev : null;
}
return null;
}
export function canGoNext(state: WizardState): boolean {
return getNextStepIndex(state) !== null;
}
export function canGoBack(state: WizardState): boolean {
return state.stepHistory.length > 0;
}
/**
* Flatten steps including loops into a linear array.
* Returns ALL top-level steps (instruction, capture_text, capture_frontmatter, llm_dialog, review, loop).
* For loops, includes the loop step itself (nested items are handled during execution).
* Exported for use in InterviewWizardModal.
*/
export function flattenSteps(steps: InterviewStep[]): InterviewStep[] {
const result: InterviewStep[] = [];
if (!steps || steps.length === 0) {
return result;
}
for (const step of steps) {
if (!step) {
console.warn("Skipping null/undefined step");
continue;
}
// Include all step types: instruction, capture_text, capture_frontmatter, llm_dialog, review, loop
// For loops, include the loop step itself (nested items handled during execution)
result.push(step);
}
return result;
}
+93
View File
@@ -0,0 +1,93 @@
import type { InterviewProfile } from "./types";
export interface FrontmatterOptions {
id: string;
title: string;
noteType: string;
interviewProfile: string;
defaults?: Record<string, unknown>;
frontmatterWhitelist: string[];
}
/**
* Write frontmatter YAML from options.
* Only includes defaults fields that are in frontmatterWhitelist.
*/
export function writeFrontmatter(opts: FrontmatterOptions): string {
const { id, title, noteType, interviewProfile, defaults, frontmatterWhitelist } = opts;
const lines: string[] = [];
lines.push("---");
// Required fields
lines.push(`id: ${escapeYamlValue(id)}`);
lines.push(`title: ${escapeYamlValue(title)}`);
lines.push(`type: ${escapeYamlValue(noteType)}`);
lines.push(`interview_profile: ${escapeYamlValue(interviewProfile)}`);
// Whitelisted defaults
if (defaults) {
for (const [key, value] of Object.entries(defaults)) {
if (frontmatterWhitelist.includes(key)) {
lines.push(`${key}: ${escapeYamlValue(value)}`);
}
}
}
lines.push("---");
return lines.join("\n");
}
/**
* Escape YAML value for frontmatter.
* Handles strings, numbers, booleans, null.
*/
function escapeYamlValue(value: unknown): string {
if (value === null || value === undefined) {
return "null";
}
if (typeof value === "boolean") {
return value ? "true" : "false";
}
if (typeof value === "number") {
return String(value);
}
if (typeof value === "string") {
// If string contains special characters, quote it
if (
value.includes(":") ||
value.includes("#") ||
value.includes("|") ||
value.includes(">") ||
value.includes("<") ||
value.includes("&") ||
value.includes("*") ||
value.includes("!") ||
value.includes("%") ||
value.includes("@") ||
value.includes("`") ||
value.includes('"') ||
value.includes("'") ||
value.includes("\n") ||
value.trim() !== value ||
value.startsWith("[") ||
value.startsWith("{")
) {
// Escape quotes and use double quotes
const escaped = value.replace(/"/g, '\\"');
return `"${escaped}"`;
}
return value;
}
// For objects/arrays, serialize as JSON string (quoted)
try {
const json = JSON.stringify(value);
return `"${json.replace(/"/g, '\\"')}"`;
} catch {
return '""';
}
}