All files / src App.tsx

40.9% Statements 45/110
50% Branches 11/22
13.51% Functions 5/37
45% Lines 45/100

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                                                    1x       1x                 1x             22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x   22x 22x     22x 21x 14x             22x               22x 7x 7x 7x         22x         22x       22x         22x                   22x               22x             22x           22x           22x                 22x     1x             22x                     22x       22x       22x       22x                       22x   22x                                                                                                                                                        
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Sidebar } from './components/Sidebar'
import { NoteList } from './components/NoteList'
import { Editor } from './components/Editor'
import { ResizeHandle } from './components/ResizeHandle'
import { CreateNoteDialog } from './components/CreateNoteDialog'
import { CreateTypeDialog } from './components/CreateTypeDialog'
import { QuickOpenPalette } from './components/QuickOpenPalette'
import { Toast } from './components/Toast'
import { CommitDialog } from './components/CommitDialog'
import { StatusBar } from './components/StatusBar'
import { useVaultLoader } from './hooks/useVaultLoader'
import { useNoteActions } from './hooks/useNoteActions'
import { useAppKeyboard } from './hooks/useAppKeyboard'
import { isTauri } from './mock-tauri'
import { useKeyboardNavigation } from './hooks/useKeyboardNavigation'
import type { SidebarSelection, GitCommit } from './types'
import './App.css'
 
// Type declaration for mock content storage
declare global {
  interface Window {
    __mockContent?: Record<string, string>
  }
}
 
const DEFAULT_SELECTION: SidebarSelection = { kind: 'filter', filter: 'all' }
 
// In web/browser mode: only Demo v2 (no real vault access)
// In native Tauri mode: Demo v2 + real Laputa vault
const VAULTS = isTauri()
  ? [
      { label: 'Demo v2', path: '/Users/luca/Workspace/laputa-app/demo-vault-v2' },
      { label: 'Laputa', path: '/Users/luca/Laputa' },
    ]
  : [
      { label: 'Demo v2', path: '/Users/luca/Workspace/laputa-app/demo-vault-v2' },
    ]
 
const BUILT_IN_TYPE_NAMES = new Set([
  'Project', 'Experiment', 'Responsibility', 'Procedure',
  'Person', 'Event', 'Topic', 'Type', 'Note', 'Essay',
  'Quarter', 'Journal', 'Evergreen',
])
 
function App() {
  const [selection, setSelection] = useState<SidebarSelection>(DEFAULT_SELECTION)
  const [sidebarWidth, setSidebarWidth] = useState(250)
  const [noteListWidth, setNoteListWidth] = useState(300)
  const [inspectorWidth, setInspectorWidth] = useState(280)
  const [inspectorCollapsed, setInspectorCollapsed] = useState(false)
  const [gitHistory, setGitHistory] = useState<GitCommit[]>([])
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [createNoteDefaultType, setCreateNoteDefaultType] = useState<string | undefined>()
  const [showCreateTypeDialog, setShowCreateTypeDialog] = useState(false)
  const [showQuickOpen, setShowQuickOpen] = useState(false)
  const [showCommitDialog, setShowCommitDialog] = useState(false)
  const [toastMessage, setToastMessage] = useState<string | null>(null)
  const [vaultPath, setVaultPath] = useState(VAULTS[0].path)
  const [showAIChat, setShowAIChat] = useState(false)
 
  const vault = useVaultLoader(vaultPath)
  const notes = useNoteActions(vault.addEntry, vault.updateContent, vault.entries, setToastMessage)
 
  // Derive custom types from vault (Type entries not in built-in list)
  const customTypes = useMemo(
    () => vault.entries
      .filter((e) => e.isA === 'Type' && !BUILT_IN_TYPE_NAMES.has(e.title))
      .map((e) => e.title)
      .sort(),
    [vault.entries],
  )
 
  // Reset UI state when vault changes
  const handleSwitchVault = useCallback((path: string) => {
    setVaultPath(path)
    setSelection(DEFAULT_SELECTION)
    setGitHistory([])
    notes.closeAllTabs()
  }, [notes])
 
  // Load git history when active tab changes
  useEffect(() => {
    Eif (!notes.activeTabPath) {
      setGitHistory([])
      return
    }
    vault.loadGitHistory(notes.activeTabPath).then(setGitHistory)
  }, [notes.activeTabPath, vault.loadGitHistory])
 
  const openCreateDialog = useCallback((type?: string) => {
    setCreateNoteDefaultType(type)
    setShowCreateDialog(true)
  }, [])
 
  const openCreateTypeDialog = useCallback(() => {
    setShowCreateTypeDialog(true)
  }, [])
 
  const handleCreateType = useCallback((name: string) => {
    notes.handleCreateType(name)
    setToastMessage(`Type "${name}" created`)
  }, [notes, setToastMessage])
 
  const handleCustomizeType = useCallback((typeName: string, icon: string, color: string) => {
    const typeEntry = vault.entries.find((e) => e.isA === 'Type' && e.title === typeName)
    if (!typeEntry) return
    // Update icon and color in frontmatter (two separate calls)
    notes.handleUpdateFrontmatter(typeEntry.path, 'icon', icon)
    notes.handleUpdateFrontmatter(typeEntry.path, 'color', color)
    // Also update the entry in-memory for instant UI feedback
    vault.updateEntry(typeEntry.path, { icon, color })
  }, [vault, notes])
 
  const handleTrashNote = useCallback(async (path: string) => {
    const now = new Date().toISOString().slice(0, 10)
    await notes.handleUpdateFrontmatter(path, 'trashed', true)
    await notes.handleUpdateFrontmatter(path, 'trashed_at', now)
    vault.updateEntry(path, { trashed: true, trashedAt: Date.now() / 1000 })
    setToastMessage('Note moved to trash')
  }, [notes, vault, setToastMessage])
 
  const handleRestoreNote = useCallback(async (path: string) => {
    await notes.handleUpdateFrontmatter(path, 'trashed', false)
    await notes.handleDeleteProperty(path, 'trashed_at')
    vault.updateEntry(path, { trashed: false, trashedAt: null })
    setToastMessage('Note restored from trash')
  }, [notes, vault, setToastMessage])
 
  const handleArchiveNote = useCallback(async (path: string) => {
    await notes.handleUpdateFrontmatter(path, 'archived', true)
    vault.updateEntry(path, { archived: true })
    setToastMessage('Note archived')
  }, [notes, vault, setToastMessage])
 
  const handleUnarchiveNote = useCallback(async (path: string) => {
    await notes.handleUpdateFrontmatter(path, 'archived', false)
    vault.updateEntry(path, { archived: false })
    setToastMessage('Note unarchived')
  }, [notes, vault, setToastMessage])
 
  const handleReorderSections = useCallback((orderedTypes: { typeName: string; order: number }[]) => {
    for (const { typeName, order } of orderedTypes) {
      const typeEntry = vault.entries.find((e) => e.isA === 'Type' && e.title === typeName)
      if (!typeEntry) continue
      notes.handleUpdateFrontmatter(typeEntry.path, 'order', order)
      vault.updateEntry(typeEntry.path, { order })
    }
  }, [vault, notes])
 
  useAppKeyboard({
    onQuickOpen: () => setShowQuickOpen(true),
    onCreateNote: openCreateDialog,
    onSave: () => setToastMessage('Saved'),
    onTrashNote: handleTrashNote,
    onArchiveNote: handleArchiveNote,
    activeTabPathRef: notes.activeTabPathRef,
    handleCloseTabRef: notes.handleCloseTabRef,
  })
 
  useKeyboardNavigation({
    tabs: notes.tabs,
    activeTabPath: notes.activeTabPath,
    entries: vault.entries,
    selection,
    allContent: vault.allContent,
    onSwitchTab: notes.handleSwitchTab,
    onReplaceActiveTab: notes.handleReplaceActiveTab,
    onSelectNote: notes.handleSelectNote,
  })
 
  const handleSidebarResize = useCallback((delta: number) => {
    setSidebarWidth((w) => Math.max(150, Math.min(400, w + delta)))
  }, [])
 
  const handleNoteListResize = useCallback((delta: number) => {
    setNoteListWidth((w) => Math.max(200, Math.min(500, w + delta)))
  }, [])
 
  const handleInspectorResize = useCallback((delta: number) => {
    setInspectorWidth((w) => Math.max(200, Math.min(500, w - delta)))
  }, [])
 
  const handleCommitPush = useCallback(async (message: string) => {
    setShowCommitDialog(false)
    try {
      const result = await vault.commitAndPush(message)
      setToastMessage(result)
      vault.loadModifiedFiles()
    } catch (err) {
      console.error('Commit failed:', err)
      setToastMessage(`Commit failed: ${err}`)
    }
  }, [vault])
 
  const activeTab = notes.tabs.find((t) => t.entry.path === notes.activeTabPath) ?? null
 
  return (
    <div className="app-shell">
      <div className="app">
        <div className="app__sidebar" style={{ width: sidebarWidth }}>
          <Sidebar entries={vault.entries} selection={selection} onSelect={setSelection} onSelectNote={notes.handleSelectNote} onCreateType={openCreateDialog} onCreateNewType={openCreateTypeDialog} onCustomizeType={handleCustomizeType} onReorderSections={handleReorderSections} modifiedCount={vault.modifiedFiles.length} onCommitPush={() => setShowCommitDialog(true)} />
        </div>
        <ResizeHandle onResize={handleSidebarResize} />
        <div className="app__note-list" style={{ width: noteListWidth }}>
          <NoteList entries={vault.entries} selection={selection} selectedNote={activeTab?.entry ?? null} allContent={vault.allContent} modifiedFiles={vault.modifiedFiles} onSelectNote={notes.handleSelectNote} onCreateNote={openCreateDialog} />
        </div>
        <ResizeHandle onResize={handleNoteListResize} />
        <div className="app__editor">
          <Editor
            tabs={notes.tabs}
            activeTabPath={notes.activeTabPath}
            entries={vault.entries}
            onSwitchTab={notes.handleSwitchTab}
            onCloseTab={notes.handleCloseTab}
            onReorderTabs={notes.handleReorderTabs}
            onNavigateWikilink={notes.handleNavigateWikilink}
            onLoadDiff={vault.loadDiff}
            onLoadDiffAtCommit={vault.loadDiffAtCommit}
            isModified={vault.isFileModified}
            onCreateNote={openCreateDialog}
            inspectorCollapsed={inspectorCollapsed}
            onToggleInspector={() => setInspectorCollapsed((c) => !c)}
            inspectorWidth={inspectorWidth}
            onInspectorResize={handleInspectorResize}
            inspectorEntry={activeTab?.entry ?? null}
            inspectorContent={activeTab?.content ?? null}
            allContent={vault.allContent}
            gitHistory={gitHistory}
            onUpdateFrontmatter={notes.handleUpdateFrontmatter}
            onDeleteProperty={notes.handleDeleteProperty}
            onAddProperty={notes.handleAddProperty}
            showAIChat={showAIChat}
            onToggleAIChat={() => setShowAIChat(c => !c)}
            vaultPath={vaultPath}
            onTrashNote={handleTrashNote}
            onRestoreNote={handleRestoreNote}
            onArchiveNote={handleArchiveNote}
            onUnarchiveNote={handleUnarchiveNote}
          />
        </div>
      </div>
      <StatusBar noteCount={vault.entries.length} vaultPath={vaultPath} vaults={VAULTS} onSwitchVault={handleSwitchVault} />
      <Toast message={toastMessage} onDismiss={() => setToastMessage(null)} />
      <QuickOpenPalette
        open={showQuickOpen}
        entries={vault.entries}
        onSelect={notes.handleSelectNote}
        onClose={() => setShowQuickOpen(false)}
      />
      <CreateNoteDialog
        open={showCreateDialog}
        onClose={() => setShowCreateDialog(false)}
        onCreate={notes.handleCreateNote}
        defaultType={createNoteDefaultType}
        customTypes={customTypes}
      />
      <CreateTypeDialog
        open={showCreateTypeDialog}
        onClose={() => setShowCreateTypeDialog(false)}
        onCreate={handleCreateType}
      />
      <CommitDialog
        open={showCommitDialog}
        modifiedCount={vault.modifiedFiles.length}
        onCommit={handleCommitPush}
        onClose={() => setShowCommitDialog(false)}
      />
    </div>
  )
}
 
export default App