Files
tolaria/src/utils/frontmatter.ts
lucaronin 65d1c753ef refactor: improve code health across 6 more files
- DynamicPropertiesPanel.tsx: extract PropertyValueCell, TypeRow, AddPropertyForm (9.06 → 9.68)
- useKeyboardNavigation.ts: extract classifyShortcut and useLatestRef (9.09 → 9.63)
- frontmatter.ts: extract parseScalar, parseInlineArray, isBlockScalar helpers (9.24 → 9.6)
- StatusBar.tsx: extract VaultMenu and VaultMenuItem components (9.23 → 10.0)
- useVaultLoader.ts: extract tauriCall helper and loadVaultData (9.35 → 10.0)
- useNoteActions.ts: extract resolveNewNote, resolveNewType, executeFrontmatterOp (9.22 → 9.38)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 10:55:45 +01:00

69 lines
1.9 KiB
TypeScript

import type { FrontmatterValue } from '../components/Inspector'
export interface ParsedFrontmatter {
[key: string]: FrontmatterValue
}
function unquote(s: string): string {
return s.replace(/^["']|["']$/g, '')
}
function collapseList(items: string[]): FrontmatterValue {
return items.length === 1 ? items[0] : items
}
function isBlockScalar(value: string): boolean {
return value === '' || value === '|' || value === '>'
}
function parseInlineArray(value: string): FrontmatterValue {
const items = value.slice(1, -1).split(',').map(s => unquote(s.trim()))
return collapseList(items)
}
function parseScalar(value: string): FrontmatterValue {
const clean = unquote(value)
if (clean.toLowerCase() === 'true') return true
if (clean.toLowerCase() === 'false') return false
return clean
}
/** Parse YAML frontmatter from content */
export function parseFrontmatter(content: string | null): ParsedFrontmatter {
if (!content) return {}
const match = content.match(/^---\n([\s\S]*?)\n---/)
if (!match) return {}
const result: ParsedFrontmatter = {}
let currentKey: string | null = null
let currentList: string[] = []
let inList = false
for (const line of match[1].split('\n')) {
const listMatch = line.match(/^ - (.*)$/)
if (listMatch && currentKey) {
inList = true
currentList.push(unquote(listMatch[1]))
continue
}
if (inList && currentKey) {
result[currentKey] = collapseList(currentList)
currentList = []
inList = false
}
const kvMatch = line.match(/^["']?([^"':]+)["']?\s*:\s*(.*)$/)
if (!kvMatch) continue
currentKey = kvMatch[1].trim()
const value = kvMatch[2].trim()
if (isBlockScalar(value)) continue
if (value.startsWith('[') && value.endsWith(']')) { result[currentKey] = parseInlineArray(value); continue }
result[currentKey] = parseScalar(value)
}
if (inList && currentKey) result[currentKey] = collapseList(currentList)
return result
}