Compare commits

..
44 Commits
Author SHA1 Message Date
Lars 0fa2197ab2 Doku MVP1.0
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-17 10:56:59 +01:00
Lars 56049b9318 Enhance Mindnet settings interface with new configuration options
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Added sections for Dictionary & Schema Configuration, Graph Traversal & Linting, Interview & Note Creation, Unresolved Link Handling, Templater Compatibility, Note Adoption, and Semantic Mapping Builder.
- Updated descriptions for various settings to provide clearer guidance in German.
- Introduced new settings for interview configuration paths, default notes folder, and handling of unresolved links.
- Improved user experience with additional validation options and clearer descriptions for existing settings.
2026-01-17 10:54:32 +01:00
Lars 5ed06e6b9a Enhance interview configuration and wizard functionality
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Added parsing for new edging configuration options in interview profiles, including mode, wrapper callout type, title, and folded state.
- Updated the InterviewWizardModal to support post-run edging, allowing for semantic mapping based on the new edging settings.
- Enhanced the unresolved link handler to pass plugin instance and settings for improved graph schema loading and post-run edging functionality.
- Improved error handling and user notifications for semantic mapping processes, ensuring better feedback during execution.
2026-01-17 10:31:44 +01:00
Lars a6ce268b04 Enhance note adoption process with confidence evaluation and settings
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Introduced a new function to evaluate adoption confidence based on file creation time and content criteria.
- Updated the adoption confirmation logic to determine when to show confirmation based on user settings.
- Added new settings for adoption confirmation mode and high-confidence time window in the settings interface.
- Improved the user experience by providing clearer options for managing note adoption behavior.
2026-01-17 10:11:30 +01:00
Lars 90eafb62f4 Implement unresolved link handling and note adoption features
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Added functionality to intercept unresolved link clicks in both Reading View and Live Preview, allowing users to create notes directly from unresolved links.
- Introduced settings for auto-starting interviews on unresolved link clicks, bypass modifiers for link interception, and options for adopting newly created notes in the editor.
- Enhanced the settings interface with new options for managing unresolved link behavior and note adoption criteria.
- Implemented a file create handler to automatically adopt new notes based on content length and user confirmation.
- Improved error handling and user notifications throughout the new features for a better user experience.
2026-01-17 10:07:07 +01:00
Lars 556145e76d Update ProfileSelectionModal to change button text and remove folder creation functionality
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Changed the button text from "Pick…" to "Anpassen" for better localization.
- Removed the folder creation button and its associated functionality to streamline the modal interface.
2026-01-17 09:12:22 +01:00
Lars ae0e699602 Folder Picker V1
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-17 08:01:04 +01:00
Lars 1f9211cbc5 Add graph schema loading and validation functionality
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Introduced methods for loading and reloading graph schema, including debounced reload on file changes.
- Enhanced the semantic mapping builder to utilize the new graph schema loading mechanism for improved caching and live updates.
- Added a validation button in the settings interface to check the existence and validity of the graph schema file, providing user feedback on the schema status.
- Improved error handling for graph schema loading to ensure clear notifications for users in case of issues.
2026-01-17 07:42:17 +01:00
Lars 58b6ffffed Add semantic mapping builder functionality and settings
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Introduced a new command to build semantic mapping blocks by section, including user prompts for overwriting existing mappings.
- Enhanced settings interface with options for mapping wrapper type, title, folded state, default edge type, unassigned handling, and overwrite permissions.
- Implemented virtualization in the EntityPickerModal for improved performance when displaying large sets of entries, including scroll handling and item rendering optimizations.
- Updated UI components to reflect new settings and functionalities, ensuring a cohesive user experience.
2026-01-17 07:27:11 +01:00
Lars 78e8216ab9 NotePicker - V1
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-17 06:28:36 +01:00
Lars b5f2c8fc67 Enhance Interview Wizard Modal with improved preview and editing functionality
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Added a "Back to Edit" button wrapper in preview mode for easier navigation back to editing.
- Updated preview rendering logic to ensure the back button visibility aligns with the current mode.
- Enhanced textarea handling to retrieve and update draft values more effectively when toggling between preview and edit modes.
- Improved error handling and fallback rendering for the Markdown preview, ensuring a better user experience during content display.
- Refactored existing rendering methods to maintain structure while clearing content, enhancing performance and reliability.
2026-01-16 22:32:36 +01:00
Lars 070cb853a9 Add heading level configuration to interview steps and rendering logic
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Introduced a new `heading_level` property in `CaptureTextLineStep` to enable customizable heading levels for interview steps.
- Updated `parseInterviewConfig` to parse and validate heading level settings.
- Enhanced rendering functions to prepend heading prefixes based on the configured heading level, improving text output formatting.
- Implemented a dropdown in the `InterviewWizardModal` for selecting heading levels, allowing users to easily adjust the heading for each step.
- Improved handling of nested loops to support heading level selection and display.
2026-01-16 22:05:36 +01:00
Lars 611ad37c42 Enhance Interview Wizard Modal with improved nested loop state management and preview functionality
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Reset nested loop state to clear both items and draft when a new item is created.
- Added a "Back to Edit" button in preview mode to facilitate easy navigation back to editing.
- Updated toolbar functionality to only display in edit mode, improving user experience during text editing.
- Enhanced rendering logic to ensure proper display of preview and editing states.
2026-01-16 20:57:27 +01:00
Lars c3357a784b Enhance nested loop functionality in Interview Wizard Modal
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Added support for tracking active loop paths, enabling nested loop navigation.
- Implemented breadcrumb navigation to display loop hierarchy and allow users to navigate back to parent loops.
- Updated rendering logic for nested loops to support fullscreen mode and improved item management with edit, delete, and navigation options.
- Enhanced user experience with context headers showing parent loop item details and improved item editing capabilities.
2026-01-16 20:53:02 +01:00
Lars 5a171987b2 Eingebette Loops
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-16 20:10:08 +01:00
Lars 684217bdf4 Pane 2 mit Edit, Delete, sort, etc.
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-16 19:25:55 +01:00
Lars 8ba098c780 MVP - Basis finalisiert. Standard Toolbar, Workflow
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-16 18:26:01 +01:00
Lars 587ef3010a Refactor markdown toolbar functionality for improved text formatting
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Removed deprecated functions and streamlined the applyMarkdownWrap function to return a ToolbarResult object.
- Introduced new functions for applying headings, bullet lists, and numbered lists, enhancing the text formatting capabilities.
- Updated the InterviewWizardModal to utilize the new toolbar functions for better integration and user experience.
- Improved selection handling and cursor positioning after formatting operations.
2026-01-16 15:13:40 +01:00
Lars d7aa9bd964 Implement Interview Wizard Modal enhancements with new CSS styles and markdown support
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Added comprehensive CSS styles for the Interview Wizard Modal, improving layout and responsiveness.
- Introduced markdown editing capabilities with a toolbar for text areas, allowing for rich text input.
- Enhanced step rendering logic to support optional prompt text for each step.
- Updated the modal structure to include sticky navigation and improved content organization.
- Refactored existing rendering methods to utilize new CSS classes for better styling consistency.
2026-01-16 14:11:04 +01:00
Lars bab84549e2 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.
2026-01-16 12:27:44 +01:00
Lars d577283af6 Add graph export and chain traversal commands; enhance linting options
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
- Introduced commands for exporting graph data and displaying chains from the current note.
- Enhanced linting functionality with options for showing canonical hints and specifying chain traversal direction.
- Added new utility functions for graph traversal and index building.
- Updated settings interface to include new options for user configuration.
2026-01-15 12:27:16 +01:00
Lars 9b8550c387 Refactor plugin to Mindnet Causal Assistant with enhanced vocabulary management and linting features. Updated manifest and package files to reflect new plugin details and dependencies. Added commands for reloading vocabulary and validating notes.
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run
2026-01-15 11:34:29 +01:00
Lishid dc2fa22c4d Fix typo in ESLint plugin link 2025-12-30 13:09:48 -05:00
Johannes Theiner 2323eddbb1 Merge pull request #164 from joethei/master
Include eslint config
2025-12-18 11:53:40 +01:00
Johannes Theiner 911b773800 Merge remote-tracking branch 'upstream/master'
# Conflicts:
#	README.md
#	src/main.ts
2025-11-14 15:24:54 +01:00
Johannes Theiner 123fc4a870 update eslint plugin version
remove builtin-modules external dependency
2025-11-14 14:28:33 +01:00
Johannes Theiner 0eca98adda update package.json 2025-11-10 22:27:46 +01:00
Johannes Theiner 92cba25647 update sample plugin with eslint instructions 2025-11-10 12:26:07 +01:00
Johannes Theiner 9984b040b6 remove testing code 2025-10-17 12:36:26 +02:00
Johannes Theiner e2a64e0534 Merge pull request #151 from adamu/main
Prefix unused variables with _
2025-09-17 18:12:44 +02:00
Johannes Theiner 8933f6ce64 Merge pull request #142 from johannrichard/declutter-version-bump
build: only write new minAppVersion requirements to `versions.json`
2025-09-17 17:54:33 +02:00
Adam Millerchip f16c1401b3 Prefix unused variables with _ 2025-08-28 14:38:40 +09:00
Johannes Theiner fa2fac56be Remove node 18 from action 2025-07-04 13:29:58 +02:00
Johannes Theiner e0485eb3ba add lock file to repo 2025-07-04 13:28:27 +02:00
Johannes Theiner dbc9096f81 Add lint action 2025-07-04 13:27:53 +02:00
Johannes Theiner 90290a8af5 Update to use released eslint plugin 2025-07-03 12:00:06 +02:00
Johannes Theiner 68ab547f2c Update to use released eslint plugin 2025-06-02 12:10:29 +02:00
Johann Richard 3fe07677b5 build: only write new minAppVersion requirements to versions.json
Only add a new version requirements if `minAppVersion` is not already in `versions.json`. Should declutter `versions.json`.
2025-04-28 08:38:38 +02:00
Johannes Theiner ba04056938 Merge remote-tracking branch 'origin/master' 2025-01-02 16:48:30 +01:00
Johannes Theiner 55f5080882 Add linting of dependencies, throwing errors when including using telemetry libraries 2025-01-02 16:48:03 +01:00
Johannes Theiner 20002ffc65 Merge branch 'obsidianmd:master' into master 2024-11-20 17:02:47 +01:00
Johannes Theiner fa15a2558e Merge remote-tracking branch 'origin/master'
# Conflicts:
#	tsconfig.json
2024-07-31 23:00:52 +02:00
Johannes Theiner 15e343739e Add stylelint and configure eslint to add custom plugin.
- Split up main.ts into multiple files.
2024-07-31 22:59:59 +02:00
Johannes Theiner b9a0e401e0 configure eslint 2024-02-29 13:18:14 +01:00
110 changed files with 23891 additions and 193 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
node_modules/
main.js
-23
View File
@@ -1,23 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"env": { "node": true },
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off"
}
}
+28
View File
@@ -0,0 +1,28 @@
name: Node.js build
on:
push:
branches: ["**"]
pull_request:
branches: ["**"]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
- run: npm ci
- run: npm run build --if-present
- run: npm run lint
+6 -10
View File
@@ -7,7 +7,7 @@ The repo depends on the latest plugin API (obsidian.d.ts) in TypeScript Definiti
This sample plugin demonstrates some of the basic functionality the plugin API can do. This sample plugin demonstrates some of the basic functionality the plugin API can do.
- Adds a ribbon icon, which shows a Notice when clicked. - Adds a ribbon icon, which shows a Notice when clicked.
- Adds a command "Open Sample Modal" which opens a Modal. - Adds a command "Open modal (simple)" which opens a Modal.
- Adds a plugin setting tab to the settings page. - Adds a plugin setting tab to the settings page.
- Registers a global click event and output 'click' to the console. - Registers a global click event and output 'click' to the console.
- Registers a global interval which logs 'setInterval' to the console. - Registers a global interval which logs 'setInterval' to the console.
@@ -55,15 +55,11 @@ Quick starting guide for new plugin devs:
- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`. - Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`.
## Improve code quality with eslint (optional) ## Improve code quality with eslint
- [ESLint](https://eslint.org/) is a tool that analyzes your code to quickly find problems. You can run ESLint against your plugin to find common bugs and ways to improve your code. - [ESLint](https://eslint.org/) is a tool that analyzes your code to quickly find problems. You can run ESLint against your plugin to find common bugs and ways to improve your code.
- To use eslint with this project, make sure to install eslint from terminal: - This project already has eslint preconfigured, you can invoke a check by running`npm run lint`
- `npm install -g eslint` - Together with a custom eslint [plugin](https://github.com/obsidianmd/eslint-plugin) for Obsidan specific code guidelines.
- To use eslint to analyze this project use this command: - A GitHub action is preconfigured to automatically lint every commit on all branches.
- `eslint main.ts`
- eslint will then create a report with suggestions for code improvement by file and line number.
- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder:
- `eslint ./src/`
## Funding URL ## Funding URL
@@ -91,4 +87,4 @@ If you have multiple URLs, you can also do:
## API Documentation ## API Documentation
See https://github.com/obsidianmd/obsidian-api See https://docs.obsidian.md
+142
View File
@@ -0,0 +1,142 @@
# HANDBUCH — Mindnet Obsidian Plugin (MVP 1.0)
## 1) Installation / Deployment (Neu aus Gitea)
Dieses Kapitel beschreibt den Prozess, wenn du das Plugin komplett neu aus Gitea holst und in Obsidian bereitstellst.
### 1.1 Voraussetzungen
- Windows (Entwicklung) + Obsidian Desktop
- Node.js installiert (CLI verfügbar)
- Falls PowerShell `npm` blockiert: `npm.cmd` nutzen
- Git Zugriff auf dein Gitea Repo
### 1.2 Repo klonen
Beispiel:
1) Ordner wählen (z.B. `C:\Dev\cursor\mindnet_obsidian`)
2) Repo klonen:
- `git clone <gitea-url> mindnet_obsidian`
3) In den Ordner wechseln:
- `cd mindnet_obsidian`
### 1.3 Dependencies installieren
Wenn PowerShell npm-scripts blockiert:
- nutze `npm.cmd install`
Standard:
- `npm install`
### 1.4 Build
- `npm run build`
Erwartetes Ergebnis:
- Plugin-Bundle (typischerweise `main.js`) wird erzeugt (abhängig von eurer Build-Konfiguration).
### 1.5 Deployment in einen Obsidian Vault (Dev)
Zielpfad:
- `<vault>/.obsidian/plugins/<plugin-id>/`
Schritte:
1) Im Vault sicherstellen:
- `.obsidian/plugins/` existiert
2) Plugin-Ordner anlegen:
- `.obsidian/plugins/mindnet-causal-assistant/`
3) Deployment (Copy):
- `manifest.json` → plugin folder
- `main.js` → plugin folder
- optional `styles.css` → plugin folder
Wenn ihr ein Script habt (empfohlen):
- `powershell -ExecutionPolicy Bypass -File scripts\deploy-local.ps1`
### 1.6 Plugin aktivieren
Obsidian:
- Settings → Community Plugins
- “Restricted mode” aus
- Plugin aktivieren
### 1.7 Typische Fehlerbilder
- “Plugin lädt nicht”:
- Obsidian neustarten
- Plugin disable/enable
- prüfen, ob `main.js` im Plugin-Ordner aktuell ist
- Keine Logs:
- DevTools öffnen: `Ctrl+Shift+I`
- Console Filter zurücksetzen
---
## 2) Konfiguration (Pfad-Settings)
### 2.1 Vocabulary
- `edge_vocabulary path` (z.B. `_system/dictionary/edge_vocabulary.md`)
- Live reload bei Dateiänderung (debounced)
### 2.2 Graph Schema
- `graph_schema path` (z.B. `_system/dictionary/graph_schema.md`)
- Wird für Empfehlungen (typical/prohibited) verwendet
### 2.3 Interview Config
- `interview_config path` (z.B. `_system/dictionary/interview_config.yaml`)
- Profiles definieren Note-Type, Defaults, Steps, Loop-Layouts
---
## 3) Workflows
### 3.1 Note erstellen
- Command: “Create note from profile”
- Profil wählen
- Titel setzen
- Folder wählen (oder default)
- Note wird erstellt und geöffnet
### 3.2 Interview durchführen
- Wizard startet automatisch (wenn aktiviert) oder manuell per Command
- Steps ausfüllen (Loops/Nested Loops möglich)
- Review → Apply & Finish
- Output wird geschrieben
### 3.3 Semantic Mapping (Edger)
**Manuell:**
- Command: “Build semantic mapping blocks (by section)”
**Automatisch (post-run):**
- Nach Interview Finish wird der Edger ausgeführt (falls im Profil aktiviert)
Output:
- pro Section ein Mapping-Block am Ende der Section:
- Wrapper callout (Default: abstract)
- gruppiert nach Edge-Typ
- Gruppen getrennt durch Leerzeile
### 3.4 Unresolved Link → Interview
- Klick auf `[[Neue Note]]`
- In Reading View: Plugin übernimmt Flow
- In Editing View: Obsidian kann Note sofort erzeugen → Plugin “adoptiert” und startet Mindnet Flow
---
## 4) Entwicklung (Dev-Workflow)
### 4.1 Build + Deploy lokal
- `npm run build`
- `scripts\deploy-local.ps1` ausführen (falls vorhanden)
- Obsidian: Plugin reload (disable/enable)
### 4.2 Tests
- `npm run test`
---
## 5) Troubleshooting
- Wizard startet nicht:
- Prüfe settings `autoStart...`
- DevTools Console auf Fehler prüfen
- Edger schreibt Blöcke an falscher Stelle:
- Prüfe Heading Parsing + Section detection
- Prüfe, ob Wrapper Block korrekt erkannt/ersetzt wird
- Schema Empfehlungen fehlen:
- Prüfe graph_schema path
- Prüfe schema loader stats/logging
---
# CHANGELOG (optional)
- v1.0.0: MVP 1.0 Feature Freeze
+45
View File
@@ -0,0 +1,45 @@
# README — Mindnet Obsidian Plugin (MVP 1.0)
## Überblick
Das Mindnet Obsidian Plugin ist ein Authoring-Tool, das dich dabei unterstützt:
- Mindnet-Notes strukturiert anzulegen (Frontmatter, IDs, Typen)
- Inhalte über konfigurierbare Interviews zu erfassen
- semantische Kanten (Edges) zu pflegen und zu validieren
- Links und Edge-Zuordnungen innerhalb einer Note section-basiert zu gruppieren (Semantic Mapping)
## Hauptkonzepte
- **Profile**: Auswahl eines “Erstell-Profils” (kann mehrere Interviews pro Note-Typ geben).
- **Interview Config (YAML)**: definiert Steps, Loops, Defaults, Frontmatter-Whitelist.
- **ID-first**: Mindnet-Graph arbeitet über Frontmatter `id` als Schlüssel.
- **Semantic Mapping**: links in einer Section werden Edge-Typen zugeordnet und als Callouts strukturiert.
## Quickstart (User)
1) Plugin installieren (siehe Handbuch: Deployment)
2) Settings:
- `edge_vocabulary path` setzen
- `graph_schema path` setzen
- `interview_config path` setzen
3) Neue Note:
- Command: **Mindnet: Create note from profile**
- Profil wählen, Titel setzen, Folder wählen
- Wizard ausfüllen, Finish
- Edger läuft optional post-run und baut Semantic Mapping Blöcke
## Commands (Auszug)
- Create/Interview:
- Mindnet: Create note from profile
- (Auto) Start Wizard nach Create (konfigurierbar)
- Mapping/Edges:
- Mindnet: Build semantic mapping blocks (by section)
- Mindnet: Reload edge vocabulary
- (post-run) Edger nach Interview Finish
- QA:
- Mindnet: Validate current note (Lint)
- Export/Graph:
- Mindnet: Export graph (JSON)
- Mindnet: Show chains from current note
## Konfigurationsdateien (typisch im Vault)
- `_system/dictionary/edge_vocabulary.md`
- `_system/dictionary/graph_schema.md`
- `_system/dictionary/interview_config.yaml`
+3 -3
View File
@@ -1,6 +1,6 @@
import esbuild from "esbuild"; import esbuild from "esbuild";
import process from "process"; import process from "process";
import builtins from "builtin-modules"; import { builtinModules } from 'node:module';
const banner = const banner =
`/* `/*
@@ -15,7 +15,7 @@ const context = await esbuild.context({
banner: { banner: {
js: banner, js: banner,
}, },
entryPoints: ["main.ts"], entryPoints: ["src/main.ts"],
bundle: true, bundle: true,
external: [ external: [
"obsidian", "obsidian",
@@ -31,7 +31,7 @@ const context = await esbuild.context({
"@lezer/common", "@lezer/common",
"@lezer/highlight", "@lezer/highlight",
"@lezer/lr", "@lezer/lr",
...builtins], ...builtinModules],
format: "cjs", format: "cjs",
target: "es2018", target: "es2018",
logLevel: "info", logLevel: "info",
+34
View File
@@ -0,0 +1,34 @@
import tseslint from 'typescript-eslint';
import obsidianmd from "eslint-plugin-obsidianmd";
import globals from "globals";
import { globalIgnores } from "eslint/config";
export default tseslint.config(
{
languageOptions: {
globals: {
...globals.browser,
},
parserOptions: {
projectService: {
allowDefaultProject: [
'eslint.config.js',
'manifest.json'
]
},
tsconfigRootDir: import.meta.dirname,
extraFileExtensions: ['.json']
},
},
},
...obsidianmd.configs.recommended,
globalIgnores([
"node_modules",
"dist",
"esbuild.config.mjs",
"eslint.config.js",
"version-bump.mjs",
"versions.json",
"main.js",
]),
);
+46
View File
@@ -0,0 +1,46 @@
- key: experience_cluster
group: experience
label: "Experience – Cluster"
note_type: experience
defaults:
status: active
steps:
- id: title
kind: capture_frontmatter
field: title
label: "Hub Titel"
required: true
# Einzeiliges Feld
- id: subtitle
kind: capture_text_line
label: "Untertitel"
prompt: "Kurzer Untertitel"
- id: intro
kind: capture_text
section: "## Einleitung"
label: "Einleitung"
prompt: "Beschreibe die Einleitung"
- id: items
kind: loop
label: "Erlebnisse"
item_label: "Erlebnis"
min_items: 1
steps:
- id: item_Headline
kind: capture_text_line
label: "Überschrift"
required: false
prompt: "Nennen kurz die Gruppenüberschrift"
- id: item_list
kind: loop
label: "Listeneinträge"
steps:
- id: list_item
kind: capture_text_line
label: "Eintrag"
required: true
prompt: "Einzelner Listeneintrag"
- id: review
kind: review
label: "Review & Apply"
checks: [lint_current_note]
-134
View File
@@ -1,134 +0,0 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
}
}
+5 -5
View File
@@ -1,11 +1,11 @@
{ {
"id": "sample-plugin", "id": "mindnet-causal-assistant",
"name": "Sample Plugin", "name": "Mindnet Causal Assistant",
"version": "1.0.0", "version": "1.0.0",
"minAppVersion": "0.15.0", "minAppVersion": "0.15.0",
"description": "Demonstrates some of the capabilities of the Obsidian API.", "description": "Linting, chain explorer and guided authoring for Mindnet causal graphs.",
"author": "Obsidian", "author": "Lars Stommer",
"authorUrl": "https://obsidian.md", "authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing", "fundingUrl": "https://obsidian.md/pricing",
"isDesktopOnly": false "isDesktopOnly": true
} }
+6747
View File
File diff suppressed because it is too large. Load diff
+19 -9
View File
@@ -3,22 +3,32 @@
"version": "1.0.0", "version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)", "description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"main": "main.js", "main": "main.js",
"type": "module",
"scripts": { "scripts": {
"dev": "node esbuild.config.mjs", "dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json" "version": "node version-bump.mjs && git add manifest.json versions.json",
"deploy:local": "powershell -ExecutionPolicy Bypass -File scripts/deploy-local.ps1",
"build:deploy": "npm run build && npm run deploy:local",
"lint": "eslint .",
"test": "vitest run"
}, },
"keywords": [], "keywords": [],
"author": "", "license": "0-BSD",
"license": "MIT",
"devDependencies": { "devDependencies": {
"@eslint/js": "9.30.1",
"@types/node": "^16.11.6", "@types/node": "^16.11.6",
"@typescript-eslint/eslint-plugin": "5.29.0", "esbuild": "0.25.5",
"@typescript-eslint/parser": "5.29.0", "eslint-plugin-obsidianmd": "0.1.9",
"builtin-modules": "3.3.0", "globals": "14.0.0",
"esbuild": "0.17.3", "jiti": "2.6.1",
"obsidian": "latest",
"tslib": "2.4.0", "tslib": "2.4.0",
"typescript": "4.7.4" "typescript": "^5.8.3",
"typescript-eslint": "8.35.1",
"vitest": "^1.6.0"
},
"dependencies": {
"obsidian": "latest",
"yaml": "^2.8.2"
} }
} }
+16
View File
@@ -0,0 +1,16 @@
param(
[string]$VaultPath = "\\nashome\mindnet\vault\mindnet_dev",
[string]$PluginId = "mindnet-causal-assistant"
)
$pluginDir = Join-Path $VaultPath ".obsidian\plugins\$PluginId"
New-Item -ItemType Directory -Force -Path $pluginDir | Out-Null
Copy-Item -Path ".\manifest.json" -Destination $pluginDir -Force
Copy-Item -Path ".\main.js" -Destination $pluginDir -Force
if (Test-Path ".\styles.css") {
Copy-Item -Path ".\styles.css" -Destination $pluginDir -Force
}
Write-Host "Deployed to $pluginDir"
+25
View File
@@ -0,0 +1,25 @@
// Mock for obsidian API in tests
export class Notice {
constructor(public message: string) {}
}
export interface App {
vault: Vault;
workspace: Workspace;
}
export interface Vault {
read(file: TFile): Promise<string>;
modify(file: TFile, content: string): Promise<void>;
getMarkdownFiles(): TFile[];
}
export interface Workspace {
getActiveFile(): TFile | null;
}
export interface TFile {
path: string;
name: string;
extension: string;
}
+266
View File
@@ -0,0 +1,266 @@
/**
* Pure functions for filtering and sorting notes.
* Unit tested and deterministic.
*/
import type { NoteIndexEntry, FilterOptions, SortOptions, GroupedNoteResult } from "./types";
/**
* Check if a path is within a folder (including subfolders).
*/
function isPathInFolder(path: string, folderPath: string | null | undefined): boolean {
if (!folderPath) {
return true; // No folder filter = include all
}
if (folderPath === "") {
// Root folder: include only files directly in root
return !path.includes("/");
}
// Check if path starts with folder path (with trailing slash)
const normalizedFolder = folderPath.endsWith("/") ? folderPath : folderPath + "/";
return path.startsWith(normalizedFolder) || path === folderPath;
}
/**
* Score a note for search relevance.
* Higher score = better match.
*/
function scoreSearchRelevance(entry: NoteIndexEntry, searchQuery: string): number {
if (!searchQuery || !searchQuery.trim()) {
return 0;
}
const query = searchQuery.toLowerCase().trim();
const basenameLower = entry.basename.toLowerCase();
const titleLower = entry.title?.toLowerCase() || "";
// Exact match on basename or title
if (basenameLower === query || titleLower === query) {
return 100;
}
// Prefix match on basename or title
if (basenameLower.startsWith(query) || titleLower.startsWith(query)) {
return 80;
}
// Contains match on basename or title
if (basenameLower.includes(query) || titleLower.includes(query)) {
return 60;
}
// Contains match on path
if (entry.path.toLowerCase().includes(query)) {
return 40;
}
return 0;
}
/**
* Apply filters to a list of notes.
*/
export function applyFilters(
notes: NoteIndexEntry[],
options: FilterOptions
): NoteIndexEntry[] {
let filtered = notes;
// Folder filter
if (options.selectedFolderPath !== undefined && options.selectedFolderPath !== null) {
filtered = filtered.filter((note) =>
isPathInFolder(note.path, options.selectedFolderPath)
);
}
// Type filter
if (options.typeSet && options.typeSet.size > 0) {
filtered = filtered.filter((note) => {
if (note.type === null) {
return options.includeNoneType === true;
}
return options.typeSet!.has(note.type);
});
} else if (options.includeNoneType === false) {
// If includeNoneType is explicitly false and no types selected, exclude null types
filtered = filtered.filter((note) => note.type !== null);
}
// Search filter (with scoring)
if (options.search && options.search.trim()) {
const query = options.search.trim();
const scored = filtered.map((note) => ({
note,
score: scoreSearchRelevance(note, query),
}));
// Only include notes with score > 0
filtered = scored
.filter((item) => item.score > 0)
.sort((a, b) => b.score - a.score) // Sort by score descending
.map((item) => item.note);
}
return filtered;
}
/**
* Sort notes by mode.
*/
export function sortNotes(
notes: NoteIndexEntry[],
options: SortOptions
): NoteIndexEntry[] {
const sorted = [...notes];
switch (options.mode) {
case "recent":
sorted.sort((a, b) => {
// Primary: mtime descending
if (b.mtime !== a.mtime) {
return b.mtime - a.mtime;
}
// Tie-break: alphabetical by basename
return a.basename.localeCompare(b.basename);
});
break;
case "alpha":
sorted.sort((a, b) => a.basename.localeCompare(b.basename));
break;
case "type":
// Will be grouped, but sort items within groups
sorted.sort((a, b) => {
const typeA = a.type || "(none)";
const typeB = b.type || "(none)";
if (typeA !== typeB) {
return typeA.localeCompare(typeB);
}
// Within same type, sort by search score if available, then alpha
if (options.searchQuery) {
const scoreA = scoreSearchRelevance(a, options.searchQuery);
const scoreB = scoreSearchRelevance(b, options.searchQuery);
if (scoreB !== scoreA) {
return scoreB - scoreA;
}
}
return a.basename.localeCompare(b.basename);
});
break;
case "folder":
// Will be grouped, but sort items within groups
sorted.sort((a, b) => {
if (a.folder !== b.folder) {
return a.folder.localeCompare(b.folder);
}
// Within same folder, sort by search score if available, then alpha
if (options.searchQuery) {
const scoreA = scoreSearchRelevance(a, options.searchQuery);
const scoreB = scoreSearchRelevance(b, options.searchQuery);
if (scoreB !== scoreA) {
return scoreB - scoreA;
}
}
return a.basename.localeCompare(b.basename);
});
break;
}
return sorted;
}
/**
* Group notes by type.
*/
export function groupByType(
notes: NoteIndexEntry[],
searchQuery?: string
): GroupedNoteResult[] {
const groups = new Map<string, NoteIndexEntry[]>();
for (const note of notes) {
const groupKey = note.type || "(none)";
if (!groups.has(groupKey)) {
groups.set(groupKey, []);
}
groups.get(groupKey)!.push(note);
}
// Convert to array and sort groups alphabetically
const result: GroupedNoteResult[] = Array.from(groups.entries())
.map(([groupKey, groupNotes]) => {
// Sort items within group by search score (if available), then alpha
const sorted = [...groupNotes];
if (searchQuery) {
sorted.sort((a, b) => {
const scoreA = scoreSearchRelevance(a, searchQuery);
const scoreB = scoreSearchRelevance(b, searchQuery);
if (scoreB !== scoreA) {
return scoreB - scoreA;
}
return a.basename.localeCompare(b.basename);
});
} else {
sorted.sort((a, b) => a.basename.localeCompare(b.basename));
}
return {
groupKey,
groupLabel: groupKey,
notes: sorted,
};
})
.sort((a, b) => a.groupKey.localeCompare(b.groupKey));
return result;
}
/**
* Group notes by folder.
*/
export function groupByFolder(
notes: NoteIndexEntry[],
searchQuery?: string
): GroupedNoteResult[] {
const groups = new Map<string, NoteIndexEntry[]>();
for (const note of notes) {
const groupKey = note.folder || "(root)";
if (!groups.has(groupKey)) {
groups.set(groupKey, []);
}
groups.get(groupKey)!.push(note);
}
// Convert to array and sort groups alphabetically
const result: GroupedNoteResult[] = Array.from(groups.entries())
.map(([groupKey, groupNotes]) => {
// Sort items within group by search score (if available), then alpha
const sorted = [...groupNotes];
if (searchQuery) {
sorted.sort((a, b) => {
const scoreA = scoreSearchRelevance(a, searchQuery);
const scoreB = scoreSearchRelevance(b, searchQuery);
if (scoreB !== scoreA) {
return scoreB - scoreA;
}
return a.basename.localeCompare(b.basename);
});
} else {
sorted.sort((a, b) => a.basename.localeCompare(b.basename));
}
return {
groupKey,
groupLabel: groupKey || "(root)",
notes: sorted,
};
})
.sort((a, b) => a.groupKey.localeCompare(b.groupKey));
return result;
}
+125
View File
@@ -0,0 +1,125 @@
/**
* Folder Tree: Builds and manages folder tree structure from note paths.
*/
import type { NoteIndexEntry, FolderTreeNode } from "./types";
/**
* Build folder tree from note entries.
*/
export function buildFolderTree(entries: NoteIndexEntry[]): FolderTreeNode {
const root: FolderTreeNode = {
name: "All folders",
path: "",
children: [],
noteCount: 0,
};
const nodeMap = new Map<string, FolderTreeNode>();
nodeMap.set("", root);
// Count notes per folder
const folderCounts = new Map<string, number>();
for (const entry of entries) {
const folder = entry.folder || "";
folderCounts.set(folder, (folderCounts.get(folder) || 0) + 1);
}
// Build tree structure
for (const entry of entries) {
const folder = entry.folder || "";
const parts = folder.split("/").filter((p) => p);
let currentPath = "";
let currentNode = root;
for (const part of parts) {
const parentPath = currentPath;
currentPath = currentPath ? `${currentPath}/${part}` : part;
if (!nodeMap.has(currentPath)) {
const newNode: FolderTreeNode = {
name: part,
path: currentPath,
children: [],
noteCount: 0,
};
nodeMap.set(currentPath, newNode);
currentNode.children.push(newNode);
}
currentNode = nodeMap.get(currentPath)!;
}
// Increment note count for this folder
currentNode.noteCount = folderCounts.get(folder) || 0;
}
// Update root count
root.noteCount = entries.length;
// Sort children alphabetically
function sortTree(node: FolderTreeNode): void {
node.children.sort((a, b) => a.name.localeCompare(b.name));
for (const child of node.children) {
sortTree(child);
}
}
sortTree(root);
return root;
}
/**
* Get all folder paths in a subtree (including the folder itself).
*/
export function getSubtreePaths(
tree: FolderTreeNode,
folderPath: string | null
): Set<string> {
const paths = new Set<string>();
if (!folderPath || folderPath === "") {
// Include all folders
function collectPaths(node: FolderTreeNode): void {
if (node.path !== "") {
paths.add(node.path);
}
for (const child of node.children) {
collectPaths(child);
}
}
collectPaths(tree);
return paths;
}
// Find the node for this folder path
function findNode(node: FolderTreeNode, targetPath: string): FolderTreeNode | null {
if (node.path === targetPath) {
return node;
}
for (const child of node.children) {
const found = findNode(child, targetPath);
if (found) {
return found;
}
}
return null;
}
const targetNode = findNode(tree, folderPath);
if (!targetNode) {
return paths;
}
// Collect all paths in subtree
function collectSubtree(node: FolderTreeNode): void {
paths.add(node.path);
for (const child of node.children) {
collectSubtree(child);
}
}
collectSubtree(targetNode);
return paths;
}
+162
View File
@@ -0,0 +1,162 @@
/**
* Note Index: Builds and maintains an index of all markdown files in the vault.
* Provides incremental updates on vault events.
*/
import { App, TFile, debounce } from "obsidian";
import type { NoteIndexEntry } from "./types";
export class NoteIndex {
private app: App;
private index: Map<string, NoteIndexEntry> = new Map();
private listeners: Set<() => void> = new Set();
private debouncedRefresh: () => void;
constructor(app: App) {
this.app = app;
// Debounce refresh to avoid excessive updates during bulk operations
this.debouncedRefresh = debounce(() => this.refresh(), 300, true);
// Listen to vault events
this.app.vault.on("create", (file) => {
if (file instanceof TFile && file.extension === "md") {
this.debouncedRefresh();
}
});
this.app.vault.on("modify", (file) => {
if (file instanceof TFile && file.extension === "md") {
this.debouncedRefresh();
}
});
this.app.vault.on("delete", (file) => {
if (file instanceof TFile && file.extension === "md") {
this.debouncedRefresh();
}
});
this.app.vault.on("rename", (file, oldPath) => {
if (file instanceof TFile && file.extension === "md") {
this.debouncedRefresh();
}
});
// Initial build
this.refresh();
}
/**
* Refresh the entire index.
*/
refresh(): void {
const newIndex = new Map<string, NoteIndexEntry>();
const markdownFiles = this.app.vault.getMarkdownFiles();
for (const file of markdownFiles) {
const entry = this.buildEntry(file);
if (entry) {
newIndex.set(entry.path, entry);
}
}
this.index = newIndex;
this.notifyListeners();
}
/**
* Build a single index entry from a file.
*/
private buildEntry(file: TFile): NoteIndexEntry | null {
try {
const path = file.path;
const folder = file.parent?.path || "/";
const basename = file.basename;
// Get metadata from cache (prefer over reading file content)
const cache = this.app.metadataCache.getFileCache(file);
const frontmatter = cache?.frontmatter;
const title = frontmatter?.title as string | undefined || null;
const type = frontmatter?.type as string | undefined || null;
// Get modification time
const stat = file.stat;
const mtime = stat?.mtime || 0;
return {
path,
folder: folder === "/" ? "" : folder,
basename,
title,
type,
mtime,
};
} catch (error) {
console.error("Error building index entry for", file.path, error);
return null;
}
}
/**
* Get all entries.
*/
getAllEntries(): NoteIndexEntry[] {
return Array.from(this.index.values());
}
/**
* Get entry by path.
*/
getEntry(path: string): NoteIndexEntry | undefined {
return this.index.get(path);
}
/**
* Get entry by basename (first match).
*/
getEntryByBasename(basename: string): NoteIndexEntry | undefined {
for (const entry of this.index.values()) {
if (entry.basename === basename) {
return entry;
}
}
return undefined;
}
/**
* Get all unique types from the index.
*/
getAllTypes(): string[] {
const types = new Set<string>();
for (const entry of this.index.values()) {
if (entry.type) {
types.add(entry.type);
}
}
return Array.from(types).sort();
}
/**
* Subscribe to index updates.
*/
onUpdate(callback: () => void): () => void {
this.listeners.add(callback);
return () => {
this.listeners.delete(callback);
};
}
/**
* Notify all listeners of an update.
*/
private notifyListeners(): void {
for (const listener of this.listeners) {
try {
listener();
} catch (error) {
console.error("Error in index update listener", error);
}
}
}
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Types for Entity Picker (Note Picker) system.
*/
export interface NoteIndexEntry {
path: string;
folder: string;
basename: string;
title: string | null;
type: string | null;
mtime: number;
}
export interface FolderTreeNode {
name: string;
path: string;
children: FolderTreeNode[];
noteCount: number;
}
export interface FilterOptions {
search?: string;
selectedFolderPath?: string | null;
typeSet?: Set<string>;
includeNoneType?: boolean;
}
export type SortMode = "recent" | "alpha" | "type" | "folder";
export interface SortOptions {
mode: SortMode;
searchQuery?: string; // For scoring relevance
}
export interface GroupedNoteResult {
groupKey: string;
groupLabel: string;
notes: NoteIndexEntry[];
}
export interface EntityPickerStep {
type: "entity_picker";
key: string;
label: string;
prompt?: string;
required?: boolean;
labelField?: string; // Optional field key to use as wikilink label
}
+61
View File
@@ -0,0 +1,61 @@
/**
* Wikilink insertion utilities.
* Pure functions for inserting wikilinks into text.
*/
/**
* Insert a wikilink into text, replacing selection if present.
*
* @param text - The full text
* @param selStart - Selection start position
* @param selEnd - Selection end position
* @param basename - The note basename to link to
* @returns Object with new text and new cursor position
*/
export function insertWikilink(
text: string,
selStart: number,
selEnd: number,
basename: string
): { text: string; cursorPos: number } {
const hasSelection = selEnd > selStart;
let wikilink: string;
if (hasSelection) {
const selectedText = text.substring(selStart, selEnd);
wikilink = `[[${basename}|${selectedText}]]`;
} else {
wikilink = `[[${basename}]]`;
}
// Replace selection with wikilink
const before = text.substring(0, selStart);
const after = text.substring(selEnd);
const newText = before + wikilink + after;
// Calculate new cursor position (after the wikilink)
const cursorPos = selStart + wikilink.length;
return { text: newText, cursorPos };
}
/**
* Insert wikilink into a textarea element.
* Updates the textarea value and cursor position.
*/
export function insertWikilinkIntoTextarea(
textarea: HTMLTextAreaElement,
basename: string
): void {
const selStart = textarea.selectionStart;
const selEnd = textarea.selectionEnd;
const currentText = textarea.value;
const result = insertWikilink(currentText, selStart, selEnd, basename);
textarea.value = result.text;
textarea.setSelectionRange(result.cursorPos, result.cursorPos);
// Trigger input event so Obsidian can update its state
textarea.dispatchEvent(new Event("input", { bubbles: true }));
}
+134
View File
@@ -0,0 +1,134 @@
import type { App, TFile } from "obsidian";
import type { Vocabulary } from "../vocab/Vocabulary";
import type { ParsedEdge } from "../parser/types";
import type { ExportBundle, ExportNode, ExportEdge } from "./types";
import { parseEdgesFromCallouts } from "../parser/parseEdgesFromCallouts";
/**
* Export graph from vault markdown files.
* Scans all markdown files, parses edges, and resolves types via vocabulary.
*/
export async function exportGraph(
app: App,
vocabulary: Vocabulary,
outputPath: string = "_system/exports/graph_export.json"
): Promise<void> {
const nodes: ExportNode[] = [];
const edges: ExportEdge[] = [];
const nodeMap = new Map<string, ExportNode>();
// Get all markdown files in vault
const markdownFiles = app.vault.getMarkdownFiles();
// Process each file
for (const file of markdownFiles) {
try {
const content = await app.vault.read(file);
const parsedEdges = parseEdgesFromCallouts(content);
// Create or get node for this file
const nodeId = file.path;
if (!nodeMap.has(nodeId)) {
const node: ExportNode = {
id: nodeId,
title: file.basename,
path: file.path,
};
nodeMap.set(nodeId, node);
nodes.push(node);
}
// Process edges from this file
for (const parsedEdge of parsedEdges) {
const normalized = vocabulary.normalize(parsedEdge.rawType);
// Process each target
for (const target of parsedEdge.targets) {
if (!target) continue;
// Extract base name from target (remove heading if present)
const parts = target.split("#");
const firstPart = parts[0];
if (!firstPart) continue;
const baseName = firstPart.trim();
if (!baseName) continue;
// Find target file by matching against all markdown files
let targetFile: TFile | null = null;
const targetPathWithMd = baseName.endsWith(".md") ? baseName : `${baseName}.md`;
// Search through markdown files for match
for (const mdFile of markdownFiles) {
const mdFileName = mdFile.name;
const mdFileBasename = mdFile.basename;
if (mdFileName && (mdFileName === targetPathWithMd || mdFileBasename === baseName)) {
targetFile = mdFile;
break;
}
}
// Determine target node ID
let targetNodeId: string;
if (targetFile) {
targetNodeId = targetFile.path;
// Create node for target file if not exists
if (!nodeMap.has(targetNodeId)) {
const targetNode: ExportNode = {
id: targetNodeId,
title: targetFile.basename,
path: targetFile.path,
};
nodeMap.set(targetNodeId, targetNode);
nodes.push(targetNode);
}
} else {
// Target file not found - use baseName as placeholder ID
targetNodeId = baseName;
// Create placeholder node if not exists
if (!nodeMap.has(targetNodeId)) {
const targetNode: ExportNode = {
id: targetNodeId,
title: baseName,
path: baseName, // placeholder path
};
nodeMap.set(targetNodeId, targetNode);
nodes.push(targetNode);
}
}
// Create edge
const edge: ExportEdge = {
source: nodeId,
target: targetNodeId,
rawType: parsedEdge.rawType,
canonicalType: normalized.canonical,
inverseType: normalized.inverse,
sourcePath: file.path,
lineStart: parsedEdge.lineStart,
lineEnd: parsedEdge.lineEnd,
};
edges.push(edge);
}
}
} catch (error) {
console.error(`Error processing file ${file.path}:`, error);
// Continue with other files
}
}
// Create export bundle
const stats = vocabulary.getStats();
const bundle: ExportBundle = {
nodes,
edges,
exportedAt: new Date().toISOString(),
vocabularyStats: {
canonicalCount: stats.canonicalCount,
aliasCount: stats.aliasCount,
},
};
// Write to file
const jsonContent = JSON.stringify(bundle, null, 2);
await app.vault.adapter.write(outputPath, jsonContent);
}
+26
View File
@@ -0,0 +1,26 @@
export interface ExportNode {
id: string; // file path or note name
title?: string;
path: string; // vault-relative path
}
export interface ExportEdge {
source: string; // node id
target: string; // node id
rawType: string; // original edge type from markdown
canonicalType: string | null; // resolved canonical type
inverseType: string | null; // resolved inverse type (if available)
sourcePath: string; // vault-relative path of source file
lineStart?: number; // 0-based line number
lineEnd?: number; // 0-based line number
}
export interface ExportBundle {
nodes: ExportNode[];
edges: ExportEdge[];
exportedAt: string; // ISO timestamp
vocabularyStats?: {
canonicalCount: number;
aliasCount: number;
};
}
+144
View File
@@ -0,0 +1,144 @@
import type { App, TFile } from "obsidian";
import type { Vocabulary } from "../vocab/Vocabulary";
import type { ParsedEdge } from "../parser/types";
import type { GraphBuildResult, NodeMeta, EdgeRecord } from "./types";
import { parseEdgesFromCallouts } from "../parser/parseEdgesFromCallouts";
import { extractFrontmatterId } from "../parser/parseFrontmatter";
import { normalizeTargetToBasename } from "./resolveTarget";
/**
* Build graph from vault markdown files.
* Uses frontmatter.id as the primary node identifier.
*/
export async function buildGraph(
app: App,
vocabulary: Vocabulary
): Promise<GraphBuildResult> {
const filePathToId = new Map<string, string>();
const basenameLowerToPath = new Map<string, string>();
const idToMeta = new Map<string, NodeMeta>();
const edges: EdgeRecord[] = [];
const warnings: GraphBuildResult["warnings"] = {
missingFrontmatterId: [],
missingTargetFile: [],
missingTargetId: [],
};
// Get all markdown files
const markdownFiles = app.vault.getMarkdownFiles();
// First pass: build node maps
for (const file of markdownFiles) {
try {
const content = await app.vault.read(file);
const id = extractFrontmatterId(content);
// Always add to basenameLowerToPath for target resolution
const basenameLower = file.basename.toLowerCase();
basenameLowerToPath.set(basenameLower, file.path);
if (!id) {
warnings.missingFrontmatterId.push(file.path);
continue; // Skip files without ID (don't add to filePathToId or idToMeta)
}
// Extract optional title from frontmatter (simple extraction)
let title: string | undefined;
const titleMatch = content.match(/^title\s*:\s*(.+)$/m);
if (titleMatch && titleMatch[1]) {
let titleValue = titleMatch[1].trim();
if ((titleValue.startsWith('"') && titleValue.endsWith('"')) ||
(titleValue.startsWith("'") && titleValue.endsWith("'"))) {
titleValue = titleValue.slice(1, -1);
}
title = titleValue;
}
// Populate maps
filePathToId.set(file.path, id);
const meta: NodeMeta = {
id,
path: file.path,
basename: file.basename,
title,
};
idToMeta.set(id, meta);
} catch (error) {
console.error(`Error processing file ${file.path}:`, error);
// Continue with other files
}
}
// Second pass: build edges
for (const file of markdownFiles) {
try {
const content = await app.vault.read(file);
const srcId = filePathToId.get(file.path);
if (!srcId) {
// File has no ID, skip edge processing
continue;
}
const parsedEdges = parseEdgesFromCallouts(content);
for (const parsedEdge of parsedEdges) {
const normalized = vocabulary.normalize(parsedEdge.rawType);
for (const target of parsedEdge.targets) {
if (!target) continue;
// Normalize target to basename
const resolvedBase = normalizeTargetToBasename(target);
const targetPath = basenameLowerToPath.get(resolvedBase.toLowerCase());
if (!targetPath) {
warnings.missingTargetFile.push({
srcPath: file.path,
target: target,
});
continue;
}
// Check if target file has an ID
const dstId = filePathToId.get(targetPath);
if (!dstId) {
// File exists but has no frontmatter ID
warnings.missingTargetId.push({
srcPath: file.path,
targetPath: targetPath,
});
continue;
}
// Create edge record
const edge: EdgeRecord = {
srcId,
dstId,
rawType: parsedEdge.rawType,
canonicalType: normalized.canonical,
inverseType: normalized.inverse,
srcPath: file.path,
dstPath: targetPath,
lineStart: parsedEdge.lineStart,
lineEnd: parsedEdge.lineEnd,
rawTarget: target,
};
edges.push(edge);
}
}
} catch (error) {
console.error(`Error processing edges for file ${file.path}:`, error);
// Continue with other files
}
}
return {
filePathToId,
basenameLowerToPath,
idToMeta,
edges,
warnings,
};
}
+54
View File
@@ -0,0 +1,54 @@
import type { EdgeRecord } from "./types";
export interface GraphIndex {
outgoing: Map<string, EdgeRecord[]>;
incoming: Map<string, EdgeRecord[]>;
}
/**
* Build index from edges for efficient traversal.
* Creates outgoing and incoming edge maps keyed by node ID.
*/
export function buildIndex(edges: EdgeRecord[]): GraphIndex {
const outgoing = new Map<string, EdgeRecord[]>();
const incoming = new Map<string, EdgeRecord[]>();
for (const edge of edges) {
// Add to outgoing map
if (!outgoing.has(edge.srcId)) {
outgoing.set(edge.srcId, []);
}
const outgoingEdges = outgoing.get(edge.srcId);
if (outgoingEdges) {
outgoingEdges.push(edge);
}
// Add to incoming map
if (!incoming.has(edge.dstId)) {
incoming.set(edge.dstId, []);
}
const incomingEdges = incoming.get(edge.dstId);
if (incomingEdges) {
incomingEdges.push(edge);
}
}
// Sort edges for deterministic ordering
for (const edges of outgoing.values()) {
edges.sort((a, b) => {
const cmp = a.dstId.localeCompare(b.dstId);
if (cmp !== 0) return cmp;
return a.srcPath.localeCompare(b.srcPath);
});
}
for (const edges of incoming.values()) {
edges.sort((a, b) => {
const cmp = a.srcId.localeCompare(b.srcId);
if (cmp !== 0) return cmp;
return a.srcPath.localeCompare(b.srcPath);
});
}
return { outgoing, incoming };
}
+100
View File
@@ -0,0 +1,100 @@
import type { GraphBuildResult, NodeMeta } from "./types";
import type { Path } from "./traverse";
export interface ChainReportOptions {
startId: string;
startMeta: NodeMeta;
paths: Path[];
direction: "forward" | "backward" | "both";
maxHops: number;
maxPaths: number;
warnings: GraphBuildResult["warnings"];
idToMeta: Map<string, NodeMeta>;
}
/**
* Render chain report as markdown.
*/
export function renderChainReport(opts: ChainReportOptions): string {
const { startId, startMeta, paths, direction, maxHops, maxPaths, warnings, idToMeta } = opts;
const lines: string[] = [];
// Header
lines.push(`# Chain Report`);
lines.push("");
lines.push(`**Start Node:** ${startMeta.basename} (id=${startId})`);
if (startMeta.title) {
lines.push(`**Title:** ${startMeta.title}`);
}
if (startMeta.path) {
lines.push(`**Path:** ${startMeta.path}`);
}
lines.push("");
lines.push(`**Traversal Config:**`);
lines.push(`- Direction: ${direction}`);
lines.push(`- Max Hops: ${maxHops}`);
lines.push(`- Max Paths: ${maxPaths}`);
lines.push("");
// Warnings summary
const totalWarnings =
warnings.missingFrontmatterId.length +
warnings.missingTargetFile.length +
warnings.missingTargetId.length;
if (totalWarnings > 0) {
lines.push(`## Warnings Summary`);
lines.push("");
if (warnings.missingFrontmatterId.length > 0) {
lines.push(`- Missing frontmatter ID: ${warnings.missingFrontmatterId.length} file(s)`);
}
if (warnings.missingTargetFile.length > 0) {
lines.push(`- Missing target files: ${warnings.missingTargetFile.length} reference(s)`);
}
if (warnings.missingTargetId.length > 0) {
lines.push(`- Missing target IDs: ${warnings.missingTargetId.length} reference(s)`);
}
lines.push("");
}
// Paths
lines.push(`## Paths (${paths.length})`);
lines.push("");
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
if (!path) continue;
lines.push(`### Path #${i + 1}`);
lines.push("");
// Render nodes and edges
for (let j = 0; j < path.nodes.length; j++) {
const nodeId = path.nodes[j];
if (!nodeId) continue;
const nodeMeta = idToMeta.get(nodeId);
const nodeLabel = nodeMeta
? `${nodeMeta.basename} (id=${nodeId})`
: `Unknown (id=${nodeId})`;
lines.push(nodeLabel);
// Add edge if not last node
if (j < path.edges.length) {
const edge = path.edges[j];
if (edge) {
const edgeLabel = edge.canonicalType
? `-- raw:"${edge.rawType}" (canonical:"${edge.canonicalType}") -->`
: `-- raw:"${edge.rawType}" -->`;
lines.push(edgeLabel);
}
}
}
lines.push("");
}
return lines.join("\n");
}
+24
View File
@@ -0,0 +1,24 @@
/**
* Normalize Obsidian link target to basename.
* Handles aliases (|) and headings (#).
*
* Examples:
* - "foo" -> "foo"
* - "foo|bar" -> "foo"
* - "foo#sec" -> "foo"
* - "foo#sec|bar" -> "foo"
* - "foo|bar#sec" -> "foo"
*/
export function normalizeTargetToBasename(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();
}
+215
View File
@@ -0,0 +1,215 @@
import type { GraphIndex } from "./GraphIndex";
import type { EdgeRecord } from "./types";
export interface PathStep {
nodeId: string;
}
export interface PathEdge {
rawType: string;
canonicalType: string;
dstId: string;
srcId: string;
lineStart: number;
srcPath: string;
}
export interface Path {
startId: string;
nodes: string[];
edges: Array<{ rawType: string; canonicalType: string; to: string }>;
}
/**
* Traverse graph forward from start node.
* Returns all paths up to maxHops length, respecting maxPaths limit.
* maxHops refers to the number of edges (hops), so maxHops=2 means up to 3 nodes.
*/
export function traverseForward(
index: GraphIndex,
startId: string,
maxHops: number,
maxPaths: number = 200,
allowedCanonicals?: Set<string>
): Path[] {
const paths: Path[] = [];
const queue: Array<{ nodes: string[]; edges: Array<{ rawType: string; canonicalType: string; to: string }> }> = [
{ nodes: [startId], edges: [] },
];
while (queue.length > 0 && paths.length < maxPaths) {
const current = queue.shift();
if (!current) break;
const currentNodeId = current.nodes[current.nodes.length - 1];
if (!currentNodeId) break;
// Check if we've reached maxHops (number of edges = nodes.length - 1)
const currentHops = current.nodes.length - 1;
if (currentHops >= maxHops) {
// Path is complete
if (current.nodes.length > 1) {
paths.push({
startId,
nodes: current.nodes,
edges: current.edges,
});
}
continue;
}
// Get outgoing edges
const outgoingEdges = index.outgoing.get(currentNodeId) || [];
if (outgoingEdges.length === 0) {
// Dead end: add as complete path if it has at least one edge
if (current.nodes.length > 1) {
paths.push({
startId,
nodes: current.nodes,
edges: current.edges,
});
}
continue;
}
for (const edge of outgoingEdges) {
// Skip edges with null canonicalType
if (!edge.canonicalType) continue;
// Filter by allowedCanonicals if provided
if (allowedCanonicals && !allowedCanonicals.has(edge.canonicalType)) {
continue;
}
// Avoid cycles: don't revisit nodes already in path
if (current.nodes.includes(edge.dstId)) {
continue;
}
// Create new path
const newNodes = [...current.nodes, edge.dstId];
const newEdges = [
...current.edges,
{
rawType: edge.rawType,
canonicalType: edge.canonicalType,
to: edge.dstId,
},
];
// Check if we've reached maxHops
const newHops = newNodes.length - 1;
if (newHops >= maxHops) {
// Path is complete
paths.push({
startId,
nodes: newNodes,
edges: newEdges,
});
} else {
// Continue exploring
queue.push({ nodes: newNodes, edges: newEdges });
}
}
}
return paths.slice(0, maxPaths);
}
/**
* Traverse graph backward from start node.
* Returns all paths up to maxHops length, respecting maxPaths limit.
* maxHops refers to the number of edges (hops), so maxHops=2 means up to 3 nodes.
*/
export function traverseBackward(
index: GraphIndex,
startId: string,
maxHops: number,
maxPaths: number = 200,
allowedCanonicals?: Set<string>
): Path[] {
const paths: Path[] = [];
const queue: Array<{ nodes: string[]; edges: Array<{ rawType: string; canonicalType: string; to: string }> }> = [
{ nodes: [startId], edges: [] },
];
while (queue.length > 0 && paths.length < maxPaths) {
const current = queue.shift();
if (!current) break;
const currentNodeId = current.nodes[current.nodes.length - 1];
if (!currentNodeId) break;
// Check if we've reached maxHops (number of edges = nodes.length - 1)
const currentHops = current.nodes.length - 1;
if (currentHops >= maxHops) {
// Path is complete
if (current.nodes.length > 1) {
paths.push({
startId,
nodes: current.nodes,
edges: current.edges,
});
}
continue;
}
// Get incoming edges
const incomingEdges = index.incoming.get(currentNodeId) || [];
if (incomingEdges.length === 0) {
// Dead end: add as complete path if it has at least one edge
if (current.nodes.length > 1) {
paths.push({
startId,
nodes: current.nodes,
edges: current.edges,
});
}
continue;
}
for (const edge of incomingEdges) {
// Skip edges with null canonicalType
if (!edge.canonicalType) continue;
// Filter by allowedCanonicals if provided
if (allowedCanonicals && !allowedCanonicals.has(edge.canonicalType)) {
continue;
}
// Avoid cycles: don't revisit nodes already in path
if (current.nodes.includes(edge.srcId)) {
continue;
}
// Create new path (backward: srcId is the "to" node)
const newNodes = [...current.nodes, edge.srcId];
const newEdges = [
...current.edges,
{
rawType: edge.rawType,
canonicalType: edge.canonicalType,
to: edge.srcId,
},
];
// Check if we've reached maxHops
const newHops = newNodes.length - 1;
if (newHops >= maxHops) {
// Path is complete
paths.push({
startId,
nodes: newNodes,
edges: newEdges,
});
} else {
// Continue exploring
queue.push({ nodes: newNodes, edges: newEdges });
}
}
}
return paths.slice(0, maxPaths);
}
+31
View File
@@ -0,0 +1,31 @@
export interface NodeMeta {
id: string;
path: string;
basename: string;
title?: string;
}
export interface EdgeRecord {
srcId: string;
dstId: string;
rawType: string;
canonicalType: string | null;
inverseType: string | null;
srcPath: string;
dstPath: string;
lineStart: number;
lineEnd: number;
rawTarget: string; // original [[...]] content for debugging
}
export interface GraphBuildResult {
filePathToId: Map<string, string>;
basenameLowerToPath: Map<string, string>;
idToMeta: Map<string, NodeMeta>;
edges: EdgeRecord[];
warnings: {
missingFrontmatterId: string[]; // file paths
missingTargetFile: Array<{ srcPath: string; target: string }>;
missingTargetId: Array<{ srcPath: string; targetPath: string }>;
};
}
+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);
}
+297
View File
@@ -0,0 +1,297 @@
/**
* Loop runtime state management.
* Pure functions for managing loop item state (draft, committed items, editing).
*/
export interface LoopRuntimeState {
items: unknown[]; // Committed items
draft: Record<string, unknown>; // Current draft being edited
editIndex: number | null; // Index of item being edited, or null for new item
activeItemStepIndex: number; // Current step index in subwizard (0-based)
}
/**
* Create initial loop state.
*/
export function createLoopState(): LoopRuntimeState {
return {
items: [],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
}
/**
* Set a field value in the draft.
*/
export function setDraftField(
state: LoopRuntimeState,
fieldId: string,
value: unknown
): LoopRuntimeState {
return {
...state,
draft: {
...state.draft,
[fieldId]: value,
},
};
}
/**
* Check if draft has any non-empty data (is dirty).
* Returns true if draft contains any non-empty string, true, non-zero number, non-empty array, or non-empty object.
*/
export function isDraftDirty(draft: Record<string, unknown>): boolean {
for (const [key, value] of Object.entries(draft)) {
if (value === null || value === undefined) {
continue;
}
if (typeof value === "string" && value.trim() !== "") {
return true;
}
if (typeof value === "boolean" && value === true) {
return true;
}
if (typeof value === "number" && value !== 0) {
return true;
}
if (Array.isArray(value) && value.length > 0) {
return true;
}
if (typeof value === "object" && Object.keys(value).length > 0) {
return true;
}
}
return false;
}
/**
* Commit draft to items (add new or update existing).
*/
export function commitDraft(state: LoopRuntimeState): LoopRuntimeState {
// If draft is not dirty, return state unchanged
if (!isDraftDirty(state.draft)) {
return state;
}
const newItems = [...state.items];
if (state.editIndex !== null && state.editIndex >= 0 && state.editIndex < newItems.length) {
// Update existing item
newItems[state.editIndex] = { ...state.draft };
} else {
// Add new item
newItems.push({ ...state.draft });
}
return {
items: newItems,
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
}
/**
* Start editing an existing item (load into draft).
*/
export function startEdit(
state: LoopRuntimeState,
index: number
): LoopRuntimeState {
if (index < 0 || index >= state.items.length) {
return state; // Invalid index, return unchanged
}
const item = state.items[index];
if (!item || typeof item !== "object") {
return state;
}
return {
...state,
draft: { ...(item as Record<string, unknown>) },
editIndex: index,
activeItemStepIndex: 0, // Reset to first step when starting edit
};
}
/**
* Delete an item at the given index.
*/
export function deleteItem(
state: LoopRuntimeState,
index: number
): LoopRuntimeState {
if (index < 0 || index >= state.items.length) {
return state; // Invalid index, return unchanged
}
const newItems = [...state.items];
newItems.splice(index, 1);
// If we were editing the deleted item or an item after it, adjust editIndex
let newEditIndex = state.editIndex;
if (state.editIndex !== null) {
if (state.editIndex === index) {
// Deleted the item we were editing
newEditIndex = null;
} else if (state.editIndex > index) {
// Deleted an item before the one we're editing, adjust index
newEditIndex = state.editIndex - 1;
}
}
return {
...state,
items: newItems,
editIndex: newEditIndex,
// Clear draft if we were editing the deleted item
draft: newEditIndex === null ? {} : state.draft,
activeItemStepIndex: newEditIndex === null ? 0 : state.activeItemStepIndex,
};
}
/**
* Move an item up (swap with previous item).
*/
export function moveItemUp(
state: LoopRuntimeState,
index: number
): LoopRuntimeState {
if (index <= 0 || index >= state.items.length) {
return state; // Cannot move first item up or invalid index
}
const newItems = [...state.items];
const temp = newItems[index];
newItems[index] = newItems[index - 1];
newItems[index - 1] = temp;
// Adjust editIndex if we're editing one of the moved items
let newEditIndex = state.editIndex;
if (state.editIndex !== null) {
if (state.editIndex === index) {
newEditIndex = index - 1;
} else if (state.editIndex === index - 1) {
newEditIndex = index;
}
}
return {
...state,
items: newItems,
editIndex: newEditIndex,
};
}
/**
* Move an item down (swap with next item).
*/
export function moveItemDown(
state: LoopRuntimeState,
index: number
): LoopRuntimeState {
if (index < 0 || index >= state.items.length - 1) {
return state; // Cannot move last item down or invalid index
}
const newItems = [...state.items];
const temp = newItems[index];
newItems[index] = newItems[index + 1];
newItems[index + 1] = temp;
// Adjust editIndex if we're editing one of the moved items
let newEditIndex = state.editIndex;
if (state.editIndex !== null) {
if (state.editIndex === index) {
newEditIndex = index + 1;
} else if (state.editIndex === index + 1) {
newEditIndex = index;
}
}
return {
...state,
items: newItems,
editIndex: newEditIndex,
};
}
/**
* Clear draft and exit edit mode.
*/
export function clearDraft(state: LoopRuntimeState): LoopRuntimeState {
return {
...state,
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
}
/**
* Set active item step index.
*/
export function setActiveItemStepIndex(
state: LoopRuntimeState,
index: number
): LoopRuntimeState {
if (index < 0) {
return state; // Invalid index
}
return {
...state,
activeItemStepIndex: index,
};
}
/**
* Move to next step in item subwizard.
*/
export function itemNextStep(
state: LoopRuntimeState,
childStepCount: number
): LoopRuntimeState {
if (state.activeItemStepIndex >= childStepCount - 1) {
return state; // Already at last step
}
return {
...state,
activeItemStepIndex: state.activeItemStepIndex + 1,
};
}
/**
* Move to previous step in item subwizard.
*/
export function itemPrevStep(state: LoopRuntimeState): LoopRuntimeState {
if (state.activeItemStepIndex <= 0) {
return state; // Already at first step
}
return {
...state,
activeItemStepIndex: state.activeItemStepIndex - 1,
};
}
/**
* Reset item wizard to first step.
*/
export function resetItemWizard(state: LoopRuntimeState): LoopRuntimeState {
return {
...state,
activeItemStepIndex: 0,
};
}
+487
View File
@@ -0,0 +1,487 @@
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 edging config
if (raw.edging && typeof raw.edging === "object") {
const edgingRaw = raw.edging as Record<string, unknown>;
profile.edging = {};
if (edgingRaw.mode === "none" || edgingRaw.mode === "post_run" || edgingRaw.mode === "inline_micro") {
profile.edging.mode = edgingRaw.mode;
}
if (typeof edgingRaw.wrapperCalloutType === "string") {
profile.edging.wrapperCalloutType = edgingRaw.wrapperCalloutType;
}
if (typeof edgingRaw.wrapperTitle === "string") {
profile.edging.wrapperTitle = edgingRaw.wrapperTitle;
}
if (typeof edgingRaw.wrapperFolded === "boolean") {
profile.edging.wrapperFolded = edgingRaw.wrapperFolded;
}
}
// 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();
}
// Parse output.join
if (raw.output && typeof raw.output === "object") {
const output = raw.output as Record<string, unknown>;
if (typeof output.join === "string") {
step.output = { join: output.join };
}
}
// Parse ui.commit
if (raw.ui && typeof raw.ui === "object") {
const ui = raw.ui as Record<string, unknown>;
if (ui.commit === "explicit_add" || ui.commit === "on_next") {
step.ui = { commit: ui.commit };
}
}
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;
}
if (typeof raw.prompt === "string" && raw.prompt.trim()) {
step.prompt = raw.prompt.trim();
}
// Parse output.template
if (raw.output && typeof raw.output === "object") {
const output = raw.output as Record<string, unknown>;
if (typeof output.template === "string") {
step.output = { template: output.template };
}
}
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();
}
// Parse output.template
if (raw.output && typeof raw.output === "object") {
const output = raw.output as Record<string, unknown>;
if (typeof output.template === "string") {
step.output = { template: output.template };
}
}
return step;
}
if (type === "capture_text_line") {
const key = getKey();
if (!key) {
return null;
}
const step: InterviewStep = {
type: "capture_text_line",
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.prompt === "string" && raw.prompt.trim()) {
step.prompt = raw.prompt.trim();
}
// Parse heading_level
if (raw.heading_level && typeof raw.heading_level === "object") {
const headingLevel = raw.heading_level as Record<string, unknown>;
step.heading_level = {
enabled: headingLevel.enabled === true,
default: typeof headingLevel.default === "number"
? Math.max(1, Math.min(6, headingLevel.default))
: 2,
};
}
// Parse output.template
if (raw.output && typeof raw.output === "object") {
const output = raw.output as Record<string, unknown>;
if (typeof output.template === "string") {
step.output = { template: output.template };
}
}
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 === "entity_picker") {
const key = getKey();
if (!key) {
return null;
}
const step: InterviewStep = {
type: "entity_picker",
key: key,
};
if (typeof raw.label === "string" && raw.label.trim()) {
step.label = raw.label.trim();
}
if (typeof raw.prompt === "string" && raw.prompt.trim()) {
step.prompt = raw.prompt.trim();
}
if (typeof raw.required === "boolean") {
step.required = raw.required;
}
if (typeof raw.labelField === "string" && raw.labelField.trim()) {
step.labelField = raw.labelField.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);
}
}
}
+341
View File
@@ -0,0 +1,341 @@
/**
* Markdown renderer for interview profiles.
* Converts collected answers into markdown output based on profile configuration.
*/
import type { InterviewProfile, InterviewStep, CaptureTextStep, CaptureTextLineStep, CaptureFrontmatterStep, LoopStep, EntityPickerStep } from "./types";
export interface RenderAnswers {
collectedData: Map<string, unknown>;
loopContexts: Map<string, unknown[]>;
}
/**
* Render profile answers to markdown string.
* Deterministic and testable.
*/
export function renderProfileToMarkdown(
profile: InterviewProfile,
answers: RenderAnswers
): string {
const output: string[] = [];
for (const step of profile.steps) {
const stepOutput = renderStep(step, answers);
if (stepOutput) {
output.push(stepOutput);
}
}
return output.join("\n\n").trim();
}
/**
* Render a single step to markdown.
*/
function renderStep(step: InterviewStep, answers: RenderAnswers): string | null {
switch (step.type) {
case "capture_text":
return renderCaptureText(step, answers);
case "capture_text_line":
return renderCaptureTextLine(step, answers);
case "capture_frontmatter":
// Frontmatter is handled separately, skip here
return null;
case "loop":
return renderLoop(step, answers);
case "entity_picker":
return renderEntityPicker(step, answers);
case "instruction":
case "llm_dialog":
case "review":
// These don't produce markdown output
return null;
default:
return null;
}
}
/**
* Render capture_text step.
*/
function renderCaptureText(step: CaptureTextStep, answers: RenderAnswers): string | null {
const value = answers.collectedData.get(step.key);
if (!value || String(value).trim() === "") {
return null;
}
const text = String(value);
// Use template if provided
if (step.output?.template) {
return renderTemplate(step.output.template, {
text,
field: step.key,
value: text,
});
}
// Default: use section if provided, otherwise just the text
if (step.section) {
return `${step.section}\n\n${text}`;
}
return text;
}
/**
* Render capture_text_line step.
*/
function renderCaptureTextLine(step: CaptureTextLineStep, answers: RenderAnswers): string | null {
const value = answers.collectedData.get(step.key);
if (!value || String(value).trim() === "") {
return null;
}
const text = String(value);
// Get heading level if configured
const headingLevelKey = `${step.key}_heading_level`;
const headingLevel = answers.collectedData.get(headingLevelKey);
let headingPrefix = "";
if (step.heading_level?.enabled) {
if (typeof headingLevel === "number") {
const level = Math.max(1, Math.min(6, headingLevel));
headingPrefix = "#".repeat(level) + " ";
} else if (step.heading_level.default) {
// Fallback to default if not set
const level = Math.max(1, Math.min(6, step.heading_level.default));
headingPrefix = "#".repeat(level) + " ";
}
}
// Use template if provided
if (step.output?.template) {
return renderTemplate(step.output.template, {
text: headingPrefix + text,
field: step.key,
value: headingPrefix + text,
heading_level: headingLevel ? String(headingLevel) : "",
});
}
// Default: text with heading prefix if configured
return headingPrefix + text;
}
/**
* Render entity_picker step.
*/
function renderEntityPicker(step: EntityPickerStep, answers: RenderAnswers): string | null {
const basename = answers.collectedData.get(step.key);
if (!basename || typeof basename !== "string" || !basename.trim()) {
return null;
}
// Check if there's a label field
let label: string | undefined;
if (step.labelField) {
const labelValue = answers.collectedData.get(step.labelField);
if (labelValue && typeof labelValue === "string" && labelValue.trim()) {
label = labelValue.trim();
}
}
// Render wikilink
if (label) {
return `[[${basename}|${label}]]`;
} else {
return `[[${basename}]]`;
}
}
/**
* Render capture_frontmatter step.
* Note: This is typically handled separately, but included for completeness.
*/
function renderCaptureFrontmatter(step: CaptureFrontmatterStep, answers: RenderAnswers): string | null {
const value = answers.collectedData.get(step.key);
if (value === undefined || value === null || String(value).trim() === "") {
return null;
}
// Use template if provided
if (step.output?.template) {
return renderTemplate(step.output.template, {
text: String(value),
field: step.field,
value: String(value),
});
}
// Default: no markdown output (frontmatter is handled separately)
return null;
}
/**
* Render loop step (recursive, supports arbitrary nesting depth).
*/
function renderLoop(step: LoopStep, answers: RenderAnswers): string | null {
return renderLoopRecursive(step, answers, 0);
}
/**
* Recursive helper to render loop items with nested steps.
* Supports arbitrary nesting depth (no hard limit, but practical limits apply due to stack size).
*/
function renderLoopRecursive(step: LoopStep, answers: RenderAnswers, depth: number): string | null {
// Safety check: prevent infinite recursion (practical limit: 100 levels)
if (depth > 100) {
console.warn(`Loop nesting depth ${depth} exceeds practical limit, stopping recursion`);
return null;
}
const items = answers.loopContexts.get(step.key);
if (!items || items.length === 0) {
return null;
}
const itemOutputs: string[] = [];
for (const item of items) {
if (!item || typeof item !== "object") {
continue;
}
const itemParts: string[] = [];
// Render each nested step for this item (recursively)
for (const nestedStep of step.items) {
const fieldValue = (item as Record<string, unknown>)[nestedStep.key];
if (nestedStep.type === "capture_text") {
if (fieldValue && String(fieldValue).trim()) {
const text = String(fieldValue);
const captureStep = nestedStep as CaptureTextStep;
// Use template if provided
if (captureStep.output?.template) {
itemParts.push(renderTemplate(captureStep.output.template, {
text,
field: nestedStep.key,
value: text,
}));
} else {
// Default: just the text
itemParts.push(text);
}
}
} else if (nestedStep.type === "capture_text_line") {
if (fieldValue && String(fieldValue).trim()) {
const text = String(fieldValue);
const captureStep = nestedStep as CaptureTextLineStep;
// Get heading level if configured (for nested loops, check in item data)
const headingLevelKey = `${nestedStep.key}_heading_level`;
const headingLevel = (item as Record<string, unknown>)[headingLevelKey];
let headingPrefix = "";
if (captureStep.heading_level?.enabled) {
if (typeof headingLevel === "number") {
const level = Math.max(1, Math.min(6, headingLevel));
headingPrefix = "#".repeat(level) + " ";
} else if (captureStep.heading_level.default) {
// Fallback to default if not set in item
const level = Math.max(1, Math.min(6, captureStep.heading_level.default));
headingPrefix = "#".repeat(level) + " ";
}
}
// Use template if provided
if (captureStep.output?.template) {
itemParts.push(renderTemplate(captureStep.output.template, {
text: headingPrefix + text,
field: nestedStep.key,
value: headingPrefix + text,
heading_level: headingLevel ? String(headingLevel) : (captureStep.heading_level?.default ? String(captureStep.heading_level.default) : ""),
}));
} else {
// Default: text with heading prefix if configured
itemParts.push(headingPrefix + text);
}
}
} else if (nestedStep.type === "capture_frontmatter") {
if (fieldValue && String(fieldValue).trim()) {
const captureStep = nestedStep as CaptureFrontmatterStep;
// Use template if provided
if (captureStep.output?.template) {
itemParts.push(renderTemplate(captureStep.output.template, {
text: String(fieldValue),
field: captureStep.field,
value: String(fieldValue),
}));
}
}
} else if (nestedStep.type === "loop") {
// Recursively handle nested loop: fieldValue should be an array of items
if (Array.isArray(fieldValue) && fieldValue.length > 0) {
const nestedLoopStep = nestedStep as LoopStep;
// Create a temporary answers object for the nested loop
// The nested loop items are stored in fieldValue, so we need to create
// a temporary loopContexts map for the nested loop
const nestedAnswers: RenderAnswers = {
collectedData: answers.collectedData,
loopContexts: new Map(answers.loopContexts),
};
nestedAnswers.loopContexts.set(nestedLoopStep.key, fieldValue);
// Recursively render the nested loop
const nestedOutput = renderLoopRecursive(nestedLoopStep, nestedAnswers, depth + 1);
if (nestedOutput) {
itemParts.push(nestedOutput);
}
}
}
}
if (itemParts.length > 0) {
itemOutputs.push(itemParts.join("\n\n"));
}
}
if (itemOutputs.length === 0) {
return null;
}
// Check if first nested step has a section header (for backwards compatibility)
const firstNestedStep = step.items[0];
let sectionHeader: string | null = null;
if (firstNestedStep && firstNestedStep.type === "capture_text" && firstNestedStep.section) {
sectionHeader = firstNestedStep.section;
}
// Join items with configured separator or default newline
const joinStr = step.output?.join || "\n\n";
const loopContent = itemOutputs.join(joinStr);
// Prepend section header if available
if (sectionHeader) {
return `${sectionHeader}\n\n${loopContent}`;
}
return loopContent;
}
/**
* Render template string with token replacement.
* Tokens: {text}, {field}, {value}
*/
function renderTemplate(template: string, tokens: { text: string; field: string; value: string; heading_level?: string }): string {
let result = template
.replace(/\{text\}/g, tokens.text)
.replace(/\{field\}/g, tokens.field)
.replace(/\{value\}/g, tokens.value);
if (tokens.heading_level !== undefined) {
result = result.replace(/\{heading_level\}/g, tokens.heading_level);
}
return result;
}
+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
}
+119
View File
@@ -0,0 +1,119 @@
/**
* 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[];
edging?: {
mode?: "none" | "post_run" | "inline_micro"; // Semantic mapping mode (default: "none")
wrapperCalloutType?: string; // Override wrapper callout type
wrapperTitle?: string; // Override wrapper title
wrapperFolded?: boolean; // Override wrapper folded state
};
}
export type InterviewStep =
| LoopStep
| LLMDialogStep
| CaptureFrontmatterStep
| CaptureTextStep
| CaptureTextLineStep
| InstructionStep
| ReviewStep
| EntityPickerStep;
export interface LoopStep {
type: "loop";
key: string;
label?: string;
items: InterviewStep[];
output?: {
join?: string; // String to join items (default: "\n\n")
};
ui?: {
commit?: "explicit_add" | "on_next"; // Commit mode (default: "explicit_add")
};
}
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;
prompt?: string; // Optional prompt text
output?: {
template?: string; // Template with tokens: {text}, {field}, {value}
};
}
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
output?: {
template?: string; // Template with tokens: {text}, {field}, {value}
};
}
export interface CaptureTextLineStep {
type: "capture_text_line";
key: string;
label?: string;
required?: boolean;
prompt?: string; // Optional prompt text
heading_level?: {
enabled?: boolean; // Show heading level selector (default: false)
default?: number; // Default heading level 1-6 (default: 2)
};
output?: {
template?: string; // Template with tokens: {text}, {field}, {value}, {heading_level}
};
}
export interface InstructionStep {
type: "instruction";
key: string;
label?: string;
content: string;
}
export interface EntityPickerStep {
type: "entity_picker";
key: string;
label?: string;
prompt?: string;
required?: boolean;
labelField?: string; // Optional field key to use as wikilink label
}
export interface ReviewStep {
type: "review";
key: string;
label?: string;
}
+111
View File
@@ -0,0 +1,111 @@
import type { InterviewProfile, InterviewStep } from "./types";
import type { LoopRuntimeState } from "./loopState";
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 (deprecated, use loopRuntimeStates)
loopRuntimeStates: Map<string, LoopRuntimeState>; // loop step key -> runtime state
patches: Patch[]; // Collected patches to apply
activeLoopPath: string[]; // Stack of loop keys representing current nesting level (e.g. ["items", "item_list"])
}
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(), // Keep for backwards compatibility
loopRuntimeStates: new Map(),
patches: [],
activeLoopPath: [], // Start at top level
};
}
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 '""';
}
}
+150
View File
@@ -0,0 +1,150 @@
import type { App } from "obsidian";
import type { ParsedEdge } from "../parser/types";
import type { Vocabulary } from "../vocab/Vocabulary";
import type { Finding } from "./types";
import { parseEdgesFromCallouts } from "../parser/parseEdgesFromCallouts";
export interface LintOptions {
showCanonicalHints?: boolean;
}
/**
* Pure function to lint parsed edges against vocabulary and file existence.
* This can be tested independently.
*/
export function lintParsedEdges(
parsedEdges: ParsedEdge[],
vocabulary: Vocabulary,
existingFileNamesSet: Set<string>,
opts: LintOptions = {}
): Finding[] {
const findings: Finding[] = [];
const { showCanonicalHints = false } = opts;
for (const edge of parsedEdges) {
const normalized = vocabulary.normalize(edge.rawType);
// R1: Check for unknown edge type (ERROR)
if (normalized.canonical === null) {
findings.push({
ruleId: "unknown_edge_type",
severity: "ERROR",
message: `Unknown edge type: "${edge.rawType}"`,
filePath: "", // Will be set by caller
lineStart: edge.lineStart,
lineEnd: edge.lineEnd,
evidence: edge.rawType,
});
} else {
// Optional: Show canonical hints (INFO)
if (showCanonicalHints) {
findings.push({
ruleId: "canonical_hint",
severity: "INFO",
message: `Edge type resolved: raw='${edge.rawType}' canonical='${normalized.canonical}'`,
filePath: "", // Will be set by caller
lineStart: edge.lineStart,
lineEnd: edge.lineStart,
evidence: edge.rawType,
});
}
}
// R3: Check for edges without targets (WARN)
if (edge.targets.length === 0) {
findings.push({
ruleId: "edge_without_target",
severity: "WARN",
message: `Edge type "${edge.rawType}" has no target notes`,
filePath: "", // Will be set by caller
lineStart: edge.lineStart,
lineEnd: edge.lineEnd,
evidence: edge.rawType,
});
}
// R2: Check for missing target notes (WARN)
// Check targets regardless of whether edge type is known or unknown
for (const target of edge.targets) {
if (!target) continue;
// Check if file exists (exact match to markdown file name)
// Target might be "Note Name" or "Note Name#heading" - we check the base name
const parts = target.split("#");
const firstPart = parts[0];
if (!firstPart) continue;
const baseName = firstPart.trim();
if (!baseName) continue;
const markdownFileName = baseName.endsWith(".md") ? baseName : `${baseName}.md`;
if (!existingFileNamesSet.has(markdownFileName) && !existingFileNamesSet.has(baseName)) {
findings.push({
ruleId: "missing_target_note",
severity: "WARN",
message: `Target note "${target}" not found in vault`,
filePath: "", // Will be set by caller
lineStart: edge.lineStart,
lineEnd: edge.lineEnd,
evidence: target,
});
}
}
}
return findings;
}
/**
* LintEngine for validating markdown notes containing edge definitions.
*/
export class LintEngine {
/**
* Lint the currently active markdown note.
*/
static async lintCurrentNote(
app: App,
vocabulary: Vocabulary,
options: LintOptions = {}
): Promise<Finding[]> {
const activeFile = app.workspace.getActiveFile();
if (!activeFile) {
throw new Error("No active file");
}
if (activeFile.extension !== "md") {
throw new Error("Active file is not a markdown file");
}
// Read file content
const content = await app.vault.read(activeFile);
// Parse edges
const parsedEdges = parseEdgesFromCallouts(content);
// Build set of existing markdown file names in vault
const existingFileNamesSet = new Set<string>();
const markdownFiles = app.vault.getMarkdownFiles();
for (const file of markdownFiles) {
existingFileNamesSet.add(file.name);
// Also add without .md extension for matching
if (file.name.endsWith(".md")) {
const baseName = file.name.slice(0, -3);
existingFileNamesSet.add(baseName);
}
}
// Run pure linting logic
const findings = lintParsedEdges(parsedEdges, vocabulary, existingFileNamesSet, options);
// Set filePath for all findings
const filePath = activeFile.path;
for (const finding of findings) {
finding.filePath = filePath;
}
return findings;
}
}
View File
Whitespace-only changes.
View File
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
View File
Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
export type Severity = "ERROR" | "WARN" | "INFO";
export interface QuickFix {
id: string;
title: string;
apply: () => Promise<void>;
}
export interface Finding {
ruleId: string;
severity: Severity;
message: string;
filePath: string;
lineStart?: number;
lineEnd?: number;
evidence?: string;
quickFixes?: QuickFix[];
}
+1114
View File
File diff suppressed because it is too large. Load diff
+93
View File
@@ -0,0 +1,93 @@
/**
* Helper functions for folder and file path handling.
*/
import { App } from "obsidian";
import { normalizeVaultPath } from "../settings";
/**
* Join folder path and basename to create full file path.
* Handles empty folder (root) correctly.
*/
export function joinFolderAndBasename(folder: string, basename: string): string {
const normalizedFolder = normalizeVaultPath(folder).trim();
const normalizedBasename = basename.trim();
if (!normalizedFolder) {
// Root folder
return normalizedBasename;
}
// Remove trailing slash if present
const cleanFolder = normalizedFolder.replace(/\/$/, "");
return `${cleanFolder}/${normalizedBasename}`;
}
/**
* Ensure unique file path by appending (2), (3), etc. if file exists.
* Returns the first available path.
*/
export async function ensureUniqueFilePath(
app: App,
desiredPath: string
): Promise<string> {
const normalizedPath = normalizeVaultPath(desiredPath);
// Check if file exists
const existingFile = app.vault.getAbstractFileByPath(normalizedPath);
if (!existingFile) {
return normalizedPath;
}
// Extract directory and basename
const lastSlash = normalizedPath.lastIndexOf("/");
const dir = lastSlash >= 0 ? normalizedPath.substring(0, lastSlash) : "";
const fullBasename = lastSlash >= 0 ? normalizedPath.substring(lastSlash + 1) : normalizedPath;
// Extract name and extension
const lastDot = fullBasename.lastIndexOf(".");
const name = lastDot >= 0 ? fullBasename.substring(0, lastDot) : fullBasename;
const ext = lastDot >= 0 ? fullBasename.substring(lastDot) : "";
// Try (2), (3), etc.
let attempt = 2;
while (attempt < 1000) {
const newBasename = `${name} (${attempt})${ext}`;
const newPath = dir ? `${dir}/${newBasename}` : newBasename;
const existing = app.vault.getAbstractFileByPath(newPath);
if (!existing) {
return newPath;
}
attempt++;
}
// Fallback: add timestamp
const timestamp = Date.now();
const newBasename = `${name}_${timestamp}${ext}`;
return dir ? `${dir}/${newBasename}` : newBasename;
}
/**
* Ensure folder exists, creating it if necessary (mkdirp).
*/
export async function ensureFolderExists(app: App, folderPath: string): Promise<void> {
const normalizedPath = normalizeVaultPath(folderPath).trim();
if (!normalizedPath) {
// Root folder, always exists
return;
}
// Check if folder exists
const existing = app.vault.getAbstractFileByPath(normalizedPath);
if (existing) {
// Already exists
return;
}
// Create folder (mkdirp)
await app.vault.createFolder(normalizedPath);
}
+158
View File
@@ -0,0 +1,158 @@
/**
* Graph Schema loader and hint provider.
*/
export interface EdgeTypeHints {
typical: string[]; // Recommended edge types
prohibited: string[]; // Prohibited edge types
}
export interface GraphSchema {
// schema[sourceType][targetType] = hints
schema: Map<string, Map<string, EdgeTypeHints>>;
}
/**
* Parse graph_schema.md markdown content.
*/
export function parseGraphSchema(markdown: string): GraphSchema {
const schema = new Map<string, Map<string, EdgeTypeHints>>();
const lines = markdown.split(/\r?\n/);
let currentSource: string | null = null;
let inTable = false;
let headerSkipped = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line === undefined) continue;
// Detect "## Source: `type`" pattern
const sourceMatch = line.match(/^##\s+Source:\s+`([^`]+)`/);
if (sourceMatch && sourceMatch[1]) {
currentSource = sourceMatch[1].trim();
inTable = false;
headerSkipped = false;
continue;
}
// Skip if no current source
if (!currentSource) continue;
// Detect table header separator (e.g., "| :--- | :--- | :--- |")
if (/^\s*\|[\s:|-]+\|\s*$/.test(line)) {
inTable = true;
headerSkipped = true; // Next non-separator line is header, skip it
continue;
}
// Process table rows
if (inTable && line.trim().startsWith("|")) {
if (headerSkipped) {
// Skip header row
headerSkipped = false;
continue;
}
// Parse table row: | targetType | typical | prohibited |
const cells = line.split("|").map((c) => c.trim()).filter((c) => c);
if (cells.length >= 2) {
const targetType = cells[0]?.replace(/`/g, "").trim() || "";
const typicalStr = cells[1] || "";
const prohibitedStr = cells[2] || "";
if (targetType) {
// Parse typical (comma-separated, may contain backticks)
const typical = parseEdgeTypeList(typicalStr);
// Parse prohibited (comma-separated, may contain backticks)
const prohibited = parseEdgeTypeList(prohibitedStr);
// Initialize source map if needed
if (!schema.has(currentSource)) {
schema.set(currentSource, new Map());
}
const sourceMap = schema.get(currentSource)!;
sourceMap.set(targetType, { typical, prohibited });
}
}
}
// Reset table state on section end (next ## Source or end of file)
if (line.startsWith("##") && !sourceMatch) {
inTable = false;
headerSkipped = false;
}
}
return { schema };
}
/**
* Parse comma-separated edge type list (may contain backticks).
*/
function parseEdgeTypeList(str: string): string[] {
if (!str || str.trim() === "-" || str.trim() === "") {
return [];
}
// Split by comma, remove backticks, trim
return str
.split(",")
.map((s) => s.replace(/`/g, "").trim())
.filter((s) => s.length > 0);
}
/**
* Get edge type hints for source/target combination with fallback order:
* exact -> target "any" -> source "any" -> both "any"
*/
export function getHints(
graphSchema: GraphSchema,
sourceType: string | null,
targetType: string | null
): EdgeTypeHints {
const empty: EdgeTypeHints = { typical: [], prohibited: [] };
if (!sourceType || !targetType) {
// Try "any" fallbacks
if (sourceType) {
return getHintsForSourceTarget(graphSchema, sourceType, "any") || empty;
}
if (targetType) {
return getHintsForSourceTarget(graphSchema, "any", targetType) || empty;
}
return getHintsForSourceTarget(graphSchema, "any", "any") || empty;
}
// Try exact match first
const exact = getHintsForSourceTarget(graphSchema, sourceType, targetType);
if (exact) return exact;
// Fallback: target "any"
const targetAny = getHintsForSourceTarget(graphSchema, sourceType, "any");
if (targetAny) return targetAny;
// Fallback: source "any"
const sourceAny = getHintsForSourceTarget(graphSchema, "any", targetType);
if (sourceAny) return sourceAny;
// Fallback: both "any"
return getHintsForSourceTarget(graphSchema, "any", "any") || empty;
}
/**
* Get hints for specific source/target combination.
*/
function getHintsForSourceTarget(
graphSchema: GraphSchema,
sourceType: string,
targetType: string
): EdgeTypeHints | null {
const sourceMap = graphSchema.schema.get(sourceType);
if (!sourceMap) return null;
const hints = sourceMap.get(targetType);
return hints || null;
}
+158
View File
@@ -0,0 +1,158 @@
/**
* Build semantic mapping blocks with edge groups.
*/
import type { LinkMapping } from "./mappingExtractor";
export interface MappingBuilderOptions {
wrapperCalloutType: string;
wrapperTitle: string;
wrapperFolded: boolean;
defaultEdgeType: string;
assignUnmapped: "none" | "defaultType" | "advisor" | "prompt";
}
/**
* Build mapping block for a section.
*/
export function buildMappingBlock(
links: string[],
existingMappings: Map<string, string>,
options: MappingBuilderOptions
): string | null {
if (links.length === 0) {
return null; // No links, no mapping block
}
// Group links by edgeType
const groups = new Map<string, string[]>();
for (const link of links) {
const edgeType = existingMappings.get(link);
if (edgeType) {
// Use existing mapping
if (!groups.has(edgeType)) {
groups.set(edgeType, []);
}
groups.get(edgeType)!.push(link);
} else {
// New link without mapping
if (options.assignUnmapped === "defaultType" && options.defaultEdgeType) {
const type = options.defaultEdgeType;
if (!groups.has(type)) {
groups.set(type, []);
}
groups.get(type)!.push(link);
} else if (options.assignUnmapped === "advisor") {
// TODO: Call suggestEdgeTypes (E1 engine stub)
// For now, use defaultType if available, otherwise skip
if (options.defaultEdgeType) {
const type = options.defaultEdgeType;
if (!groups.has(type)) {
groups.set(type, []);
}
groups.get(type)!.push(link);
}
// Otherwise skip (assignUnmapped="none" behavior)
}
// If assignUnmapped="none", skip unmapped links
}
}
if (groups.size === 0) {
return null; // No mapped links
}
// Build wrapper callout
const foldMarker = options.wrapperFolded ? "-" : "+";
const wrapperHeader = `> [!${options.wrapperCalloutType}]${foldMarker} ${options.wrapperTitle}`;
const blockLines: string[] = [wrapperHeader];
// Sort groups deterministically: existing types first (by insertion order), then alphabetically
const groupEntries = Array.from(groups.entries());
// Separate existing types from new types
const existingTypes = new Set(existingMappings.values());
const existingGroups: [string, string[]][] = [];
const newGroups: [string, string[]][] = [];
for (const [edgeType, links] of groupEntries) {
if (existingTypes.has(edgeType)) {
existingGroups.push([edgeType, links]);
} else {
newGroups.push([edgeType, links]);
}
}
// Sort existing groups by original order (first occurrence in existingMappings)
existingGroups.sort((a, b) => {
// Get first link with this type from existingMappings
let aOrder = Infinity;
let bOrder = Infinity;
let index = 0;
const aType = a?.[0] || "";
const bType = b?.[0] || "";
for (const [link, type] of existingMappings.entries()) {
if (type === aType && aOrder === Infinity) aOrder = index;
if (type === bType && bOrder === Infinity) bOrder = index;
index++;
}
return aOrder - bOrder;
});
// Sort new groups alphabetically
newGroups.sort((a, b) => a[0].localeCompare(b[0]));
// Combine: existing first, then new
const sortedGroups = [...existingGroups, ...newGroups];
// Build edge groups
for (let i = 0; i < sortedGroups.length; i++) {
const group = sortedGroups[i];
if (!group) continue;
const [edgeType, groupLinks] = group;
if (!edgeType || !groupLinks) continue;
// Add blank quoted line separator between groups (except before first)
if (i > 0) {
blockLines.push(">");
}
// Edge header
blockLines.push(`>> [!edge] ${edgeType}`);
// Links (sorted alphabetically for determinism)
const sortedLinks = [...groupLinks].sort();
for (const link of sortedLinks) {
blockLines.push(`>> [[${link}]]`);
}
}
// Add block-id marker for future detection
blockLines.push(`> ^map-${Date.now()}`);
return blockLines.join("\n");
}
/**
* Insert mapping block at end of section content.
*/
export function insertMappingBlock(
sectionContent: string,
mappingBlock: string
): string {
// Remove trailing whitespace
const trimmed = sectionContent.trimEnd();
// Ensure two newlines before mapping block
if (trimmed.endsWith("\n\n")) {
return trimmed + mappingBlock;
} else if (trimmed.endsWith("\n")) {
return trimmed + "\n" + mappingBlock;
} else {
return trimmed + "\n\n" + mappingBlock;
}
}
+159
View File
@@ -0,0 +1,159 @@
/**
* Extract existing edge mappings from a section and detect/remove wrapper blocks.
*/
import { parseEdgesFromCallouts } from "../parser/parseEdgesFromCallouts";
export interface LinkMapping {
link: string;
edgeType: string;
}
export interface SectionMappingState {
existingMappings: Map<string, string>; // link -> edgeType
wrapperBlockStartLine: number | null; // Line where wrapper block starts
wrapperBlockEndLine: number | null; // Line where wrapper block ends (exclusive)
}
/**
* Extract existing mappings from a section.
* Also detects the wrapper block location.
*/
export function extractExistingMappings(
sectionContent: string,
wrapperCalloutType: string,
wrapperTitle: string
): SectionMappingState {
const existingMappings = new Map<string, string>();
const lines = sectionContent.split(/\r?\n/);
// Parse edges from callouts
const edges = parseEdgesFromCallouts(sectionContent);
// Build mapping: link -> edgeType
for (const edge of edges) {
for (const target of edge.targets) {
// If link already mapped, keep first occurrence (or could merge, but simpler: first wins)
if (!existingMappings.has(target)) {
existingMappings.set(target, edge.rawType);
}
}
}
// Detect wrapper block
const wrapperBlock = detectWrapperBlock(lines, wrapperCalloutType, wrapperTitle);
return {
existingMappings,
wrapperBlockStartLine: wrapperBlock?.startLine ?? null,
wrapperBlockEndLine: wrapperBlock?.endLine ?? null,
};
}
interface WrapperBlockLocation {
startLine: number;
endLine: number;
}
/**
* Detect wrapper callout block in lines.
* Looks for: > [!<calloutType>] <title> or > [!<calloutType>]- <title>
* Also checks for block-id marker like ^map-...
*/
function detectWrapperBlock(
lines: string[],
calloutType: string,
title: string
): WrapperBlockLocation | null {
const calloutTypeLower = calloutType.toLowerCase();
const titleLower = title.toLowerCase();
// Pattern 1: > [!<calloutType>] <title> or > [!<calloutType>]- <title> or > [!<calloutType>]+ <title>
const calloutHeaderRegex = new RegExp(
`^\\s*>\\s*\\[!${calloutTypeLower.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\]\\s*[+-]?\\s*(.+)$`,
"i"
);
let wrapperStart: number | null = null;
let wrapperEnd: number | null = null;
let inWrapper = false;
let quoteLevel = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line === undefined) continue;
const trimmed = line.trim();
const match = line.match(calloutHeaderRegex);
if (match && match[1]) {
const headerTitle = match[1].trim().toLowerCase();
// Check if title matches (case-insensitive, partial match for flexibility)
if (headerTitle.includes(titleLower) || titleLower.includes(headerTitle)) {
wrapperStart = i;
inWrapper = true;
quoteLevel = (line.match(/^\s*(>+)/)?.[1]?.length || 0);
continue;
}
}
if (inWrapper) {
// Check for block-id marker (^map-...)
if (trimmed.match(/^\^map-/)) {
// Found end marker, wrapper ends after this line
wrapperEnd = i + 1;
break;
}
// Check if we're still in the callout (quote level)
const currentQuoteLevel = (line.match(/^\s*(>+)/)?.[1]?.length || 0);
// If quote level drops below wrapper level and line is not blank, end wrapper
if (trimmed !== "" && currentQuoteLevel < quoteLevel) {
wrapperEnd = i;
break;
}
// If we hit a heading (not in quotes), end wrapper
if (!line.startsWith(">") && trimmed.match(/^#{1,6}\s+/)) {
wrapperEnd = i;
break;
}
}
}
// If we're still in wrapper at end, close it
if (inWrapper && wrapperStart !== null && wrapperEnd === null) {
wrapperEnd = lines.length;
}
if (wrapperStart !== null && wrapperEnd !== null) {
return {
startLine: wrapperStart,
endLine: wrapperEnd,
};
}
return null;
}
/**
* Remove wrapper block from section content.
*/
export function removeWrapperBlock(
sectionContent: string,
wrapperStartLine: number,
wrapperEndLine: number
): string {
const lines = sectionContent.split(/\r?\n/);
// Remove lines in wrapper block range
const before = lines.slice(0, wrapperStartLine);
const after = lines.slice(wrapperEndLine);
// Join and clean up trailing/leading whitespace
const result = [...before, ...after].join("\n");
// Remove excessive blank lines at the end
return result.replace(/\n{3,}$/, "\n\n");
}
+77
View File
@@ -0,0 +1,77 @@
/**
* Schema helper for computing typical/prohibited edge types.
*/
import type { EdgeVocabulary } from "../vocab/types";
import type { GraphSchema } from "./graphSchema";
import { getHints } from "./graphSchema";
export interface EdgeTypeSuggestion {
typical: string[]; // Recommended edge types
prohibited: string[]; // Prohibited edge types
}
/**
* Compute edge type suggestions based on source and target types.
* Uses GraphSchema if provided, otherwise returns empty arrays.
*/
export function computeEdgeSuggestions(
vocabulary: EdgeVocabulary,
sourceType: string | null,
targetType: string | null,
graphSchema: GraphSchema | null = null
): EdgeTypeSuggestion {
if (graphSchema) {
return getHints(graphSchema, sourceType, targetType);
}
// No schema available, return empty
return {
typical: [],
prohibited: [],
};
}
/**
* Get all available edge types from vocabulary (canonical + aliases).
*/
export function getAllEdgeTypes(vocabulary: EdgeVocabulary): Array<{
canonical: string;
aliases: string[];
displayName: string; // First alias or canonical
}> {
const result: Array<{
canonical: string;
aliases: string[];
displayName: string;
}> = [];
for (const [canonical, entry] of vocabulary.byCanonical.entries()) {
const firstAlias = entry.aliases.length > 0 ? entry.aliases[0] : null;
const displayName = firstAlias || canonical;
result.push({
canonical,
aliases: entry.aliases,
displayName,
});
}
// Sort by display name
result.sort((a, b) => a.displayName.localeCompare(b.displayName));
return result;
}
/**
* Group edge types by category (if available).
* MVP: Returns single "All" category.
*/
export function groupEdgeTypesByCategory(
edgeTypes: Array<{ canonical: string; aliases: string[]; displayName: string }>
): Map<string, Array<{ canonical: string; aliases: string[]; displayName: string }>> {
// TODO: Implement category grouping from schema
// For MVP, return single "All" category
const grouped = new Map<string, Array<{ canonical: string; aliases: string[]; displayName: string }>>();
grouped.set("All", edgeTypes);
return grouped;
}
+110
View File
@@ -0,0 +1,110 @@
/**
* Section parser: Split markdown by headings and extract wikilinks per section.
*/
export interface NoteSection {
heading: string | null; // null for content before first heading
headingLevel: number; // 0 for content before first heading
content: string; // Full content of section (including heading)
startLine: number; // Line index where section starts
endLine: number; // Line index where section ends (exclusive)
links: string[]; // Deduplicated wikilinks found in this section
}
/**
* Split markdown content into sections by headings.
*/
export function splitIntoSections(markdown: string): NoteSection[] {
const lines = markdown.split(/\r?\n/);
const sections: NoteSection[] = [];
let currentSection: NoteSection | null = null;
let currentContent: string[] = [];
let currentStartLine = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line === undefined) continue;
// Check if line is a heading
const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
if (headingMatch) {
// Save previous section if exists
if (currentSection !== null || currentContent.length > 0) {
const content = currentContent.join("\n");
const links = extractWikilinks(content);
sections.push({
heading: currentSection?.heading || null,
headingLevel: currentSection?.headingLevel || 0,
content: content,
startLine: currentStartLine,
endLine: i,
links: links,
});
}
// Start new section
const headingLevel = (headingMatch[1]?.length || 0);
const headingText = (headingMatch[2]?.trim() || "");
currentSection = {
heading: headingText,
headingLevel: headingLevel,
content: line,
startLine: i,
endLine: i + 1,
links: [],
};
currentContent = [line];
currentStartLine = i;
} else {
// Add line to current section
if (currentSection) {
currentContent.push(line);
currentSection.content = currentContent.join("\n");
currentSection.endLine = i + 1;
} else {
// Content before first heading
currentContent.push(line);
}
}
}
// Save last section
if (currentSection || currentContent.length > 0) {
const content = currentContent.join("\n");
const links = extractWikilinks(content);
sections.push({
heading: currentSection?.heading || null,
headingLevel: currentSection?.headingLevel || 0,
content: content,
startLine: currentStartLine,
endLine: lines.length,
links: links,
});
}
return sections;
}
/**
* Extract all wikilinks from markdown text (deduplicated).
*/
export function extractWikilinks(markdown: string): string[] {
const links = new Set<string>();
const wikilinkRegex = /\[\[([^\]]+?)\]\]/g;
let match: RegExpExecArray | null;
while ((match = wikilinkRegex.exec(markdown)) !== null) {
if (match[1]) {
const link = match[1].trim();
if (link) {
links.add(link);
}
}
}
return Array.from(links).sort(); // Deterministic ordering
}
+277
View File
@@ -0,0 +1,277 @@
/**
* Semantic Mapping Builder: Build mapping blocks for sections.
*/
import { App, TFile, Notice } from "obsidian";
import type { MindnetSettings } from "../settings";
import { splitIntoSections, type NoteSection } from "./sectionParser";
import { parseEdgesFromCallouts } from "../parser/parseEdgesFromCallouts";
import {
extractExistingMappings,
removeWrapperBlock,
type SectionMappingState,
} from "./mappingExtractor";
import {
buildMappingBlock,
insertMappingBlock,
type MappingBuilderOptions,
} from "./mappingBuilder";
import { buildSectionWorklist, getSourceType } from "./worklistBuilder";
import { LinkPromptModal, type LinkPromptDecision } from "../ui/LinkPromptModal";
import { VocabularyLoader } from "../vocab/VocabularyLoader";
import { parseEdgeVocabulary } from "../vocab/parseEdgeVocabulary";
import type { EdgeVocabulary } from "../vocab/types";
import { parseGraphSchema, type GraphSchema } from "./graphSchema";
export interface BuildResult {
sectionsProcessed: number;
sectionsWithMappings: number;
totalLinks: number;
existingMappingsKept: number;
newMappingsAssigned: number;
unmappedLinksSkipped: number;
}
/**
* Build semantic mapping blocks for all sections in a note.
*/
export async function buildSemanticMappings(
app: App,
file: TFile,
settings: MindnetSettings,
allowOverwrite: boolean,
plugin?: { ensureGraphSchemaLoaded?: () => Promise<GraphSchema | null> }
): Promise<BuildResult> {
const content = await app.vault.read(file);
const lines = content.split(/\r?\n/);
// Load vocabulary and schema if prompt mode
let vocabulary: EdgeVocabulary | null = null;
let graphSchema: GraphSchema | null = null;
if (settings.unassignedHandling === "prompt") {
try {
const vocabText = await VocabularyLoader.loadText(app, settings.edgeVocabularyPath);
vocabulary = parseEdgeVocabulary(vocabText);
} catch (e) {
new Notice(`Failed to load edge vocabulary: ${e instanceof Error ? e.message : String(e)}`);
return {
sectionsProcessed: 0,
sectionsWithMappings: 0,
totalLinks: 0,
existingMappingsKept: 0,
newMappingsAssigned: 0,
unmappedLinksSkipped: 0,
};
}
// Load graph schema (optional, continue if not found)
if (plugin && plugin.ensureGraphSchemaLoaded) {
// Use plugin's ensureGraphSchemaLoaded for caching and live reload
graphSchema = await plugin.ensureGraphSchemaLoaded();
} else {
// Fallback: direct load (no caching)
try {
const schemaText = await VocabularyLoader.loadText(app, settings.graphSchemaPath);
graphSchema = parseGraphSchema(schemaText);
} catch (e) {
console.warn(`Graph schema not available: ${e instanceof Error ? e.message : String(e)}`);
// Continue without schema
}
}
}
// Get source type
const sourceType = getSourceType(app, file);
// Split into sections
const sections = splitIntoSections(content);
const result: BuildResult = {
sectionsProcessed: 0,
sectionsWithMappings: 0,
totalLinks: 0,
existingMappingsKept: 0,
newMappingsAssigned: 0,
unmappedLinksSkipped: 0,
};
// Process sections in reverse order (to preserve line indices when modifying)
const modifiedSections: Array<{ section: NoteSection; newContent: string }> = [];
for (const section of sections) {
result.sectionsProcessed++;
if (section.links.length === 0) {
// No links, skip
modifiedSections.push({
section,
newContent: section.content,
});
continue;
}
result.totalLinks += section.links.length;
// Extract existing mappings
const mappingState = extractExistingMappings(
section.content,
settings.mappingWrapperCalloutType,
settings.mappingWrapperTitle
);
// Remove wrapper block if exists
let sectionContentWithoutWrapper = section.content;
if (mappingState.wrapperBlockStartLine !== null && mappingState.wrapperBlockEndLine !== null) {
sectionContentWithoutWrapper = removeWrapperBlock(
section.content,
mappingState.wrapperBlockStartLine,
mappingState.wrapperBlockEndLine
);
}
// Determine final mappings based on mode
const mappingsToUse = new Map<string, string>();
if (settings.unassignedHandling === "prompt" && vocabulary) {
// Prompt mode: interactive assignment
const worklist = await buildSectionWorklist(
app,
section.content,
section.heading,
settings.mappingWrapperCalloutType,
settings.mappingWrapperTitle
);
// Process each link in worklist
for (const item of worklist.items) {
// Always prompt user (even for existing mappings)
// Keep is the default option if currentType exists
const prompt = new LinkPromptModal(app, item, vocabulary, sourceType, graphSchema);
const decision = await prompt.show();
// Apply decision
if (decision.action === "keep") {
mappingsToUse.set(item.link, decision.edgeType);
if (mappingState.existingMappings.has(item.link)) {
result.existingMappingsKept++;
}
} else if (decision.action === "change") {
// Use canonical type (alias is for display only)
mappingsToUse.set(item.link, decision.edgeType);
if (mappingState.existingMappings.has(item.link)) {
// Changed existing
} else {
result.newMappingsAssigned++;
}
} else {
// Skip
if (!mappingState.existingMappings.has(item.link)) {
result.unmappedLinksSkipped++;
}
}
}
} else {
// Silent modes: none/defaultType/advisor
// Always include existing mappings
for (const [link, edgeType] of mappingState.existingMappings.entries()) {
if (section.links.includes(link)) {
mappingsToUse.set(link, edgeType);
result.existingMappingsKept++;
}
}
// Handle unmapped based on mode
for (const link of section.links) {
if (!mappingsToUse.has(link)) {
if (settings.unassignedHandling === "defaultType" && settings.defaultEdgeType) {
mappingsToUse.set(link, settings.defaultEdgeType);
result.newMappingsAssigned++;
} else if (settings.unassignedHandling === "advisor" && settings.defaultEdgeType) {
// TODO: Call advisor (E1 engine stub)
mappingsToUse.set(link, settings.defaultEdgeType);
result.newMappingsAssigned++;
} else {
result.unmappedLinksSkipped++;
}
}
}
}
// Build new mapping block
const builderOptions: MappingBuilderOptions = {
wrapperCalloutType: settings.mappingWrapperCalloutType,
wrapperTitle: settings.mappingWrapperTitle,
wrapperFolded: settings.mappingWrapperFolded,
defaultEdgeType: settings.defaultEdgeType,
assignUnmapped: "none", // Already handled above, so set to "none" to avoid double-processing
};
// Build mapping block
const mappingBlock = buildMappingBlock(section.links, mappingsToUse, builderOptions);
if (mappingBlock) {
result.sectionsWithMappings++;
// Insert mapping block at end of section
const newContent = insertMappingBlock(sectionContentWithoutWrapper, mappingBlock);
modifiedSections.push({
section,
newContent,
});
} else {
// No mapping block needed
modifiedSections.push({
section,
newContent: sectionContentWithoutWrapper,
});
}
}
// Rebuild full content
const newContent = rebuildContentFromSections(lines, modifiedSections);
// Write back to file
await app.vault.modify(file, newContent);
return result;
}
/**
* Rebuild content from modified sections.
* Preserves original line structure where possible.
*/
function rebuildContentFromSections(
originalLines: string[],
modifiedSections: Array<{ section: NoteSection; newContent: string }>
): string {
// Sort sections by startLine (ascending)
const sorted = [...modifiedSections].sort((a, b) => a.section.startLine - b.section.startLine);
const result: string[] = [];
let lastEndLine = 0;
for (const { section, newContent } of sorted) {
// Add any content between last section and this one
if (section.startLine > lastEndLine) {
const gap = originalLines.slice(lastEndLine, section.startLine).join("\n");
if (gap) {
result.push(gap);
}
}
// Add modified section content
result.push(newContent);
lastEndLine = section.endLine;
}
// Add any remaining content after last section
if (lastEndLine < originalLines.length) {
const remaining = originalLines.slice(lastEndLine).join("\n");
if (remaining) {
result.push(remaining);
}
}
return result.join("\n");
}
+88
View File
@@ -0,0 +1,88 @@
/**
* Build worklist of links for prompt mode.
*/
import { App, TFile } from "obsidian";
import type { EdgeVocabulary } from "../vocab/types";
import { extractWikilinks } from "./sectionParser";
import { extractExistingMappings } from "./mappingExtractor";
export interface LinkWorkItem {
link: string; // Wikilink basename
targetType: string | null; // Note type from metadataCache/frontmatter
currentType: string | null; // Existing edge type mapping, if any
}
export interface SectionWorklist {
sectionHeading: string | null;
items: LinkWorkItem[];
}
/**
* Build worklist for a section.
*/
export async function buildSectionWorklist(
app: App,
sectionContent: string,
sectionHeading: string | null,
wrapperCalloutType: string,
wrapperTitle: string
): Promise<SectionWorklist> {
// Extract all wikilinks (deduplicated)
const links = extractWikilinks(sectionContent);
// Extract existing mappings
const mappingState = extractExistingMappings(
sectionContent,
wrapperCalloutType,
wrapperTitle
);
// Build worklist items
const items: LinkWorkItem[] = [];
for (const link of links) {
// Get target file
const targetFile = app.metadataCache.getFirstLinkpathDest(link, "");
// Get target type from frontmatter
let targetType: string | null = null;
if (targetFile) {
const cache = app.metadataCache.getFileCache(targetFile);
if (cache?.frontmatter) {
targetType = cache.frontmatter.type || cache.frontmatter.noteType || null;
if (targetType && typeof targetType !== "string") {
targetType = String(targetType);
}
}
}
// Get current mapping
const currentType = mappingState.existingMappings.get(link) || null;
items.push({
link,
targetType,
currentType,
});
}
return {
sectionHeading,
items,
};
}
/**
* Get source type from current file.
*/
export function getSourceType(app: App, file: TFile): string | null {
const cache = app.metadataCache.getFileCache(file);
if (cache?.frontmatter) {
const type = cache.frontmatter.type || cache.frontmatter.noteType || null;
if (type && typeof type === "string") {
return type;
}
}
return null;
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./types";
export * from "./parseEdgesFromCallouts";
+78
View File
@@ -0,0 +1,78 @@
import type { ParsedEdge } from "./types";
const EDGE_HEADER_RE = /^\s*(>+)\s*\[!edge\]\s*(.+?)\s*$/i;
const TARGET_LINK_RE = /\[\[([^\]]+?)\]\]/g;
/**
* Extract edges from any callout nesting:
* - Edge starts with: > [!edge] <type> (any number of '>' allowed)
* - Collect targets from subsequent lines while quoteLevel >= edgeLevel
* - Stop when:
* a) next [!edge] header appears, OR
* b) quoteLevel drops below edgeLevel (block ends), ignoring blank lines
*/
export function parseEdgesFromCallouts(markdown: string): ParsedEdge[] {
const lines = markdown.split(/\r?\n/);
const edges: ParsedEdge[] = [];
let current: ParsedEdge | null = null;
let currentEdgeLevel = 0;
const getQuoteLevel = (line: string): number => {
const m = line.match(/^\s*(>+)/);
return m && m[1] ? m[1].length : 0;
};
const flush = (endLine: number) => {
if (!current) return;
current.lineEnd = endLine;
if (current.targets.length > 0) edges.push(current);
current = null;
currentEdgeLevel = 0;
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line === undefined) continue;
// Start of a new edge block
const edgeMatch = line.match(EDGE_HEADER_RE);
if (edgeMatch && edgeMatch[1] && edgeMatch[2]) {
flush(i - 1);
currentEdgeLevel = edgeMatch[1].length;
current = {
rawType: edgeMatch[2].trim(),
targets: [],
lineStart: i,
lineEnd: i,
};
continue;
}
if (!current) continue;
const trimmed = line.trim();
const ql = getQuoteLevel(line);
// End of the current edge block if quote level drops below the edge header level
// (ignore blank lines)
if (trimmed !== "" && ql < currentEdgeLevel) {
flush(i - 1);
continue;
}
// Collect targets (multiple per line allowed)
TARGET_LINK_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = TARGET_LINK_RE.exec(line)) !== null) {
if (m[1]) {
const t = m[1].trim();
if (t) current.targets.push(t);
}
}
}
flush(lines.length - 1);
return edges;
}
+51
View File
@@ -0,0 +1,51 @@
/**
* Extract frontmatter ID from markdown content.
* Only parses YAML frontmatter at the top of the file (between first two '---' lines).
* Returns the value of key 'id' as string if present; else null.
* Tolerant: id may be number in YAML -> converts to string.
*/
export function extractFrontmatterId(markdown: string): string | null {
const lines = markdown.split(/\r?\n/);
// Check if file starts with frontmatter delimiter
if (lines.length === 0 || lines[0]?.trim() !== "---") {
return null;
}
// Find closing delimiter
let endIndex = -1;
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (line && line.trim() === "---") {
endIndex = i;
break;
}
}
if (endIndex === -1) {
// No closing delimiter found
return null;
}
// Parse YAML between delimiters
const frontmatterLines = lines.slice(1, endIndex);
const frontmatterText = frontmatterLines.join("\n");
// Simple YAML parser for id field
// Match "id: value" or "id:value" (with optional quotes)
const idMatch = frontmatterText.match(/^id\s*:\s*(.+)$/m);
if (!idMatch || !idMatch[1]) {
return null;
}
let idValue = idMatch[1].trim();
// Remove quotes if present
if ((idValue.startsWith('"') && idValue.endsWith('"')) ||
(idValue.startsWith("'") && idValue.endsWith("'"))) {
idValue = idValue.slice(1, -1);
}
// Convert to string (handles numeric values)
return String(idValue);
}
+15
View File
@@ -0,0 +1,15 @@
export interface NodeMeta {
id?: string;
title?: string;
type?: string;
status?: string;
tags?: string[];
date?: string;
}
export interface ParsedEdge {
rawType: string;
targets: string[]; // link texts without [[ ]]
lineStart: number; // 0-based
lineEnd: number; // 0-based
}
+30
View File
@@ -0,0 +1,30 @@
/**
* Graph Schema loader with caching.
*/
import { App, Notice } from "obsidian";
import { normalizeVaultPath } from "../settings";
import { parseGraphSchema, type GraphSchema } from "../mapping/graphSchema";
import { VocabularyLoader } from "../vocab/VocabularyLoader";
export class GraphSchemaLoader {
/**
* Load graph schema from vault.
*/
static async load(app: App, vaultRelativePath: string): Promise<GraphSchema> {
const text = await VocabularyLoader.loadText(app, vaultRelativePath);
return parseGraphSchema(text);
}
/**
* Validate that graph schema file exists in vault.
*/
static async validate(app: App, vaultRelativePath: string): Promise<boolean> {
try {
await VocabularyLoader.loadText(app, vaultRelativePath);
return true;
} catch (e) {
return false;
}
}
}
+66
View File
@@ -0,0 +1,66 @@
export interface MindnetSettings {
edgeVocabularyPath: string; // vault-relativ
graphSchemaPath: string; // vault-relativ (später)
maxHops: number;
strictMode: boolean;
showCanonicalHints: boolean;
chainDirection: "forward" | "backward" | "both";
interviewConfigPath: string; // vault-relativ
autoStartInterviewOnCreate: boolean;
interceptUnresolvedLinkClicks: boolean;
autoStartOnUnresolvedClick: boolean; // Auto-start interview when creating note from unresolved link
bypassModifier: "Alt" | "Ctrl" | "Shift" | "None"; // Modifier key to bypass intercept (Reading View)
editorFollowModifier: "Alt" | "Ctrl" | "Shift" | "None"; // Modifier key required for editor intercept (Live Preview/Source)
waitForFirstModifyAfterCreate: boolean; // Wait for Templater to modify file before starting wizard
waitForModifyTimeoutMs: number; // Timeout in ms for waiting for modify event
debugLogging: boolean; // Enable debug logging for unresolved link handling
adoptNewNotesInEditor: boolean; // Auto-adopt newly created notes in editor
adoptMaxChars: number; // Max content length to consider note as adopt-candidate
adoptConfirmMode: "always" | "onlyLowConfidence" | "never"; // When to show adoption confirmation
highConfidenceWindowMs: number; // Time window in ms for high-confidence adoption
// Semantic mapping builder settings
mappingWrapperCalloutType: string; // default: "abstract"
mappingWrapperTitle: string; // default: "🕸️ Semantic Mapping"
mappingWrapperFolded: boolean; // default: true
defaultEdgeType: string; // default: ""
unassignedHandling: "prompt" | "none" | "defaultType" | "advisor"; // default: "prompt"
allowOverwriteExistingMappings: boolean; // default: false
defaultNotesFolder: string; // default: "" (vault root)
}
export const DEFAULT_SETTINGS: MindnetSettings = {
edgeVocabularyPath: "_system/dictionary/edge_vocabulary.md",
graphSchemaPath: "_system/dictionary/graph_schema.md",
maxHops: 3,
strictMode: false,
showCanonicalHints: false,
chainDirection: "forward",
interviewConfigPath: "_system/dictionary/interview_config.yaml",
autoStartInterviewOnCreate: false,
interceptUnresolvedLinkClicks: true,
autoStartOnUnresolvedClick: true,
bypassModifier: "Alt",
editorFollowModifier: "Ctrl",
waitForFirstModifyAfterCreate: true,
waitForModifyTimeoutMs: 1200,
debugLogging: false,
adoptNewNotesInEditor: true,
adoptMaxChars: 200,
adoptConfirmMode: "onlyLowConfidence",
highConfidenceWindowMs: 3000,
mappingWrapperCalloutType: "abstract",
mappingWrapperTitle: "🕸️ Semantic Mapping",
mappingWrapperFolded: true,
defaultEdgeType: "",
unassignedHandling: "prompt",
allowOverwriteExistingMappings: false,
defaultNotesFolder: "",
};
/**
* Optional helper: normalize to Obsidian vault paths (forward slashes).
*/
export function normalizeVaultPath(p: string): string {
return (p || "").trim().replace(/\\/g, "/");
}
+151
View File
@@ -0,0 +1,151 @@
/**
* Unit tests for filtering and sorting functions.
*/
import { describe, it, expect } from "vitest";
import { applyFilters, sortNotes, groupByType, groupByFolder } from "../../entityPicker/filters";
import type { NoteIndexEntry, FilterOptions, SortOptions } from "../../entityPicker/types";
const createEntry = (
basename: string,
folder: string = "",
type: string | null = null,
mtime: number = 1000
): NoteIndexEntry => ({
path: folder ? `${folder}/${basename}.md` : `${basename}.md`,
folder,
basename,
title: null,
type,
mtime,
});
describe("applyFilters", () => {
const notes: NoteIndexEntry[] = [
createEntry("Note1", "folder1", "type1"),
createEntry("Note2", "folder1/subfolder", "type1"),
createEntry("Note3", "folder2", "type2"),
createEntry("Note4", "", "type1"),
];
it("should filter by folder (including subfolders)", () => {
const options: FilterOptions = {
selectedFolderPath: "folder1",
};
const result = applyFilters(notes, options);
expect(result).toHaveLength(2);
expect(result.map((n) => n.basename)).toEqual(["Note1", "Note2"]);
});
it("should filter by type", () => {
const options: FilterOptions = {
typeSet: new Set(["type1"]),
};
const result = applyFilters(notes, options);
expect(result).toHaveLength(3);
expect(result.map((n) => n.basename)).toEqual(["Note1", "Note2", "Note4"]);
});
it("should filter by search query", () => {
const options: FilterOptions = {
search: "Note1",
};
const result = applyFilters(notes, options);
expect(result).toHaveLength(1);
expect(result[0]?.basename).toBe("Note1");
});
it("should combine multiple filters", () => {
const options: FilterOptions = {
selectedFolderPath: "folder1",
typeSet: new Set(["type1"]),
search: "Note",
};
const result = applyFilters(notes, options);
expect(result).toHaveLength(2);
expect(result.map((n) => n.basename)).toEqual(["Note1", "Note2"]);
});
it("should include none type when requested", () => {
const notesWithNone = [
...notes,
createEntry("Note5", "folder1", null),
];
const options: FilterOptions = {
typeSet: new Set(["type1"]),
includeNoneType: true,
};
const result = applyFilters(notesWithNone, options);
const hasNote5 = result.some((n) => n.basename === "Note5");
expect(hasNote5).toBe(true);
});
});
describe("sortNotes", () => {
const notes: NoteIndexEntry[] = [
createEntry("NoteC", "", null, 3000),
createEntry("NoteA", "", null, 1000),
createEntry("NoteB", "", null, 2000),
];
it("should sort by recent (mtime desc)", () => {
const options: SortOptions = { mode: "recent" };
const result = sortNotes(notes, options);
expect(result.map((n) => n.basename)).toEqual(["NoteC", "NoteB", "NoteA"]);
});
it("should sort alphabetically", () => {
const options: SortOptions = { mode: "alpha" };
const result = sortNotes(notes, options);
expect(result.map((n) => n.basename)).toEqual(["NoteA", "NoteB", "NoteC"]);
});
});
describe("groupByType", () => {
const notes: NoteIndexEntry[] = [
createEntry("Note1", "", "type1"),
createEntry("Note2", "", "type2"),
createEntry("Note3", "", "type1"),
createEntry("Note4", "", null),
];
it("should group notes by type", () => {
const result = groupByType(notes);
expect(result).toHaveLength(3);
const type1Group = result.find((g) => g.groupKey === "type1");
const type2Group = result.find((g) => g.groupKey === "type2");
const noneGroup = result.find((g) => g.groupKey === "(none)");
expect(type1Group?.notes).toHaveLength(2);
expect(type2Group?.notes).toHaveLength(1);
expect(noneGroup?.notes).toHaveLength(1);
});
});
describe("groupByFolder", () => {
const notes: NoteIndexEntry[] = [
createEntry("Note1", "folder1"),
createEntry("Note2", "folder2"),
createEntry("Note3", "folder1"),
createEntry("Note4", ""),
];
it("should group notes by folder", () => {
const result = groupByFolder(notes);
expect(result).toHaveLength(3);
const folder1Group = result.find((g) => g.groupKey === "folder1");
const folder2Group = result.find((g) => g.groupKey === "folder2");
const rootGroup = result.find((g) => g.groupKey === "(root)");
expect(folder1Group?.notes).toHaveLength(2);
expect(folder2Group?.notes).toHaveLength(1);
expect(rootGroup?.notes).toHaveLength(1);
});
});
+56
View File
@@ -0,0 +1,56 @@
/**
* Unit tests for wikilink insertion functions.
*/
import { describe, it, expect } from "vitest";
import { insertWikilink } from "../../entityPicker/wikilink";
describe("insertWikilink", () => {
it("should insert wikilink when no selection", () => {
const text = "Hello world";
const result = insertWikilink(text, 6, 6, "MyNote");
expect(result.text).toBe("Hello [[MyNote]]world");
expect(result.cursorPos).toBe(18); // After "Hello [[MyNote]]"
});
it("should replace selection with wikilink containing selected text", () => {
const text = "Hello world";
const result = insertWikilink(text, 0, 5, "MyNote");
expect(result.text).toBe("[[MyNote|Hello]] world");
expect(result.cursorPos).toBe(20); // After "[[MyNote|Hello]]"
});
it("should handle multiline selection", () => {
const text = "Line 1\nLine 2\nLine 3";
const result = insertWikilink(text, 0, 12, "MyNote");
expect(result.text).toBe("[[MyNote|Line 1\nLine 2]]\nLine 3");
expect(result.cursorPos).toBe(27); // After "[[MyNote|Line 1\nLine 2]]"
});
it("should not delete unrelated text", () => {
const text = "Before selection after";
const result = insertWikilink(text, 7, 16, "MyNote");
expect(result.text).toBe("Before [[MyNote|selection]] after");
expect(result.cursorPos).toBe(31); // After "[[MyNote|selection]]"
});
it("should handle empty text", () => {
const text = "";
const result = insertWikilink(text, 0, 0, "MyNote");
expect(result.text).toBe("[[MyNote]]");
expect(result.cursorPos).toBe(10);
});
it("should handle selection at end of text", () => {
const text = "Hello ";
const result = insertWikilink(text, 6, 6, "MyNote");
expect(result.text).toBe("Hello [[MyNote]]");
expect(result.cursorPos).toBe(16);
});
});
+137
View File
@@ -0,0 +1,137 @@
import { describe, it, expect } from "vitest";
import type { ParsedEdge } from "../../parser/types";
import type { ExportEdge } from "../../export/types";
import { Vocabulary } from "../../vocab/Vocabulary";
import { parseEdgeVocabulary } from "../../vocab/parseEdgeVocabulary";
describe("exportGraph edge mapping", () => {
// Create a minimal vocabulary for testing
const vocabMd = `
| System-Typ (Canonical) | Inverser Typ | Erlaubte Aliasse (User) | Beschreibung |
| :--- | :--- | :--- | :--- |
| \`caused_by\` | \`resulted_in\` | \`wegen\`, \`ausgelöst_durch\` | Test |
| \`impacts\` | \`impacted_by\` | *(Kein Alias)* | Test |
`;
const vocabulary = new Vocabulary(parseEdgeVocabulary(vocabMd));
function createExportEdge(
parsedEdge: ParsedEdge,
source: string,
target: string
): ExportEdge {
const normalized = vocabulary.normalize(parsedEdge.rawType);
return {
source,
target,
rawType: parsedEdge.rawType,
canonicalType: normalized.canonical,
inverseType: normalized.inverse,
sourcePath: source,
lineStart: parsedEdge.lineStart,
lineEnd: parsedEdge.lineEnd,
};
}
it("maps edge with canonical type correctly", () => {
const parsedEdge: ParsedEdge = {
rawType: "caused_by",
targets: ["TargetNote"],
lineStart: 5,
lineEnd: 7,
};
const exportEdge = createExportEdge(parsedEdge, "source.md", "target.md");
expect(exportEdge.rawType).toBe("caused_by");
expect(exportEdge.canonicalType).toBe("caused_by");
expect(exportEdge.inverseType).toBe("resulted_in");
expect(exportEdge.source).toBe("source.md");
expect(exportEdge.target).toBe("target.md");
expect(exportEdge.lineStart).toBe(5);
expect(exportEdge.lineEnd).toBe(7);
});
it("maps edge with alias correctly", () => {
const parsedEdge: ParsedEdge = {
rawType: "wegen",
targets: ["TargetNote"],
lineStart: 10,
lineEnd: 10,
};
const exportEdge = createExportEdge(parsedEdge, "source.md", "target.md");
expect(exportEdge.rawType).toBe("wegen");
expect(exportEdge.canonicalType).toBe("caused_by");
expect(exportEdge.inverseType).toBe("resulted_in");
});
it("maps edge with unknown type correctly", () => {
const parsedEdge: ParsedEdge = {
rawType: "unknown_type",
targets: ["TargetNote"],
lineStart: 0,
lineEnd: 0,
};
const exportEdge = createExportEdge(parsedEdge, "source.md", "target.md");
expect(exportEdge.rawType).toBe("unknown_type");
expect(exportEdge.canonicalType).toBe(null);
expect(exportEdge.inverseType).toBe(null);
});
it("preserves rawType even when canonical is resolved", () => {
const parsedEdge: ParsedEdge = {
rawType: "ausgelöst_durch",
targets: ["TargetNote"],
lineStart: 3,
lineEnd: 3,
};
const exportEdge = createExportEdge(parsedEdge, "source.md", "target.md");
expect(exportEdge.rawType).toBe("ausgelöst_durch");
expect(exportEdge.canonicalType).toBe("caused_by");
expect(exportEdge.inverseType).toBe("resulted_in");
});
it("handles edge without inverse type", () => {
// Use impacts which has no aliases but has inverse
const parsedEdge: ParsedEdge = {
rawType: "impacts",
targets: ["TargetNote"],
lineStart: 0,
lineEnd: 0,
};
const exportEdge = createExportEdge(parsedEdge, "source.md", "target.md");
expect(exportEdge.rawType).toBe("impacts");
expect(exportEdge.canonicalType).toBe("impacts");
expect(exportEdge.inverseType).toBe("impacted_by");
});
it("handles multiple targets per edge", () => {
const parsedEdge: ParsedEdge = {
rawType: "caused_by",
targets: ["Target1", "Target2", "Target3"],
lineStart: 0,
lineEnd: 5,
};
const edge1 = createExportEdge(parsedEdge, "source.md", "target1.md");
const edge2 = createExportEdge(parsedEdge, "source.md", "target2.md");
const edge3 = createExportEdge(parsedEdge, "source.md", "target3.md");
expect(edge1.target).toBe("target1.md");
expect(edge2.target).toBe("target2.md");
expect(edge3.target).toBe("target3.md");
expect(edge1.rawType).toBe("caused_by");
expect(edge2.rawType).toBe("caused_by");
expect(edge3.rawType).toBe("caused_by");
expect(edge1.canonicalType).toBe("caused_by");
expect(edge2.canonicalType).toBe("caused_by");
expect(edge3.canonicalType).toBe("caused_by");
});
});
+369
View File
@@ -0,0 +1,369 @@
import { describe, it, expect } from "vitest";
import type { GraphBuildResult } from "../../graph/types";
import { Vocabulary } from "../../vocab/Vocabulary";
import { parseEdgeVocabulary } from "../../vocab/parseEdgeVocabulary";
import { normalizeTargetToBasename } from "../../graph/resolveTarget";
import { extractFrontmatterId } from "../../parser/parseFrontmatter";
import { parseEdgesFromCallouts } from "../../parser/parseEdgesFromCallouts";
interface FileFixture {
path: string;
basename: string;
content: string;
}
/**
* Pure function to build graph from in-memory fixtures.
* This can be tested without Obsidian App.
*/
function buildGraphFromFixtures(
fixtures: FileFixture[],
vocabulary: Vocabulary
): GraphBuildResult {
const filePathToId = new Map<string, string>();
const basenameLowerToPath = new Map<string, string>();
const idToMeta = new Map<string, { id: string; path: string; basename: string; title?: string }>();
const edges: GraphBuildResult["edges"] = [];
const warnings: GraphBuildResult["warnings"] = {
missingFrontmatterId: [],
missingTargetFile: [],
missingTargetId: [],
};
// First pass: build node maps
for (const file of fixtures) {
const id = extractFrontmatterId(file.content);
// Always add to basenameLowerToPath for target resolution
const basenameLower = file.basename.toLowerCase();
basenameLowerToPath.set(basenameLower, file.path);
if (!id) {
warnings.missingFrontmatterId.push(file.path);
continue;
}
// Extract optional title
let title: string | undefined;
const titleMatch = file.content.match(/^title\s*:\s*(.+)$/m);
if (titleMatch && titleMatch[1]) {
let titleValue = titleMatch[1].trim();
if ((titleValue.startsWith('"') && titleValue.endsWith('"')) ||
(titleValue.startsWith("'") && titleValue.endsWith("'"))) {
titleValue = titleValue.slice(1, -1);
}
title = titleValue;
}
filePathToId.set(file.path, id);
idToMeta.set(id, {
id,
path: file.path,
basename: file.basename,
title,
});
}
// Second pass: build edges
for (const file of fixtures) {
const srcId = filePathToId.get(file.path);
if (!srcId) {
continue;
}
const parsedEdges = parseEdgesFromCallouts(file.content);
for (const parsedEdge of parsedEdges) {
const normalized = vocabulary.normalize(parsedEdge.rawType);
for (const target of parsedEdge.targets) {
if (!target) continue;
const resolvedBase = normalizeTargetToBasename(target);
const targetPath = basenameLowerToPath.get(resolvedBase.toLowerCase());
if (!targetPath) {
warnings.missingTargetFile.push({
srcPath: file.path,
target: target,
});
continue;
}
const dstId = filePathToId.get(targetPath);
if (!dstId) {
warnings.missingTargetId.push({
srcPath: file.path,
targetPath: targetPath,
});
continue;
}
edges.push({
srcId,
dstId,
rawType: parsedEdge.rawType,
canonicalType: normalized.canonical,
inverseType: normalized.inverse,
srcPath: file.path,
dstPath: targetPath,
lineStart: parsedEdge.lineStart,
lineEnd: parsedEdge.lineEnd,
rawTarget: target,
});
}
}
}
return {
filePathToId,
basenameLowerToPath,
idToMeta,
edges,
warnings,
};
}
describe("buildGraphFromFixtures", () => {
const vocabMd = `
| System-Typ (Canonical) | Inverser Typ | Erlaubte Aliasse (User) | Beschreibung |
| :--- | :--- | :--- | :--- |
| \`caused_by\` | \`resulted_in\` | \`wegen\` | Test |
`;
const vocabulary = new Vocabulary(parseEdgeVocabulary(vocabMd));
it("skips files without frontmatter id", () => {
const fixtures: FileFixture[] = [
{
path: "file1.md",
basename: "file1",
content: `---
title: File 1
---
Content.
`,
},
{
path: "file2.md",
basename: "file2",
content: `---
id: node-2
title: File 2
---
Content.
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
expect(result.warnings.missingFrontmatterId).toEqual(["file1.md"]);
expect(result.idToMeta.has("node-2")).toBe(true);
expect(result.idToMeta.has("node-1")).toBe(false);
});
it("resolves targets with aliases and headings", () => {
const fixtures: FileFixture[] = [
{
path: "source.md",
basename: "source",
content: `---
id: src-1
---
> [!edge] caused_by
> [[target#section|Alias]]
`,
},
{
path: "target.md",
basename: "target",
content: `---
id: tgt-1
---
Content.
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
expect(result.edges.length).toBe(1);
const edge = result.edges[0];
if (!edge) throw new Error("Expected edge");
expect(edge.srcId).toBe("src-1");
expect(edge.dstId).toBe("tgt-1");
expect(edge.rawTarget).toBe("target#section|Alias");
expect(edge.canonicalType).toBe("caused_by");
});
it("creates edges with correct srcId and dstId", () => {
const fixtures: FileFixture[] = [
{
path: "a.md",
basename: "a",
content: `---
id: node-a
---
> [!edge] caused_by
> [[b]]
`,
},
{
path: "b.md",
basename: "b",
content: `---
id: node-b
---
Content.
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
expect(result.edges.length).toBe(1);
const edge = result.edges[0];
if (!edge) throw new Error("Expected edge");
expect(edge.srcId).toBe("node-a");
expect(edge.dstId).toBe("node-b");
expect(edge.srcPath).toBe("a.md");
expect(edge.dstPath).toBe("b.md");
});
it("warns about missing target file", () => {
const fixtures: FileFixture[] = [
{
path: "source.md",
basename: "source",
content: `---
id: src-1
---
> [!edge] caused_by
> [[missing]]
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
expect(result.edges.length).toBe(0);
expect(result.warnings.missingTargetFile.length).toBe(1);
expect(result.warnings.missingTargetFile[0]?.target).toBe("missing");
});
it("warns about target file without id", () => {
const fixtures: FileFixture[] = [
{
path: "source.md",
basename: "source",
content: `---
id: src-1
---
> [!edge] caused_by
> [[target]]
`,
},
{
path: "target.md",
basename: "target",
content: `---
title: Target
---
Content without id.
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
// Target file exists but has no ID, so it's added to basenameLowerToPath
// but not to filePathToId, so we get missingTargetId warning
expect(result.edges.length).toBe(0);
expect(result.warnings.missingTargetId.length).toBe(1);
const warning = result.warnings.missingTargetId[0];
if (!warning) throw new Error("Expected missingTargetId warning");
expect(warning.targetPath).toBe("target.md");
expect(warning.srcPath).toBe("source.md");
});
it("handles unknown edge types", () => {
const fixtures: FileFixture[] = [
{
path: "a.md",
basename: "a",
content: `---
id: node-a
---
> [!edge] unknown_type
> [[b]]
`,
},
{
path: "b.md",
basename: "b",
content: `---
id: node-b
---
Content.
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
expect(result.edges.length).toBe(1);
const edge = result.edges[0];
if (!edge) throw new Error("Expected edge");
expect(edge.rawType).toBe("unknown_type");
expect(edge.canonicalType).toBe(null);
expect(edge.inverseType).toBe(null);
});
it("handles aliases in edge types", () => {
const fixtures: FileFixture[] = [
{
path: "a.md",
basename: "a",
content: `---
id: node-a
---
> [!edge] wegen
> [[b]]
`,
},
{
path: "b.md",
basename: "b",
content: `---
id: node-b
---
Content.
`,
},
];
const result = buildGraphFromFixtures(fixtures, vocabulary);
expect(result.edges.length).toBe(1);
const edge = result.edges[0];
if (!edge) throw new Error("Expected edge");
expect(edge.rawType).toBe("wegen");
expect(edge.canonicalType).toBe("caused_by");
expect(edge.inverseType).toBe("resulted_in");
});
});
+116
View File
@@ -0,0 +1,116 @@
import { describe, it, expect } from "vitest";
import type { EdgeRecord } from "../../graph/types";
import { buildIndex } from "../../graph/GraphIndex";
describe("buildIndex", () => {
it("builds outgoing map correctly", () => {
const edges: EdgeRecord[] = [
{
srcId: "a",
dstId: "b",
rawType: "caused_by",
canonicalType: "caused_by",
inverseType: "resulted_in",
srcPath: "a.md",
dstPath: "b.md",
lineStart: 0,
lineEnd: 0,
rawTarget: "b",
},
{
srcId: "a",
dstId: "c",
rawType: "impacts",
canonicalType: "impacts",
inverseType: "impacted_by",
srcPath: "a.md",
dstPath: "c.md",
lineStart: 1,
lineEnd: 1,
rawTarget: "c",
},
];
const index = buildIndex(edges);
expect(index.outgoing.get("a")?.length).toBe(2);
const bOutgoing = index.outgoing.get("b");
expect(bOutgoing === undefined || bOutgoing.length === 0).toBe(true);
const cOutgoing = index.outgoing.get("c");
expect(cOutgoing === undefined || cOutgoing.length === 0).toBe(true);
});
it("builds incoming map correctly", () => {
const edges: EdgeRecord[] = [
{
srcId: "a",
dstId: "b",
rawType: "caused_by",
canonicalType: "caused_by",
inverseType: "resulted_in",
srcPath: "a.md",
dstPath: "b.md",
lineStart: 0,
lineEnd: 0,
rawTarget: "b",
},
{
srcId: "c",
dstId: "b",
rawType: "impacts",
canonicalType: "impacts",
inverseType: "impacted_by",
srcPath: "c.md",
dstPath: "b.md",
lineStart: 0,
lineEnd: 0,
rawTarget: "b",
},
];
const index = buildIndex(edges);
const aIncoming = index.incoming.get("a");
expect(aIncoming === undefined || aIncoming.length === 0).toBe(true);
expect(index.incoming.get("b")?.length).toBe(2);
const cIncoming = index.incoming.get("c");
expect(cIncoming === undefined || cIncoming.length === 0).toBe(true);
});
it("sorts edges deterministically", () => {
const edges: EdgeRecord[] = [
{
srcId: "a",
dstId: "z",
rawType: "caused_by",
canonicalType: "caused_by",
inverseType: null,
srcPath: "a.md",
dstPath: "z.md",
lineStart: 0,
lineEnd: 0,
rawTarget: "z",
},
{
srcId: "a",
dstId: "b",
rawType: "caused_by",
canonicalType: "caused_by",
inverseType: null,
srcPath: "a.md",
dstPath: "b.md",
lineStart: 0,
lineEnd: 0,
rawTarget: "b",
},
];
const index = buildIndex(edges);
const outgoing = index.outgoing.get("a");
if (!outgoing) throw new Error("Expected outgoing edges");
expect(outgoing.length).toBe(2);
expect(outgoing[0]?.dstId).toBe("b");
expect(outgoing[1]?.dstId).toBe("z");
});
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect } from "vitest";
import { normalizeTargetToBasename } from "../../graph/resolveTarget";
describe("normalizeTargetToBasename", () => {
it("returns basename for simple target", () => {
expect(normalizeTargetToBasename("foo")).toBe("foo");
});
it("removes alias separator", () => {
expect(normalizeTargetToBasename("foo|bar")).toBe("foo");
});
it("removes heading separator", () => {
expect(normalizeTargetToBasename("foo#sec")).toBe("foo");
});
it("removes heading separator when alias is present", () => {
expect(normalizeTargetToBasename("foo#sec|bar")).toBe("foo");
});
it("removes alias separator when heading is in alias", () => {
expect(normalizeTargetToBasename("foo|bar#sec")).toBe("foo");
});
it("handles whitespace", () => {
expect(normalizeTargetToBasename(" foo ")).toBe("foo");
expect(normalizeTargetToBasename("foo | bar")).toBe("foo");
});
});
+181
View File
@@ -0,0 +1,181 @@
import { describe, it, expect } from "vitest";
import type { EdgeRecord } from "../../graph/types";
import { buildIndex } from "../../graph/GraphIndex";
import { traverseForward, traverseBackward } from "../../graph/traverse";
function createEdge(
srcId: string,
dstId: string,
rawType: string,
canonicalType: string | null
): EdgeRecord {
return {
srcId,
dstId,
rawType,
canonicalType,
inverseType: null,
srcPath: `${srcId}.md`,
dstPath: `${dstId}.md`,
lineStart: 0,
lineEnd: 0,
rawTarget: dstId,
};
}
describe("traverseForward", () => {
it("traverses simple chain", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("b", "c", "caused_by", "caused_by"),
];
const index = buildIndex(edges);
const paths = traverseForward(index, "a", 3, 200);
expect(paths.length).toBeGreaterThan(0);
const path = paths[0];
if (!path) throw new Error("Expected path");
expect(path.nodes).toContain("a");
expect(path.nodes).toContain("b");
expect(path.nodes).toContain("c");
});
it("respects maxHops", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("b", "c", "caused_by", "caused_by"),
createEdge("c", "d", "caused_by", "caused_by"),
createEdge("d", "e", "caused_by", "caused_by"),
];
const index = buildIndex(edges);
const paths = traverseForward(index, "a", 2, 200);
for (const path of paths) {
expect(path.nodes.length).toBeLessThanOrEqual(3); // maxHops + 1
expect(path.edges.length).toBeLessThanOrEqual(2); // maxHops
}
});
it("avoids cycles", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("b", "a", "caused_by", "caused_by"), // cycle
];
const index = buildIndex(edges);
const paths = traverseForward(index, "a", 5, 200);
// Should not have paths longer than 2 nodes (a -> b, but not back to a)
for (const path of paths) {
const nodeCounts = new Map<string, number>();
for (const nodeId of path.nodes) {
nodeCounts.set(nodeId, (nodeCounts.get(nodeId) || 0) + 1);
}
// Each node should appear at most once
for (const count of nodeCounts.values()) {
expect(count).toBe(1);
}
}
});
it("ignores edges with null canonicalType", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "unknown", null),
createEdge("a", "c", "caused_by", "caused_by"),
];
const index = buildIndex(edges);
const paths = traverseForward(index, "a", 3, 200);
// Should only find path to c, not b
const hasPathToB = paths.some(p => p.nodes.includes("b"));
const hasPathToC = paths.some(p => p.nodes.includes("c"));
expect(hasPathToB).toBe(false);
expect(hasPathToC).toBe(true);
});
it("filters by allowedCanonicals", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("a", "c", "impacts", "impacts"),
];
const index = buildIndex(edges);
const allowed = new Set<string>(["caused_by"]);
const paths = traverseForward(index, "a", 3, 200, allowed);
// Should only find path to b, not c
const hasPathToB = paths.some(p => p.nodes.includes("b"));
const hasPathToC = paths.some(p => p.nodes.includes("c"));
expect(hasPathToB).toBe(true);
expect(hasPathToC).toBe(false);
});
it("respects maxPaths limit", () => {
// Create a star graph with many outgoing edges
const edges: EdgeRecord[] = [];
for (let i = 0; i < 100; i++) {
edges.push(createEdge("a", `b${i}`, "caused_by", "caused_by"));
}
const index = buildIndex(edges);
const paths = traverseForward(index, "a", 3, 50);
expect(paths.length).toBeLessThanOrEqual(50);
});
});
describe("traverseBackward", () => {
it("traverses backward chain", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("c", "b", "caused_by", "caused_by"),
];
const index = buildIndex(edges);
const paths = traverseBackward(index, "b", 3, 200);
expect(paths.length).toBeGreaterThan(0);
const hasPathFromA = paths.some(p => p.nodes.includes("a"));
const hasPathFromC = paths.some(p => p.nodes.includes("c"));
expect(hasPathFromA).toBe(true);
expect(hasPathFromC).toBe(true);
});
it("respects maxHops in backward traversal", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("c", "a", "caused_by", "caused_by"),
createEdge("d", "c", "caused_by", "caused_by"),
];
const index = buildIndex(edges);
const paths = traverseBackward(index, "b", 2, 200);
for (const path of paths) {
expect(path.nodes.length).toBeLessThanOrEqual(3); // maxHops + 1
}
});
it("avoids cycles in backward traversal", () => {
const edges: EdgeRecord[] = [
createEdge("a", "b", "caused_by", "caused_by"),
createEdge("b", "a", "caused_by", "caused_by"), // cycle
];
const index = buildIndex(edges);
const paths = traverseBackward(index, "a", 5, 200);
for (const path of paths) {
const nodeCounts = new Map<string, number>();
for (const nodeId of path.nodes) {
nodeCounts.set(nodeId, (nodeCounts.get(nodeId) || 0) + 1);
}
for (const count of nodeCounts.values()) {
expect(count).toBe(1);
}
}
});
});
@@ -0,0 +1,117 @@
import { describe, it, expect } from "vitest";
import {
extractTargetFromData,
extractBasenameFromTarget,
} from "../../interview/extractTargetFromAnchor";
describe("extractBasenameFromTarget", () => {
it("preserves simple basename", () => {
expect(extractBasenameFromTarget("test-note")).toBe("test-note");
});
it("preserves spaces and case", () => {
expect(extractBasenameFromTarget("My Note")).toBe("My Note");
expect(extractBasenameFromTarget("My Test Note")).toBe("My Test Note");
});
it("removes alias separator", () => {
expect(extractBasenameFromTarget("test-note|Alias Text")).toBe("test-note");
expect(extractBasenameFromTarget("My Note|Display Name")).toBe("My Note");
});
it("removes heading separator", () => {
expect(extractBasenameFromTarget("test-note#Section")).toBe("test-note");
expect(extractBasenameFromTarget("My Note#Section")).toBe("My Note");
});
it("removes alias and heading", () => {
expect(extractBasenameFromTarget("test-note#Section|Alias")).toBe("test-note");
expect(extractBasenameFromTarget("My Note#Section|Alias")).toBe("My Note");
});
it("handles alias before heading", () => {
expect(extractBasenameFromTarget("test-note|Alias#Section")).toBe("test-note");
});
it("trims whitespace", () => {
expect(extractBasenameFromTarget(" test-note ")).toBe("test-note");
expect(extractBasenameFromTarget(" My Note ")).toBe("My Note");
});
});
describe("extractTargetFromData", () => {
it("extracts from data-href attribute", () => {
const result = extractTargetFromData("test-note", null);
expect(result).toBe("test-note");
});
it("extracts from data-href with alias", () => {
const result = extractTargetFromData("test-note|Alias Text", null);
expect(result).toBe("test-note");
});
it("extracts from data-href with heading", () => {
const result = extractTargetFromData("test-note#Section", null);
expect(result).toBe("test-note");
});
it("extracts from data-href with alias and heading", () => {
const result = extractTargetFromData("test-note#Section|Alias", null);
expect(result).toBe("test-note");
});
it("preserves spaces from data-href", () => {
const result = extractTargetFromData("My Note", null);
expect(result).toBe("My Note");
});
it("preserves spaces from data-href with alias", () => {
const result = extractTargetFromData("My Note|Display", null);
expect(result).toBe("My Note");
});
it("falls back to text content if data-href missing", () => {
const result = extractTargetFromData(null, "test-note");
expect(result).toBe("test-note");
});
it("falls back to text content with alias", () => {
const result = extractTargetFromData(null, "test-note|Alias Text");
expect(result).toBe("test-note");
});
it("preserves spaces from text content", () => {
const result = extractTargetFromData(null, "My Note");
expect(result).toBe("My Note");
});
it("returns null if neither data-href nor text content", () => {
const result = extractTargetFromData(null, null);
expect(result).toBe(null);
});
it("prefers data-href over text content", () => {
const result = extractTargetFromData("data-href-note", "text-note");
expect(result).toBe("data-href-note");
});
it("trims whitespace from text content", () => {
const result = extractTargetFromData(null, " test-note ");
expect(result).toBe("test-note");
});
it("handles Live Preview format (data-href with spaces)", () => {
const result = extractTargetFromData("My Live Preview Note", null);
expect(result).toBe("My Live Preview Note");
});
it("handles Live Preview format with alias", () => {
const result = extractTargetFromData("My Note|Display Text", null);
expect(result).toBe("My Note");
});
it("handles Live Preview format with heading", () => {
const result = extractTargetFromData("My Note#Section", null);
expect(result).toBe("My Note");
});
});
+520
View File
@@ -0,0 +1,520 @@
import { describe, it, expect } from "vitest";
import {
createLoopState,
setDraftField,
isDraftDirty,
commitDraft,
startEdit,
deleteItem,
moveItemUp,
moveItemDown,
clearDraft,
setActiveItemStepIndex,
itemNextStep,
itemPrevStep,
resetItemWizard,
type LoopRuntimeState,
} from "../../interview/loopState";
describe("loopState", () => {
describe("createLoopState", () => {
it("should create initial empty state", () => {
const state = createLoopState();
expect(state.items).toEqual([]);
expect(state.draft).toEqual({});
expect(state.editIndex).toBeNull();
});
});
describe("setDraftField", () => {
it("should set a field in draft", () => {
const state = createLoopState();
const newState = setDraftField(state, "field1", "value1");
expect(newState.draft.field1).toBe("value1");
expect(newState.items).toEqual([]);
expect(newState.editIndex).toBeNull();
});
it("should update existing field", () => {
const state = createLoopState();
let newState = setDraftField(state, "field1", "value1");
newState = setDraftField(newState, "field1", "value2");
expect(newState.draft.field1).toBe("value2");
});
it("should not mutate original state", () => {
const state = createLoopState();
setDraftField(state, "field1", "value1");
expect(state.draft).toEqual({});
});
});
describe("isDraftDirty", () => {
it("should return false for empty draft", () => {
expect(isDraftDirty({})).toBe(false);
});
it("should return true for non-empty string", () => {
expect(isDraftDirty({ text: "content" })).toBe(true);
});
it("should return false for empty string", () => {
expect(isDraftDirty({ text: "" })).toBe(false);
expect(isDraftDirty({ text: " " })).toBe(false);
});
it("should return true for boolean true", () => {
expect(isDraftDirty({ flag: true })).toBe(true);
});
it("should return false for boolean false", () => {
expect(isDraftDirty({ flag: false })).toBe(false);
});
it("should return true for non-zero number", () => {
expect(isDraftDirty({ count: 5 })).toBe(true);
expect(isDraftDirty({ count: -1 })).toBe(true);
});
it("should return false for zero", () => {
expect(isDraftDirty({ count: 0 })).toBe(false);
});
it("should return true for non-empty array", () => {
expect(isDraftDirty({ items: [1, 2] })).toBe(true);
});
it("should return false for empty array", () => {
expect(isDraftDirty({ items: [] })).toBe(false);
});
it("should return true for non-empty object", () => {
expect(isDraftDirty({ obj: { key: "value" } })).toBe(true);
});
it("should return false for empty object", () => {
expect(isDraftDirty({ obj: {} })).toBe(false);
});
it("should ignore null and undefined", () => {
expect(isDraftDirty({ nullVal: null, undefinedVal: undefined })).toBe(false);
});
});
describe("commitDraft", () => {
it("should add new item when editIndex is null", () => {
const state = createLoopState();
let newState = setDraftField(state, "field1", "value1");
newState = commitDraft(newState);
expect(newState.items.length).toBe(1);
expect(newState.items[0]).toEqual({ field1: "value1" });
expect(newState.draft).toEqual({});
expect(newState.editIndex).toBeNull();
});
it("should update existing item when editIndex is set", () => {
const state: LoopRuntimeState = {
items: [{ field1: "old" }],
draft: { field1: "new" },
editIndex: 0,
activeItemStepIndex: 0,
};
const newState = commitDraft(state);
expect(newState.items.length).toBe(1);
expect(newState.items[0]).toEqual({ field1: "new" });
expect(newState.draft).toEqual({});
expect(newState.editIndex).toBeNull();
});
it("should not commit if draft is not dirty", () => {
const state = createLoopState();
const newState = commitDraft(state);
expect(newState.items.length).toBe(0);
expect(newState.draft).toEqual({});
});
it("should not mutate original state", () => {
const state = createLoopState();
let newState = setDraftField(state, "field1", "value1");
commitDraft(newState);
expect(newState.draft).toEqual({ field1: "value1" });
});
});
describe("startEdit", () => {
it("should load item into draft and set editIndex", () => {
const state: LoopRuntimeState = {
items: [{ field1: "value1", field2: "value2" }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = startEdit(state, 0);
expect(newState.draft).toEqual({ field1: "value1", field2: "value2" });
expect(newState.editIndex).toBe(0);
expect(newState.items.length).toBe(1);
});
it("should handle invalid index", () => {
const state: LoopRuntimeState = {
items: [{ field1: "value1" }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = startEdit(state, 5);
expect(newState).toBe(state); // Should return unchanged
});
it("should not mutate original state", () => {
const state: LoopRuntimeState = {
items: [{ field1: "value1" }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
startEdit(state, 0);
expect(state.draft).toEqual({});
expect(state.editIndex).toBeNull();
});
});
describe("deleteItem", () => {
it("should delete item at index", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }, { id: 3 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = deleteItem(state, 1);
expect(newState.items.length).toBe(2);
expect(newState.items[0]).toEqual({ id: 1 });
expect(newState.items[1]).toEqual({ id: 3 });
});
it("should clear draft if editing deleted item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }],
draft: { id: 2 },
editIndex: 1,
activeItemStepIndex: 1,
};
const newState = deleteItem(state, 1);
expect(newState.items.length).toBe(1);
expect(newState.editIndex).toBeNull();
expect(newState.draft).toEqual({});
});
it("should adjust editIndex when deleting before edited item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }, { id: 3 }],
draft: { id: 3 },
editIndex: 2,
activeItemStepIndex: 0,
};
const newState = deleteItem(state, 1);
expect(newState.items.length).toBe(2);
expect(newState.editIndex).toBe(1); // Adjusted from 2 to 1
});
it("should handle invalid index", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = deleteItem(state, 5);
expect(newState).toBe(state); // Should return unchanged
});
});
describe("moveItemUp", () => {
it("should move item up", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }, { id: 3 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = moveItemUp(state, 1);
expect(newState.items[0]).toEqual({ id: 2 });
expect(newState.items[1]).toEqual({ id: 1 });
expect(newState.items[2]).toEqual({ id: 3 });
});
it("should adjust editIndex when moving edited item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }],
draft: { id: 2 },
editIndex: 1,
activeItemStepIndex: 0,
};
const newState = moveItemUp(state, 1);
expect(newState.items[0]).toEqual({ id: 2 });
expect(newState.editIndex).toBe(0);
});
it("should adjust editIndex when moving item before edited item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }, { id: 3 }],
draft: { id: 3 },
editIndex: 2,
activeItemStepIndex: 0,
};
const newState = moveItemUp(state, 1);
// After moving item 1 up: [id:2, id:1, id:3]
expect(newState.items[0]).toEqual({ id: 2 });
expect(newState.items[1]).toEqual({ id: 1 });
expect(newState.items[2]).toEqual({ id: 3 }); // Item 3 stays at index 2
expect(newState.editIndex).toBe(2); // Still editing item 3, still at index 2
});
it("should not move first item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = moveItemUp(state, 0);
expect(newState).toBe(state); // Should return unchanged
});
it("should handle invalid index", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = moveItemUp(state, 5);
expect(newState).toBe(state); // Should return unchanged
});
});
describe("moveItemDown", () => {
it("should move item down", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }, { id: 3 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = moveItemDown(state, 1);
expect(newState.items[0]).toEqual({ id: 1 });
expect(newState.items[1]).toEqual({ id: 3 });
expect(newState.items[2]).toEqual({ id: 2 });
});
it("should adjust editIndex when moving edited item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }],
draft: { id: 1 },
editIndex: 0,
activeItemStepIndex: 0,
};
const newState = moveItemDown(state, 0);
expect(newState.items[0]).toEqual({ id: 2 });
expect(newState.items[1]).toEqual({ id: 1 });
expect(newState.editIndex).toBe(1);
});
it("should not move last item", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }, { id: 2 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = moveItemDown(state, 1);
expect(newState).toBe(state); // Should return unchanged
});
it("should handle invalid index", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }],
draft: {},
editIndex: null,
activeItemStepIndex: 0,
};
const newState = moveItemDown(state, 5);
expect(newState).toBe(state); // Should return unchanged
});
});
describe("clearDraft", () => {
it("should clear draft and reset editIndex", () => {
const state: LoopRuntimeState = {
items: [{ id: 1 }],
draft: { field1: "value1" },
editIndex: 0,
activeItemStepIndex: 2,
};
const newState = clearDraft(state);
expect(newState.draft).toEqual({});
expect(newState.editIndex).toBeNull();
expect(newState.items.length).toBe(1);
});
it("should not mutate original state", () => {
const state: LoopRuntimeState = {
items: [],
draft: { field1: "value1" },
editIndex: 0,
activeItemStepIndex: 1,
};
clearDraft(state);
expect(state.draft).toEqual({ field1: "value1" });
expect(state.editIndex).toBe(0);
expect(state.activeItemStepIndex).toBe(1);
});
});
describe("subwizard navigation", () => {
it("should set active item step index", () => {
const state = createLoopState();
const newState = setActiveItemStepIndex(state, 2);
expect(newState.activeItemStepIndex).toBe(2);
expect(newState.items).toEqual([]);
});
it("should not set negative index", () => {
const state = createLoopState();
const newState = setActiveItemStepIndex(state, -1);
expect(newState).toBe(state); // Should return unchanged
});
it("should move to next step", () => {
const state = createLoopState();
let newState = itemNextStep(state, 3);
expect(newState.activeItemStepIndex).toBe(1);
newState = itemNextStep(newState, 3);
expect(newState.activeItemStepIndex).toBe(2);
});
it("should not move beyond last step", () => {
const state: LoopRuntimeState = {
items: [],
draft: {},
editIndex: null,
activeItemStepIndex: 2,
};
const newState = itemNextStep(state, 3);
expect(newState).toBe(state); // Should return unchanged
});
it("should move to previous step", () => {
const state: LoopRuntimeState = {
items: [],
draft: {},
editIndex: null,
activeItemStepIndex: 2,
};
let newState = itemPrevStep(state);
expect(newState.activeItemStepIndex).toBe(1);
newState = itemPrevStep(newState);
expect(newState.activeItemStepIndex).toBe(0);
});
it("should not move before first step", () => {
const state = createLoopState();
const newState = itemPrevStep(state);
expect(newState).toBe(state); // Should return unchanged
});
it("should reset item wizard to first step", () => {
const state: LoopRuntimeState = {
items: [],
draft: {},
editIndex: null,
activeItemStepIndex: 3,
};
const newState = resetItemWizard(state);
expect(newState.activeItemStepIndex).toBe(0);
});
it("should reset to first step when starting edit", () => {
const state: LoopRuntimeState = {
items: [{ field1: "value1" }],
draft: {},
editIndex: null,
activeItemStepIndex: 2,
};
const newState = startEdit(state, 0);
expect(newState.activeItemStepIndex).toBe(0);
expect(newState.editIndex).toBe(0);
});
it("should reset to first step when committing draft", () => {
const state: LoopRuntimeState = {
items: [],
draft: { field1: "value1" },
editIndex: null,
activeItemStepIndex: 2,
};
const newState = commitDraft(state);
expect(newState.activeItemStepIndex).toBe(0);
expect(newState.items.length).toBe(1);
});
it("should allow commit:on_next even when not on last step", () => {
// Test that commit logic works regardless of activeItemStepIndex
const state: LoopRuntimeState = {
items: [],
draft: { field1: "value1", field2: "value2" },
editIndex: null,
activeItemStepIndex: 1, // Not on last step
};
// Draft is dirty, should commit
expect(isDraftDirty(state.draft)).toBe(true);
const newState = commitDraft(state);
expect(newState.items.length).toBe(1);
expect(newState.activeItemStepIndex).toBe(0);
expect(newState.draft).toEqual({});
});
});
});
@@ -0,0 +1,348 @@
import { describe, it, expect } from "vitest";
import { parseInterviewConfig, validateConfig } from "../../interview/parseInterviewConfig";
import type { InterviewConfig } from "../../interview/types";
describe("parseInterviewConfig", () => {
const fixtureYaml = `
version: "2.0"
frontmatterWhitelist:
- title
- id
- date
- tags
profiles:
- key: profile1
label: "Test Profile 1"
note_type: "note"
group: "test"
defaults:
template: "default"
steps:
- type: loop
key: items_loop
label: "Items Loop"
items:
- type: capture_frontmatter
key: title_field
label: "Title"
field: title
required: true
- type: capture_text
key: content_field
label: "Content"
required: false
- type: llm_dialog
key: llm_step
label: "LLM Dialog"
prompt: "What is the main topic?"
system_prompt: "You are a helpful assistant."
model: "gpt-4"
temperature: 0.7
max_tokens: 500
- key: profile2
label: "Test Profile 2"
note_type: "interview"
steps:
- type: capture_frontmatter
key: date_field
field: date
required: false
- type: llm_dialog
key: analysis
prompt: "Analyze the content"
`;
it("parses YAML correctly", () => {
const result = parseInterviewConfig(fixtureYaml);
expect(result.errors.length).toBe(0);
expect(result.config.version).toBe("2.0");
expect(result.config.frontmatterWhitelist).toEqual(["title", "id", "date", "tags"]);
expect(result.config.profiles.length).toBe(2);
});
it("parses profile structure correctly", () => {
const result = parseInterviewConfig(fixtureYaml);
const profile1 = result.config.profiles[0];
if (!profile1) throw new Error("Expected profile1");
expect(profile1.key).toBe("profile1");
expect(profile1.label).toBe("Test Profile 1");
expect(profile1.note_type).toBe("note");
expect(profile1.group).toBe("test");
expect(profile1.defaults).toEqual({ template: "default" });
expect(profile1.steps.length).toBe(2);
});
it("parses loop step correctly", () => {
const result = parseInterviewConfig(fixtureYaml);
const profile1 = result.config.profiles[0];
if (!profile1) throw new Error("Expected profile1");
const loopStep = profile1.steps[0];
if (!loopStep || loopStep.type !== "loop") {
throw new Error("Expected loop step");
}
expect(loopStep.key).toBe("items_loop");
expect(loopStep.label).toBe("Items Loop");
expect(loopStep.items.length).toBe(2);
const firstItem = loopStep.items[0];
if (!firstItem || firstItem.type !== "capture_frontmatter") {
throw new Error("Expected capture_frontmatter step");
}
expect(firstItem.key).toBe("title_field");
expect(firstItem.field).toBe("title");
expect(firstItem.required).toBe(true);
});
it("parses llm_dialog step correctly", () => {
const result = parseInterviewConfig(fixtureYaml);
const profile1 = result.config.profiles[0];
if (!profile1) throw new Error("Expected profile1");
const llmStep = profile1.steps[1];
if (!llmStep || llmStep.type !== "llm_dialog") {
throw new Error("Expected llm_dialog step");
}
expect(llmStep.key).toBe("llm_step");
expect(llmStep.prompt).toBe("What is the main topic?");
expect(llmStep.system_prompt).toBe("You are a helpful assistant.");
expect(llmStep.model).toBe("gpt-4");
expect(llmStep.temperature).toBe(0.7);
expect(llmStep.max_tokens).toBe(500);
});
it("parses capture_frontmatter step correctly", () => {
const result = parseInterviewConfig(fixtureYaml);
const profile2 = result.config.profiles[1];
if (!profile2) throw new Error("Expected profile2");
const captureStep = profile2.steps[0];
if (!captureStep || captureStep.type !== "capture_frontmatter") {
throw new Error("Expected capture_frontmatter step");
}
expect(captureStep.key).toBe("date_field");
expect(captureStep.field).toBe("date");
expect(captureStep.required).toBe(false);
});
it("parses capture_text step correctly", () => {
const result = parseInterviewConfig(fixtureYaml);
const profile1 = result.config.profiles[0];
if (!profile1) throw new Error("Expected profile1");
const loopStep = profile1.steps[0];
if (!loopStep || loopStep.type !== "loop") {
throw new Error("Expected loop step");
}
const captureTextStep = loopStep.items[1];
if (!captureTextStep || captureTextStep.type !== "capture_text") {
throw new Error("Expected capture_text step");
}
expect(captureTextStep.key).toBe("content_field");
expect(captureTextStep.required).toBe(false);
});
it("validates unique profile keys", () => {
const yamlWithDuplicate = `
version: "2.0"
frontmatterWhitelist: []
profiles:
- key: profile1
label: "Profile 1"
note_type: "note"
steps: []
- key: profile1
label: "Profile 1 Duplicate"
note_type: "note"
steps: []
`;
const result = parseInterviewConfig(yamlWithDuplicate);
const validationErrors = validateConfig(result.config);
expect(validationErrors.some(e => e.includes("Duplicate profile key"))).toBe(true);
});
it("validates capture_frontmatter.field in whitelist", () => {
const yamlWithInvalidField = `
version: "2.0"
frontmatterWhitelist:
- title
- id
profiles:
- key: profile1
label: "Profile 1"
note_type: "note"
steps:
- type: capture_frontmatter
key: invalid_field
field: invalid_field_name
`;
const result = parseInterviewConfig(yamlWithInvalidField);
const validationErrors = validateConfig(result.config);
expect(
validationErrors.some(e =>
e.includes("capture_frontmatter field 'invalid_field_name' not in frontmatterWhitelist")
)
).toBe(true);
});
it("validates capture_frontmatter.field in nested loop", () => {
const yamlWithNestedInvalidField = `
version: "2.0"
frontmatterWhitelist:
- title
profiles:
- key: profile1
label: "Profile 1"
note_type: "note"
steps:
- type: loop
key: items
items:
- type: capture_frontmatter
key: invalid
field: invalid_field
`;
const result = parseInterviewConfig(yamlWithNestedInvalidField);
const validationErrors = validateConfig(result.config);
expect(
validationErrors.some(e =>
e.includes("capture_frontmatter field 'invalid_field' not in frontmatterWhitelist")
)
).toBe(true);
});
it("handles invalid YAML gracefully", () => {
const invalidYaml = "invalid: yaml: content: [";
const result = parseInterviewConfig(invalidYaml);
expect(result.errors.length).toBeGreaterThan(0);
expect(result.config.profiles.length).toBe(0);
});
it("handles missing required fields", () => {
const incompleteYaml = `
version: "2.0"
frontmatterWhitelist: []
profiles:
- key: profile1
label: "Profile 1"
# missing note_type
steps: []
`;
const result = parseInterviewConfig(incompleteYaml);
// Profile should be skipped due to missing note_type
expect(result.config.profiles.length).toBe(0);
expect(result.errors.length).toBeGreaterThan(0);
});
it("parses YAML with 'kind' and 'id' fields (real-world format)", () => {
const yamlWithKindAndId = `
version: 2
frontmatter_whitelist:
- id
- title
- type
profiles:
- key: experience_hub
group: experience
label: "Experience – Hub"
note_type: experience
defaults:
status: active
steps:
- id: title
kind: capture_frontmatter
field: title
label: "Hub Titel"
required: true
- id: items
kind: loop
label: "Erlebnisse"
steps:
- id: item_text
kind: capture_text
label: "Erlebnis"
required: true
- id: review
kind: review
label: "Review & Apply"
`;
const result = parseInterviewConfig(yamlWithKindAndId);
// Log errors for debugging
if (result.errors.length > 0) {
console.log("Parse errors:", result.errors);
}
expect(result.errors.length).toBe(0);
expect(result.config.profiles.length).toBe(1);
const profile = result.config.profiles[0];
if (!profile) throw new Error("Expected profile");
expect(profile.key).toBe("experience_hub");
expect(profile.label).toBe("Experience – Hub");
expect(profile.note_type).toBe("experience");
expect(profile.group).toBe("experience");
expect(profile.steps.length).toBe(3);
// First step: capture_frontmatter
const titleStep = profile.steps[0];
if (!titleStep || titleStep.type !== "capture_frontmatter") {
throw new Error("Expected capture_frontmatter step");
}
expect(titleStep.key).toBe("title");
expect(titleStep.field).toBe("title");
expect(titleStep.label).toBe("Hub Titel");
expect(titleStep.required).toBe(true);
// Second step: loop
const loopStep = profile.steps[1];
if (!loopStep || loopStep.type !== "loop") {
throw new Error("Expected loop step");
}
expect(loopStep.key).toBe("items");
expect(loopStep.label).toBe("Erlebnisse");
expect(loopStep.items.length).toBe(1);
const nestedStep = loopStep.items[0];
if (!nestedStep || nestedStep.type !== "capture_text") {
throw new Error("Expected capture_text step in loop");
}
expect(nestedStep.key).toBe("item_text");
expect(nestedStep.label).toBe("Erlebnis");
expect(nestedStep.required).toBe(true);
// Third step: review
const reviewStep = profile.steps[2];
if (!reviewStep || reviewStep.type !== "review") {
throw new Error("Expected review step");
}
expect(reviewStep.key).toBe("review");
expect(reviewStep.label).toBe("Review & Apply");
});
});
+142
View File
@@ -0,0 +1,142 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { InterviewProfile } from "../../interview/types";
describe("Post-run edging integration", () => {
let mockApp: any;
let mockFile: any;
let mockSettings: any;
let mockBuildSemanticMappings: any;
beforeEach(() => {
mockApp = {
vault: {
read: vi.fn().mockResolvedValue("Content"),
},
};
mockFile = {
path: "test.md",
basename: "test",
};
mockSettings = {
mappingWrapperCalloutType: "abstract",
mappingWrapperTitle: "🕸️ Semantic Mapping",
mappingWrapperFolded: true,
unassignedHandling: "prompt",
allowOverwriteExistingMappings: false,
};
mockBuildSemanticMappings = vi.fn().mockResolvedValue({
sectionsProcessed: 2,
sectionsWithMappings: 2,
totalLinks: 5,
existingMappingsKept: 3,
newMappingsAssigned: 2,
unmappedLinksSkipped: 0,
});
});
it("should invoke builder when profile has edging.mode=post_run", async () => {
const profile: InterviewProfile = {
key: "test-profile",
label: "Test Profile",
note_type: "note",
steps: [],
edging: {
mode: "post_run",
},
};
// This is a unit test for the hook path
// In real implementation, this would be called from InterviewWizardModal
const shouldRunEdging = profile.edging?.mode === "post_run";
expect(shouldRunEdging).toBe(true);
});
it("should not invoke builder when profile has edging.mode=none", () => {
const profile: InterviewProfile = {
key: "test-profile",
label: "Test Profile",
note_type: "note",
steps: [],
edging: {
mode: "none",
},
};
const shouldRunEdging = profile.edging?.mode === "post_run";
expect(shouldRunEdging).toBe(false);
});
it("should not invoke builder when profile has no edging config", () => {
const profile: InterviewProfile = {
key: "test-profile",
label: "Test Profile",
note_type: "note",
steps: [],
};
const shouldRunEdging = profile.edging?.mode === "post_run";
expect(shouldRunEdging).toBe(false);
});
it("should use profile edging config over settings", () => {
const profile: InterviewProfile = {
key: "test-profile",
label: "Test Profile",
note_type: "note",
steps: [],
edging: {
mode: "post_run",
wrapperCalloutType: "info",
wrapperTitle: "Custom Title",
wrapperFolded: false,
},
};
const settings = {
mappingWrapperCalloutType: "abstract",
mappingWrapperTitle: "Default Title",
mappingWrapperFolded: true,
};
// Profile config should override settings
const finalCalloutType = profile.edging?.wrapperCalloutType || settings.mappingWrapperCalloutType;
const finalTitle = profile.edging?.wrapperTitle || settings.mappingWrapperTitle;
const finalFolded = profile.edging?.wrapperFolded !== undefined
? profile.edging.wrapperFolded
: settings.mappingWrapperFolded;
expect(finalCalloutType).toBe("info");
expect(finalTitle).toBe("Custom Title");
expect(finalFolded).toBe(false);
});
it("should use settings defaults when profile edging config is partial", () => {
const profile: InterviewProfile = {
key: "test-profile",
label: "Test Profile",
note_type: "note",
steps: [],
edging: {
mode: "post_run",
wrapperCalloutType: "info",
// wrapperTitle and wrapperFolded not specified
},
};
const settings = {
mappingWrapperCalloutType: "abstract",
mappingWrapperTitle: "Default Title",
mappingWrapperFolded: true,
};
const finalCalloutType = profile.edging?.wrapperCalloutType || settings.mappingWrapperCalloutType;
const finalTitle = profile.edging?.wrapperTitle || settings.mappingWrapperTitle;
const finalFolded = profile.edging?.wrapperFolded !== undefined
? profile.edging.wrapperFolded
: settings.mappingWrapperFolded;
expect(finalCalloutType).toBe("info"); // From profile
expect(finalTitle).toBe("Default Title"); // From settings (fallback)
expect(finalFolded).toBe(true); // From settings (fallback)
});
});
+322
View File
@@ -0,0 +1,322 @@
import { describe, it, expect } from "vitest";
import { renderProfileToMarkdown, type RenderAnswers } from "../../interview/renderer";
import type { InterviewProfile } from "../../interview/types";
describe("renderer", () => {
describe("renderProfileToMarkdown", () => {
it("should render experience_cluster profile without generic labels", () => {
const profile: InterviewProfile = {
key: "experience_cluster",
label: "Experience Cluster",
note_type: "experience",
steps: [
{
type: "loop",
key: "experiences",
items: [
{
type: "capture_text",
key: "experience_text",
label: "Erlebnis",
section: "## 🧩 Erlebnisse",
},
],
},
],
};
const answers: RenderAnswers = {
collectedData: new Map(),
loopContexts: new Map([
[
"experiences",
[
{ experience_text: "Erstes wichtiges Erlebnis mit Details" },
{ experience_text: "Zweites Erlebnis mit mehr Kontext" },
],
],
]),
};
const result = renderProfileToMarkdown(profile, answers);
// Should contain the section header and both experiences
expect(result).toContain("## 🧩 Erlebnisse");
expect(result).toContain("Erstes wichtiges Erlebnis mit Details");
expect(result).toContain("Zweites Erlebnis mit mehr Kontext");
// Should NOT contain generic labels
expect(result).not.toContain("## Items");
expect(result).not.toContain("Überschrift 1");
expect(result).not.toContain("Liste 1");
expect(result).not.toContain("Erlebnis 1");
expect(result).not.toContain("Erlebnis 2");
});
it("should render experience_hub minimal case", () => {
const profile: InterviewProfile = {
key: "experience_hub",
label: "Experience Hub",
note_type: "experience",
steps: [
{
type: "loop",
key: "items",
items: [
{
type: "capture_text",
key: "item_text",
label: "Erlebnis",
},
],
},
],
};
const answers: RenderAnswers = {
collectedData: new Map(),
loopContexts: new Map([
[
"items",
[{ item_text: "Ein einzelnes Erlebnis" }],
],
]),
};
const result = renderProfileToMarkdown(profile, answers);
// Should contain the experience text
expect(result).toContain("Ein einzelnes Erlebnis");
// Should NOT contain generic labels
expect(result).not.toContain("## Items");
expect(result).not.toContain("Überschrift");
expect(result).not.toContain("Liste");
});
it("should use output.template for capture_text when provided", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "capture_text",
key: "custom_text",
label: "Custom Text",
output: {
template: "### {field}\n\n{text}",
},
},
],
};
const answers: RenderAnswers = {
collectedData: new Map([["custom_text", "Mein Textinhalt"]]),
loopContexts: new Map(),
};
const result = renderProfileToMarkdown(profile, answers);
expect(result).toContain("### custom_text");
expect(result).toContain("Mein Textinhalt");
});
it("should use output.join for loop when provided", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "loop",
key: "items",
items: [
{
type: "capture_text",
key: "text",
label: "Text",
},
],
output: {
join: "\n- ",
},
},
],
};
const answers: RenderAnswers = {
collectedData: new Map(),
loopContexts: new Map([
[
"items",
[
{ text: "Item 1" },
{ text: "Item 2" },
],
],
]),
};
const result = renderProfileToMarkdown(profile, answers);
// Should use custom join separator
expect(result).toContain("Item 1\n- Item 2");
});
it("should skip empty values", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "capture_text",
key: "empty_text",
label: "Empty Text",
},
{
type: "capture_text",
key: "filled_text",
label: "Filled Text",
},
],
};
const answers: RenderAnswers = {
collectedData: new Map([
["empty_text", ""],
["filled_text", "Content here"],
]),
loopContexts: new Map(),
};
const result = renderProfileToMarkdown(profile, answers);
expect(result).not.toContain("empty_text");
expect(result).toContain("Content here");
});
it("should handle section header for capture_text", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "capture_text",
key: "sectioned_text",
label: "Sectioned Text",
section: "## My Section",
},
],
};
const answers: RenderAnswers = {
collectedData: new Map([["sectioned_text", "Content under section"]]),
loopContexts: new Map(),
};
const result = renderProfileToMarkdown(profile, answers);
expect(result).toContain("## My Section");
expect(result).toContain("Content under section");
});
it("should render multiple loop items correctly", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "loop",
key: "multi_items",
items: [
{
type: "capture_text",
key: "text",
label: "Text",
},
],
},
],
};
const answers: RenderAnswers = {
collectedData: new Map(),
loopContexts: new Map([
[
"multi_items",
[
{ text: "First item" },
{ text: "Second item" },
{ text: "Third item" },
],
],
]),
};
const result = renderProfileToMarkdown(profile, answers);
expect(result).toContain("First item");
expect(result).toContain("Second item");
expect(result).toContain("Third item");
// Should not have item numbers or generic labels
expect(result).not.toMatch(/Item \d+/);
expect(result).not.toContain("## Items");
});
it("should render capture_text_line step", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "capture_text_line",
key: "single_line",
label: "Single Line",
prompt: "Enter a single line of text",
},
],
};
const answers: RenderAnswers = {
collectedData: new Map([["single_line", "This is a single line"]]),
loopContexts: new Map(),
};
const result = renderProfileToMarkdown(profile, answers);
expect(result).toContain("This is a single line");
});
it("should use output.template for capture_text_line when provided", () => {
const profile: InterviewProfile = {
key: "test_profile",
label: "Test Profile",
note_type: "test",
steps: [
{
type: "capture_text_line",
key: "tagged_line",
label: "Tagged Line",
output: {
template: "- {text}",
},
},
],
};
const answers: RenderAnswers = {
collectedData: new Map([["tagged_line", "My tag"]]),
loopContexts: new Map(),
};
const result = renderProfileToMarkdown(profile, answers);
expect(result).toBe("- My tag");
});
});
});
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect } from "vitest";
import { slugify } from "../../interview/slugify";
describe("slugify", () => {
it("converts simple text to slug", () => {
expect(slugify("Hello World")).toBe("hello_world");
});
it("handles special characters", () => {
expect(slugify("Hello-World!")).toBe("hello_world");
});
it("handles accented characters", () => {
expect(slugify("Café")).toBe("cafe");
expect(slugify("Müller")).toBe("muller");
});
it("handles numbers", () => {
expect(slugify("Test123")).toBe("test123");
});
it("collapses multiple separators", () => {
expect(slugify("Hello---World")).toBe("hello_world");
expect(slugify("Hello World")).toBe("hello_world");
});
it("removes leading/trailing separators", () => {
expect(slugify("---Hello---")).toBe("hello");
expect(slugify("___Test___")).toBe("test");
});
it("handles empty string", () => {
expect(slugify("")).toBe("");
});
it("handles only special characters", () => {
expect(slugify("!!!")).toBe("");
expect(slugify("---")).toBe("");
});
it("preserves underscores", () => {
expect(slugify("test_case")).toBe("test_case");
});
it("handles mixed case", () => {
expect(slugify("HelloWorld")).toBe("helloworld");
});
it("handles unicode characters", () => {
expect(slugify("Hello 世界")).toBe("hello");
});
});
@@ -0,0 +1,162 @@
import { describe, it, expect } from "vitest";
import { writeFrontmatter } from "../../interview/writeFrontmatter";
describe("writeFrontmatter", () => {
it("writes basic frontmatter", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test Title",
noteType: "note",
interviewProfile: "profile1",
frontmatterWhitelist: [],
});
expect(result).toContain("id: test123");
expect(result).toContain("title: Test Title");
expect(result).toContain("type: note");
expect(result).toContain("interview_profile: profile1");
expect(result).toContain("---");
});
it("includes whitelisted defaults", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test Title",
noteType: "note",
interviewProfile: "profile1",
defaults: {
template: "default",
author: "John",
invalid: "should not appear",
},
frontmatterWhitelist: ["template", "author"],
});
expect(result).toContain("template: default");
expect(result).toContain("author: John");
expect(result).not.toContain("invalid:");
});
it("quotes strings with special characters", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test: Title",
noteType: "note",
interviewProfile: "profile1",
frontmatterWhitelist: [],
});
expect(result).toContain('title: "Test: Title"');
});
it("handles numbers", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test",
noteType: "note",
interviewProfile: "profile1",
defaults: {
count: 42,
rating: 4.5,
},
frontmatterWhitelist: ["count", "rating"],
});
expect(result).toContain("count: 42");
expect(result).toContain("rating: 4.5");
});
it("handles booleans", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test",
noteType: "note",
interviewProfile: "profile1",
defaults: {
published: true,
draft: false,
},
frontmatterWhitelist: ["published", "draft"],
});
expect(result).toContain("published: true");
expect(result).toContain("draft: false");
});
it("handles null values", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test",
noteType: "note",
interviewProfile: "profile1",
defaults: {
author: null,
},
frontmatterWhitelist: ["author"],
});
expect(result).toContain("author: null");
});
it("handles strings with quotes", () => {
const result = writeFrontmatter({
id: "test123",
title: 'Test "Quote" Title',
noteType: "note",
interviewProfile: "profile1",
frontmatterWhitelist: [],
});
expect(result).toContain('title: "Test \\"Quote\\" Title"');
});
it("handles strings with newlines", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test\nMulti\nLine",
noteType: "note",
interviewProfile: "profile1",
frontmatterWhitelist: [],
});
// YAML will format multiline strings differently, so we just check it's quoted
expect(result).toContain('title: "');
expect(result).toContain("Test");
expect(result).toContain("Multi");
expect(result).toContain("Line");
});
it("handles arrays and objects as JSON strings", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test",
noteType: "note",
interviewProfile: "profile1",
defaults: {
tags: ["tag1", "tag2"],
meta: { key: "value" },
},
frontmatterWhitelist: ["tags", "meta"],
});
expect(result).toContain('tags: "');
expect(result).toContain('meta: "');
});
it("skips non-whitelisted defaults", () => {
const result = writeFrontmatter({
id: "test123",
title: "Test",
noteType: "note",
interviewProfile: "profile1",
defaults: {
allowed: "yes",
forbidden: "no",
},
frontmatterWhitelist: ["allowed"],
});
expect(result).toContain("allowed: yes");
expect(result).not.toContain("forbidden:");
});
});
+205
View File
@@ -0,0 +1,205 @@
import { describe, it, expect } from "vitest";
import type { ParsedEdge } from "../../parser/types";
import { lintParsedEdges } from "../../lint/LintEngine";
import { Vocabulary } from "../../vocab/Vocabulary";
import { parseEdgeVocabulary } from "../../vocab/parseEdgeVocabulary";
describe("lintParsedEdges", () => {
// Create a minimal vocabulary for testing
const vocabMd = `
| System-Typ (Canonical) | Inverser Typ | Erlaubte Aliasse (User) | Beschreibung |
| :--- | :--- | :--- | :--- |
| \`caused_by\` | \`resulted_in\` | \`wegen\`, \`ausgelöst_durch\` | Test |
| \`impacts\` | \`impacted_by\` | *(Kein Alias)* | Test |
`;
const vocabulary = new Vocabulary(parseEdgeVocabulary(vocabMd));
it("reports unknown edge type as ERROR", () => {
const edges: ParsedEdge[] = [
{
rawType: "unknown_type",
targets: [],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>();
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
expect(findings.length).toBe(2); // unknown_edge_type + edge_without_target
const finding = findings.find(f => f.ruleId === "unknown_edge_type");
if (!finding) throw new Error("Expected unknown_edge_type finding");
expect(finding.severity).toBe("ERROR");
expect(finding.message).toContain("unknown_type");
});
it("does not report known aliases as errors or warnings", () => {
const edges: ParsedEdge[] = [
{
rawType: "wegen", // alias, not canonical
targets: ["SomeNote"],
lineStart: 5,
lineEnd: 5,
},
];
const existingFiles = new Set<string>(["SomeNote.md"]);
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
// Should not have unknown_edge_type or alias_not_normalized
const unknownFinding = findings.find(f => f.ruleId === "unknown_edge_type");
expect(unknownFinding).toBeUndefined();
const aliasFinding = findings.find(f => f.ruleId === "alias_not_normalized");
expect(aliasFinding).toBeUndefined();
});
it("reports missing target notes as WARN", () => {
const edges: ParsedEdge[] = [
{
rawType: "caused_by",
targets: ["MissingNote", "ExistingNote"],
lineStart: 0,
lineEnd: 2,
},
];
const existingFiles = new Set<string>(["ExistingNote.md", "ExistingNote"]);
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
const finding = findings.find(f => f.ruleId === "missing_target_note");
if (!finding) throw new Error("Expected missing_target_note finding");
expect(finding.severity).toBe("WARN");
expect(finding.message).toContain("MissingNote");
expect(finding.evidence).toBe("MissingNote");
});
it("reports missing targets even for unknown edge types", () => {
const edges: ParsedEdge[] = [
{
rawType: "unknown_type",
targets: ["MissingNote"],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>();
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
const unknownFinding = findings.find(f => f.ruleId === "unknown_edge_type");
expect(unknownFinding).toBeDefined();
const missingFinding = findings.find(f => f.ruleId === "missing_target_note");
expect(missingFinding).toBeDefined();
});
it("reports edge without targets as WARN", () => {
const edges: ParsedEdge[] = [
{
rawType: "caused_by",
targets: [],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>();
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
const finding = findings.find(f => f.ruleId === "edge_without_target");
if (!finding) throw new Error("Expected edge_without_target finding");
expect(finding.severity).toBe("WARN");
expect(finding.message).toContain("caused_by");
expect(finding.message).toContain("no target notes");
});
it("handles target notes with headings", () => {
const edges: ParsedEdge[] = [
{
rawType: "caused_by",
targets: ["Note#heading"],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>(["Note.md"]);
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
const missingFinding = findings.find(f => f.ruleId === "missing_target_note");
expect(missingFinding).toBeUndefined();
});
it("handles target notes without .md extension", () => {
const edges: ParsedEdge[] = [
{
rawType: "caused_by",
targets: ["NoteName"],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>(["NoteName.md"]);
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
const missingFinding = findings.find(f => f.ruleId === "missing_target_note");
expect(missingFinding).toBeUndefined();
});
it("shows canonical hints when option enabled", () => {
const edges: ParsedEdge[] = [
{
rawType: "wegen", // alias
targets: ["SomeNote"],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>(["SomeNote.md"]);
const findings = lintParsedEdges(edges, vocabulary, existingFiles, { showCanonicalHints: true });
const hintFinding = findings.find(f => f.ruleId === "canonical_hint");
if (!hintFinding) throw new Error("Expected canonical_hint finding");
expect(hintFinding.severity).toBe("INFO");
expect(hintFinding.message).toContain("wegen");
expect(hintFinding.message).toContain("caused_by");
});
it("does not show canonical hints when option disabled", () => {
const edges: ParsedEdge[] = [
{
rawType: "wegen",
targets: ["SomeNote"],
lineStart: 0,
lineEnd: 0,
},
];
const existingFiles = new Set<string>(["SomeNote.md"]);
const findings = lintParsedEdges(edges, vocabulary, existingFiles, { showCanonicalHints: false });
const hintFinding = findings.find(f => f.ruleId === "canonical_hint");
expect(hintFinding).toBeUndefined();
});
it("preserves line numbers in findings", () => {
const edges: ParsedEdge[] = [
{
rawType: "unknown",
targets: [],
lineStart: 42,
lineEnd: 45,
},
];
const existingFiles = new Set<string>();
const findings = lintParsedEdges(edges, vocabulary, existingFiles);
const finding = findings.find(f => f.ruleId === "unknown_edge_type");
if (!finding) throw new Error("Expected finding");
expect(finding.lineStart).toBe(42);
expect(finding.lineEnd).toBe(45);
});
});
+36
View File
@@ -0,0 +1,36 @@
/**
* Unit tests for folder helpers.
*/
import { describe, it, expect } from "vitest";
import { joinFolderAndBasename, ensureUniqueFilePath } from "../../mapping/folderHelpers";
describe("joinFolderAndBasename", () => {
it("should join folder and basename", () => {
expect(joinFolderAndBasename("folder1/folder2", "note.md")).toBe("folder1/folder2/note.md");
});
it("should handle empty folder (root)", () => {
expect(joinFolderAndBasename("", "note.md")).toBe("note.md");
});
it("should handle folder with trailing slash", () => {
expect(joinFolderAndBasename("folder/", "note.md")).toBe("folder/note.md");
});
it("should normalize paths", () => {
expect(joinFolderAndBasename("folder1\\folder2", "note.md")).toBe("folder1/folder2/note.md");
});
it("should trim whitespace", () => {
expect(joinFolderAndBasename(" folder ", " note.md ")).toBe("folder/note.md");
});
});
describe("ensureUniqueFilePath", () => {
// Note: Full tests would require mocking App and vault
// These are basic structure tests
it("should be a function", () => {
expect(typeof ensureUniqueFilePath).toBe("function");
});
});
+97
View File
@@ -0,0 +1,97 @@
/**
* Unit tests for GraphSchema loader.
*/
import { describe, it, expect } from "vitest";
import { parseGraphSchema, getHints } from "../../mapping/graphSchema";
const fixtureSchema = `---
id: graph_schema
title: Graph Topology & Preferences (Atomic)
---
## Source: \`person\`
| Target-Note-type | Typical Edge-Types | Prohibited Edge-Types |
| :--- | :--- | :--- |
| \`skill\` | \`experienced_in\`, \`expert_for\` | \`caused_by\`, \`solves\` |
| \`any\` | \`related_to\` | - |
## Source: \`skill\`
| Target-Note-type | Typical Edge-Types | Prohibited Edge-Types |
| :--- | :--- | :--- |
| \`person\` | \`mastered_by\` | \`consists_of\` |
| \`any\` | \`references\`, \`related_to\` | - |
## Source: \`any\`
| Target-Note-type | Typical Edge-Types | Prohibited Edge-Types |
| :--- | :--- | :--- |
| \`any\` | \`related_to\`, \`references\` | - |
`;
describe("parseGraphSchema", () => {
it("should parse schema with multiple sources", () => {
const schema = parseGraphSchema(fixtureSchema);
expect(schema.schema.has("person")).toBe(true);
expect(schema.schema.has("skill")).toBe(true);
expect(schema.schema.has("any")).toBe(true);
});
it("should parse typical and prohibited edge types", () => {
const schema = parseGraphSchema(fixtureSchema);
const personMap = schema.schema.get("person");
expect(personMap).toBeDefined();
const skillHints = personMap?.get("skill");
expect(skillHints?.typical).toContain("experienced_in");
expect(skillHints?.typical).toContain("expert_for");
expect(skillHints?.prohibited).toContain("caused_by");
expect(skillHints?.prohibited).toContain("solves");
});
it("should handle any fallback", () => {
const schema = parseGraphSchema(fixtureSchema);
const personMap = schema.schema.get("person");
const anyHints = personMap?.get("any");
expect(anyHints?.typical).toContain("related_to");
expect(anyHints?.prohibited).toHaveLength(0);
});
});
describe("getHints", () => {
it("should return exact match", () => {
const schema = parseGraphSchema(fixtureSchema);
const hints = getHints(schema, "person", "skill");
expect(hints.typical).toContain("experienced_in");
expect(hints.prohibited).toContain("caused_by");
});
it("should fallback to target any", () => {
const schema = parseGraphSchema(fixtureSchema);
const hints = getHints(schema, "person", "unknown_type");
expect(hints.typical).toContain("related_to");
});
it("should fallback to source any", () => {
const schema = parseGraphSchema(fixtureSchema);
const hints = getHints(schema, "unknown_source", "person");
// Should fallback to "any" -> "any"
expect(hints.typical).toContain("related_to");
});
it("should fallback to both any", () => {
const schema = parseGraphSchema(fixtureSchema);
const hints = getHints(schema, null, null);
expect(hints.typical).toContain("related_to");
});
});
+126
View File
@@ -0,0 +1,126 @@
/**
* Unit tests for mapping builder.
*/
import { describe, it, expect } from "vitest";
import { buildMappingBlock, insertMappingBlock } from "../../mapping/mappingBuilder";
import type { MappingBuilderOptions } from "../../mapping/mappingBuilder";
const defaultOptions: MappingBuilderOptions = {
wrapperCalloutType: "abstract",
wrapperTitle: "🕸️ Semantic Mapping",
wrapperFolded: true,
defaultEdgeType: "",
assignUnmapped: "none",
};
describe("buildMappingBlock", () => {
it("should return null if no links", () => {
const result = buildMappingBlock([], new Map(), defaultOptions);
expect(result).toBeNull();
});
it("should group links by edgeType", () => {
const links = ["Link1", "Link2", "Link3"];
const mappings = new Map<string, string>([
["Link1", "causes"],
["Link2", "causes"],
["Link3", "enables"],
]);
const result = buildMappingBlock(links, mappings, defaultOptions);
expect(result).not.toBeNull();
expect(result).toContain(">> [!edge] causes");
expect(result).toContain(">> [!edge] enables");
expect(result).toContain(">> [[Link1]]");
expect(result).toContain(">> [[Link2]]");
expect(result).toContain(">> [[Link3]]");
});
it("should separate groups with blank quoted line", () => {
const links = ["Link1", "Link2"];
const mappings = new Map<string, string>([
["Link1", "causes"],
["Link2", "enables"],
]);
const result = buildMappingBlock(links, mappings, defaultOptions);
expect(result).not.toBeNull();
// Check for separator: ">" between groups
const lines = result!.split("\n");
const causesIndex = lines.findIndex((l) => l.includes("[!edge] causes"));
const separatorIndex = causesIndex + 1;
const enablesIndex = lines.findIndex((l) => l.includes("[!edge] enables"));
expect(separatorIndex).toBeLessThan(enablesIndex);
expect(lines[separatorIndex]).toBe(">");
});
it("should skip unmapped links when assignUnmapped is 'none'", () => {
const links = ["Link1", "Link2"];
const mappings = new Map<string, string>([
["Link1", "causes"],
// Link2 has no mapping
]);
const result = buildMappingBlock(links, mappings, defaultOptions);
expect(result).toContain("Link1");
expect(result).not.toContain("Link2");
});
it("should assign defaultType when assignUnmapped is 'defaultType'", () => {
const links = ["Link1", "Link2"];
const mappings = new Map<string, string>([
["Link1", "causes"],
// Link2 has no mapping
]);
const options: MappingBuilderOptions = {
...defaultOptions,
assignUnmapped: "defaultType",
defaultEdgeType: "enables",
};
const result = buildMappingBlock(links, mappings, options);
expect(result).toContain("Link1");
expect(result).toContain("Link2");
expect(result).toContain(">> [!edge] enables");
expect(result).toContain(">> [[Link2]]");
});
});
describe("insertMappingBlock", () => {
it("should insert block with two newlines", () => {
const sectionContent = `# Section
Content here.`;
const mappingBlock = `> [!abstract] 🕸️ Semantic Mapping
>> [!edge] causes
>> [[Link1]]`;
const result = insertMappingBlock(sectionContent, mappingBlock);
expect(result).toContain("Content here.");
expect(result).toContain("🕸️ Semantic Mapping");
// Should have two newlines between
expect(result).toMatch(/Content here\.\n\n> \[!abstract\]/);
});
it("should handle content ending with newlines", () => {
const sectionContent = `# Section
Content here.
`;
const mappingBlock = `> [!abstract] 🕸️ Semantic Mapping`;
const result = insertMappingBlock(sectionContent, mappingBlock);
// Should not add excessive newlines
expect(result.split(/\n\n\n/)).toHaveLength(1);
});
});
@@ -0,0 +1,67 @@
/**
* Unit tests for mapping extractor.
*/
import { describe, it, expect } from "vitest";
import { extractExistingMappings, removeWrapperBlock } from "../../mapping/mappingExtractor";
describe("extractExistingMappings", () => {
it("should extract mappings from edge callouts", () => {
const sectionContent = `# Section
Content with [[Link1]] and [[Link2]].
> [!abstract] 🕸️ Semantic Mapping
>> [!edge] causes
>> [[Link1]]
>> [!edge] enables
>> [[Link2]]
`;
const state = extractExistingMappings(sectionContent, "abstract", "🕸️ Semantic Mapping");
expect(state.existingMappings.get("Link1")).toBe("causes");
expect(state.existingMappings.get("Link2")).toBe("enables");
expect(state.wrapperBlockStartLine).not.toBeNull();
});
it("should detect wrapper block location", () => {
const sectionContent = `# Section
Content.
> [!abstract]- 🕸️ Semantic Mapping
>> [!edge] causes
>> [[Link1]]
> ^map-123
`;
const state = extractExistingMappings(sectionContent, "abstract", "🕸️ Semantic Mapping");
expect(state.wrapperBlockStartLine).toBe(3);
expect(state.wrapperBlockEndLine).toBe(7); // After block-id marker
});
});
describe("removeWrapperBlock", () => {
it("should remove wrapper block from content", () => {
const content = `# Section
Content before.
> [!abstract] 🕸️ Semantic Mapping
>> [!edge] causes
>> [[Link1]]
> ^map-123
Content after.
`;
const result = removeWrapperBlock(content, 3, 7);
expect(result).toContain("Content before.");
expect(result).toContain("Content after.");
expect(result).not.toContain("🕸️ Semantic Mapping");
expect(result).not.toContain("[!edge] causes");
});
});
+81
View File
@@ -0,0 +1,81 @@
/**
* Unit tests for section parser.
*/
import { describe, it, expect } from "vitest";
import { splitIntoSections, extractWikilinks } from "../../mapping/sectionParser";
describe("splitIntoSections", () => {
it("should split note with multiple headings", () => {
const markdown = `# Heading 1
Content with [[Link1]] and [[Link2]].
## Heading 2
More content with [[Link3]].
### Heading 3
Even more content.
`;
const sections = splitIntoSections(markdown);
expect(sections).toHaveLength(4);
expect(sections[0]?.heading).toBeNull();
expect(sections[0]?.headingLevel).toBe(0);
expect(sections[1]?.heading).toBe("Heading 1");
expect(sections[1]?.headingLevel).toBe(1);
expect(sections[2]?.heading).toBe("Heading 2");
expect(sections[2]?.headingLevel).toBe(2);
expect(sections[3]?.heading).toBe("Heading 3");
expect(sections[3]?.headingLevel).toBe(3);
});
it("should extract links per section", () => {
const markdown = `# Section 1
Content with [[Link1]] and [[Link2]].
## Section 2
More content with [[Link3]].
`;
const sections = splitIntoSections(markdown);
expect(sections[1]?.links).toContain("Link1");
expect(sections[1]?.links).toContain("Link2");
expect(sections[2]?.links).toContain("Link3");
expect(sections[2]?.links).not.toContain("Link1");
});
it("should handle note without headings", () => {
const markdown = `Content with [[Link1]] and [[Link2]].`;
const sections = splitIntoSections(markdown);
expect(sections).toHaveLength(1);
expect(sections[0]?.heading).toBeNull();
expect(sections[0]?.links).toContain("Link1");
expect(sections[0]?.links).toContain("Link2");
});
});
describe("extractWikilinks", () => {
it("should extract and deduplicate wikilinks", () => {
const markdown = `Content with [[Link1]], [[Link2]], and [[Link1]] again.`;
const links = extractWikilinks(markdown);
expect(links).toHaveLength(2);
expect(links).toContain("Link1");
expect(links).toContain("Link2");
});
it("should handle empty content", () => {
const links = extractWikilinks("");
expect(links).toHaveLength(0);
});
});
@@ -0,0 +1,73 @@
import { describe, it, expect } from "vitest";
import { parseEdgesFromCallouts } from "../../parser/parseEdgesFromCallouts";
describe("parseEdgesFromCallouts", () => {
it("parses edge blocks embedded inside other callouts", () => {
const md = `
> [!abstract]- 🧩 Some Block
>> Some text
>> [!edge] caused_by
>> [[A]]
>> [[B]]
>> More text
Outside.
`.trim();
const edges = parseEdgesFromCallouts(md);
expect(edges.length).toBe(1);
const edge = edges[0];
if (!edge) throw new Error("Expected edge to exist");
expect(edge.rawType).toBe("caused_by");
expect(edge.targets).toEqual(["A", "B"]);
});
it("stops when quote level drops below edge level", () => {
const md = `
> [!abstract]
>> [!edge] resulted_in
>> [[X]]
Normal text ends quote.
`.trim();
const edges = parseEdgesFromCallouts(md);
expect(edges.length).toBe(1);
const edge = edges[0];
if (!edge) throw new Error("Expected edge to exist");
expect(edge.rawType).toBe("resulted_in");
expect(edge.targets).toEqual(["X"]);
});
it("starts a new edge when another edge header appears", () => {
const md = `
> [!edge] caused_by
> [[A]]
> [!edge] resulted_in
> [[B]]
`.trim();
const edges = parseEdgesFromCallouts(md);
expect(edges.length).toBe(2);
const edge0 = edges[0];
const edge1 = edges[1];
if (!edge0 || !edge1) throw new Error("Expected edges to exist");
expect(edge0.rawType).toBe("caused_by");
expect(edge0.targets).toEqual(["A"]);
expect(edge1.rawType).toBe("resulted_in");
expect(edge1.targets).toEqual(["B"]);
});
it("allows multiple links in one line", () => {
const md = `
>> [!edge] impacts
>> [[Y]] [[Z]]
`.trim();
const edges = parseEdgesFromCallouts(md);
expect(edges.length).toBe(1);
const edge = edges[0];
if (!edge) throw new Error("Expected edge to exist");
expect(edge.rawType).toBe("impacts");
expect(edge.targets).toEqual(["Y", "Z"]);
});
});
+95
View File
@@ -0,0 +1,95 @@
import { describe, it, expect } from "vitest";
import { extractFrontmatterId } from "../../parser/parseFrontmatter";
describe("extractFrontmatterId", () => {
it("extracts id from frontmatter", () => {
const md = `---
id: test-id
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe("test-id");
});
it("returns null when no frontmatter", () => {
const md = `Content without frontmatter.`;
expect(extractFrontmatterId(md)).toBe(null);
});
it("returns null when no id field", () => {
const md = `---
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe(null);
});
it("converts numeric id to string", () => {
const md = `---
id: 123
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe("123");
});
it("handles quoted id", () => {
const md = `---
id: "quoted-id"
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe("quoted-id");
});
it("handles single-quoted id", () => {
const md = `---
id: 'single-quoted'
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe("single-quoted");
});
it("handles id with colon in value", () => {
const md = `---
id: "id:with:colons"
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe("id:with:colons");
});
it("returns null when frontmatter not closed", () => {
const md = `---
id: test-id
title: Test
Content here.
`;
expect(extractFrontmatterId(md)).toBe(null);
});
it("handles id without space after colon", () => {
const md = `---
id:test-id
title: Test
---
Content here.
`;
expect(extractFrontmatterId(md)).toBe("test-id");
});
});
@@ -0,0 +1,15 @@
/**
* Unit tests for GraphSchemaLoader.
*/
import { describe, it, expect } from "vitest";
import { GraphSchemaLoader } from "../../schema/GraphSchemaLoader";
import { normalizeVaultPath } from "../../settings";
describe("GraphSchemaLoader", () => {
it("should normalize vault paths correctly", () => {
expect(normalizeVaultPath("_system/dictionary/graph_schema.md")).toBe("_system/dictionary/graph_schema.md");
expect(normalizeVaultPath("_system\\dictionary\\graph_schema.md")).toBe("_system/dictionary/graph_schema.md");
expect(normalizeVaultPath(" _system/dictionary/graph_schema.md ")).toBe("_system/dictionary/graph_schema.md");
});
});
+354
View File
@@ -0,0 +1,354 @@
import { describe, it, expect } from "vitest";
import {
applyMarkdownWrap,
applyWikiLink,
applyHeading,
applyBullets,
applyNumberedList,
} from "../../ui/markdownToolbar";
describe("markdownToolbar", () => {
describe("applyMarkdownWrap", () => {
it("should wrap selected text", () => {
const text = "Hello world";
const result = applyMarkdownWrap(text, 0, 5, "**", "**");
expect(result.newText).toBe("**Hello** world");
// Cursor should be after the wrapped text
expect(result.newSelectionStart).toBe(9); // After "**Hello**"
expect(result.newSelectionEnd).toBe(9);
});
it("should insert at cursor when no selection", () => {
const text = "Hello world";
const result = applyMarkdownWrap(text, 5, 5, "**", "**");
expect(result.newText).toBe("Hello**** world");
expect(result.newSelectionStart).toBe(7);
expect(result.newSelectionEnd).toBe(7);
});
});
describe("applyWikiLink", () => {
it("should wrap selected text with wikilink", () => {
const text = "See my note";
const result = applyWikiLink(text, 4, 6);
expect(result.newText).toBe("See [[my]] note");
expect(result.newSelectionStart).toBe(10); // After "[[my]]"
expect(result.newSelectionEnd).toBe(10);
});
it("should insert [[text]] with selection when no text selected", () => {
const text = "Hello world";
const result = applyWikiLink(text, 5, 5);
expect(result.newText).toBe("Hello[[text]] world");
expect(result.newSelectionStart).toBe(7);
expect(result.newSelectionEnd).toBe(11); // "text" selected
});
});
describe("applyHeading", () => {
it("should add H2 prefix to line", () => {
const text = "My heading\nSome text";
const result = applyHeading(text, 0, 11, 2);
expect(result.newText).toBe("## My heading\nSome text");
expect(result.newSelectionStart).toBe(0);
expect(result.newSelectionEnd).toBeGreaterThan(0);
});
it("should toggle H2 prefix if already present", () => {
const text = "## My heading\nSome text";
const result = applyHeading(text, 0, 14, 2);
// Should remove the ## prefix
expect(result.newText).toContain("My heading");
expect(result.newText).not.toContain("## ##");
expect(result.newText).not.toContain("## My heading");
expect(result.newSelectionStart).toBe(0);
});
it("should not add duplicate heading prefix", () => {
const text = "## My heading\nSome text";
const result = applyHeading(text, 0, 14, 2);
// Should remove existing heading, not add another
const result2 = applyHeading(result.newText, 0, result.newText.indexOf("\n"), 2);
expect(result2.newText).toContain("## My heading");
expect(result2.newText).not.toContain("## ## My heading");
});
it("should handle multi-line selection - all lines should get heading", () => {
const text = "Line 1\nLine 2\nLine 3";
const result = applyHeading(text, 0, 13, 2);
expect(result.newText).toContain("## Line 1");
expect(result.newText).toContain("## Line 2");
expect(result.newText).not.toContain("## Line 3"); // Third line unchanged (not in selection)
});
it("should apply heading to all selected lines", () => {
const text = "First line\nSecond line\nThird line";
const result = applyHeading(text, 0, 22, 2); // Select first two lines
expect(result.newText).toContain("## First line");
expect(result.newText).toContain("## Second line");
expect(result.newText).toContain("Third line"); // Third line unchanged
});
it("should preserve indentation", () => {
const text = " Indented line";
const result = applyHeading(text, 0, 15, 2);
expect(result.newText).toBe(" ## Indented line");
});
it("should not delete existing text", () => {
const text = "This is important content";
const result = applyHeading(text, 0, 25, 2);
expect(result.newText).toContain("This is important content");
expect(result.newText.length).toBeGreaterThan(text.length);
});
it("should operate on complete lines for partial selection within one line", () => {
const text = "This is a long line with important content";
const result = applyHeading(text, 5, 15, 2); // Select "is a long"
expect(result.newText).toContain("## This is a long line with important content");
expect(result.newText).toContain("line with important content"); // Should not be deleted
});
it("should operate on complete lines for multi-line partial selection", () => {
const text = "First line content\nSecond line content\nThird line content";
const result = applyHeading(text, 5, 30, 2); // Start mid-first, end mid-second
expect(result.newText).toContain("## First line content");
expect(result.newText).toContain("## Second line content");
expect(result.newText).toContain("Third line content"); // Third line should remain unchanged
});
it("should not include next line when selection ends at newline", () => {
const text = "Item 1\nItem 2\nItem 3";
const result = applyHeading(text, 0, 6, 2); // Select "Item 1\n" (ends at newline)
expect(result.newText).toContain("## Item 1");
expect(result.newText).toContain("Item 2"); // Should not have heading
expect(result.newText).toContain("Item 3"); // Should not have heading
});
it("should toggle correctly when all non-empty lines have same heading level", () => {
const text = "## Item 1\n## Item 2\n\n## Item 3";
const result = applyHeading(text, 0, 25, 2);
expect(result.newText).toContain("Item 1");
expect(result.newText).toContain("Item 2");
expect(result.newText).toContain("\n\n"); // Empty line preserved
expect(result.newText).toContain("Item 3");
expect(result.newText).not.toMatch(/^#+\s/); // No headings should remain
});
it("should replace different heading levels with requested level", () => {
const text = "## Item 1\n### Item 2\n\n## Item 3";
const result = applyHeading(text, 0, 25, 2);
// Lines with ## should be removed (toggle), lines with ### should be replaced with ##
expect(result.newText).toContain("Item 1"); // ## removed
expect(result.newText).toContain("## Item 2"); // ### replaced with ##
expect(result.newText).toContain("\n\n"); // Empty line preserved
expect(result.newText).toContain("Item 3"); // ## removed
});
it("should replace existing heading with new level", () => {
const text = "### Existing heading";
const result = applyHeading(text, 0, 20, 2);
// Should replace ### with ##, not add ## before ###
expect(result.newText).toBe("## Existing heading");
expect(result.newText).not.toContain("###");
expect(result.newText).not.toContain("## ##");
});
it("should toggle when same heading level is applied again", () => {
const text = "## Existing heading";
const result = applyHeading(text, 0, 20, 2);
// Should remove ## because it's the same level
expect(result.newText).toBe("Existing heading");
expect(result.newText).not.toContain("##");
});
it("should toggle all lines when multiple lines with same heading are selected", () => {
const text = "## Line 1\n## Line 2\n## Line 3";
const result = applyHeading(text, 0, 25, 2);
// All lines should have heading removed
expect(result.newText).toContain("Line 1");
expect(result.newText).toContain("Line 2");
expect(result.newText).toContain("Line 3");
expect(result.newText).not.toContain("##");
});
it("should not delete text when partially selected heading line is toggled", () => {
const text = "## This is a complete heading line";
const result = applyHeading(text, 5, 15, 2); // Select "is a compl"
// Should toggle the heading, but keep all text
expect(result.newText).toContain("This is a complete heading line");
expect(result.newText).not.toContain("##");
// Verify no text was deleted
expect(result.newText.length).toBeGreaterThanOrEqual(text.length - 3); // -3 for "## "
});
it("should not add duplicate heading when whole heading line is selected and toggled", () => {
const text = "## Complete heading line";
const result = applyHeading(text, 0, 25, 2); // Select entire line
// Should remove heading (toggle), not add another
expect(result.newText).toBe("Complete heading line");
expect(result.newText).not.toContain("##");
// Apply again should add heading back
const result2 = applyHeading(result.newText, 0, 25, 2);
expect(result2.newText).toBe("## Complete heading line");
expect(result2.newText).not.toContain("## ##");
});
});
describe("applyBullets", () => {
it("should add bullet prefix to selected lines", () => {
const text = "Item 1\nItem 2\nItem 3";
const result = applyBullets(text, 0, 18);
expect(result.newText).toContain("- Item 1");
expect(result.newText).toContain("- Item 2");
expect(result.newText).toContain("- Item 3");
});
it("should toggle bullets if already present", () => {
const text = "- Item 1\n- Item 2";
const result = applyBullets(text, 0, 15);
expect(result.newText).toContain("Item 1");
expect(result.newText).toContain("Item 2");
expect(result.newText).not.toContain("- ");
});
it("should preserve indentation", () => {
const text = " Item 1\n Item 2";
const result = applyBullets(text, 0, 16);
expect(result.newText).toContain(" - Item 1");
expect(result.newText).toContain(" - Item 2");
});
it("should skip empty lines", () => {
const text = "Item 1\n\nItem 2";
const result = applyBullets(text, 0, 12);
expect(result.newText).toContain("- Item 1");
expect(result.newText).toContain("\n\n");
expect(result.newText).toContain("- Item 2");
// Verify both items are present
const lines = result.newText.split("\n");
expect(lines.filter(l => l.includes("Item")).length).toBeGreaterThanOrEqual(2);
});
it("should not delete existing text", () => {
const text = "Important content here";
const result = applyBullets(text, 0, 22);
expect(result.newText).toContain("Important content here");
expect(result.newText.length).toBeGreaterThanOrEqual(text.length);
});
it("should operate on complete lines for partial selection within one line", () => {
const text = "This is a long line with important content";
const result = applyBullets(text, 5, 15); // Select "is a long"
expect(result.newText).toContain("- This is a long line with important content");
expect(result.newText).toContain("line with important content"); // Should not be deleted
});
it("should operate on complete lines for multi-line partial selection", () => {
const text = "First line content\nSecond line content\nThird line content";
const result = applyBullets(text, 5, 30); // Start mid-first, end mid-second
expect(result.newText).toContain("- First line content");
expect(result.newText).toContain("- Second line content");
expect(result.newText).toContain("Third line content"); // Third line should remain unchanged
});
it("should not include next line when selection ends at newline", () => {
const text = "Item 1\nItem 2\nItem 3";
const result = applyBullets(text, 0, 6); // Select "Item 1\n" (ends at newline)
expect(result.newText).toContain("- Item 1");
expect(result.newText).toContain("Item 2"); // Should not have bullet
expect(result.newText).toContain("Item 3"); // Should not have bullet
});
it("should toggle correctly when all non-empty lines have bullets", () => {
const text = "- Item 1\n- Item 2\n\n- Item 3";
const result = applyBullets(text, 0, 25);
expect(result.newText).toContain("Item 1");
expect(result.newText).toContain("Item 2");
expect(result.newText).toContain("\n\n"); // Empty line preserved
expect(result.newText).toContain("Item 3");
expect(result.newText).not.toContain("- ");
});
});
describe("applyNumberedList", () => {
it("should add numbered prefix to selected lines", () => {
const text = "Item 1\nItem 2\nItem 3";
const result = applyNumberedList(text, 0, 18);
expect(result.newText).toContain("1. Item 1");
expect(result.newText).toContain("2. Item 2");
expect(result.newText).toContain("3. Item 3");
});
it("should toggle numbered list if already present", () => {
const text = "1. Item 1\n2. Item 2";
const result = applyNumberedList(text, 0, 17);
expect(result.newText).toContain("Item 1");
expect(result.newText).toContain("Item 2");
expect(result.newText).not.toMatch(/\d+\.\s/);
});
it("should preserve indentation", () => {
const text = " Item 1\n Item 2";
const result = applyNumberedList(text, 0, 16);
expect(result.newText).toContain(" 1. Item 1");
expect(result.newText).toContain(" 2. Item 2");
// Verify both items are present
const lines = result.newText.split("\n");
expect(lines.filter(l => l.includes("Item")).length).toBeGreaterThanOrEqual(2);
});
it("should not delete existing text", () => {
const text = "Important content";
const result = applyNumberedList(text, 0, 18);
expect(result.newText).toContain("Important content");
expect(result.newText.length).toBeGreaterThanOrEqual(text.length);
});
it("should operate on complete lines for partial selection within one line", () => {
const text = "This is a long line with important content";
const result = applyNumberedList(text, 5, 15); // Select "is a long"
expect(result.newText).toContain("1. This is a long line with important content");
expect(result.newText).toContain("line with important content"); // Should not be deleted
});
it("should operate on complete lines for multi-line partial selection", () => {
const text = "First line content\nSecond line content\nThird line content";
const result = applyNumberedList(text, 5, 30); // Start mid-first, end mid-second
expect(result.newText).toContain("1. First line content");
expect(result.newText).toContain("2. Second line content");
expect(result.newText).toContain("Third line content"); // Third line should remain unchanged
});
it("should not include next line when selection ends at newline", () => {
const text = "Item 1\nItem 2\nItem 3";
const result = applyNumberedList(text, 0, 6); // Select "Item 1\n" (ends at newline)
expect(result.newText).toContain("1. Item 1");
expect(result.newText).toContain("Item 2"); // Should not have number
expect(result.newText).toContain("Item 3"); // Should not have number
});
it("should not number empty lines", () => {
const text = "Item 1\n\nItem 2";
const result = applyNumberedList(text, 0, 12);
expect(result.newText).toContain("1. Item 1");
expect(result.newText).toContain("\n\n"); // Empty line preserved
expect(result.newText).toContain("2. Item 2");
// Verify empty line is not numbered
const lines = result.newText.split("\n");
const emptyLineIndex = lines.findIndex(l => l.trim() === "");
expect(emptyLineIndex).toBeGreaterThanOrEqual(0);
expect(lines[emptyLineIndex]).not.toMatch(/^\d+\.\s/);
});
it("should toggle correctly when all non-empty lines have numbers", () => {
const text = "1. Item 1\n2. Item 2\n\n3. Item 3";
const result = applyNumberedList(text, 0, 25);
expect(result.newText).toContain("Item 1");
expect(result.newText).toContain("Item 2");
expect(result.newText).toContain("\n\n"); // Empty line preserved
expect(result.newText).toContain("Item 3");
expect(result.newText).not.toMatch(/\d+\.\s/);
});
});
});
@@ -0,0 +1,145 @@
import { describe, it, expect } from "vitest";
import {
evaluateAdoptionConfidence,
type PendingCreateHint,
} from "../../unresolvedLink/adoptHelpers";
import { TFile } from "obsidian";
describe("evaluateAdoptionConfidence", () => {
it("returns high confidence for recent file with matching hint", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 1000 }, // 1 second ago
} as TFile;
const content = "Some content";
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 500,
};
const result = evaluateAdoptionConfidence(file, content, 200, hint, 3000);
expect(result).toBe("high");
});
it("returns low confidence for old file", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 10000 }, // 10 seconds ago
} as TFile;
const content = "Some content";
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 500,
};
const result = evaluateAdoptionConfidence(file, content, 200, hint, 3000);
expect(result).toBe("low");
});
it("returns low confidence for file with id", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 1000 },
} as TFile;
const content = `---
id: note_123
---
Body`;
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 500,
};
const result = evaluateAdoptionConfidence(file, content, 200, hint, 3000);
expect(result).toBe("low");
});
it("returns low confidence for file exceeding maxChars", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 1000 },
} as TFile;
const content = "x".repeat(300); // Exceeds maxChars
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 500,
};
const result = evaluateAdoptionConfidence(file, content, 200, hint, 3000);
expect(result).toBe("low");
});
it("returns high confidence for very recent file even without hint", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 500 }, // Very recent (0.5 seconds)
} as TFile;
const content = "Some content";
const result = evaluateAdoptionConfidence(file, content, 200, null, 3000);
expect(result).toBe("high");
});
it("returns low confidence for recent file without hint if not very recent", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 2500 }, // 2.5 seconds ago (not very recent)
} as TFile;
const content = "Some content";
const result = evaluateAdoptionConfidence(file, content, 200, null, 3000);
expect(result).toBe("low");
});
it("returns high confidence when hint matches even if file is slightly older", () => {
const file = {
basename: "test-note",
stat: { ctime: Date.now() - 2500 }, // 2.5 seconds ago
} as TFile;
const content = "Some content";
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 2000, // Hint is 2 seconds ago, within window
};
const result = evaluateAdoptionConfidence(file, content, 200, hint, 3000);
expect(result).toBe("high");
});
});
describe("adoptConfirmMode behavior", () => {
// Pure function to test confirm mode logic
function shouldShowAdoptionConfirm(
mode: "always" | "onlyLowConfidence" | "never",
confidence: "high" | "low"
): boolean {
if (mode === "always") {
return true;
}
if (mode === "never") {
return false;
}
// onlyLowConfidence: show only for low confidence
return confidence === "low";
}
it("always mode shows confirm for both high and low confidence", () => {
expect(shouldShowAdoptionConfirm("always", "high")).toBe(true);
expect(shouldShowAdoptionConfirm("always", "low")).toBe(true);
});
it("never mode never shows confirm", () => {
expect(shouldShowAdoptionConfirm("never", "high")).toBe(false);
expect(shouldShowAdoptionConfirm("never", "low")).toBe(false);
});
it("onlyLowConfidence mode shows confirm only for low confidence", () => {
expect(shouldShowAdoptionConfirm("onlyLowConfidence", "high")).toBe(false);
expect(shouldShowAdoptionConfirm("onlyLowConfidence", "low")).toBe(true);
});
});
@@ -0,0 +1,148 @@
import { describe, it, expect } from "vitest";
import {
isAdoptCandidate,
matchesPendingHint,
mergeFrontmatter,
type PendingCreateHint,
} from "../../unresolvedLink/adoptHelpers";
import { TFile } from "obsidian";
describe("isAdoptCandidate", () => {
it("returns true for empty content", () => {
expect(isAdoptCandidate("", 200)).toBe(true);
expect(isAdoptCandidate(" ", 200)).toBe(true);
});
it("returns true for content without frontmatter id", () => {
expect(isAdoptCandidate("Some text", 200)).toBe(true);
expect(isAdoptCandidate("Some text\nwith multiple lines", 200)).toBe(true);
});
it("returns true for content with frontmatter but no id", () => {
const content = `---
title: Test
---
Body content`;
expect(isAdoptCandidate(content, 200)).toBe(true);
});
it("returns false for content with id", () => {
const content = `---
id: note_123
title: Test
---
Body`;
expect(isAdoptCandidate(content, 200)).toBe(false);
});
it("returns false for content exceeding maxChars", () => {
const longContent = "x".repeat(300);
expect(isAdoptCandidate(longContent, 200)).toBe(false);
});
it("returns true for content within maxChars even with frontmatter", () => {
const content = `---
title: Test
---
Short body`;
expect(isAdoptCandidate(content, 200)).toBe(true);
});
});
describe("matchesPendingHint", () => {
it("returns true when basename matches and within time window", () => {
const file = { basename: "test-note" } as TFile;
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 1000, // 1 second ago
};
expect(matchesPendingHint(file, hint, 3000)).toBe(true);
});
it("returns false when basename doesn't match", () => {
const file = { basename: "other-note" } as TFile;
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 1000,
};
expect(matchesPendingHint(file, hint, 3000)).toBe(false);
});
it("returns false when time window exceeded", () => {
const file = { basename: "test-note" } as TFile;
const hint: PendingCreateHint = {
basename: "test-note",
sourcePath: "source.md",
timestamp: Date.now() - 5000, // 5 seconds ago
};
expect(matchesPendingHint(file, hint, 3000)).toBe(false);
});
it("returns false when hint is null", () => {
const file = { basename: "test-note" } as TFile;
expect(matchesPendingHint(file, null, 3000)).toBe(false);
});
});
describe("mergeFrontmatter", () => {
it("prepends frontmatter to content without existing frontmatter", () => {
const content = "Body content";
const frontmatter = `---
id: note_123
title: Test
---`;
const result = mergeFrontmatter(content, frontmatter);
expect(result).toContain("id: note_123");
expect(result).toContain("title: Test");
expect(result).toContain("Body content");
});
it("merges with existing frontmatter preserving existing fields", () => {
const content = `---
title: Existing
custom: value
---
Body content`;
const frontmatter = `---
id: note_123
title: New
type: note
---`;
const result = mergeFrontmatter(content, frontmatter);
expect(result).toContain("id: note_123");
expect(result).toContain("title: Existing"); // Existing takes precedence
expect(result).toContain("type: note");
expect(result).toContain("custom: value");
expect(result).toContain("Body content");
});
it("preserves body content when merging", () => {
const content = `---
title: Test
---
Line 1
Line 2
Line 3`;
const frontmatter = `---
id: note_123
---`;
const result = mergeFrontmatter(content, frontmatter);
expect(result).toContain("Line 1");
expect(result).toContain("Line 2");
expect(result).toContain("Line 3");
});
it("handles empty body", () => {
const content = `---
title: Test
---`;
const frontmatter = `---
id: note_123
---`;
const result = mergeFrontmatter(content, frontmatter);
expect(result).toContain("id: note_123");
expect(result).toContain("title: Test");
});
});
@@ -0,0 +1,183 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { normalizeLinkTarget, isUnresolvedLink, waitForFileModify, parseWikilinkAtPosition } from "../../unresolvedLink/linkHelpers";
import { App, TFile } from "obsidian";
describe("normalizeLinkTarget", () => {
it("preserves simple basename", () => {
expect(normalizeLinkTarget("test-note")).toBe("test-note");
});
it("preserves spaces and case", () => {
expect(normalizeLinkTarget("My Note")).toBe("My Note");
expect(normalizeLinkTarget("My Test Note")).toBe("My Test Note");
});
it("removes alias separator", () => {
expect(normalizeLinkTarget("test-note|Alias Text")).toBe("test-note");
expect(normalizeLinkTarget("My Note|Display Name")).toBe("My Note");
});
it("removes heading separator", () => {
expect(normalizeLinkTarget("test-note#Section")).toBe("test-note");
expect(normalizeLinkTarget("My Note#Section")).toBe("My Note");
});
it("removes alias and heading", () => {
expect(normalizeLinkTarget("test-note#Section|Alias")).toBe("test-note");
expect(normalizeLinkTarget("My Note#Section|Alias")).toBe("My Note");
});
it("trims whitespace", () => {
expect(normalizeLinkTarget(" test-note ")).toBe("test-note");
expect(normalizeLinkTarget(" My Note ")).toBe("My Note");
});
it("handles empty string", () => {
expect(normalizeLinkTarget("")).toBe("");
});
});
describe("parseWikilinkAtPosition", () => {
it("finds wikilink at cursor position", () => {
const line = "This is a [[test-note]] link";
const result = parseWikilinkAtPosition(line, 15); // Position inside [[test-note]]
expect(result).toBe("test-note");
});
it("finds wikilink with alias", () => {
const line = "This is a [[test-note|Display Text]] link";
const result = parseWikilinkAtPosition(line, 15);
expect(result).toBe("test-note|Display Text");
});
it("finds wikilink with heading", () => {
const line = "This is a [[test-note#Section]] link";
const result = parseWikilinkAtPosition(line, 15);
expect(result).toBe("test-note#Section");
});
it("finds nearest wikilink when cursor is outside", () => {
const line = "This is a [[test-note]] link";
const result = parseWikilinkAtPosition(line, 5); // Position before link
expect(result).toBe("test-note");
});
it("returns null when no wikilink found", () => {
const line = "This is plain text";
const result = parseWikilinkAtPosition(line, 5);
expect(result).toBe(null);
});
it("returns null when cursor is too far from link", () => {
const line = "This is a [[test-note]] link";
const result = parseWikilinkAtPosition(line, 0); // Position at start, too far
expect(result).toBe(null);
});
it("handles multiple wikilinks and finds the correct one", () => {
const line = "[[first]] and [[second]] links";
const result1 = parseWikilinkAtPosition(line, 5); // Near first
const result2 = parseWikilinkAtPosition(line, 20); // Near second
expect(result1).toBe("first");
expect(result2).toBe("second");
});
});
describe("isUnresolvedLink", () => {
let mockApp: Partial<App>;
let mockMetadataCache: any;
beforeEach(() => {
mockMetadataCache = {
getFirstLinkpathDest: vi.fn(),
};
mockApp = {
metadataCache: mockMetadataCache as any,
};
});
it("returns true when file is not found", () => {
mockMetadataCache.getFirstLinkpathDest.mockReturnValue(null);
const result = isUnresolvedLink(mockApp as App, "test-note", "source.md");
expect(result).toBe(true);
expect(mockMetadataCache.getFirstLinkpathDest).toHaveBeenCalledWith("test-note", "source.md");
});
it("returns false when file is found", () => {
const mockFile = { path: "test-note.md" } as TFile;
mockMetadataCache.getFirstLinkpathDest.mockReturnValue(mockFile);
const result = isUnresolvedLink(mockApp as App, "test-note", "source.md");
expect(result).toBe(false);
});
it("returns false for empty target", () => {
const result = isUnresolvedLink(mockApp as App, "", "source.md");
expect(result).toBe(false);
expect(mockMetadataCache.getFirstLinkpathDest).not.toHaveBeenCalled();
});
});
describe("waitForFileModify", () => {
let mockApp: Partial<App>;
let mockVault: any;
let mockFile: TFile;
let modifyHandler: ((file: TFile) => void) | null;
beforeEach(() => {
modifyHandler = null;
mockFile = { path: "test.md" } as TFile;
mockVault = {
on: vi.fn((event: string, fn: any) => {
if (event === "modify") {
modifyHandler = fn;
}
}),
off: vi.fn(),
};
mockApp = {
vault: mockVault as any,
};
});
it("resolves with 'modified' when file modify event fires", async () => {
const promise = waitForFileModify(mockApp as App, mockFile, 1000);
// Simulate modify event immediately (before timeout)
if (modifyHandler) {
modifyHandler(mockFile);
}
const result = await promise;
expect(result).toBe("modified");
expect(mockVault.off).toHaveBeenCalled();
});
it("resolves with 'timeout' when timeout expires", async () => {
// Don't trigger modify handler - simulate no modify event
const promise = waitForFileModify(mockApp as App, mockFile, 50);
// Wait for timeout (should be ~50ms)
const result = await promise;
expect(result).toBe("timeout");
expect(mockVault.off).toHaveBeenCalled();
}, 200); // Increase test timeout
it("ignores modify events for other files", async () => {
const otherFile = { path: "other.md" } as TFile;
const promise = waitForFileModify(mockApp as App, mockFile, 50);
// Simulate modify event for different file (should be ignored)
if (modifyHandler) {
modifyHandler(otherFile);
}
// Wait for timeout (other file modify should not trigger resolution)
const result = await promise;
expect(result).toBe("timeout"); // Should timeout because other file was modified
expect(mockVault.off).toHaveBeenCalled();
}, 200); // Increase test timeout
});
+169
View File
@@ -0,0 +1,169 @@
import { describe, it, expect } from "vitest";
import { parseEdgeVocabulary } from "../../vocab/parseEdgeVocabulary";
import { Vocabulary } from "../../vocab/Vocabulary";
describe("parseEdgeVocabulary", () => {
const fixtureMd = `
# Edge Vocabulary
## Causal Relations
| System-Typ (Canonical) | Inverser Typ | Erlaubte Aliasse (User) | Beschreibung |
| :--- | :--- | :--- | :--- |
| **\`caused_by\`** | \`resulted_in\` | \`ausgelöst_durch\`, \`wegen\`, \`verursacht_durch\` | Describes causation |
| \`impacts\` | \`impacted_by\` | *(Kein Alias)* | Impact relationship |
| \`influences\` | \`influenced_by\` | \`beeinflusst\`, \`wirkt_auf\` | Influence relation |
## Other Relations
| System-Typ (Canonical) | Inverser Typ | Erlaubte Aliasse (User) | Beschreibung |
| :--- | :--- | :--- | :--- |
| \`relates_to\` | \`related_from\` | \`verwandt_mit\`, \`bezogen_auf\` | General relation |
`;
it("parses canonical types correctly", () => {
const vocab = parseEdgeVocabulary(fixtureMd);
expect(vocab.byCanonical.has("caused_by")).toBe(true);
expect(vocab.byCanonical.has("impacts")).toBe(true);
expect(vocab.byCanonical.has("influences")).toBe(true);
expect(vocab.byCanonical.has("relates_to")).toBe(true);
});
it("parses inverse types correctly", () => {
const vocab = parseEdgeVocabulary(fixtureMd);
const causedBy = vocab.byCanonical.get("caused_by");
if (!causedBy) throw new Error("Expected caused_by entry");
expect(causedBy.inverse).toBe("resulted_in");
const impacts = vocab.byCanonical.get("impacts");
if (!impacts) throw new Error("Expected impacts entry");
expect(impacts.inverse).toBe("impacted_by");
});
it("handles (Kein Alias) correctly", () => {
const vocab = parseEdgeVocabulary(fixtureMd);
const impacts = vocab.byCanonical.get("impacts");
if (!impacts) throw new Error("Expected impacts entry");
expect(impacts.aliases).toEqual([]);
});
it("parses multiple aliases correctly", () => {
const vocab = parseEdgeVocabulary(fixtureMd);
const causedBy = vocab.byCanonical.get("caused_by");
if (!causedBy) throw new Error("Expected caused_by entry");
expect(causedBy.aliases).toEqual(["ausgelöst_durch", "wegen", "verursacht_durch"]);
const influences = vocab.byCanonical.get("influences");
if (!influences) throw new Error("Expected influences entry");
expect(influences.aliases).toEqual(["beeinflusst", "wirkt_auf"]);
});
it("builds alias-to-canonical mapping", () => {
const vocab = parseEdgeVocabulary(fixtureMd);
expect(vocab.aliasToCanonical.get("ausgelöst_durch")).toBe("caused_by");
expect(vocab.aliasToCanonical.get("wegen")).toBe("caused_by");
expect(vocab.aliasToCanonical.get("verursacht_durch")).toBe("caused_by");
expect(vocab.aliasToCanonical.get("beeinflusst")).toBe("influences");
expect(vocab.aliasToCanonical.get("wirkt_auf")).toBe("influences");
});
it("parses multiple tables correctly", () => {
const vocab = parseEdgeVocabulary(fixtureMd);
expect(vocab.byCanonical.size).toBe(4);
expect(vocab.byCanonical.has("caused_by")).toBe(true);
expect(vocab.byCanonical.has("impacts")).toBe(true);
expect(vocab.byCanonical.has("influences")).toBe(true);
expect(vocab.byCanonical.has("relates_to")).toBe(true);
});
});
describe("Vocabulary wrapper", () => {
const fixtureMd = `
| System-Typ (Canonical) | Inverser Typ | Erlaubte Aliasse (User) | Beschreibung |
| :--- | :--- | :--- | :--- |
| **\`caused_by\`** | \`resulted_in\` | \`ausgelöst_durch\`, \`wegen\` | Test |
| \`impacts\` | \`impacted_by\` | *(Kein Alias)* | Test |
`;
it("getCanonical returns canonical for canonical input", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
expect(vocab.getCanonical("caused_by")).toBe("caused_by");
expect(vocab.getCanonical("impacts")).toBe("impacts");
});
it("getCanonical returns canonical for alias input (case-insensitive)", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
expect(vocab.getCanonical("wegen")).toBe("caused_by");
expect(vocab.getCanonical("WEGEN")).toBe("caused_by");
expect(vocab.getCanonical("ausgelöst_durch")).toBe("caused_by");
expect(vocab.getCanonical("AUSGELÖST_DURCH")).toBe("caused_by");
});
it("getCanonical returns null for unknown input", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
expect(vocab.getCanonical("unknown")).toBe(null);
expect(vocab.getCanonical("")).toBe(null);
});
it("getInverse returns inverse for canonical", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
expect(vocab.getInverse("caused_by")).toBe("resulted_in");
expect(vocab.getInverse("impacts")).toBe("impacted_by");
});
it("getInverse returns null for unknown canonical", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
expect(vocab.getInverse("unknown")).toBe(null);
});
it("normalize returns correct result for canonical", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
const result = vocab.normalize("caused_by");
expect(result.raw).toBe("caused_by");
expect(result.canonical).toBe("caused_by");
expect(result.inverse).toBe("resulted_in");
});
it("normalize returns correct result for alias (case-insensitive)", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
const result = vocab.normalize("wegen");
expect(result.raw).toBe("wegen");
expect(result.canonical).toBe("caused_by");
expect(result.inverse).toBe("resulted_in");
const resultUpper = vocab.normalize("WEGEN");
expect(resultUpper.raw).toBe("WEGEN");
expect(resultUpper.canonical).toBe("caused_by");
expect(resultUpper.inverse).toBe("resulted_in");
});
it("normalize returns null canonical for unknown input", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
const result = vocab.normalize("unknown");
expect(result.raw).toBe("unknown");
expect(result.canonical).toBe(null);
expect(result.inverse).toBe(null);
});
it("getStats returns correct counts", () => {
const vocab = new Vocabulary(parseEdgeVocabulary(fixtureMd));
const stats = vocab.getStats();
expect(stats.canonicalCount).toBe(2);
expect(stats.aliasCount).toBe(2); // ausgelöst_durch, wegen
});
});
+71
View File
@@ -0,0 +1,71 @@
/**
* Modal for confirming adoption of a newly created note.
*/
import { Modal, Notice } from "obsidian";
export interface AdoptNoteResult {
adopt: boolean;
}
export class AdoptNoteModal extends Modal {
private result: AdoptNoteResult | null = null;
private resolve: ((result: AdoptNoteResult) => void) | null = null;
private fileName: string;
constructor(app: any, fileName: string) {
super(app);
this.fileName = fileName;
}
onOpen(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Convert to Mindnet note?" });
contentEl.createEl("p", {
text: `The note "${this.fileName}" appears to be newly created. Would you like to convert it to a Mindnet note?`,
});
const buttonContainer = contentEl.createEl("div");
buttonContainer.style.display = "flex";
buttonContainer.style.gap = "0.5em";
buttonContainer.style.justifyContent = "flex-end";
buttonContainer.style.marginTop = "1em";
const noBtn = buttonContainer.createEl("button", { text: "No" });
noBtn.onclick = () => {
this.result = { adopt: false };
this.close();
};
const yesBtn = buttonContainer.createEl("button", {
text: "Yes",
cls: "mod-cta",
});
yesBtn.onclick = () => {
this.result = { adopt: true };
this.close();
};
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
if (this.resolve) {
this.resolve(this.result || { adopt: false });
}
}
/**
* Show modal and return promise that resolves with user's choice.
*/
async show(): Promise<AdoptNoteResult> {
return new Promise((resolve) => {
this.resolve = resolve;
this.open();
});
}
}
+70
View File
@@ -0,0 +1,70 @@
/**
* Confirmation modal for overwriting existing mappings.
*/
import { Modal } from "obsidian";
export interface ConfirmOverwriteResult {
confirmed: boolean;
}
export class ConfirmOverwriteModal extends Modal {
private result: ConfirmOverwriteResult = { confirmed: false };
private resolve: ((result: ConfirmOverwriteResult) => void) | null = null;
constructor(app: any) {
super(app);
}
onOpen(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("confirm-overwrite-modal");
contentEl.createEl("h2", { text: "Overwrite existing mappings?" });
const message = contentEl.createEl("p", {
text: "This will rebuild all mapping blocks and may change existing edge type assignments. Continue?",
});
message.style.marginBottom = "1em";
const buttonContainer = contentEl.createEl("div");
buttonContainer.style.display = "flex";
buttonContainer.style.gap = "0.5em";
buttonContainer.style.justifyContent = "flex-end";
const cancelBtn = buttonContainer.createEl("button", { text: "Cancel" });
cancelBtn.onclick = () => {
this.result.confirmed = false;
this.close();
};
const confirmBtn = buttonContainer.createEl("button", {
text: "Yes, overwrite",
cls: "mod-cta",
});
confirmBtn.onclick = () => {
this.result.confirmed = true;
this.close();
};
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
if (this.resolve) {
this.resolve(this.result);
}
}
/**
* Show modal and return promise that resolves with user's choice.
*/
async show(): Promise<ConfirmOverwriteResult> {
return new Promise((resolve) => {
this.resolve = resolve;
this.open();
});
}
}
+182
View File
@@ -0,0 +1,182 @@
/**
* Modal for choosing an edge type.
*/
import { Modal, Setting } from "obsidian";
import type { EdgeVocabulary } from "../vocab/types";
import type { GraphSchema } from "../mapping/graphSchema";
import { getAllEdgeTypes, groupEdgeTypesByCategory, computeEdgeSuggestions } from "../mapping/schemaHelper";
export interface EdgeTypeChoice {
edgeType: string; // Canonical edge type
alias?: string; // Selected alias if multiple aliases exist
}
export class EdgeTypeChooserModal extends Modal {
private result: EdgeTypeChoice | null = null;
private resolve: ((result: EdgeTypeChoice | null) => void) | null = null;
private vocabulary: EdgeVocabulary;
private sourceType: string | null;
private targetType: string | null;
private graphSchema: GraphSchema | null;
private selectedCanonical: string | null = null;
constructor(
app: any,
vocabulary: EdgeVocabulary,
sourceType: string | null,
targetType: string | null,
graphSchema: GraphSchema | null = null
) {
super(app);
this.vocabulary = vocabulary;
this.sourceType = sourceType;
this.targetType = targetType;
this.graphSchema = graphSchema;
}
onOpen(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("edge-type-chooser-modal");
contentEl.createEl("h2", { text: "Choose edge type" });
// Get suggestions
const suggestions = computeEdgeSuggestions(
this.vocabulary,
this.sourceType,
this.targetType,
this.graphSchema
);
const allEdgeTypes = getAllEdgeTypes(this.vocabulary);
const grouped = groupEdgeTypesByCategory(allEdgeTypes);
// Recommended section (if any)
if (suggestions.typical.length > 0) {
contentEl.createEl("h3", { text: "⭐ Recommended (schema)" });
const recommendedContainer = contentEl.createEl("div", { cls: "edge-type-list" });
for (const canonical of suggestions.typical) {
const entry = this.vocabulary.byCanonical.get(canonical);
if (!entry) continue;
const displayName = entry.aliases.length > 0 ? entry.aliases[0] : canonical;
const btn = recommendedContainer.createEl("button", {
text: `⭐ ${displayName}`,
cls: "mod-cta",
});
btn.onclick = () => {
this.selectEdgeType(canonical, entry.aliases);
};
}
}
// All categories
contentEl.createEl("h3", { text: "📂 All categories" });
for (const [category, types] of grouped.entries()) {
if (category !== "All") {
contentEl.createEl("h4", { text: category });
}
const container = contentEl.createEl("div", { cls: "edge-type-list" });
for (const { canonical, aliases, displayName } of types) {
const isProhibited = suggestions.prohibited.includes(canonical);
const isTypical = suggestions.typical.includes(canonical);
let prefix = "→";
if (isTypical) prefix = "⭐";
if (isProhibited) prefix = "🚫";
const btn = container.createEl("button", {
text: `${prefix} ${displayName}`,
});
if (isProhibited) {
btn.addClass("prohibited");
}
btn.onclick = () => {
this.selectEdgeType(canonical, aliases);
};
}
}
// Cancel button
const buttonContainer = contentEl.createEl("div");
buttonContainer.style.display = "flex";
buttonContainer.style.justifyContent = "flex-end";
buttonContainer.style.marginTop = "1em";
const cancelBtn = buttonContainer.createEl("button", { text: "Cancel" });
cancelBtn.onclick = () => {
this.result = null;
this.close();
};
}
private selectEdgeType(canonical: string, aliases: string[]): void {
if (aliases.length === 0) {
// No aliases, use canonical directly
this.result = { edgeType: canonical };
this.close();
} else if (aliases.length === 1) {
// Single alias, use it
this.result = { edgeType: canonical, alias: aliases[0] };
this.close();
} else {
// Multiple aliases, show alias chooser
this.selectedCanonical = canonical;
this.showAliasChooser(aliases);
}
}
private showAliasChooser(aliases: string[]): void {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Choose alias" });
contentEl.createEl("p", { text: `Multiple aliases available for ${this.selectedCanonical}` });
const container = contentEl.createEl("div", { cls: "alias-list" });
for (const alias of aliases) {
const btn = container.createEl("button", {
text: alias,
cls: "mod-cta",
});
btn.onclick = () => {
if (this.selectedCanonical) {
this.result = { edgeType: this.selectedCanonical, alias };
this.close();
}
};
}
const backBtn = container.createEl("button", { text: "← Back" });
backBtn.onclick = () => {
this.onOpen(); // Reopen main chooser
};
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
if (this.resolve) {
this.resolve(this.result);
}
}
/**
* Show modal and return promise that resolves with user's choice.
*/
async show(): Promise<EdgeTypeChoice | null> {
return new Promise((resolve) => {
this.resolve = resolve;
this.open();
});
}
}
+717
View File
@@ -0,0 +1,717 @@
/**
* Entity Picker Modal: Fast Obsidian-optimized note picker.
* Supports search, folder tree, type filter, sorting, and grouping.
*/
import {
App,
Modal,
Setting,
TFile,
} from "obsidian";
import { NoteIndex } from "../entityPicker/noteIndex";
import {
applyFilters,
sortNotes,
groupByType,
groupByFolder,
} from "../entityPicker/filters";
import {
buildFolderTree,
getSubtreePaths,
} from "../entityPicker/folderTree";
import type {
NoteIndexEntry,
FilterOptions,
SortOptions,
FolderTreeNode,
GroupedNoteResult,
} from "../entityPicker/types";
export interface EntityPickerResult {
basename: string;
path: string;
}
export class EntityPickerModal extends Modal {
private noteIndex: NoteIndex;
private onSelect: (result: EntityPickerResult) => void;
// State
private searchQuery: string = "";
private selectedFolderPath: string | null = null;
private selectedTypes: Set<string> = new Set();
private includeNoneType: boolean = true;
private sortMode: "recent" | "alpha" | "type" | "folder" = "recent";
// UI elements
private searchInputEl: HTMLInputElement | null = null;
private folderTreeContainer: HTMLElement | null = null;
private resultsContainer: HTMLElement | null = null;
private typeFilterContainer: HTMLElement | null = null;
// Folder tree state
private expandedFolders: Set<string> = new Set();
private folderTree: FolderTreeNode | null = null;
// Virtualization state for performance
private visibleStartIndex: number = 0;
private visibleEndIndex: number = 100; // Initial visible items
private itemsPerPage: number = 100; // Items to render at once
private allFilteredEntries: NoteIndexEntry[] = []; // Cache filtered results
private renderScheduled: boolean = false;
constructor(
app: App,
noteIndex: NoteIndex,
onSelect: (result: EntityPickerResult) => void
) {
super(app);
this.noteIndex = noteIndex;
this.onSelect = onSelect;
// Initialize expanded folders (expand root by default)
this.expandedFolders.add("");
// Subscribe to index updates
this.noteIndex.onUpdate(() => {
this.refresh();
});
}
onOpen(): void {
const { contentEl, modalEl } = this;
contentEl.empty();
contentEl.addClass("entity-picker-modal");
// Make modal larger
modalEl.style.width = "clamp(900px, 90vw, 1400px)";
modalEl.style.height = "clamp(600px, 85vh, 900px)";
modalEl.style.maxWidth = "90vw";
modalEl.style.maxHeight = "85vh";
// Build folder tree
this.folderTree = buildFolderTree(this.noteIndex.getAllEntries());
// Header: Search + Sort
const header = contentEl.createEl("div", { cls: "entity-picker-header" });
header.style.display = "flex";
header.style.gap = "0.5em";
header.style.marginBottom = "1em";
header.style.alignItems = "center";
// Search input
const searchContainer = header.createEl("div");
searchContainer.style.flex = "1";
const searchSetting = new Setting(searchContainer);
searchSetting.settingEl.style.border = "none";
searchSetting.settingEl.style.padding = "0";
searchSetting.addText((text) => {
this.searchInputEl = text.inputEl;
text.setPlaceholder("Search notes...");
text.setValue(this.searchQuery);
// Debounce search for performance
let searchTimeout: number | null = null;
text.onChange((value) => {
this.searchQuery = value;
// Debounce search updates (300ms)
if (searchTimeout !== null) {
clearTimeout(searchTimeout);
}
searchTimeout = window.setTimeout(() => {
this.refresh();
}, 300);
});
text.inputEl.style.width = "100%";
});
// Sort dropdown
const sortContainer = header.createEl("div");
sortContainer.style.flexShrink = "0";
const sortSetting = new Setting(sortContainer);
sortSetting.settingEl.style.border = "none";
sortSetting.settingEl.style.padding = "0";
sortSetting.addDropdown((dropdown) => {
dropdown.addOption("recent", "Recent");
dropdown.addOption("alpha", "Alphabetical");
dropdown.addOption("type", "By Type");
dropdown.addOption("folder", "By Folder");
dropdown.setValue(this.sortMode);
dropdown.onChange((value) => {
this.sortMode = value as "recent" | "alpha" | "type" | "folder";
this.refresh();
});
});
// Type filter button
const typeFilterBtn = header.createEl("button", {
text: "Types",
cls: "mod-cta",
});
typeFilterBtn.style.flexShrink = "0";
typeFilterBtn.onclick = () => {
this.toggleTypeFilter();
};
// Main container: 2 panes
const mainContainer = contentEl.createEl("div", {
cls: "entity-picker-main",
});
mainContainer.style.display = "flex";
mainContainer.style.gap = "1em";
mainContainer.style.height = "calc(85vh - 120px)"; // Account for header and padding
mainContainer.style.minHeight = "500px";
// Left pane: Folder tree (wider)
const leftPane = mainContainer.createEl("div", {
cls: "entity-picker-left",
});
leftPane.style.width = "40%";
leftPane.style.minWidth = "300px";
leftPane.style.border = "1px solid var(--background-modifier-border)";
leftPane.style.borderRadius = "4px";
leftPane.style.padding = "0.75em";
leftPane.style.overflowY = "auto";
this.folderTreeContainer = leftPane;
// Right pane: Results
const rightPane = mainContainer.createEl("div", {
cls: "entity-picker-right",
});
rightPane.style.flex = "1";
rightPane.style.border = "1px solid var(--background-modifier-border)";
rightPane.style.borderRadius = "4px";
rightPane.style.padding = "0.75em";
rightPane.style.overflowY = "auto";
rightPane.style.position = "relative";
this.resultsContainer = rightPane;
// Add scroll listener for virtualization
rightPane.addEventListener("scroll", () => {
this.handleScroll();
}, { passive: true });
// Type filter popover (hidden by default)
this.typeFilterContainer = contentEl.createEl("div", {
cls: "entity-picker-type-filter",
});
this.typeFilterContainer.style.display = "none";
this.typeFilterContainer.style.position = "absolute";
this.typeFilterContainer.style.background = "var(--background-primary)";
this.typeFilterContainer.style.border = "1px solid var(--background-modifier-border)";
this.typeFilterContainer.style.borderRadius = "4px";
this.typeFilterContainer.style.padding = "0.5em";
this.typeFilterContainer.style.zIndex = "1000";
this.typeFilterContainer.style.maxHeight = "300px";
this.typeFilterContainer.style.overflowY = "auto";
// Initial render
this.refresh();
// Focus search input
setTimeout(() => {
this.searchInputEl?.focus();
}, 100);
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
}
private refresh(): void {
if (!this.folderTreeContainer || !this.resultsContainer) {
return;
}
// Reset virtualization when filters/search change
this.visibleStartIndex = 0;
this.visibleEndIndex = this.itemsPerPage;
// Render folder tree
this.renderFolderTree();
// Render results (with virtualization) - this filters/sorts ALL entries
this.renderResults();
// Render type filter
this.renderTypeFilter();
}
private handleScroll(): void {
if (!this.resultsContainer || this.allFilteredEntries.length === 0) {
return;
}
// Throttle scroll handling
if (this.renderScheduled) {
return;
}
this.renderScheduled = true;
requestAnimationFrame(() => {
this.renderScheduled = false;
const container = this.resultsContainer!;
const scrollTop = container.scrollTop;
const containerHeight = container.clientHeight;
const scrollHeight = container.scrollHeight;
// Calculate visible range
const itemHeight = 60; // Approximate height per item (including padding)
const buffer = 5; // Render 5 extra items above/below
const newStartIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - buffer);
const newEndIndex = Math.min(
this.allFilteredEntries.length,
Math.ceil((scrollTop + containerHeight) / itemHeight) + buffer
);
// Only re-render if visible range changed significantly
if (Math.abs(newStartIndex - this.visibleStartIndex) > 10 ||
Math.abs(newEndIndex - this.visibleEndIndex) > 10) {
this.visibleStartIndex = newStartIndex;
this.visibleEndIndex = newEndIndex;
// Only re-render the visible items, don't re-filter/re-sort
this.renderVisibleItems();
}
});
}
private renderFolderTree(): void {
if (!this.folderTreeContainer || !this.folderTree) {
return;
}
this.folderTreeContainer.empty();
const renderNode = (node: FolderTreeNode, depth: number = 0): void => {
const nodeEl = this.folderTreeContainer!.createEl("div", {
cls: "folder-tree-node",
});
nodeEl.style.paddingLeft = `${depth * 1.5}em`;
nodeEl.style.paddingTop = "0.25em";
nodeEl.style.paddingBottom = "0.25em";
nodeEl.style.cursor = "pointer";
nodeEl.style.display = "flex";
nodeEl.style.alignItems = "center";
nodeEl.style.gap = "0.5em";
// Highlight if selected
if (node.path === this.selectedFolderPath) {
nodeEl.style.background = "var(--background-modifier-active-hover)";
}
// Expand/collapse button (if has children)
if (node.children.length > 0) {
const expandBtn = nodeEl.createEl("span", {
text: this.expandedFolders.has(node.path) ? "▼" : "▶",
cls: "folder-tree-expand",
});
expandBtn.style.width = "1em";
expandBtn.style.fontSize = "0.8em";
expandBtn.onclick = (e) => {
e.stopPropagation();
if (this.expandedFolders.has(node.path)) {
this.expandedFolders.delete(node.path);
} else {
this.expandedFolders.add(node.path);
}
this.renderFolderTree();
};
} else {
const spacer = nodeEl.createEl("span", { text: " " });
spacer.style.width = "1em";
}
// Folder name
const nameEl = nodeEl.createEl("span", {
text: node.name,
cls: "folder-tree-name",
});
nameEl.style.flex = "1";
// Count
const countEl = nodeEl.createEl("span", {
text: `(${node.noteCount})`,
cls: "folder-tree-count",
});
countEl.style.fontSize = "0.85em";
countEl.style.color = "var(--text-muted)";
// Click handler
nodeEl.onclick = () => {
this.selectedFolderPath = node.path === "" ? null : node.path;
this.refresh();
};
// Render children if expanded
if (node.children.length > 0 && this.expandedFolders.has(node.path)) {
for (const child of node.children) {
renderNode(child, depth + 1);
}
}
};
renderNode(this.folderTree);
}
private renderResults(): void {
if (!this.resultsContainer) {
return;
}
// Get all entries
let entries = this.noteIndex.getAllEntries();
// Apply filters
const filterOptions: FilterOptions = {
search: this.searchQuery || undefined,
selectedFolderPath: this.selectedFolderPath,
typeSet: this.selectedTypes.size > 0 ? this.selectedTypes : undefined,
includeNoneType: this.includeNoneType,
};
entries = applyFilters(entries, filterOptions);
// Sort
const sortOptions: SortOptions = {
mode: this.sortMode,
searchQuery: this.searchQuery || undefined,
};
entries = sortNotes(entries, sortOptions);
// Cache filtered entries for virtualization
this.allFilteredEntries = entries;
// Group if needed
if (this.sortMode === "type") {
const groups = groupByType(entries, this.searchQuery);
this.renderGroupedResults(groups);
} else if (this.sortMode === "folder") {
const groups = groupByFolder(entries, this.searchQuery);
this.renderGroupedResults(groups);
} else {
this.renderFlatResults(entries);
}
}
private renderVisibleItems(): void {
// Re-render only visible items from cached filtered entries (for scroll updates)
if (!this.resultsContainer || this.allFilteredEntries.length === 0) {
return;
}
// Use the same logic as renderFlatResults but with cached entries
this.renderFlatResults(this.allFilteredEntries);
}
private renderFlatResults(entries: NoteIndexEntry[]): void {
if (!this.resultsContainer) {
return;
}
if (entries.length === 0) {
const emptyEl = this.resultsContainer.createEl("div", {
text: "No notes found",
cls: "entity-picker-empty",
});
emptyEl.style.padding = "1em";
emptyEl.style.textAlign = "center";
emptyEl.style.color = "var(--text-muted)";
return;
}
// Virtualization: only render visible items
const visibleEntries = entries.slice(this.visibleStartIndex, this.visibleEndIndex);
const itemHeight = 60; // Approximate height per item
const offsetY = this.visibleStartIndex * itemHeight;
// Clear container
this.resultsContainer.empty();
// Add spacer for items before visible range
if (this.visibleStartIndex > 0) {
const topSpacer = this.resultsContainer.createEl("div");
topSpacer.style.height = `${offsetY}px`;
}
// Render visible items
for (const entry of visibleEntries) {
const itemEl = this.resultsContainer.createEl("div", {
cls: "entity-picker-item",
});
itemEl.style.padding = "0.5em";
itemEl.style.cursor = "pointer";
itemEl.style.borderBottom = "1px solid var(--background-modifier-border)";
itemEl.onmouseenter = () => {
itemEl.style.background = "var(--background-modifier-hover)";
};
itemEl.onmouseleave = () => {
itemEl.style.background = "";
};
// Basename/Title
const nameEl = itemEl.createEl("div", {
text: entry.title || entry.basename,
cls: "entity-picker-item-name",
});
nameEl.style.fontWeight = "500";
// Meta: type, folder
const metaEl = itemEl.createEl("div", {
cls: "entity-picker-item-meta",
});
metaEl.style.fontSize = "0.85em";
metaEl.style.color = "var(--text-muted)";
metaEl.style.display = "flex";
metaEl.style.gap = "1em";
if (entry.type) {
metaEl.createEl("span", { text: `Type: ${entry.type}` });
}
if (entry.folder) {
metaEl.createEl("span", { text: `Folder: ${entry.folder}` });
}
// Click handler
itemEl.onclick = () => {
this.selectEntry(entry);
};
}
// Add spacer for items after visible range
const remainingItems = entries.length - this.visibleEndIndex;
if (remainingItems > 0) {
const bottomSpacer = this.resultsContainer.createEl("div");
bottomSpacer.style.height = `${remainingItems * itemHeight}px`;
}
// Show count if many items
if (entries.length > this.itemsPerPage) {
const countEl = this.resultsContainer.createEl("div", {
cls: "entity-picker-count",
});
countEl.style.padding = "0.5em";
countEl.style.textAlign = "center";
countEl.style.fontSize = "0.85em";
countEl.style.color = "var(--text-muted)";
countEl.style.borderTop = "1px solid var(--background-modifier-border)";
countEl.textContent = `Showing ${this.visibleStartIndex + 1}-${Math.min(this.visibleEndIndex, entries.length)} of ${entries.length} notes`;
}
}
private renderGroupedResults(groups: GroupedNoteResult[]): void {
if (!this.resultsContainer) {
return;
}
if (groups.length === 0) {
const emptyEl = this.resultsContainer.createEl("div", {
text: "No notes found",
cls: "entity-picker-empty",
});
emptyEl.style.padding = "1em";
emptyEl.style.textAlign = "center";
emptyEl.style.color = "var(--text-muted)";
return;
}
// For grouped results, render all groups but virtualize items within groups
// This is simpler than full virtualization across groups
let itemIndex = 0;
let renderedItems = 0;
const maxItemsToRender = this.itemsPerPage * 2; // Allow more for grouped view
for (const group of groups) {
// Group header
const groupHeader = this.resultsContainer.createEl("div", {
cls: "entity-picker-group-header",
});
groupHeader.style.padding = "0.5em";
groupHeader.style.fontWeight = "600";
groupHeader.style.background = "var(--background-modifier-border)";
groupHeader.style.borderTop = "1px solid var(--background-modifier-border)";
groupHeader.style.borderBottom = "1px solid var(--background-modifier-border)";
groupHeader.textContent = `${group.groupLabel} (${group.notes.length})`;
// Group items (with virtualization if too many)
const groupItemsToRender = group.notes.length > 50
? group.notes.slice(0, 50)
: group.notes;
for (const entry of groupItemsToRender) {
itemIndex++;
// Skip if we've rendered enough items
if (renderedItems >= maxItemsToRender) {
break;
}
renderedItems++;
const itemEl = this.resultsContainer.createEl("div", {
cls: "entity-picker-item",
});
itemEl.style.padding = "0.5em";
itemEl.style.cursor = "pointer";
itemEl.style.borderBottom = "1px solid var(--background-modifier-border)";
itemEl.onmouseenter = () => {
itemEl.style.background = "var(--background-modifier-hover)";
};
itemEl.onmouseleave = () => {
itemEl.style.background = "";
};
// Basename/Title
const nameEl = itemEl.createEl("div", {
text: entry.title || entry.basename,
cls: "entity-picker-item-name",
});
nameEl.style.fontWeight = "500";
// Meta: folder (type is in group header)
if (entry.folder) {
const metaEl = itemEl.createEl("div", {
text: `Folder: ${entry.folder}`,
cls: "entity-picker-item-meta",
});
metaEl.style.fontSize = "0.85em";
metaEl.style.color = "var(--text-muted)";
}
// Click handler
itemEl.onclick = () => {
this.selectEntry(entry);
};
}
// Show "more items" indicator if truncated
if (group.notes.length > 50) {
const moreEl = this.resultsContainer.createEl("div", {
cls: "entity-picker-more",
});
moreEl.style.padding = "0.5em";
moreEl.style.textAlign = "center";
moreEl.style.fontSize = "0.85em";
moreEl.style.color = "var(--text-muted)";
moreEl.style.fontStyle = "italic";
moreEl.textContent = `... and ${group.notes.length - 50} more in this group`;
}
if (renderedItems >= maxItemsToRender) {
break;
}
}
// Show total count if many items
const totalItems = groups.reduce((sum, g) => sum + g.notes.length, 0);
if (totalItems > maxItemsToRender) {
const countEl = this.resultsContainer.createEl("div", {
cls: "entity-picker-count",
});
countEl.style.padding = "0.5em";
countEl.style.textAlign = "center";
countEl.style.fontSize = "0.85em";
countEl.style.color = "var(--text-muted)";
countEl.style.borderTop = "1px solid var(--background-modifier-border)";
countEl.textContent = `Showing first ${maxItemsToRender} of ${totalItems} notes. Use search/filters to narrow results.`;
}
}
private renderTypeFilter(): void {
if (!this.typeFilterContainer) {
return;
}
const allTypes = this.noteIndex.getAllTypes();
this.typeFilterContainer.empty();
// "(none)" option
const noneOption = this.typeFilterContainer.createEl("div", {
cls: "type-filter-option",
});
noneOption.style.padding = "0.25em";
noneOption.style.cursor = "pointer";
noneOption.style.display = "flex";
noneOption.style.alignItems = "center";
noneOption.style.gap = "0.5em";
const noneCheckbox = noneOption.createEl("input", {
type: "checkbox",
});
noneCheckbox.checked = this.includeNoneType;
noneCheckbox.onchange = () => {
this.includeNoneType = noneCheckbox.checked;
this.refresh();
};
noneOption.createEl("label", { text: "(none)" });
noneOption.onclick = () => {
noneCheckbox.checked = !noneCheckbox.checked;
this.includeNoneType = noneCheckbox.checked;
this.refresh();
};
// Type options
for (const type of allTypes) {
const option = this.typeFilterContainer.createEl("div", {
cls: "type-filter-option",
});
option.style.padding = "0.25em";
option.style.cursor = "pointer";
option.style.display = "flex";
option.style.alignItems = "center";
option.style.gap = "0.5em";
const checkbox = option.createEl("input", {
type: "checkbox",
});
checkbox.checked = this.selectedTypes.has(type);
checkbox.onchange = () => {
if (checkbox.checked) {
this.selectedTypes.add(type);
} else {
this.selectedTypes.delete(type);
}
this.refresh();
};
option.createEl("label", { text: type });
option.onclick = () => {
checkbox.checked = !checkbox.checked;
if (checkbox.checked) {
this.selectedTypes.add(type);
} else {
this.selectedTypes.delete(type);
}
this.refresh();
};
}
}
private toggleTypeFilter(): void {
if (!this.typeFilterContainer) {
return;
}
const isVisible = this.typeFilterContainer.style.display !== "none";
if (isVisible) {
this.typeFilterContainer.style.display = "none";
} else {
// Position near the button
this.typeFilterContainer.style.display = "block";
// Simple positioning (could be improved)
this.typeFilterContainer.style.top = "60px";
this.typeFilterContainer.style.right = "20px";
}
}
private selectEntry(entry: NoteIndexEntry): void {
this.onSelect({
basename: entry.basename,
path: entry.path,
});
this.close();
}
}
+461
View File
@@ -0,0 +1,461 @@
/**
* Modal for selecting a folder from the vault.
*/
import { Modal, Notice } from "obsidian";
import { buildFolderTree } from "../entityPicker/folderTree";
import { NoteIndex } from "../entityPicker/noteIndex";
import type { FolderTreeNode } from "../entityPicker/types";
export interface FolderTreeResult {
folderPath: string; // Vault-relative path, empty string for root
}
interface FolderNodeState {
expanded: boolean;
}
export class FolderTreeModal extends Modal {
private result: FolderTreeResult | null = null;
private resolve: ((result: FolderTreeResult | null) => void) | null = null;
private noteIndex: NoteIndex;
private selectedFolderPath: string = ""; // Empty = root
private nodeStates: Map<string, FolderNodeState> = new Map(); // path -> state
constructor(app: any, noteIndex: NoteIndex, initialFolderPath: string = "") {
super(app);
this.noteIndex = noteIndex;
this.selectedFolderPath = initialFolderPath;
}
onOpen(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("folder-tree-modal");
contentEl.createEl("h2", { text: "Select folder" });
// Build folder tree from note paths AND empty folders
const allEntries = this.noteIndex.getAllEntries();
// Also get all folders from vault (including empty ones)
// Use vault.adapter to get all folders
const folderPaths = new Set<string>();
// Add folders from note entries
for (const entry of allEntries) {
if (entry.folder) {
folderPaths.add(entry.folder);
}
}
// Get all folders from vault (including empty)
// Iterate through vault's abstract files to find folders
const allAbstractFiles = this.app.vault.getAllFolders();
for (const folder of allAbstractFiles) {
if (folder.path) {
folderPaths.add(folder.path);
}
}
// Convert to NoteIndexEntry format for buildFolderTree
// We need to create entries for folders that don't have notes
const folderEntries: Array<import("../entityPicker/types").NoteIndexEntry> = [];
for (const folderPath of folderPaths) {
// Check if we already have entries for this folder
const hasEntries = allEntries.some((e) => e.folder === folderPath);
if (!hasEntries) {
// Create a dummy entry for empty folder
folderEntries.push({
path: folderPath,
folder: folderPath,
basename: folderPath.split("/").pop() || "",
title: null,
type: null,
mtime: 0,
});
}
}
// Combine with note entries
const combinedEntries = [...allEntries, ...folderEntries];
const folderTree = buildFolderTree(combinedEntries);
// Current selection display
const currentDisplay = contentEl.createEl("div", { cls: "current-folder" });
currentDisplay.style.marginBottom = "1em";
currentDisplay.style.padding = "0.5em";
currentDisplay.style.backgroundColor = "var(--background-secondary)";
currentDisplay.style.borderRadius = "4px";
const currentLabel = currentDisplay.createEl("span", {
text: "Current: ",
cls: "current-label",
});
const currentPath = currentDisplay.createEl("span", {
text: this.selectedFolderPath || "(root)",
cls: "current-path",
});
currentPath.style.fontWeight = "bold";
// Tree container
const treeContainer = contentEl.createEl("div", { cls: "folder-tree-container" });
treeContainer.style.maxHeight = "400px";
treeContainer.style.overflowY = "auto";
treeContainer.style.border = "1px solid var(--background-modifier-border)";
treeContainer.style.borderRadius = "4px";
treeContainer.style.padding = "0.5em";
// Store scroll position before rendering (if container already exists)
const existingContainer = contentEl.querySelector(".folder-tree-container");
const scrollTop = existingContainer instanceof HTMLElement ? existingContainer.scrollTop : 0;
// Render tree
this.renderFolderTree(folderTree, treeContainer);
// Scroll to selected folder or restore position
setTimeout(() => {
if (this.selectedFolderPath) {
// Scroll to selected folder
const selectedElement = treeContainer.querySelector(`[data-folder-path="${this.selectedFolderPath}"]`);
if (selectedElement && selectedElement instanceof HTMLElement) {
selectedElement.scrollIntoView({ behavior: "auto", block: "center" });
}
} else if (scrollTop > 0) {
// Restore previous scroll position
treeContainer.scrollTop = scrollTop;
}
}, 10);
// Buttons
const buttonContainer = contentEl.createEl("div");
buttonContainer.style.display = "flex";
buttonContainer.style.gap = "0.5em";
buttonContainer.style.justifyContent = "flex-end";
buttonContainer.style.marginTop = "1em";
const cancelBtn = buttonContainer.createEl("button", { text: "Cancel" });
cancelBtn.onclick = () => {
this.result = null;
this.close();
};
const selectRootBtn = buttonContainer.createEl("button", {
text: "Select root",
});
selectRootBtn.onclick = () => {
this.selectedFolderPath = "";
this.result = { folderPath: "" };
this.close();
};
const newRootFolderBtn = buttonContainer.createEl("button", {
text: "New folder in root…",
});
newRootFolderBtn.onclick = async () => {
const folderName = await this.promptForFolderName();
if (folderName && folderName.trim()) {
try {
await this.app.vault.createFolder(folderName.trim());
new Notice(`Folder created: ${folderName.trim()}`);
// Refresh note index
this.noteIndex.refresh();
// Re-render
this.onOpen();
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
new Notice(`Failed to create folder: ${msg}`);
}
}
};
const confirmBtn = buttonContainer.createEl("button", {
text: "Confirm",
cls: "mod-cta",
});
confirmBtn.onclick = () => {
this.result = { folderPath: this.selectedFolderPath };
this.close();
};
}
private renderFolderTree(
tree: FolderTreeNode,
container: HTMLElement,
level: number = 0
): void {
// Skip root node (empty path), render its children
if (tree.path === "") {
// Render root's children
for (const child of tree.children) {
this.renderFolderNode(child, container, level);
}
} else {
// Render this node
this.renderFolderNode(tree, container, level);
}
}
private renderFolderNode(
node: FolderTreeNode,
container: HTMLElement,
level: number
): void {
const isSelected = node.path === this.selectedFolderPath;
const hasChildren = node.children.length > 0;
const state = this.nodeStates.get(node.path) || { expanded: level < 2 }; // Auto-expand first 2 levels
if (!this.nodeStates.has(node.path)) {
this.nodeStates.set(node.path, state);
}
const folderItem = container.createEl("div", {
cls: `folder-item ${isSelected ? "is-selected" : ""}`,
});
folderItem.setAttribute("data-folder-path", node.path);
folderItem.style.display = "flex";
folderItem.style.alignItems = "center";
folderItem.style.padding = "0.25em 0.5em";
folderItem.style.cursor = "pointer";
folderItem.style.borderRadius = "4px";
folderItem.style.marginLeft = `${level * 1.5}em`;
if (isSelected) {
folderItem.style.backgroundColor = "var(--interactive-hover)";
folderItem.style.fontWeight = "bold";
}
folderItem.onmouseenter = () => {
if (!isSelected) {
folderItem.style.backgroundColor = "var(--background-modifier-hover)";
}
};
folderItem.onmouseleave = () => {
if (!isSelected) {
folderItem.style.backgroundColor = "";
}
};
// Expand/collapse button
const expandBtn = folderItem.createEl("span", {
text: hasChildren ? (state.expanded ? "▼" : "▶") : " ",
cls: "expand-icon",
});
expandBtn.style.width = "1em";
expandBtn.style.marginRight = "0.25em";
expandBtn.style.fontSize = "0.8em";
expandBtn.style.cursor = hasChildren ? "pointer" : "default";
expandBtn.style.userSelect = "none";
if (hasChildren) {
expandBtn.onclick = (e) => {
e.stopPropagation();
state.expanded = !state.expanded;
this.onOpen(); // Re-render
};
}
// Folder icon and name
const folderLabel = folderItem.createEl("span", {
text: `📁 ${node.name}`,
});
folderLabel.style.flex = "1";
// Note count
if (node.noteCount > 0) {
const countSpan = folderItem.createEl("span", {
text: ` (${node.noteCount})`,
cls: "note-count",
});
countSpan.style.color = "var(--text-muted)";
countSpan.style.fontSize = "0.9em";
countSpan.style.marginRight = "0.5em";
}
// Action buttons container
const actionsContainer = folderItem.createEl("div", {
cls: "folder-actions",
});
actionsContainer.style.display = "flex";
actionsContainer.style.gap = "0.25em";
actionsContainer.style.opacity = "0";
actionsContainer.style.transition = "opacity 0.2s";
folderItem.onmouseenter = () => {
if (!isSelected) {
folderItem.style.backgroundColor = "var(--background-modifier-hover)";
}
actionsContainer.style.opacity = "1";
};
folderItem.onmouseleave = () => {
if (!isSelected) {
folderItem.style.backgroundColor = "";
}
actionsContainer.style.opacity = "0";
};
// Select button
const selectBtn = actionsContainer.createEl("button", {
text: "Select",
cls: "mod-cta",
});
selectBtn.style.fontSize = "0.85em";
selectBtn.style.padding = "0.2em 0.5em";
selectBtn.onclick = (e) => {
e.stopPropagation();
this.selectedFolderPath = node.path;
// Update display without full re-render to preserve scroll
this.updateSelectionDisplay();
};
// New folder button
const newFolderBtn = actionsContainer.createEl("button", {
text: "+",
title: "Create subfolder",
});
newFolderBtn.style.fontSize = "0.9em";
newFolderBtn.style.padding = "0.2em 0.4em";
newFolderBtn.style.minWidth = "1.5em";
newFolderBtn.onclick = async (e) => {
e.stopPropagation();
const folderName = await this.promptForFolderName();
if (folderName && folderName.trim()) {
const newFolderPath = node.path
? `${node.path}/${folderName.trim()}`
: folderName.trim();
try {
await this.app.vault.createFolder(newFolderPath);
new Notice(`Folder created: ${newFolderPath}`);
// Refresh note index
this.noteIndex.refresh();
// Expand parent and select new folder
state.expanded = true;
this.selectedFolderPath = newFolderPath;
// Re-render (will scroll to selected folder)
this.onOpen();
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
new Notice(`Failed to create folder: ${msg}`);
}
}
};
// Main click: select folder
folderItem.onclick = () => {
this.selectedFolderPath = node.path;
// Update display without full re-render to preserve scroll
this.updateSelectionDisplay();
};
// Render children if expanded
if (hasChildren && state.expanded) {
const childrenContainer = container.createEl("div", {
cls: "folder-children",
});
for (const child of node.children) {
this.renderFolderNode(child, childrenContainer, level + 1);
}
}
}
private async promptForFolderName(): Promise<string | null> {
return new Promise((resolve) => {
const modal = new Modal(this.app);
modal.titleEl.textContent = "New folder name";
const inputContainer = modal.contentEl.createEl("div");
const input = inputContainer.createEl("input", {
type: "text",
placeholder: "Folder name",
});
input.style.width = "100%";
input.style.marginBottom = "1em";
const buttonContainer = modal.contentEl.createEl("div");
buttonContainer.style.display = "flex";
buttonContainer.style.gap = "0.5em";
buttonContainer.style.justifyContent = "flex-end";
const cancelBtn = buttonContainer.createEl("button", { text: "Cancel" });
cancelBtn.onclick = () => {
modal.close();
resolve(null);
};
const createBtn = buttonContainer.createEl("button", {
text: "Create",
cls: "mod-cta",
});
createBtn.onclick = () => {
const value = input.value.trim();
modal.close();
resolve(value || null);
};
input.onkeydown = (evt) => {
if (evt.key === "Enter") {
createBtn.click();
} else if (evt.key === "Escape") {
cancelBtn.click();
}
};
modal.open();
input.focus();
input.select();
});
}
private updateSelectionDisplay(): void {
const { contentEl } = this;
// Update current selection display
const currentPath = contentEl.querySelector(".current-path");
if (currentPath) {
currentPath.textContent = this.selectedFolderPath || "(root)";
}
// Update selected state in tree
const allItems = Array.from(contentEl.querySelectorAll(".folder-item"));
for (const item of allItems) {
const itemPath = item.getAttribute("data-folder-path");
if (itemPath === this.selectedFolderPath) {
item.addClass("is-selected");
if (item instanceof HTMLElement) {
item.style.backgroundColor = "var(--interactive-hover)";
item.style.fontWeight = "bold";
}
} else {
item.removeClass("is-selected");
if (item instanceof HTMLElement) {
item.style.backgroundColor = "";
item.style.fontWeight = "";
}
}
}
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
if (this.resolve) {
this.resolve(this.result);
}
}
/**
* Show modal and return promise that resolves with user's choice.
*/
async show(): Promise<FolderTreeResult | null> {
return new Promise((resolve) => {
this.resolve = resolve;
this.open();
});
}
}
File diff suppressed because it is too large. Load diff
+183
View File
@@ -0,0 +1,183 @@
/**
* Modal for prompting edge type assignment for a single link.
*/
import { Modal } from "obsidian";
import type { LinkWorkItem } from "../mapping/worklistBuilder";
import type { EdgeVocabulary } from "../vocab/types";
import type { GraphSchema } from "../mapping/graphSchema";
import { EdgeTypeChooserModal, type EdgeTypeChoice } from "./EdgeTypeChooserModal";
import { computeEdgeSuggestions } from "../mapping/schemaHelper";
export type LinkPromptDecision =
| { action: "keep"; edgeType: string }
| { action: "change"; edgeType: string; alias?: string }
| { action: "skip" };
export class LinkPromptModal extends Modal {
private item: LinkWorkItem;
private vocabulary: EdgeVocabulary;
private sourceType: string | null;
private graphSchema: GraphSchema | null;
private result: LinkPromptDecision | null = null;
private resolve: ((result: LinkPromptDecision) => void) | null = null;
constructor(
app: any,
item: LinkWorkItem,
vocabulary: EdgeVocabulary,
sourceType: string | null,
graphSchema: GraphSchema | null = null
) {
super(app);
this.item = item;
this.vocabulary = vocabulary;
this.sourceType = sourceType;
this.graphSchema = graphSchema;
}
onOpen(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("link-prompt-modal");
// Link info
const linkInfo = contentEl.createEl("div", { cls: "link-info" });
linkInfo.createEl("h2", { text: `Link: [[${this.item.link}]]` });
if (this.item.targetType) {
linkInfo.createEl("p", { text: `Target type: ${this.item.targetType}` });
}
// Current mapping (if exists)
if (this.item.currentType) {
const currentInfo = linkInfo.createEl("p", { cls: "current-mapping" });
currentInfo.textContent = `Current edge type: ${this.item.currentType}`;
// Check if current type is prohibited
if (this.graphSchema) {
const suggestions = computeEdgeSuggestions(
this.vocabulary,
this.sourceType,
this.item.targetType,
this.graphSchema
);
if (suggestions.prohibited.includes(this.item.currentType)) {
const warning = linkInfo.createEl("span", {
text: " ⚠️ Prohibited",
cls: "prohibited-warning",
});
warning.style.color = "var(--text-error)";
warning.style.fontWeight = "bold";
}
}
}
// Action buttons
const buttonContainer = contentEl.createEl("div", { cls: "action-buttons" });
buttonContainer.style.display = "flex";
buttonContainer.style.flexDirection = "column";
buttonContainer.style.gap = "0.5em";
buttonContainer.style.marginTop = "1em";
if (this.item.currentType) {
// Keep current
const keepBtn = buttonContainer.createEl("button", {
text: `✅ Keep (${this.item.currentType})`,
cls: "mod-cta",
});
keepBtn.onclick = () => {
this.result = { action: "keep", edgeType: this.item.currentType! };
this.close();
};
// Change type
const changeBtn = buttonContainer.createEl("button", {
text: "Change type...",
});
changeBtn.onclick = async () => {
const chooser = new EdgeTypeChooserModal(
this.app,
this.vocabulary,
this.sourceType,
this.item.targetType,
this.graphSchema
);
const choice = await chooser.show();
if (choice) {
this.result = {
action: "change",
edgeType: choice.edgeType,
alias: choice.alias,
};
this.close();
}
};
// Skip
const skipBtn = buttonContainer.createEl("button", {
text: "Skip link",
});
skipBtn.onclick = () => {
this.result = { action: "skip" };
this.close();
};
} else {
// No current mapping
// Skip
const skipBtn = buttonContainer.createEl("button", {
text: "⏩ Skip link",
});
skipBtn.onclick = () => {
this.result = { action: "skip" };
this.close();
};
// Choose type
const chooseBtn = buttonContainer.createEl("button", {
text: "Choose type...",
cls: "mod-cta",
});
chooseBtn.onclick = async () => {
const chooser = new EdgeTypeChooserModal(
this.app,
this.vocabulary,
this.sourceType,
this.item.targetType,
this.graphSchema
);
const choice = await chooser.show();
if (choice) {
this.result = {
action: "change",
edgeType: choice.edgeType,
alias: choice.alias,
};
this.close();
}
};
}
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
if (this.resolve && this.result) {
this.resolve(this.result);
} else if (this.resolve) {
// User closed without decision, treat as skip
this.resolve({ action: "skip" });
}
}
/**
* Show modal and return promise that resolves with user's decision.
*/
async show(): Promise<LinkPromptDecision> {
return new Promise((resolve) => {
this.resolve = resolve;
this.open();
});
}
}
+610
View File
@@ -0,0 +1,610 @@
import { App, Notice, PluginSettingTab, Setting } from "obsidian";
import type MindnetCausalAssistantPlugin from "../main";
import { VocabularyLoader } from "../vocab/VocabularyLoader";
export class MindnetSettingTab extends PluginSettingTab {
plugin: MindnetCausalAssistantPlugin;
constructor(app: App, plugin: MindnetCausalAssistantPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Mindnet Settings" });
// ============================================
// 1. Dictionary & Schema Configuration
// ============================================
containerEl.createEl("h3", { text: "📚 Dictionary & Schema" });
containerEl.createEl("p", {
text: "Konfigurationsdateien für Edge-Vokabular, Graph-Schema und Interview-Profile.",
cls: "setting-item-description",
});
// Edge vocabulary path
new Setting(containerEl)
.setName("Edge vocabulary path")
.setDesc(
"Pfad zur Edge-Vokabular-Datei (Markdown). Definiert verfügbare Edge-Typen und deren Beschreibungen. Wird für die semantische Mapping-Erstellung verwendet."
)
.addText((text) =>
text
.setPlaceholder("_system/dictionary/edge_vocabulary.md")
.setValue(this.plugin.settings.edgeVocabularyPath)
.onChange(async (value) => {
this.plugin.settings.edgeVocabularyPath = value;
await this.plugin.saveSettings();
})
)
.addButton((button) =>
button
.setButtonText("Validate")
.setCta()
.onClick(async () => {
try {
const text = await VocabularyLoader.loadText(
this.app,
this.plugin.settings.edgeVocabularyPath
);
new Notice(
`Edge vocabulary file found (${text.length} characters)`
);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
new Notice(
`Failed to load edge vocabulary: ${msg}`
);
}
})
);
// Graph schema path
new Setting(containerEl)
.setName("Graph schema path")
.setDesc(
"Pfad zur Graph-Schema-Datei (Markdown). Definiert typische und verbotene Edge-Typen für verschiedene Quelltypen. Wird für Empfehlungen beim Mapping verwendet."
)
.addText((text) =>
text
.setPlaceholder("_system/dictionary/graph_schema.md")
.setValue(this.plugin.settings.graphSchemaPath)
.onChange(async (value) => {
this.plugin.settings.graphSchemaPath = value;
await this.plugin.saveSettings();
})
)
.addButton((button) =>
button
.setButtonText("Validate")
.setCta()
.onClick(async () => {
try {
const { GraphSchemaLoader } = await import("../schema/GraphSchemaLoader");
const isValid = await GraphSchemaLoader.validate(
this.app,
this.plugin.settings.graphSchemaPath
);
if (isValid) {
const schema = await GraphSchemaLoader.load(
this.app,
this.plugin.settings.graphSchemaPath
);
const ruleCount = schema.schema.size;
new Notice(
`Graph schema file found (${ruleCount} source types)`
);
} else {
new Notice("Graph schema file not found or invalid");
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
new Notice(`Failed to validate graph schema: ${msg}`);
}
})
);
// Interview config path
new Setting(containerEl)
.setName("Interview config path")
.setDesc(
"Pfad zur Interview-Konfigurationsdatei (YAML). Definiert verfügbare Interview-Profile mit ihren Schritten und Einstellungen."
)
.addText((text) =>
text
.setPlaceholder("_system/dictionary/interview_config.yaml")
.setValue(this.plugin.settings.interviewConfigPath)
.onChange(async (value) => {
this.plugin.settings.interviewConfigPath = value;
await this.plugin.saveSettings();
})
)
.addButton((button) =>
button
.setButtonText("Validate")
.setCta()
.onClick(async () => {
try {
const { InterviewConfigLoader } = await import("../interview/InterviewConfigLoader");
const result = await InterviewConfigLoader.loadConfig(
this.app,
this.plugin.settings.interviewConfigPath
);
if (result.errors.length > 0) {
new Notice(
`Interview config loaded with ${result.errors.length} error(s). Check console.`
);
console.warn("Interview config errors:", result.errors);
} else {
new Notice(
`Interview config file found (${result.config.profiles.length} profile(s))`
);
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
new Notice(`Failed to load interview config: ${msg}`);
}
})
);
// ============================================
// 2. Graph Traversal & Linting
// ============================================
containerEl.createEl("h3", { text: "🔍 Graph Traversal & Linting" });
containerEl.createEl("p", {
text: "Einstellungen für Graph-Durchquerung und Lint-Validierung.",
cls: "setting-item-description",
});
// Max hops
new Setting(containerEl)
.setName("Max hops")
.setDesc(
"Maximale Anzahl von Hops (Schritten) bei der Graph-Durchquerung. Bestimmt, wie tief der Graph durchsucht wird."
)
.addText((text) =>
text
.setPlaceholder("3")
.setValue(String(this.plugin.settings.maxHops))
.onChange(async (value) => {
const numValue = parseInt(value, 10);
if (!isNaN(numValue) && numValue > 0) {
this.plugin.settings.maxHops = numValue;
await this.plugin.saveSettings();
}
})
);
// Chain direction
new Setting(containerEl)
.setName("Chain direction")
.setDesc(
"Richtung für Chain-Traversal: 'Forward' (vorwärts), 'Backward' (rückwärts) oder 'Both' (beide Richtungen)."
)
.addDropdown((dropdown) =>
dropdown
.addOption("forward", "Forward")
.addOption("backward", "Backward")
.addOption("both", "Both")
.setValue(this.plugin.settings.chainDirection)
.onChange(async (value) => {
if (value === "forward" || value === "backward" || value === "both") {
this.plugin.settings.chainDirection = value;
await this.plugin.saveSettings();
}
})
);
// Strict mode
new Setting(containerEl)
.setName("Strict mode")
.setDesc(
"Aktiviert den strikten Validierungsmodus. Erzwingt strengere Regeln bei der Lint-Validierung."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.strictMode)
.onChange(async (value) => {
this.plugin.settings.strictMode = value;
await this.plugin.saveSettings();
})
);
// Show canonical hints
new Setting(containerEl)
.setName("Show canonical hints")
.setDesc(
"Zeigt INFO-Hinweise mit kanonischer Edge-Typ-Auflösung in den Lint-Ergebnissen an. Hilfreich für die Debugging von Edge-Typ-Zuordnungen."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.showCanonicalHints)
.onChange(async (value) => {
this.plugin.settings.showCanonicalHints = value;
await this.plugin.saveSettings();
})
);
// ============================================
// 3. Interview & Note Creation
// ============================================
containerEl.createEl("h3", { text: "📝 Interview & Note Creation" });
containerEl.createEl("p", {
text: "Einstellungen für Interview-Wizard und Notiz-Erstellung.",
cls: "setting-item-description",
});
// Auto-start interview on create
new Setting(containerEl)
.setName("Auto-start interview on create")
.setDesc(
"Startet automatisch den Interview-Wizard, wenn eine neue Notiz über ein Profil erstellt wird."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.autoStartInterviewOnCreate)
.onChange(async (value) => {
this.plugin.settings.autoStartInterviewOnCreate = value;
await this.plugin.saveSettings();
})
);
// Default notes folder
new Setting(containerEl)
.setName("Default notes folder")
.setDesc(
"Standard-Ordner für neue Notizen (vault-relativer Pfad, leer für Root). Profil-spezifische Defaults haben Vorrang."
)
.addText((text) =>
text
.setPlaceholder("")
.setValue(this.plugin.settings.defaultNotesFolder)
.onChange(async (value) => {
this.plugin.settings.defaultNotesFolder = value || "";
await this.plugin.saveSettings();
})
);
// ============================================
// 4. Unresolved Link Handling
// ============================================
containerEl.createEl("h3", { text: "🔗 Unresolved Link Handling" });
containerEl.createEl("p", {
text: "Konfiguration für das Verhalten bei Klicks auf nicht aufgelöste Links.",
cls: "setting-item-description",
});
// Intercept unresolved links
new Setting(containerEl)
.setName("Intercept unresolved link clicks")
.setDesc(
"Aktiviert die Abfangen von Klicks auf nicht aufgelöste interne Links. Öffnet die Profilauswahl, wenn auf einen nicht existierenden Link geklickt wird."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.interceptUnresolvedLinkClicks)
.onChange(async (value) => {
this.plugin.settings.interceptUnresolvedLinkClicks = value;
await this.plugin.saveSettings();
})
);
// Auto-start interview on unresolved click
new Setting(containerEl)
.setName("Auto-start interview on unresolved link click")
.setDesc(
"Startet automatisch den Interview-Wizard, wenn eine Notiz aus einem nicht aufgelösten Link erstellt wird. Erfordert, dass 'Intercept unresolved link clicks' aktiviert ist."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.autoStartOnUnresolvedClick)
.onChange(async (value) => {
this.plugin.settings.autoStartOnUnresolvedClick = value;
await this.plugin.saveSettings();
})
);
// Bypass modifier (Reading View)
new Setting(containerEl)
.setName("Bypass modifier (Reading View)")
.setDesc(
"Modifier-Taste zum Umgehen des Link-Intercepts in der Leseansicht. Wenn diese Taste gedrückt wird, wird der Standard-Link-Klick ausgeführt (z.B. zum Erstellen einer leeren Notiz)."
)
.addDropdown((dropdown) =>
dropdown
.addOption("Alt", "Alt")
.addOption("Ctrl", "Ctrl/Cmd")
.addOption("Shift", "Shift")
.addOption("None", "None")
.setValue(this.plugin.settings.bypassModifier)
.onChange(async (value) => {
if (value === "Alt" || value === "Ctrl" || value === "Shift" || value === "None") {
this.plugin.settings.bypassModifier = value;
await this.plugin.saveSettings();
}
})
);
// Editor follow modifier (Live Preview/Source)
new Setting(containerEl)
.setName("Editor follow modifier (Live Preview/Source)")
.setDesc(
"Modifier-Taste, die im Editor (Live Preview/Source) gedrückt werden muss, um den Link-Intercept zu aktivieren. Standard: Ctrl/Cmd. Verhindert versehentliche Intercepts beim normalen Bearbeiten."
)
.addDropdown((dropdown) =>
dropdown
.addOption("Alt", "Alt")
.addOption("Ctrl", "Ctrl/Cmd")
.addOption("Shift", "Shift")
.addOption("None", "None")
.setValue(this.plugin.settings.editorFollowModifier)
.onChange(async (value) => {
if (value === "Alt" || value === "Ctrl" || value === "Shift" || value === "None") {
this.plugin.settings.editorFollowModifier = value;
await this.plugin.saveSettings();
}
})
);
// ============================================
// 5. Templater Compatibility
// ============================================
containerEl.createEl("h3", { text: "⚙️ Templater Compatibility" });
containerEl.createEl("p", {
text: "Einstellungen für die Kompatibilität mit dem Templater-Plugin.",
cls: "setting-item-description",
});
// Wait for first modify after create
new Setting(containerEl)
.setName("Wait for first modify after create")
.setDesc(
"Wartet, bis Templater die Datei modifiziert hat, bevor der Wizard gestartet wird. Empfohlen, wenn Templater verwendet wird, um Konflikte zu vermeiden."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.waitForFirstModifyAfterCreate)
.onChange(async (value) => {
this.plugin.settings.waitForFirstModifyAfterCreate = value;
await this.plugin.saveSettings();
})
);
// Modify timeout
new Setting(containerEl)
.setName("Modify timeout (ms)")
.setDesc(
"Timeout in Millisekunden für das Warten auf ein File-Modify-Event. Wenn Templater nicht innerhalb dieser Zeit reagiert, wird der Wizard trotzdem gestartet."
)
.addText((text) =>
text
.setPlaceholder("1200")
.setValue(String(this.plugin.settings.waitForModifyTimeoutMs))
.onChange(async (value) => {
const numValue = parseInt(value, 10);
if (!isNaN(numValue) && numValue > 0) {
this.plugin.settings.waitForModifyTimeoutMs = numValue;
await this.plugin.saveSettings();
}
})
);
// ============================================
// 6. Note Adoption
// ============================================
containerEl.createEl("h3", { text: "🔄 Note Adoption" });
containerEl.createEl("p", {
text: "Einstellungen für die automatische Übernahme neu erstellter Notizen im Editor.",
cls: "setting-item-description",
});
// Adopt new notes in editor
new Setting(containerEl)
.setName("Adopt new notes in editor")
.setDesc(
"Übernimmt automatisch neu erstellte Notizen im Editor und konvertiert sie in das Mindnet-Format (mit Frontmatter-ID). Nützlich, wenn Obsidian eine Notiz direkt erstellt, bevor unser Intercept greift."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.adoptNewNotesInEditor)
.onChange(async (value) => {
this.plugin.settings.adoptNewNotesInEditor = value;
await this.plugin.saveSettings();
})
);
// Adopt max chars
new Setting(containerEl)
.setName("Adopt max chars")
.setDesc(
"Maximale Inhaltslänge (in Zeichen), um eine Notiz als Übernahme-Kandidat zu betrachten. Leere oder sehr kurze Notizen werden bevorzugt übernommen."
)
.addText((text) =>
text
.setPlaceholder("200")
.setValue(String(this.plugin.settings.adoptMaxChars))
.onChange(async (value) => {
const numValue = parseInt(value, 10);
if (!isNaN(numValue) && numValue > 0) {
this.plugin.settings.adoptMaxChars = numValue;
await this.plugin.saveSettings();
}
})
);
// Adopt confirm mode
new Setting(containerEl)
.setName("Adopt confirm mode")
.setDesc(
"Wann die Übernahme-Bestätigung angezeigt wird: 'Always ask' (immer fragen), 'Only for low confidence' (nur bei niedriger Konfidenz, überspringt bei hoher Konfidenz), oder 'Never ask' (nie fragen, automatisch übernehmen)."
)
.addDropdown((dropdown) =>
dropdown
.addOption("always", "Always ask")
.addOption("onlyLowConfidence", "Only for low confidence")
.addOption("never", "Never ask")
.setValue(this.plugin.settings.adoptConfirmMode)
.onChange(async (value) => {
if (value === "always" || value === "onlyLowConfidence" || value === "never") {
this.plugin.settings.adoptConfirmMode = value;
await this.plugin.saveSettings();
}
})
);
// High confidence window
new Setting(containerEl)
.setName("High confidence window (ms)")
.setDesc(
"Zeitfenster in Millisekunden für die hohe Konfidenz-Übernahme. Notizen, die innerhalb dieses Zeitfensters nach einem Klick erstellt wurden, werden mit hoher Konfidenz als Übernahme-Kandidaten betrachtet."
)
.addText((text) =>
text
.setPlaceholder("3000")
.setValue(String(this.plugin.settings.highConfidenceWindowMs))
.onChange(async (value) => {
const numValue = parseInt(value, 10);
if (!isNaN(numValue) && numValue > 0) {
this.plugin.settings.highConfidenceWindowMs = numValue;
await this.plugin.saveSettings();
}
})
);
// ============================================
// 7. Semantic Mapping Builder
// ============================================
containerEl.createEl("h3", { text: "🕸️ Semantic Mapping Builder" });
containerEl.createEl("p", {
text: "Einstellungen für den Semantic Mapping Builder, der automatisch Mapping-Blöcke in Notizen erstellt.",
cls: "setting-item-description",
});
// Wrapper callout type
new Setting(containerEl)
.setName("Mapping wrapper callout type")
.setDesc(
"Callout-Typ für den Mapping-Wrapper (z.B. 'abstract', 'info', 'note'). Bestimmt das visuelle Erscheinungsbild des Mapping-Blocks."
)
.addText((text) =>
text
.setPlaceholder("abstract")
.setValue(this.plugin.settings.mappingWrapperCalloutType)
.onChange(async (value) => {
this.plugin.settings.mappingWrapperCalloutType = value || "abstract";
await this.plugin.saveSettings();
})
);
// Wrapper title
new Setting(containerEl)
.setName("Mapping wrapper title")
.setDesc(
"Titel-Text für den Mapping-Wrapper-Callout. Wird als Überschrift des Mapping-Blocks angezeigt."
)
.addText((text) =>
text
.setPlaceholder("🕸️ Semantic Mapping")
.setValue(this.plugin.settings.mappingWrapperTitle)
.onChange(async (value) => {
this.plugin.settings.mappingWrapperTitle = value || "🕸️ Semantic Mapping";
await this.plugin.saveSettings();
})
);
// Wrapper folded
new Setting(containerEl)
.setName("Mapping wrapper folded")
.setDesc(
"Startet mit dem Mapping-Wrapper-Callout eingeklappt (collapsed). Reduziert visuellen Lärm in der Notiz."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.mappingWrapperFolded)
.onChange(async (value) => {
this.plugin.settings.mappingWrapperFolded = value;
await this.plugin.saveSettings();
})
);
// Unassigned handling
new Setting(containerEl)
.setName("Unassigned handling")
.setDesc(
"Wie Links ohne bestehende Mappings behandelt werden: 'Prompt (interactive)' (interaktive Auswahl), 'None (skip unmapped)' (überspringen), 'Use default edge type' (Standard-Typ verwenden), oder 'Use advisor' (zukünftig: E1-Engine)."
)
.addDropdown((dropdown) =>
dropdown
.addOption("prompt", "Prompt (interactive)")
.addOption("none", "None (skip unmapped)")
.addOption("defaultType", "Use default edge type")
.addOption("advisor", "Use advisor (future: E1 engine)")
.setValue(this.plugin.settings.unassignedHandling)
.onChange(async (value) => {
if (value === "prompt" || value === "none" || value === "defaultType" || value === "advisor") {
this.plugin.settings.unassignedHandling = value;
await this.plugin.saveSettings();
}
})
);
// Default edge type
new Setting(containerEl)
.setName("Default edge type")
.setDesc(
"Standard-Edge-Typ für nicht zugeordnete Links. Wird nur verwendet, wenn 'Unassigned handling' auf 'Use default edge type' gesetzt ist."
)
.addText((text) =>
text
.setPlaceholder("")
.setValue(this.plugin.settings.defaultEdgeType)
.onChange(async (value) => {
this.plugin.settings.defaultEdgeType = value;
await this.plugin.saveSettings();
})
);
// Allow overwrite existing mappings
new Setting(containerEl)
.setName("Allow overwrite existing mappings")
.setDesc(
"Wenn aktiviert, wird vor dem Überschreiben bestehender Edge-Typ-Zuordnungen eine Bestätigung angefordert. Wenn deaktiviert, werden bestehende Mappings immer beibehalten."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.allowOverwriteExistingMappings)
.onChange(async (value) => {
this.plugin.settings.allowOverwriteExistingMappings = value;
await this.plugin.saveSettings();
})
);
// ============================================
// 8. Debug & Development
// ============================================
containerEl.createEl("h3", { text: "🐛 Debug & Development" });
containerEl.createEl("p", {
text: "Einstellungen für Debugging und Entwicklung.",
cls: "setting-item-description",
});
// Debug logging
new Setting(containerEl)
.setName("Debug logging")
.setDesc(
"Aktiviert ausführliches Debug-Logging für das Unresolved-Link-Handling. Logs erscheinen in der Browser-Konsole (F12). Nützlich für die Fehlersuche."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.debugLogging)
.onChange(async (value) => {
this.plugin.settings.debugLogging = value;
await this.plugin.saveSettings();
})
);
}
}
View File
Whitespace-only changes.
+218
View File
@@ -0,0 +1,218 @@
import { App, Modal, Notice, Setting, TFile } from "obsidian";
import type { InterviewConfig, InterviewProfile } from "../interview/types";
import { FolderTreeModal, type FolderTreeResult } from "./FolderTreeModal";
import { NoteIndex } from "../entityPicker/noteIndex";
export interface ProfileSelectionResult {
profile: InterviewProfile;
title: string;
folderPath: string; // Vault-relative path, empty string for root
}
export class ProfileSelectionModal extends Modal {
result: ProfileSelectionResult | null = null;
onSubmit: (result: ProfileSelectionResult) => void;
config: InterviewConfig;
initialTitle: string;
defaultFolderPath: string;
private noteIndex: NoteIndex;
constructor(
app: App,
config: InterviewConfig,
onSubmit: (result: ProfileSelectionResult) => void,
initialTitle: string = "",
defaultFolderPath: string = ""
) {
super(app);
this.config = config;
this.onSubmit = onSubmit;
this.initialTitle = initialTitle;
this.defaultFolderPath = defaultFolderPath;
this.noteIndex = new NoteIndex(app);
}
onOpen(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Create Note from Profile" });
// Group profiles by group
const grouped = new Map<string, InterviewProfile[]>();
const ungrouped: InterviewProfile[] = [];
for (const profile of this.config.profiles) {
if (profile.group) {
if (!grouped.has(profile.group)) {
grouped.set(profile.group, []);
}
const groupProfiles = grouped.get(profile.group);
if (groupProfiles) {
groupProfiles.push(profile);
}
} else {
ungrouped.push(profile);
}
}
let selectedProfile: InterviewProfile | null = null;
let titleInput: string = this.initialTitle;
let folderPath: string = this.defaultFolderPath;
// Title input
const titleSetting = new Setting(contentEl)
.setName("Title")
.setDesc("Note title")
.addText((text) => {
text.setValue(this.initialTitle).onChange((value) => {
titleInput = value;
});
text.inputEl.focus();
text.inputEl.select();
});
// Folder selection
const folderDisplay = contentEl.createEl("div", { cls: "folder-display" });
folderDisplay.style.marginBottom = "1em";
folderDisplay.style.padding = "0.5em";
folderDisplay.style.backgroundColor = "var(--background-secondary)";
folderDisplay.style.borderRadius = "4px";
const folderLabel = folderDisplay.createEl("span", {
text: "Folder: ",
cls: "folder-label",
});
const folderPathSpan = folderDisplay.createEl("span", {
text: folderPath || "(root)",
cls: "folder-path",
});
folderPathSpan.style.fontWeight = "bold";
const folderButtonContainer = folderDisplay.createEl("div");
folderButtonContainer.style.display = "flex";
folderButtonContainer.style.gap = "0.5em";
folderButtonContainer.style.marginTop = "0.5em";
const pickFolderBtn = folderButtonContainer.createEl("button", {
text: "Anpassen",
});
pickFolderBtn.onclick = async () => {
const folderModal = new FolderTreeModal(this.app, this.noteIndex, folderPath);
const result = await folderModal.show();
if (result) {
folderPath = result.folderPath;
folderPathSpan.textContent = folderPath || "(root)";
}
};
// Profile selection (grouped)
for (const [groupName, profiles] of grouped.entries()) {
contentEl.createEl("h3", { text: groupName });
for (const profile of profiles) {
const setting = new Setting(contentEl)
.setName(profile.label)
.setDesc(`Type: ${profile.note_type}`)
.addButton((button) => {
button.setButtonText("Select").onClick(() => {
// Clear previous selection
contentEl.querySelectorAll(".profile-selected").forEach((el) => {
if (el instanceof HTMLElement) {
el.removeClass("profile-selected");
}
});
// Mark as selected
setting.settingEl.addClass("profile-selected");
selectedProfile = profile;
// Update folder path from profile defaults
const profileFolder = (profile.defaults?.folder as string) || this.defaultFolderPath || "";
folderPath = profileFolder;
folderPathSpan.textContent = folderPath || "(root)";
// Log selection
console.log("Profile selected", {
key: profile.key,
label: profile.label,
noteType: profile.note_type,
stepCount: profile.steps?.length || 0,
defaultFolder: profileFolder,
});
});
});
}
}
// Ungrouped profiles
if (ungrouped.length > 0) {
if (grouped.size > 0) {
contentEl.createEl("h3", { text: "Other" });
}
for (const profile of ungrouped) {
const setting = new Setting(contentEl)
.setName(profile.label)
.setDesc(`Type: ${profile.note_type}`)
.addButton((button) => {
button.setButtonText("Select").onClick(() => {
// Clear previous selection
contentEl.querySelectorAll(".profile-selected").forEach((el) => {
if (el instanceof HTMLElement) {
el.removeClass("profile-selected");
}
});
// Mark as selected
setting.settingEl.addClass("profile-selected");
selectedProfile = profile;
// Update folder path from profile defaults
const profileFolder = (profile.defaults?.folder as string) || this.defaultFolderPath || "";
folderPath = profileFolder;
folderPathSpan.textContent = folderPath || "(root)";
// Log selection
console.log("Profile selected", {
key: profile.key,
label: profile.label,
noteType: profile.note_type,
stepCount: profile.steps?.length || 0,
defaultFolder: profileFolder,
});
});
});
}
}
// Submit button
new Setting(contentEl).addButton((button) => {
button
.setButtonText("Create Note")
.setCta()
.onClick(() => {
if (!selectedProfile) {
new Notice("Please select a profile");
return;
}
if (!titleInput.trim()) {
new Notice("Please enter a title");
return;
}
this.result = {
profile: selectedProfile,
title: titleInput.trim(),
folderPath: folderPath.trim(),
};
this.onSubmit(this.result);
this.close();
});
});
}
onClose(): void {
const { contentEl } = this;
contentEl.empty();
}
}
+530
View File
@@ -0,0 +1,530 @@
/**
* Markdown toolbar helpers for text editors.
*/
/**
* Result of a toolbar operation.
*/
export interface ToolbarResult {
newText: string;
newSelectionStart: number;
newSelectionEnd: number;
}
/**
* Apply markdown formatting to selected text.
* If no selection, inserts before/after at cursor position.
*/
export function applyMarkdownWrap(
text: string,
selectionStart: number,
selectionEnd: number,
before: string,
after: string = ""
): ToolbarResult {
const selectedText = text.substring(selectionStart, selectionEnd);
let newText: string;
let newSelectionStart: number;
let newSelectionEnd: number;
if (selectedText) {
// Wrap selected text
newText = text.substring(0, selectionStart) + before + selectedText + after + text.substring(selectionEnd);
newSelectionStart = selectionStart + before.length + selectedText.length + after.length;
newSelectionEnd = newSelectionStart;
} else {
// Insert at cursor position
newText = text.substring(0, selectionStart) + before + after + text.substring(selectionEnd);
newSelectionStart = selectionStart + before.length;
newSelectionEnd = newSelectionStart;
}
return { newText, newSelectionStart, newSelectionEnd };
}
/**
* Apply wiki link formatting to selected text.
* If no selection, inserts [[text]] with cursor between brackets.
*/
export function applyWikiLink(
text: string,
selectionStart: number,
selectionEnd: number
): ToolbarResult {
const selectedText = text.substring(selectionStart, selectionEnd);
let newText: string;
let newSelectionStart: number;
let newSelectionEnd: number;
if (selectedText) {
// Wrap selected text with [[...]]
newText = text.substring(0, selectionStart) + "[[" + selectedText + "]]" + text.substring(selectionEnd);
newSelectionStart = selectionStart + 2 + selectedText.length + 2;
newSelectionEnd = newSelectionStart;
} else {
// Insert [[text]] with cursor between brackets
newText = text.substring(0, selectionStart) + "[[text]]" + text.substring(selectionEnd);
newSelectionStart = selectionStart + 2;
newSelectionEnd = selectionStart + 6; // Select "text"
}
return { newText, newSelectionStart, newSelectionEnd };
}
/**
* Apply heading prefix to current line(s).
* Toggles heading if already present.
* Always operates on complete lines, even for partial selections.
* Never deletes text content.
*/
export function applyHeading(
text: string,
selectionStart: number,
selectionEnd: number,
level: 2 | 3
): ToolbarResult {
const prefix = "#".repeat(level) + " ";
// Find line boundaries: operate on complete lines touched by selection
// startLine: beginning of first line touched by selection
const startLine = selectionStart > 0
? text.lastIndexOf("\n", selectionStart - 1) + 1
: 0;
// effectiveEnd: if selection ends at newline, don't include next line
const effectiveEnd = (selectionEnd > 0 && text[selectionEnd - 1] === "\n")
? selectionEnd - 1
: selectionEnd;
// endLine: end of last line touched by selection (including newline if present)
const nextNewline = text.indexOf("\n", effectiveEnd);
const endLine = nextNewline >= 0 ? nextNewline + 1 : text.length;
// Extract the complete block of lines to edit
const block = text.substring(startLine, endLine);
const lines = block.split("\n");
// Check if all non-empty lines have the exact same heading prefix as requested
// Must match exactly (e.g., "## " not "### " or "# ")
const nonEmptyLines = lines.filter((line) => line.trim());
const hasSameHeading = nonEmptyLines.length > 0 &&
nonEmptyLines.every((line) => {
const trimmed = line.trim();
// Check if line starts with exactly the requested prefix
// Match the heading pattern and compare to requested prefix
const headingMatch = trimmed.match(/^(#+\s)/);
return headingMatch && headingMatch[1] === prefix;
});
let newText: string;
let newSelectionStart: number;
let newSelectionEnd: number;
if (hasSameHeading) {
// Toggle: Remove heading prefix from ALL lines if they match the requested level
const unprefixedLines = lines.map((line) => {
if (line.trim()) {
const trimmed = line.trim();
// Check if line has exactly the requested heading prefix
const headingMatch = trimmed.match(/^(#+\s)/);
if (headingMatch && headingMatch[1] === prefix) {
// Remove the matching heading prefix, preserve indentation
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch?.[1] ?? "";
// Remove the prefix (e.g., "## ")
const content = trimmed.substring(prefix.length);
return indent + content;
}
}
return line; // Empty lines or lines without matching prefix stay as-is
});
const newBlock = unprefixedLines.join("\n");
newText = text.substring(0, startLine) + newBlock + text.substring(endLine);
newSelectionStart = startLine;
newSelectionEnd = startLine + newBlock.length;
} else {
// Add or replace heading prefix: remove any existing heading, then add new one
const prefixedLines = lines.map((line) => {
if (line.trim()) {
// Preserve indentation
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch?.[1] ?? "";
// Get content without indentation
const withoutIndent = line.substring(indent.length);
// Remove any existing heading prefix (one or more # followed by space)
// Use a more robust regex that handles multiple spaces
const content = withoutIndent.replace(/^#+\s+/, "").trimStart();
// Ensure we have content (not just whitespace)
if (content) {
return indent + prefix + content;
}
// If content is empty after removing heading, return original line
return line;
}
return line; // Preserve empty lines
});
const newBlock = prefixedLines.join("\n");
newText = text.substring(0, startLine) + newBlock + text.substring(endLine);
newSelectionStart = startLine;
newSelectionEnd = startLine + newBlock.length;
}
return { newText, newSelectionStart, newSelectionEnd };
}
/**
* Apply bullet list prefix to selected lines.
* Toggles bullets if already present.
* Always operates on complete lines, even for partial selections.
*/
export function applyBullets(
text: string,
selectionStart: number,
selectionEnd: number
): ToolbarResult {
const prefix = "- ";
// Find line boundaries: operate on complete lines touched by selection
// startLine: beginning of first line touched by selection
const startLine = selectionStart > 0
? text.lastIndexOf("\n", selectionStart - 1) + 1
: 0;
// effectiveEnd: if selection ends at newline, don't include next line
const effectiveEnd = (selectionEnd > 0 && text[selectionEnd - 1] === "\n")
? selectionEnd - 1
: selectionEnd;
// endLine: end of last line touched by selection (including newline if present)
const nextNewline = text.indexOf("\n", effectiveEnd);
const endLine = nextNewline >= 0 ? nextNewline + 1 : text.length;
// Extract the complete block of lines to edit
const block = text.substring(startLine, endLine);
const lines = block.split("\n");
// Check if all non-empty lines have bullet prefix
const nonEmptyLines = lines.filter((line) => line.trim());
const hasBullets = nonEmptyLines.length > 0 &&
nonEmptyLines.every((line) => {
const trimmed = line.trim();
return trimmed.startsWith(prefix.trim());
});
let newText: string;
let newSelectionStart: number;
let newSelectionEnd: number;
if (hasBullets) {
// Remove bullet prefix from all lines
const unprefixedLines = lines.map((line) => {
const trimmed = line.trim();
if (trimmed.startsWith(prefix.trim())) {
// Remove prefix, preserve indentation
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch?.[1] ?? "";
return indent + trimmed.substring(prefix.length);
}
return line; // Empty lines or lines without prefix stay as-is
});
const newBlock = unprefixedLines.join("\n");
newText = text.substring(0, startLine) + newBlock + text.substring(endLine);
newSelectionStart = startLine;
newSelectionEnd = startLine + newBlock.length;
} else {
// Add bullet prefix to each non-empty line
const prefixedLines = lines.map((line) => {
if (line.trim()) {
// Preserve indentation
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch?.[1] ?? "";
const content = line.substring(indent.length);
return indent + prefix + content;
}
return line; // Preserve empty lines
});
const newBlock = prefixedLines.join("\n");
newText = text.substring(0, startLine) + newBlock + text.substring(endLine);
newSelectionStart = startLine;
newSelectionEnd = startLine + newBlock.length;
}
return { newText, newSelectionStart, newSelectionEnd };
}
/**
* Apply numbered list prefix to selected lines.
* Toggles numbered list if already present.
* Always operates on complete lines, even for partial selections.
*/
export function applyNumberedList(
text: string,
selectionStart: number,
selectionEnd: number
): ToolbarResult {
// Find line boundaries: operate on complete lines touched by selection
// startLine: beginning of first line touched by selection
const startLine = selectionStart > 0
? text.lastIndexOf("\n", selectionStart - 1) + 1
: 0;
// effectiveEnd: if selection ends at newline, don't include next line
const effectiveEnd = (selectionEnd > 0 && text[selectionEnd - 1] === "\n")
? selectionEnd - 1
: selectionEnd;
// endLine: end of last line touched by selection (including newline if present)
const nextNewline = text.indexOf("\n", effectiveEnd);
const endLine = nextNewline >= 0 ? nextNewline + 1 : text.length;
// Extract the complete block of lines to edit
const block = text.substring(startLine, endLine);
const lines = block.split("\n");
// Check if all non-empty lines have numbered prefix
const nonEmptyLines = lines.filter((line) => line.trim());
const hasNumbers = nonEmptyLines.length > 0 &&
nonEmptyLines.every((line) => {
const trimmed = line.trim();
return /^\d+\.\s/.test(trimmed);
});
let newText: string;
let newSelectionStart: number;
let newSelectionEnd: number;
if (hasNumbers) {
// Remove numbered prefix from all lines
const unprefixedLines = lines.map((line) => {
const trimmed = line.trim();
const match = trimmed.match(/^(\d+\.\s)(.*)$/);
if (match) {
// Preserve indentation
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch?.[1] ?? "";
return indent + match[2];
}
return line; // Empty lines or lines without prefix stay as-is
});
const newBlock = unprefixedLines.join("\n");
newText = text.substring(0, startLine) + newBlock + text.substring(endLine);
newSelectionStart = startLine;
newSelectionEnd = startLine + newBlock.length;
} else {
// Add numbered prefix to each non-empty line
let counter = 1;
const prefixedLines = lines.map((line) => {
if (line.trim()) {
// Preserve indentation
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch?.[1] ?? "";
const content = line.substring(indent.length);
return indent + `${counter++}. ${content}`;
}
return line; // Preserve empty lines (do not number blank lines)
});
const newBlock = prefixedLines.join("\n");
newText = text.substring(0, startLine) + newBlock + text.substring(endLine);
newSelectionStart = startLine;
newSelectionEnd = startLine + newBlock.length;
}
return { newText, newSelectionStart, newSelectionEnd };
}
/**
* Apply toolbar operation to textarea.
*/
function applyToTextarea(
textarea: HTMLTextAreaElement,
result: ToolbarResult
): void {
textarea.value = result.newText;
textarea.setSelectionRange(result.newSelectionStart, result.newSelectionEnd);
textarea.focus();
textarea.dispatchEvent(new Event("input", { bubbles: true }));
}
/**
* Create markdown toolbar with buttons.
*/
export function createMarkdownToolbar(
textarea: HTMLTextAreaElement,
onTogglePreview?: () => void,
onPickNote?: (app: any) => void
): HTMLElement {
const toolbar = document.createElement("div");
toolbar.className = "markdown-toolbar";
toolbar.style.display = "flex";
toolbar.style.gap = "0.25em";
toolbar.style.padding = "0.5em";
toolbar.style.borderBottom = "1px solid var(--background-modifier-border)";
toolbar.style.flexWrap = "wrap";
toolbar.style.alignItems = "center";
// Bold
const boldBtn = createToolbarButton("B", "Bold (Ctrl+B)", () => {
const result = applyMarkdownWrap(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd,
"**",
"**"
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(boldBtn);
// Italic
const italicBtn = createToolbarButton("I", "Italic (Ctrl+I)", () => {
const result = applyMarkdownWrap(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd,
"*",
"*"
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(italicBtn);
// H2
const h2Btn = createToolbarButton("H2", "Heading 2", () => {
const result = applyHeading(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd,
2
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(h2Btn);
// H3
const h3Btn = createToolbarButton("H3", "Heading 3", () => {
const result = applyHeading(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd,
3
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(h3Btn);
// Bullet List
const bulletBtn = createToolbarButton("•", "Bullet List", () => {
const result = applyBullets(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(bulletBtn);
// Numbered List
const numberedBtn = createToolbarButton("1.", "Numbered List", () => {
const result = applyNumberedList(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(numberedBtn);
// Code
const codeBtn = createToolbarButton("</>", "Code (Ctrl+`)", () => {
const result = applyMarkdownWrap(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd,
"`",
"`"
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(codeBtn);
// Link (WikiLink)
const linkBtn = createToolbarButton("🔗", "Wiki Link", () => {
const result = applyWikiLink(
textarea.value,
textarea.selectionStart,
textarea.selectionEnd
);
applyToTextarea(textarea, result);
});
toolbar.appendChild(linkBtn);
// Pick note button (if callback provided)
if (onPickNote) {
const pickNoteBtn = createToolbarButton("📎", "Pick note…", () => {
// Get app from window (Obsidian exposes it globally)
const app = (window as any).app;
if (app && onPickNote) {
onPickNote(app);
} else {
console.warn("App not available for entity picker");
}
});
toolbar.appendChild(pickNoteBtn);
}
// Preview toggle
if (onTogglePreview) {
const previewBtn = createToolbarButton("👁️", "Toggle Preview", () => {
onTogglePreview();
});
previewBtn.style.marginLeft = "auto";
toolbar.appendChild(previewBtn);
}
return toolbar;
}
/**
* Create a toolbar button.
*/
function createToolbarButton(
label: string,
title: string,
onClick: () => void
): HTMLElement {
const button = document.createElement("button");
button.textContent = label;
button.title = title;
button.className = "markdown-toolbar-button";
button.style.padding = "0.25em 0.5em";
button.style.border = "1px solid var(--background-modifier-border)";
button.style.borderRadius = "4px";
button.style.background = "var(--background-primary)";
button.style.cursor = "pointer";
button.style.fontSize = "0.9em";
button.style.minWidth = "2em";
button.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
onClick();
});
button.addEventListener("mouseenter", () => {
button.style.background = "var(--interactive-hover)";
});
button.addEventListener("mouseleave", () => {
button.style.background = "var(--background-primary)";
});
return button;
}
+186
View File
@@ -0,0 +1,186 @@
/**
* Helper functions for adopting newly created notes.
*/
import { TFile } from "obsidian";
import { extractFrontmatterId } from "../parser/parseFrontmatter";
export interface PendingCreateHint {
basename: string;
sourcePath: string;
timestamp: number;
}
/**
* Check if a file is a candidate for adoption.
* A file is adoptable if:
* - Content is empty/whitespace OR content length < maxChars
* - Frontmatter has no "id" field
*/
export function isAdoptCandidate(
content: string,
maxChars: number
): boolean {
// Check content length
const trimmedContent = content.trim();
if (trimmedContent.length > maxChars) {
return false;
}
// Check if frontmatter has id
const frontmatterId = extractFrontmatterId(content);
if (frontmatterId) {
return false; // Already has id, not a fresh note
}
return true;
}
/**
* Check if a created file matches a pending create hint.
* Returns true if basename matches and within time window.
*/
export function matchesPendingHint(
file: TFile,
hint: PendingCreateHint | null,
timeWindowMs: number = 3000
): boolean {
if (!hint) return false;
const fileBasename = file.basename;
const timeDiff = Date.now() - hint.timestamp;
return (
fileBasename === hint.basename &&
timeDiff >= 0 &&
timeDiff <= timeWindowMs
);
}
/**
* Evaluate confidence level for adoption.
* Returns "high" if file is recently created and matches criteria, "low" otherwise.
*/
export function evaluateAdoptionConfidence(
file: TFile,
content: string,
maxChars: number,
hint: PendingCreateHint | null,
timeWindowMs: number
): "high" | "low" {
// Check if file is recently created (within time window)
const fileCtime = file.stat.ctime;
const timeSinceCreation = Date.now() - fileCtime;
const isRecent = timeSinceCreation >= 0 && timeSinceCreation <= timeWindowMs;
if (!isRecent) {
return "low";
}
// Check if adopt candidate (no id, content length OK)
if (!isAdoptCandidate(content, maxChars)) {
return "low";
}
// High confidence if pending hint matches (optional but recommended)
if (matchesPendingHint(file, hint, timeWindowMs)) {
return "high";
}
// Also high confidence if file is very recent (within window) and adopt candidate
// This handles cases where pending hint might not be set
if (isRecent && timeSinceCreation <= 2000) {
// Very recent (within 2 seconds) = high confidence
return "high";
}
return "low";
}
/**
* Merge new frontmatter into existing content.
* Preserves existing frontmatter fields and body content.
*/
export function mergeFrontmatter(
existingContent: string,
newFrontmatter: string
): string {
const lines = existingContent.split(/\r?\n/);
// Check if file has existing frontmatter
if (lines.length > 0 && lines[0]?.trim() === "---") {
// Find closing delimiter
let endIndex = -1;
for (let i = 1; i < lines.length; i++) {
if (lines[i]?.trim() === "---") {
endIndex = i;
break;
}
}
if (endIndex !== -1) {
// Parse existing frontmatter
const existingFrontmatterLines = lines.slice(1, endIndex);
const existingFrontmatterText = existingFrontmatterLines.join("\n");
const bodyLines = lines.slice(endIndex + 1);
// Parse new frontmatter (remove --- delimiters)
const newFrontmatterLines = newFrontmatter.split(/\r?\n/);
const newFrontmatterText = newFrontmatterLines
.filter((line) => line.trim() !== "---")
.join("\n");
// Merge: existing fields take precedence, new fields are added
const merged = mergeYamlFields(existingFrontmatterText, newFrontmatterText);
// Reconstruct content
return `---\n${merged}\n---\n${bodyLines.join("\n")}`;
}
}
// No existing frontmatter, just prepend new one
const body = existingContent.trim();
if (body) {
return `${newFrontmatter}\n\n${body}`;
}
return newFrontmatter;
}
/**
* Merge two YAML field sets.
* Existing fields take precedence over new fields.
*/
function mergeYamlFields(existing: string, newFields: string): string {
const existingMap = parseYamlFields(existing);
const newMap = parseYamlFields(newFields);
// Merge: new fields only if not in existing
const merged = { ...newMap, ...existingMap };
// Convert back to YAML
const lines: string[] = [];
for (const [key, value] of Object.entries(merged)) {
lines.push(`${key}: ${value}`);
}
return lines.join("\n");
}
/**
* Simple YAML field parser.
* Returns map of key: value pairs.
*/
function parseYamlFields(yamlText: string): Record<string, string> {
const map: Record<string, string> = {};
const lines = yamlText.split(/\r?\n/);
for (const line of lines) {
const match = line.match(/^([^:]+):\s*(.+)$/);
if (match && match[1] && match[2]) {
const key = match[1].trim();
const value = match[2].trim();
map[key] = value;
}
}
return map;
}
+160
View File
@@ -0,0 +1,160 @@
/**
* Helper functions for unresolved link detection and handling.
*/
import { App, TFile } from "obsidian";
/**
* Normalize link target by removing alias separator (|) and heading separator (#).
* Preserves spaces and case.
* Examples:
* - "file#sec|alias" -> "file"
* - "My Note" -> "My Note"
* - "My Note|Display" -> "My Note"
*/
export function normalizeLinkTarget(raw: string): string {
if (!raw) return "";
// Split by pipe (alias separator) and take first part
const parts = raw.split("|");
const firstPart = parts[0];
if (!firstPart) return raw.trim();
// Split by hash (heading separator) and take first part
const baseParts = firstPart.split("#");
const base = baseParts[0];
if (!base) return raw.trim();
return base.trim();
}
/**
* Extract link target from an anchor element.
* Prefers data-href attribute, falls back to textContent.
* Returns normalized target (without alias/heading).
*/
export function extractLinkTargetFromAnchor(anchor: HTMLElement): string | null {
const dataHref = anchor.getAttribute("data-href");
const textContent = anchor.textContent;
// Try data-href first
if (dataHref) {
return normalizeLinkTarget(dataHref);
}
// Fall back to text content
if (textContent) {
return normalizeLinkTarget(textContent.trim());
}
return null;
}
/**
* Check if a link target is unresolved (file doesn't exist).
* Uses metadataCache as single source of truth.
*/
export function isUnresolvedLink(
app: App,
target: string,
sourcePath: string
): boolean {
if (!target) return false;
const resolvedFile = app.metadataCache.getFirstLinkpathDest(target, sourcePath);
return resolvedFile === null;
}
/**
* Parse wikilink at cursor position in a line of text.
* Finds the nearest [[...]] that contains or is near the cursor position.
* Returns the raw target (with alias/heading) or null if not found.
*/
export function parseWikilinkAtPosition(
lineText: string,
cursorPosInLine: number
): string | null {
if (!lineText || cursorPosInLine < 0) return null;
// Find all [[...]] pairs in the line
const linkPattern = /\[\[([^\]]+)\]\]/g;
const matches: Array<{ start: number; end: number; target: string }> = [];
let match;
while ((match = linkPattern.exec(lineText)) !== null) {
const start = match.index;
const end = match.index + match[0].length;
const target = match[1]; // Content between [[ and ]]
if (target) {
matches.push({ start, end, target });
}
}
if (matches.length === 0) return null;
// Find the link that contains the cursor or is closest to it
for (const link of matches) {
if (cursorPosInLine >= link.start && cursorPosInLine <= link.end) {
// Cursor is inside this link
return link.target;
}
}
// If cursor is not inside any link, find the nearest one
let nearestLink: { start: number; end: number; target: string } | null = null;
let minDistance = Infinity;
for (const link of matches) {
// Distance to link start or end, whichever is closer
const distToStart = Math.abs(cursorPosInLine - link.start);
const distToEnd = Math.abs(cursorPosInLine - link.end);
const distance = Math.min(distToStart, distToEnd);
if (distance < minDistance) {
minDistance = distance;
nearestLink = link;
}
}
// Only return if reasonably close (e.g., within 10 characters)
if (nearestLink && minDistance <= 10) {
return nearestLink.target;
}
return null;
}
/**
* Wait for a file to be modified after creation, or timeout.
* Returns "modified" if modify event fired, "timeout" otherwise.
* Useful for Templater compatibility.
*/
export function waitForFileModify(
app: App,
file: TFile,
timeoutMs: number
): Promise<"modified" | "timeout"> {
return new Promise((resolve) => {
let resolved = false;
const timeout = setTimeout(() => {
if (!resolved) {
resolved = true;
app.vault.off("modify", handler);
resolve("timeout");
}
}, timeoutMs);
const handler = (modifiedFile: TFile) => {
if (modifiedFile.path === file.path && !resolved) {
resolved = true;
clearTimeout(timeout);
app.vault.off("modify", handler);
resolve("modified");
}
};
app.vault.on("modify", handler);
});
}
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more