Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | 1x 7x 7x 7x 7x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 7x 7x 22x 7x 7x 22x 22x | import { useCallback, useEffect, useRef, useState } from 'react'
import { invoke } from '@tauri-apps/api/core'
import { isTauri, mockInvoke, addMockEntry, updateMockContent } from '../mock-tauri'
import type { VaultEntry } from '../types'
import type { FrontmatterValue } from '../components/Inspector'
interface Tab {
entry: VaultEntry
content: string
}
// Mock frontmatter helpers for browser testing
function updateMockFrontmatter(path: string, key: string, value: FrontmatterValue): string {
const content = window.__mockContent?.[path] || ''
const yamlKey = key.includes(' ') ? `"${key}"` : key
let yamlValue: string
if (Array.isArray(value)) {
yamlValue = '\n' + value.map(v => ` - "${v}"`).join('\n')
} else if (typeof value === 'boolean') {
yamlValue = value ? 'true' : 'false'
} else if (value === null) {
yamlValue = 'null'
} else {
yamlValue = String(value)
}
if (!content.startsWith('---\n')) {
return `---\n${yamlKey}: ${yamlValue}\n---\n${content}`
}
const fmEnd = content.indexOf('\n---', 4)
if (fmEnd === -1) return content
const fm = content.slice(4, fmEnd)
const rest = content.slice(fmEnd + 4)
const keyPattern = new RegExp(`^["']?${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']?\\s*:`, 'm')
if (keyPattern.test(fm)) {
const lines = fm.split('\n')
const newLines: string[] = []
let i = 0
while (i < lines.length) {
if (keyPattern.test(lines[i])) {
i++
while (i < lines.length && lines[i].startsWith(' - ')) i++
if (Array.isArray(value)) {
newLines.push(`${yamlKey}:${yamlValue}`)
} else {
newLines.push(`${yamlKey}: ${yamlValue}`)
}
continue
}
newLines.push(lines[i])
i++
}
return `---\n${newLines.join('\n')}\n---${rest}`
} else {
if (Array.isArray(value)) {
return `---\n${fm}\n${yamlKey}:${yamlValue}\n---${rest}`
} else {
return `---\n${fm}\n${yamlKey}: ${yamlValue}\n---${rest}`
}
}
}
function deleteMockFrontmatterProperty(path: string, key: string): string {
const content = window.__mockContent?.[path] || ''
if (!content.startsWith('---\n')) return content
const fmEnd = content.indexOf('\n---', 4)
if (fmEnd === -1) return content
const fm = content.slice(4, fmEnd)
const rest = content.slice(fmEnd + 4)
const keyPattern = new RegExp(`^["']?${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']?\\s*:`, 'm')
const lines = fm.split('\n')
const newLines: string[] = []
let i = 0
while (i < lines.length) {
if (keyPattern.test(lines[i])) {
i++
while (i < lines.length && lines[i].startsWith(' - ')) i++
continue
}
newLines.push(lines[i])
i++
}
return `---\n${newLines.join('\n')}\n---${rest}`
}
const TAB_ORDER_KEY = 'laputa-tab-order'
function saveTabOrder(tabs: Tab[]) {
try {
localStorage.setItem(TAB_ORDER_KEY, JSON.stringify(tabs.map(t => t.entry.path)))
} catch { /* localStorage may be unavailable */ }
}
function loadTabOrder(): string[] {
try {
const stored = localStorage.getItem(TAB_ORDER_KEY)
return stored ? JSON.parse(stored) : []
} catch {
return []
}
}
async function loadNoteContent(path: string): Promise<string> {
return isTauri()
? invoke<string>('get_note_content', { path })
: mockInvoke<string>('get_note_content', { path })
}
async function replaceTabWithEntry(
entry: VaultEntry,
currentPath: string,
setTabs: React.Dispatch<React.SetStateAction<Tab[]>>,
setActiveTabPath: React.Dispatch<React.SetStateAction<string | null>>,
) {
const applyReplace = (content: string) => {
setTabs((prev) => prev.map((t) =>
t.entry.path === currentPath ? { entry, content } : t
))
setActiveTabPath(entry.path)
}
try {
applyReplace(await loadNoteContent(entry.path))
} catch (err) {
console.warn('Failed to load note content for replace:', err)
applyReplace('')
}
}
export function useNoteActions(
addEntry: (entry: VaultEntry, content: string) => void,
updateContent: (path: string, content: string) => void,
entries: VaultEntry[],
setToastMessage: (msg: string | null) => void,
) {
const [tabs, setTabs] = useState<Tab[]>([])
const [activeTabPath, setActiveTabPath] = useState<string | null>(null)
const activeTabPathRef = useRef(activeTabPath)
activeTabPathRef.current = activeTabPath
const tabsRef = useRef(tabs)
tabsRef.current = tabs
const handleCloseTabRef = useRef<(path: string) => void>(() => {})
const handleSelectNote = useCallback(async (entry: VaultEntry) => {
// If already open, just switch — instant
if (tabsRef.current.some((t) => t.entry.path === entry.path)) {
setActiveTabPath(entry.path)
return
}
// Load content async, then add tab and set active together
try {
const content = await loadNoteContent(entry.path)
setTabs((prev) => {
if (prev.some((t) => t.entry.path === entry.path)) return prev
return [...prev, { entry, content }]
})
setActiveTabPath(entry.path)
} catch (err) {
console.warn('Failed to load note content:', err)
setTabs((prev) => {
if (prev.some((t) => t.entry.path === entry.path)) return prev
return [...prev, { entry, content: '' }]
})
setActiveTabPath(entry.path)
}
}, [])
const handleCloseTab = useCallback((path: string) => {
setTabs((prev) => {
const next = prev.filter((t) => t.entry.path !== path)
if (path === activeTabPathRef.current && next.length > 0) {
const closedIdx = prev.findIndex((t) => t.entry.path === path)
const newIdx = Math.min(closedIdx, next.length - 1)
setActiveTabPath(next[newIdx].entry.path)
} else if (next.length === 0) {
setActiveTabPath(null)
}
return next
})
}, [])
handleCloseTabRef.current = handleCloseTab
const handleSwitchTab = useCallback((path: string) => {
setActiveTabPath(path)
}, [])
const handleNavigateWikilink = useCallback((target: string) => {
const targetLower = target.toLowerCase()
const slugToWords = (s: string) => s.replace(/-/g, ' ').toLowerCase()
const targetAsWords = slugToWords(target.split('/').pop() ?? target)
const found = entries.find((e) => {
if (e.title.toLowerCase() === targetLower) return true
if (e.aliases.some((a) => a.toLowerCase() === targetLower)) return true
const pathStem = e.path.replace(/^.*\/Laputa\//, '').replace(/\.md$/, '')
if (pathStem.toLowerCase() === targetLower) return true
const fileStem = e.filename.replace(/\.md$/, '')
if (fileStem.toLowerCase() === targetLower.split('/').pop()) return true
if (e.title.toLowerCase() === targetAsWords) return true
return false
})
if (found) {
handleSelectNote(found)
} else {
console.warn(`Navigation target not found: ${target}`)
}
}, [entries, handleSelectNote])
const handleCreateNote = useCallback(async (title: string, type: string) => {
const typeToFolder: Record<string, string> = {
Note: 'note', Project: 'project', Experiment: 'experiment',
Responsibility: 'responsibility', Procedure: 'procedure',
Person: 'person', Event: 'event', Topic: 'topic',
}
// Custom types use lowercased type name as folder
const folder = typeToFolder[type] || type.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
const path = `/Users/luca/Laputa/${folder}/${slug}.md`
const now = Math.floor(Date.now() / 1000)
const noStatusTypes = new Set(['Topic', 'Person'])
const newEntry: VaultEntry = {
path, filename: `${slug}.md`, title, isA: type,
aliases: [], belongsTo: [], relatedTo: [],
status: noStatusTypes.has(type) ? null : 'Active',
owner: null, cadence: null, archived: false, trashed: false, trashedAt: null,
modifiedAt: now, createdAt: now, fileSize: 0,
snippet: '', relationships: {}, icon: null, color: null, order: null,
}
const frontmatter = [
'---', `title: ${title}`, `is_a: ${type}`,
...(newEntry.status ? [`status: ${newEntry.status}`] : []),
'---',
].join('\n')
const content = `${frontmatter}\n\n# ${title}\n\n`
if (!isTauri()) {
addMockEntry(newEntry, content)
}
addEntry(newEntry, content)
handleSelectNote(newEntry)
}, [handleSelectNote, addEntry])
const handleCreateType = useCallback(async (typeName: string) => {
const slug = typeName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
const path = `/Users/luca/Laputa/type/${slug}.md`
const now = Math.floor(Date.now() / 1000)
const newEntry: VaultEntry = {
path, filename: `${slug}.md`, title: typeName, isA: 'Type',
aliases: [], belongsTo: [], relatedTo: [],
status: null, owner: null, cadence: null, archived: false, trashed: false, trashedAt: null,
modifiedAt: now, createdAt: now, fileSize: 0,
snippet: '', relationships: {}, icon: null, color: null, order: null,
}
const content = `---\nIs A: Type\n---\n\n# ${typeName}\n\n`
if (!isTauri()) {
addMockEntry(newEntry, content)
}
addEntry(newEntry, content)
handleSelectNote(newEntry)
}, [handleSelectNote, addEntry])
const handleUpdateFrontmatter = useCallback(async (path: string, key: string, value: FrontmatterValue) => {
try {
let newContent: string
if (isTauri()) {
let rustValue: unknown = value
if (Array.isArray(value)) rustValue = value
else if (typeof value === 'boolean') rustValue = value
else if (typeof value === 'number') rustValue = value
else if (value === null) rustValue = null
else rustValue = String(value)
newContent = await invoke<string>('update_frontmatter', { path, key, value: rustValue })
} else {
newContent = updateMockFrontmatter(path, key, value)
updateMockContent(path, newContent)
}
setTabs((prev) => prev.map((t) =>
t.entry.path === path ? { ...t, content: newContent } : t
))
updateContent(path, newContent)
setToastMessage('Property updated')
} catch (err) {
console.error('Failed to update frontmatter:', err)
setToastMessage('Failed to update property')
}
}, [updateContent, setToastMessage])
const handleDeleteProperty = useCallback(async (path: string, key: string) => {
try {
let newContent: string
if (isTauri()) {
newContent = await invoke<string>('delete_frontmatter_property', { path, key })
} else {
newContent = deleteMockFrontmatterProperty(path, key)
updateMockContent(path, newContent)
}
setTabs((prev) => prev.map((t) =>
t.entry.path === path ? { ...t, content: newContent } : t
))
updateContent(path, newContent)
setToastMessage('Property deleted')
} catch (err) {
console.error('Failed to delete property:', err)
setToastMessage('Failed to delete property')
}
}, [updateContent, setToastMessage])
const handleAddProperty = useCallback(async (path: string, key: string, value: FrontmatterValue) => {
return handleUpdateFrontmatter(path, key, value)
}, [handleUpdateFrontmatter])
const handleReplaceActiveTab = useCallback(async (entry: VaultEntry) => {
const currentPath = activeTabPathRef.current
if (!currentPath) { handleSelectNote(entry); return }
if (currentPath === entry.path) return
replaceTabWithEntry(entry, currentPath, setTabs, setActiveTabPath)
}, [handleSelectNote])
const handleReorderTabs = useCallback((fromIndex: number, toIndex: number) => {
setTabs((prev) => {
const next = [...prev]
const [moved] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, moved)
saveTabOrder(next)
return next
})
}, [])
// Persist tab order to localStorage whenever tabs change
useEffect(() => {
Iif (tabs.length > 0) {
saveTabOrder(tabs)
} else {
try { localStorage.removeItem(TAB_ORDER_KEY) } catch { /* noop */ }
}
}, [tabs])
// Restore tab order from localStorage on mount
useEffect(() => {
const savedOrder = loadTabOrder()
Eif (savedOrder.length === 0) return
setTabs((prev) => {
if (prev.length <= 1) return prev
const pathToTab = new Map(prev.map(t => [t.entry.path, t]))
const ordered: Tab[] = []
for (const path of savedOrder) {
const tab = pathToTab.get(path)
if (tab) {
ordered.push(tab)
pathToTab.delete(path)
}
}
// Append any tabs not in saved order (newly opened)
for (const tab of pathToTab.values()) {
ordered.push(tab)
}
return ordered
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const closeAllTabs = useCallback(() => {
setTabs([])
setActiveTabPath(null)
}, [])
return {
tabs,
activeTabPath,
activeTabPathRef,
handleCloseTabRef,
handleSelectNote,
handleCloseTab,
handleSwitchTab,
handleReorderTabs,
handleNavigateWikilink,
handleCreateNote,
handleCreateType,
handleUpdateFrontmatter,
handleDeleteProperty,
handleAddProperty,
handleReplaceActiveTab,
closeAllTabs,
}
}
|