feat: add Timestamp and Toggle components; implement TreeIcon and EditorActions components

- Introduced Timestamp component for displaying formatted dates and relative time.
- Added Toggle component for switch-like functionality with customizable sizes.
- Implemented TreeIcon component for rendering tree icons using Phosphor icons.
- Created EditorActions component for explain and improve actions with icons.
- Developed FileTabs component for managing open files with close functionality.
- Added LazyInlineMonacoEditor and LazyMonacoEditor for lazy loading Monaco editor.
- Implemented NavigationItem for navigation with badges and icons.
- Created PageHeaderContent for displaying page headers with icons and descriptions.
- Added JSON configuration files for various UI components and layouts.
- Enhanced data binding with new computed data source hook.
- Updated component registry and types for new components.
- Configured Vite for improved hot module replacement experience.
This commit is contained in:
2026-01-18 21:42:51 +00:00
parent f69220e7e4
commit bef28e8c91
97 changed files with 4422 additions and 56 deletions

View File

@@ -0,0 +1,76 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
const componentsToAnalyze = {
molecules: ['DataSourceCard', 'EditorToolbar', 'EmptyEditorState', 'MonacoEditorPanel', 'SearchBar'],
organisms: ['EmptyCanvasState', 'PageHeader', 'SchemaEditorCanvas', 'SchemaEditorPropertiesPanel',
'SchemaEditorSidebar', 'SchemaEditorStatusBar', 'SchemaEditorToolbar', 'ToolbarActions'],
}
async function analyzeComponent(category: string, component: string): Promise<void> {
const tsFile = path.join(rootDir, `src/components/${category}/${component}.tsx`)
const content = await fs.readFile(tsFile, 'utf-8')
// Check if it's pure composition (only uses UI primitives)
const hasBusinessLogic = /useState|useEffect|useCallback|useMemo|useReducer|useRef/.test(content)
const hasComplexLogic = /if\s*\(.*\{|switch\s*\(|for\s*\(|while\s*\(/.test(content)
const hasCustomFunctions = /function\s+\w+\(|const\s+\w+\s*=\s*\([^)]*\)\s*=>/.test(content)
// Extract what it imports
const imports = content.match(/import\s+\{[^}]+\}\s+from\s+['"][^'"]+['"]/g) || []
const importedComponents = imports.flatMap(imp => {
const match = imp.match(/\{([^}]+)\}/)
return match ? match[1].split(',').map(s => s.trim()) : []
})
// Check if it only imports from ui/atoms (pure composition)
const onlyUIPrimitives = imports.every(imp =>
imp.includes('@/components/ui/') ||
imp.includes('@/components/atoms/') ||
imp.includes('@/lib/utils') ||
imp.includes('lucide-react') ||
imp.includes('@phosphor-icons')
)
const lineCount = content.split('\n').length
console.log(`\n📄 ${component}`)
console.log(` Lines: ${lineCount}`)
console.log(` Has hooks: ${hasBusinessLogic ? '❌' : '✅'}`)
console.log(` Has complex logic: ${hasComplexLogic ? '❌' : '✅'}`)
console.log(` Only UI primitives: ${onlyUIPrimitives ? '✅' : '❌'}`)
console.log(` Imports: ${importedComponents.slice(0, 5).join(', ')}${importedComponents.length > 5 ? '...' : ''}`)
if (!hasBusinessLogic && onlyUIPrimitives && lineCount < 100) {
console.log(` 🎯 CANDIDATE FOR PURE JSON`)
}
}
async function main() {
console.log('🔍 Analyzing components for pure JSON conversion...\n')
console.log('Looking for components that:')
console.log(' - No hooks (useState, useEffect, etc.)')
console.log(' - No complex logic')
console.log(' - Only import UI primitives')
console.log(' - Are simple compositions\n')
for (const [category, components] of Object.entries(componentsToAnalyze)) {
console.log(`\n═══ ${category.toUpperCase()} ═══`)
for (const component of components) {
try {
await analyzeComponent(category, component)
} catch (e) {
console.log(`\n📄 ${component}`)
console.log(` ⚠️ Could not analyze: ${e}`)
}
}
}
console.log('\n\n✨ Analysis complete!')
}
main().catch(console.error)

View File

@@ -0,0 +1,141 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
// Components we want to remove (restored dependencies)
const targetComponents = {
ui: ['accordion', 'alert', 'aspect-ratio', 'avatar', 'badge', 'button', 'card',
'checkbox', 'collapsible', 'dialog', 'hover-card', 'input', 'label',
'popover', 'progress', 'radio-group', 'resizable', 'scroll-area',
'separator', 'skeleton', 'sheet', 'switch', 'tabs', 'textarea', 'toggle', 'tooltip'],
molecules: ['DataSourceCard', 'EditorToolbar', 'EmptyEditorState', 'MonacoEditorPanel', 'SearchBar'],
organisms: ['EmptyCanvasState', 'PageHeader', 'SchemaEditorCanvas', 'SchemaEditorPropertiesPanel',
'SchemaEditorSidebar', 'SchemaEditorStatusBar', 'SchemaEditorToolbar', 'ToolbarActions'],
atoms: ['Input']
}
interface ImportInfo {
file: string
line: number
importStatement: string
importedComponents: string[]
fromPath: string
}
async function findAllImports(): Promise<ImportInfo[]> {
const imports: ImportInfo[] = []
const searchDirs = [
'src/components',
'src/pages',
'src/lib',
'src'
]
for (const dir of searchDirs) {
const dirPath = path.join(rootDir, dir)
try {
await processDirectory(dirPath, imports)
} catch (e) {
// Directory might not exist, skip
}
}
return imports
}
async function processDirectory(dir: string, imports: ImportInfo[]): Promise<void> {
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory() && !entry.name.includes('node_modules')) {
await processDirectory(fullPath, imports)
} else if (entry.isFile() && (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts'))) {
await processFile(fullPath, imports)
}
}
}
async function processFile(filePath: string, imports: ImportInfo[]): Promise<void> {
const content = await fs.readFile(filePath, 'utf-8')
const lines = content.split('\n')
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
// Check for imports from our target components
for (const [category, components] of Object.entries(targetComponents)) {
for (const component of components) {
const patterns = [
`from ['"]@/components/${category}/${component}['"]`,
`from ['"]./${component}['"]`,
`from ['"]../${component}['"]`,
]
for (const pattern of patterns) {
if (new RegExp(pattern).test(line)) {
// Extract imported components
const importMatch = line.match(/import\s+(?:\{([^}]+)\}|(\w+))\s+from/)
const importedComponents = importMatch
? (importMatch[1] || importMatch[2]).split(',').map(s => s.trim())
: []
imports.push({
file: filePath.replace(rootDir, '').replace(/\\/g, '/'),
line: i + 1,
importStatement: line.trim(),
importedComponents,
fromPath: component
})
}
}
}
}
}
}
async function main() {
console.log('🔍 Finding all imports of target components...\n')
const imports = await findAllImports()
if (imports.length === 0) {
console.log('✅ No imports found! Components can be safely deleted.')
return
}
console.log(`❌ Found ${imports.length} imports that need refactoring:\n`)
const byFile: Record<string, ImportInfo[]> = {}
for (const imp of imports) {
if (!byFile[imp.file]) byFile[imp.file] = []
byFile[imp.file].push(imp)
}
for (const [file, fileImports] of Object.entries(byFile)) {
console.log(`📄 ${file}`)
for (const imp of fileImports) {
console.log(` Line ${imp.line}: ${imp.importStatement}`)
console.log(` → Imports: ${imp.importedComponents.join(', ')}`)
}
console.log()
}
console.log('\n📊 Summary by category:')
const byCategory: Record<string, number> = {}
for (const imp of imports) {
const key = imp.fromPath
byCategory[key] = (byCategory[key] || 0) + 1
}
for (const [component, count] of Object.entries(byCategory).sort((a, b) => b[1] - a[1])) {
console.log(` ${component}: ${count} imports`)
}
}
main().catch(console.error)

View File

@@ -0,0 +1,127 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
// Components we restored (the ones we want to potentially convert to JSON)
const restoredComponents = {
ui: ['accordion', 'alert', 'aspect-ratio', 'avatar', 'badge', 'button', 'card',
'checkbox', 'collapsible', 'dialog', 'hover-card', 'input', 'label',
'popover', 'progress', 'radio-group', 'resizable', 'scroll-area',
'separator', 'skeleton', 'sheet', 'switch', 'tabs', 'textarea', 'toggle', 'tooltip'],
molecules: ['DataSourceCard', 'EditorToolbar', 'EmptyEditorState', 'MonacoEditorPanel', 'SearchBar'],
organisms: ['EmptyCanvasState', 'PageHeader', 'SchemaEditorCanvas', 'SchemaEditorPropertiesPanel',
'SchemaEditorSidebar', 'SchemaEditorStatusBar', 'SchemaEditorToolbar', 'ToolbarActions'],
atoms: ['Input'],
}
interface ComponentAnalysis {
name: string
category: string
pureJSONEligible: boolean
reasons: string[]
complexity: 'simple' | 'medium' | 'complex'
hasHooks: boolean
hasConditionalLogic: boolean
hasHelperFunctions: boolean
hasComplexProps: boolean
importsCustomComponents: boolean
onlyImportsUIorAtoms: boolean
}
async function analyzeComponent(category: string, component: string): Promise<ComponentAnalysis> {
const tsFile = path.join(rootDir, `src/components/${category}/${component}.tsx`)
const content = await fs.readFile(tsFile, 'utf-8')
const hasHooks = /useState|useEffect|useCallback|useMemo|useReducer|useRef|useContext/.test(content)
const hasConditionalLogic = /\?|if\s*\(|switch\s*\(/.test(content)
const hasHelperFunctions = /(?:const|function)\s+\w+\s*=\s*\([^)]*\)\s*=>/.test(content) && /return\s+\(/.test(content.split('return (')[0] || '')
const hasComplexProps = /\.\w+\s*\?/.test(content) || /Object\./.test(content) || /Array\./.test(content)
// Check imports
const importLines = content.match(/import\s+.*?\s+from\s+['"](.*?)['"]/g) || []
const importsCustomComponents = importLines.some(line =>
/@\/components\/(molecules|organisms)/.test(line)
)
const onlyImportsUIorAtoms = importLines.every(line => {
if (!line.includes('@/components/')) return true
return /@\/components\/(ui|atoms)/.test(line)
})
const reasons: string[] = []
if (hasHooks) reasons.push('Has React hooks')
if (hasHelperFunctions) reasons.push('Has helper functions')
if (hasComplexProps) reasons.push('Has complex prop access')
if (importsCustomComponents) reasons.push('Imports molecules/organisms')
if (!onlyImportsUIorAtoms && !importsCustomComponents) reasons.push('Imports non-UI components')
// Determine if eligible for pure JSON
const pureJSONEligible = !hasHooks && !hasHelperFunctions && !hasComplexProps && onlyImportsUIorAtoms
// Complexity scoring
let complexity: 'simple' | 'medium' | 'complex' = 'simple'
if (hasHooks || hasHelperFunctions || hasComplexProps) {
complexity = 'complex'
} else if (hasConditionalLogic || importsCustomComponents) {
complexity = 'medium'
}
return {
name: component,
category,
pureJSONEligible,
reasons,
complexity,
hasHooks,
hasConditionalLogic,
hasHelperFunctions,
hasComplexProps,
importsCustomComponents,
onlyImportsUIorAtoms,
}
}
async function main() {
console.log('🔍 Analyzing restored components for pure JSON eligibility...\\n')
const eligible: ComponentAnalysis[] = []
const ineligible: ComponentAnalysis[] = []
for (const [category, components] of Object.entries(restoredComponents)) {
for (const component of components) {
try {
const analysis = await analyzeComponent(category, component)
if (analysis.pureJSONEligible) {
eligible.push(analysis)
} else {
ineligible.push(analysis)
}
} catch (e) {
console.log(`⚠️ ${component} - Could not analyze: ${e}`)
}
}
}
console.log(`\\n✅ ELIGIBLE FOR PURE JSON (${eligible.length} components)\\n`)
for (const comp of eligible) {
console.log(` ${comp.name} (${comp.category})`)
console.log(` Complexity: ${comp.complexity}`)
console.log(` Conditional: ${comp.hasConditionalLogic ? 'Yes' : 'No'}`)
}
console.log(`\\n❌ MUST STAY TYPESCRIPT (${ineligible.length} components)\\n`)
for (const comp of ineligible) {
console.log(` ${comp.name} (${comp.category})`)
console.log(` Complexity: ${comp.complexity}`)
console.log(` Reasons: ${comp.reasons.join(', ')}`)
}
console.log(`\\n📊 Summary:`)
console.log(` Eligible for JSON: ${eligible.length}`)
console.log(` Must stay TypeScript: ${ineligible.length}`)
console.log(` Conversion rate: ${Math.round(eligible.length / (eligible.length + ineligible.length) * 100)}%`)
}
main().catch(console.error)

View File

@@ -0,0 +1,158 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
/**
* Strategy: Replace static imports with dynamic component loading
*
* Before:
* import { Button } from '@/components/ui/button'
* <Button variant="primary">Click</Button>
*
* After:
* import { getComponent } from '@/lib/component-loader'
* const Button = getComponent('Button')
* <Button variant="primary">Click</Button>
*/
interface RefactorTask {
file: string
replacements: Array<{
oldImport: string
newImport: string
components: string[]
}>
}
const targetComponents = {
ui: ['button', 'card', 'badge', 'label', 'input', 'separator', 'scroll-area',
'tabs', 'dialog', 'textarea', 'tooltip', 'switch', 'alert', 'skeleton',
'progress', 'collapsible', 'resizable', 'popover', 'hover-card', 'checkbox',
'accordion', 'aspect-ratio', 'avatar', 'radio-group', 'sheet', 'toggle'],
molecules: ['DataSourceCard', 'EditorToolbar', 'EmptyEditorState', 'MonacoEditorPanel', 'SearchBar'],
organisms: ['EmptyCanvasState', 'PageHeader', 'SchemaEditorCanvas', 'SchemaEditorPropertiesPanel',
'SchemaEditorSidebar', 'SchemaEditorStatusBar', 'SchemaEditorToolbar', 'ToolbarActions'],
atoms: ['Input']
}
async function refactorFile(filePath: string): Promise<boolean> {
let content = await fs.readFile(filePath, 'utf-8')
let modified = false
// Find all imports to replace
const importLines: string[] = []
const componentsToLoad = new Set<string>()
for (const [category, components] of Object.entries(targetComponents)) {
for (const component of components) {
const patterns = [
new RegExp(`import\\s+\\{([^}]+)\\}\\s+from\\s+['"]@/components/${category}/${component}['"]`, 'g'),
new RegExp(`import\\s+(\\w+)\\s+from\\s+['"]@/components/${category}/${component}['"]`, 'g'),
]
for (const pattern of patterns) {
const matches = content.matchAll(pattern)
for (const match of matches) {
const importedItems = match[1].split(',').map(s => s.trim().split(' as ')[0].trim())
importedItems.forEach(item => componentsToLoad.add(item))
// Remove the import line
content = content.replace(match[0], '')
modified = true
}
}
}
}
if (!modified) return false
// Add dynamic component loader import at top
const loaderImport = `import { loadComponent } from '@/lib/component-loader'\n`
// Add component loading statements
const componentLoads = Array.from(componentsToLoad)
.map(comp => `const ${comp} = loadComponent('${comp}')`)
.join('\n')
// Find first import statement location
const firstImportMatch = content.match(/^import\s/m)
if (firstImportMatch && firstImportMatch.index !== undefined) {
content = content.slice(0, firstImportMatch.index) +
loaderImport + '\n' +
componentLoads + '\n\n' +
content.slice(firstImportMatch.index)
}
await fs.writeFile(filePath, content)
return true
}
async function createComponentLoader() {
const loaderPath = path.join(rootDir, 'src/lib/component-loader.ts')
const loaderContent = `/**
* Dynamic Component Loader
* Loads components from the registry at runtime instead of static imports
*/
import { ComponentType, lazy } from 'react'
const componentCache = new Map<string, ComponentType<any>>()
export function loadComponent(componentName: string): ComponentType<any> {
if (componentCache.has(componentName)) {
return componentCache.get(componentName)!
}
// Try to load from different sources
const loaders = [
() => import(\`@/components/ui/\${componentName.toLowerCase()}\`),
() => import(\`@/components/atoms/\${componentName}\`),
() => import(\`@/components/molecules/\${componentName}\`),
() => import(\`@/components/organisms/\${componentName}\`),
]
// Create lazy component
const LazyComponent = lazy(async () => {
for (const loader of loaders) {
try {
const module = await loader()
return { default: module[componentName] || module.default }
} catch (e) {
continue
}
}
throw new Error(\`Component \${componentName} not found\`)
})
componentCache.set(componentName, LazyComponent)
return LazyComponent
}
export function getComponent(componentName: string): ComponentType<any> {
return loadComponent(componentName)
}
`
await fs.writeFile(loaderPath, loaderContent)
console.log('✅ Created component-loader.ts')
}
async function main() {
console.log('🚀 Starting AGGRESSIVE refactoring to eliminate static imports...\n')
console.log('⚠️ WARNING: This is a MAJOR refactoring affecting 975+ import statements!\n')
console.log('Press Ctrl+C now if you want to reconsider...\n')
await new Promise(resolve => setTimeout(resolve, 3000))
console.log('🔧 Creating dynamic component loader...')
await createComponentLoader()
console.log('\n📝 This approach requires significant testing and may break things.')
console.log(' Recommendation: Manual refactoring of high-value components instead.\n')
}
main().catch(console.error)