From 881c11b5dafa058aa788dd0b0ba877854abc5656 Mon Sep 17 00:00:00 2001 From: Elias <36868565+Prodigist@users.noreply.github.com> Date: Mon, 19 May 2025 01:58:26 +0100 Subject: [PATCH] Added MathJax support, Improved Documentation --- .gitignore | 4 +- CONTRIBUTING.md | 17 +- README.md | 561 +++++++------------------------ docs/03_STATE_MANAGEMENT.md | 219 ++++++++++++ docs/04_FILE_SYSTEM_ACCESS.md | 198 +++++++++++ docs/EXAMPLES/README.md | 1 + main.tsx | 614 +++++++++++++++++++++------------- manifest.json | 2 +- package-lock.json | 4 +- package.json | 2 +- versions.json | 3 +- 11 files changed, 931 insertions(+), 694 deletions(-) create mode 100644 docs/03_STATE_MANAGEMENT.md create mode 100644 docs/04_FILE_SYSTEM_ACCESS.md create mode 100644 docs/EXAMPLES/README.md diff --git a/.gitignore b/.gitignore index 8272cc2..20ff2eb 100644 --- a/.gitignore +++ b/.gitignore @@ -49,4 +49,6 @@ src/core/tailwind.ts # Build artifacts (commonly ignored) main.js.map *.tsbuildinfo -.DS_Store \ No newline at end of file +.DS_Store + +forgottenStuff.txt \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7215f94..b61ca54 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,11 +9,14 @@ First off, thank you for considering contributing to ReactiveNotes! It's people Before diving in, check our current focus areas: - ๐Ÿ“ฑ Mobile support optimization -- ๐ŸŽจ Enhanced visualization capabilities -- ๐Ÿ”„ State management improvements +- ~~๐ŸŽจ Enhanced visualization capabilities~~ +- ~~๐Ÿ”„ State management improvements~~ +* ๐Ÿงฉ Component Templates *(New Focus)* +* ๐Ÿ–ฑ๏ธ GUI for Component Snippets *(New Focus)* - ๐Ÿงช Testing infrastructure -- ๐Ÿ“š Documentation enhancements +- ~~๐Ÿ“š Documentation enhancements~~ +> **Extra note:** If utilising or implementing pre-existing functionality, the general idea is to mirror standard use cases to minimise learning curves for contributors and users alike. ## ๐Ÿ”ง Development Setup ### Prerequisites @@ -68,11 +71,10 @@ ReactiveNotes/ โ”‚ โ”‚ โ”œโ”€โ”€ core/ โ”‚ โ”‚ โ””โ”€โ”€ ui/ โ”‚ โ”œโ”€โ”€ services/ # Core services -โ”‚ โ”‚ โ”œโ”€โ”€ storage.ts -โ”‚ โ”‚ โ””โ”€โ”€ marketData.ts +โ”‚ โ”‚ โ””โ”€โ”€ storage.ts โ”‚ โ”œโ”€โ”€ hooks/ # Custom React hooks โ”‚ โ”œโ”€โ”€ utils/ # Utility functions -โ”‚ โ””โ”€โ”€ main.tsx # Plugin entry point +โ”œโ”€โ”€ main.tsx # Plugin entry point โ”œโ”€โ”€ styles/ # CSS and Tailwind configs โ”œโ”€โ”€ tests/ # Test files โ””โ”€โ”€ types/ # TypeScript definitions @@ -315,7 +317,6 @@ We follow [Semantic Versioning](https://semver.org/): ## ๐Ÿค Community Guidelines ### Communication -- Be respectful and inclusive - Keep discussions technical - Provide context with questions - Use appropriate channels @@ -328,7 +329,7 @@ We follow [Semantic Versioning](https://semver.org/): ### Recognition Contributors are recognized in: -- CONTRIBUTORS.md +- CONTRIBUTORS.md (coming soon) - Release notes - Community spotlights diff --git a/README.md b/README.md index 1f3b694..4a4cb1e 100644 --- a/README.md +++ b/README.md @@ -17,11 +17,17 @@ Transform your Obsidian vault into a reactive computational environment. Reactiv - **Dynamic & Interactive**: Turn static notes into living documents - **Extensible Foundation**: Build your own tools and visualizations ## Compatibility - - Obsidian v1.4.0 or higher - React v18.2.0 +--- + +**New to ReactiveNotes? Start here!** + +**[๐ŸŽจ See it in Action! (Examples)](./docs/EXAMPLES/README.md)**: Explore a gallery of what you can build. + +--- ## ๐Ÿš€ Quick Start ### Installation @@ -50,56 +56,113 @@ export default Greeting; ```` **Component Requirements:** -- Must include a default export - Must be self-contained in one code block -- Component ro Render must be the first component within codeblock +- Component to Render must be the first component within codeblock -### Component Structure +## ๐Ÿ’ป Core Features -A typical component structure follows this basic structure: -```` -```react -// Optional: CDN imports at the top -import ExternalLib from 'https://cdnjs.cloudflare.com/...'; +### 1. React Components in Notes +Build dynamic UIs directly in your notes with React 18 and TypeScript. Features robust error handling, lifecycle management, and real-time updates. -// Component definition -const MyComponent = () => { - // 1. Hooks - const [state, setState] = useState(null); - const componentRef = useRef(null); - - // 2. Effects & Lifecycle - useEffect(() => { - // Setup code - return () => { - // Cleanup code - }; - }, []); - - // 3. Helper functions - const handleEvent = () => { - // Event handling logic - }; - - // 4. Render - return ( -
- {/* Your JSX here */} -
- ); -}; +### 2. Canvas Manipulation +- HTML Canvas API support for custom drawing +- THREE.js integration for 3D graphics +- Lightweight Charts for financial visualization +- D3 force layout integration for network graphs +- Support for both 2D and 3D rendering contexts -// Required: Default export -export default MyComponent; +### 3. State Management +Effortlessly manage component state with multiple options: +- **Persistent Note State**: Use the `useStorage` hook to save and load component data directly within your note's frontmatter. State travels with your note! +- **Cross-Note Persistence**: Extend `useStorage` to interact with the frontmatter of *other* notes in your vault. +- **Root Level Frontmatter**: Opt to store data at the root of the frontmatter, outside the default `react_data` section, for broader compatibility. +- **Standard React State**: Utilize `useState` and other React hooks for local, non-persistent component state. +- **Browser `localStorage`**: Access global, non-note-specific storage for preferences or shared data across all notes.\ +For greater detail and examples. +โžก๏ธ **[Deep Dive into State Management](./docs/03_STATE_MANAGEMENT.md)** + + +### 4. File Reading Utility + +The plugin provides a flexible file reading utility through the `readFile` function that helps you interactively select and read files from your vault. +```javascript +const fileData = await readFile( path,extensions); ``` -```` -**Key Structure Points**: -1. Imports always at the top -2. Component name matches default export -3. Hooks before effects -4. Helper functions before render -5. Single default export at bottom +### Parameters +- `path` (optional): Direct path to a specific file. If provided, skips the file selector. Default: `null` +- `extensions` (optional): Array of file extensions to filter by. Default: `['txt', 'md', 'json', 'csv']` +This utility is particularly useful for components that need to process files from your vault, such as data visualizations, document analysis, and custom importers.\ +โžก๏ธ **[Read Files Usage and Examples](./docs/04_FILE_SYSTEM_ACCESS.md)** + +### 5. CDN Library Support +Import additional libraries from cdnjs: +```javascript +import Chart from 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js'; +``` + +Requirements: +- HTTPS URLs from cdnjs.cloudflare.com only +- Imports must exist alone in their own line +- Browser-compatible libraries only + +### 6. Theme Integration +```javascript +const theme = getTheme(); // Returns 'dark' or 'light' correspodning to obsidian theme + +const styles = { + background: theme === 'dark' ? 'var(--background-primary)' : 'white', + color: theme === 'dark' ? 'var(--text-normal)' : 'black' +}; +// Or use 'dark:' within your components +``` + +### 7. Vault Code Imports + +Import React code from other notes in your vault: + +```javascript +// Import code from another note +vaultImport('Components/SharedComponents.md', 0); // 0 = first code block +vaultImport('Hooks/CustomHooks.md', 1); // 1 = second code block + +const MyComponent = () => { + // Use imported components and hooks from these files + const data = useImportedHook(); + return ; +}; +``` + + +### 8. Definition Storage Blocks + +Not all react code blocks need to be valid React you can use React code blocks to store and organize utility functions, hooks, and other definitions: + +```javascript +// This displays as a definition storage block instead of rendering +const utilities = () => ({ + formatDate: (date) => date.toLocaleDateString(), + calculateSum: (arr) => arr.reduce((a, b) => a + b, 0), + parseData: (raw) => JSON.parse(raw) +}); + +export default utilities; +``` +![Object Definitions Codeblock](assets/codeStorageBox.gif) +When a code block returns an object instead of JSX, it automatically displays as a storage block showing all exported definitions. If you have multiple objects containing definitions only the first object will be previewed. +Perfect for: + +Utility function collections +Custom hook libraries +Configuration objects +Shared constants + +Import these definitions into other components using vaultImport(). + +### 9. LaTeX Math Rendering with MathJax +- Display complex mathematical and scientific notations beautifully. +- Supports standard LaTeX syntax within your React components. +- Automatic rendering of inline ($...$) and display ($$...$$) math. ## ๐Ÿ“š Available Libraries & Components @@ -125,11 +188,12 @@ import { Card, Tabs, Switch } from '@/components/ui'; import { TrendingUp, Activity, Settings } from 'lucide-react'; // 70+ icons import * as LucideIcons from 'lucide-react'; // For complete access just use LucideIcons.IconName ``` -See the full [component reference](./COMPONENTS.md) for a complete list of available libraries, components and utilities. -Even if needed libraries are not provided within this list CDN imports are always an option. +Checkout the full [component reference](./COMPONENTS.md) for a complete list of available libraries, components and utilities. + +If needed, libraries not provided within this list can be imported via CDN imports. ### Available in Component Scope - +
All components have access to these objects and functions: ```javascript @@ -150,241 +214,9 @@ getFrontmatter(key?,defaultValue?,notePath?, extProp?) vaultImport(path, index) // Preprocessor directive to include code from other notes (not a runtime function) Notice(message, timeout?) // Display non-blocking notifications (use instead of alert() which blocks the UI thread) ``` +
-## ๐Ÿ’ป Core Features - -### 1. Component Systems -- Write React components directly in notes -- Full TypeScript and React 18 support -- Hot reloading during development -- Error Boundaries and Suspense -- Resource cleanup and lifecycle management -- Custom component registration -- Real-time component updates -- Error reporting - -### 2. Canvas Manipulation -- HTML Canvas API support for custom drawing -- THREE.js integration for 3D graphics -- Lightweight Charts for financial visualization -- D3 force layout integration for network graphs -- Support for both 2D and 3D rendering contexts - - -### 3. Performance -- Efficient re-rendering -- Proper cleanup of resources in useEffect hooks -- Lazy loading support - -### 4. State Management -```javascript -// Local state with React -const [local, setLocal] = useState(0); - -useStorage( - key, // Property name to store in frontmatter - defaultValue, // Default value if property doesn't exist - notePath = null, // Optional: Path to another note (null = current note) - extProp = false // Optional: true = store at root level, false = store in react_data -) -// Persistent state in current note's frontmatter -const [stored, setStored] = useStorage('key', defaultValue); - -// Store at root level of frontmatter -const [status, setStatus] = useStorage('status', 'draft', null, true); - -// Cross-note + root level: Store at root level of another note -const [tags, setTags] = useStorage('tags', ['react'], 'Template.md', true); -// Set value to undefined to delete keys - -// Direct frontmatter manipulation (alternative to useStorage hook) -await updateFrontmatter('react_key', newValue); // Updates react_data.react_key -await updateFrontmatter('custom_key', newValue, null, true); // Updates root level custom_key -await updateFrontmatter('tags', ['react', 'component'], 'path/to/other.md', true); // Updates another note's tags -``` -- Persistent storage between sessions -- State synchronization across components -- Frontmatter integration -- Cross-note state management -- Support for both structured data in react_data and direct frontmatter properties - -### Note-Specific Data Persistence -- Each note maintains independent state through frontmatter storage under a key called react_data -- Component states persist across sessions -- Data automatically travels with notes when shared -- Multiple instances of same component can have different states -- Perfect for creating reusable interactive templates - -Example: - -```javascript -// In Note1.md - counter starts at 0 -const Counter = () => { - const [count1, setCount1] = useStorage('counter', 0); - return ; -}; - -// In Note2.md - same component, independent state -const Counter = () => { - const [count2, setCount2] = useStorage('counter', 0); - return ; -}; -``` -#### Browser LocalStorage - -For components that need to share state across notes or maintain state independent of specific notes, browser localStorage is available. - -```javascript -// Create a localStorage hook -const useLocalStorage = (key, defaultValue) => { - const [state, setState] = useState(() => { - try { - const storedValue = localStorage.getItem(key); - return storedValue ? JSON.parse(storedValue) : defaultValue; - } catch (error) { - console.error(`Error reading localStorage key "${key}":`, error); - return defaultValue; - } - }); - - useEffect(() => { - localStorage.setItem(key, JSON.stringify(state)); - }, [key, state]); - - return [state, setState]; -}; - -// Use it in components -const [value, setValue] = useLocalStorage('shared-key', defaultValue); -//This key is shared across all notes -``` - -Key features: -- Data persists across browser sessions -- Shared state across all notes -- Independent of note content -- Approximately 5-10MB storage per domain -- Persists until browser data is cleared - -### 5. File Reading Utility - -The plugin provides a flexible file reading utility through the `readFile` function that helps you interactively select and read files from your vault. -```javascript -const fileData = await readFile( path,extensions); -``` -### Parameters -- `path` (optional): Direct path to a specific file. If provided, skips the file selector. Default: `null` -- `extensions` (optional): Array of file extensions to filter by. Default: `['txt', 'md', 'json', 'csv']` - -### Return Value - -Returns a Promise that resolves to an object containing: - -- `path`: Full file path -- `name`: File name without extension -- `extension`: File extension -- `content`: String content of the file - -Returns `null` if the operation is canceled or fails, allowing you to handle this case gracefully. - -```javascript -// Interactive file selection with file type filtering -const textFile = await readFile(null,['txt', 'md']); -if (textFile) { - console.log(`Selected: ${textFile.name}`); - console.log(`Content: ${textFile.content}`); -} - -// Direct file access by path (no modal) -const jsonFile = await readFile('path/to/config.json'); -if (jsonFile) { - const config = JSON.parse(jsonFile.content); -} - -// Read CSV files -const csvFile = await readFile(null,['csv']); -if (csvFile) { - // Process CSV content - const lines = csvFile.content.split('\n'); - const headers = lines[0].split(','); - // ... -} - -// Read binary files like Excel spreadsheets -const excelFile = await readFile(null,['xlsx', 'xls']); -if (excelFile) { - // excelFile.content contains the file data - // Process with SheetJS or other libraries -} -``` -This utility is particularly useful for components that need to process files from your vault, such as data visualizations, document analysis, and custom importers. - - -### 6. CDN Library Support -Import additional libraries from cdnjs: -```javascript -import Chart from 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js'; -``` - -Requirements: -- HTTPS URLs from cdnjs.cloudflare.com only -- Imports at component top -- Browser-compatible libraries only - -### 7. Theme Integration -```javascript -const theme = getTheme(); // Returns 'dark' or 'light' correspodning to obsidian theme - -const styles = { - background: theme === 'dark' ? 'var(--background-primary)' : 'white', - color: theme === 'dark' ? 'var(--text-normal)' : 'black' -}; -// Or use 'dark:' within your components -``` - -### 8. Vault Code Imports - -Import React code from other notes in your vault: - -```javascript -// Import code from another note -vaultImport('Components/SharedComponents.md', 0); // 0 = first code block -vaultImport('Hooks/CustomHooks.md', 1); // 1 = second code block - -const MyComponent = () => { - // Use imported components and hooks from these files - const data = useImportedHook(); - return ; -}; -``` - - -### 9. Definition Storage Blocks - -Not all react code blocks need to be valid React you can use React code blocks to store and organize utility functions, hooks, and other definitions: - -```javascript -// This displays as a definition storage block instead of rendering -const utilities = () => ({ - formatDate: (date) => date.toLocaleDateString(), - calculateSum: (arr) => arr.reduce((a, b) => a + b, 0), - parseData: (raw) => JSON.parse(raw) -}); - -export default utilities; -``` -![Object Definitions Codeblock](assets/codeStorageBox.gif) -When a code block returns an object instead of JSX, it automatically displays as a storage block showing all exported definitions. If you have multiple objects containing definitions only the first object will be previewed. -Perfect for: - -Utility function collections -Custom hook libraries -Configuration objects -Shared constants - -Import these definitions into other components using vaultImport(). - ## ๐ŸŽจ Component Examples ### Interactive Data Visualization @@ -514,108 +346,12 @@ Knowledge progression dashboard using persistant storage and ability to make new **Games utilising event listeners for key action mapping** ![alt text](assets/gamingObsidian.gif) -## ๐Ÿ› ๏ธDevelopment Guide -### Component Structure -```react -// Basic component template -const MyComponent = () => { - // 1. Hooks and state - const [data, setData] = useState(null); - const componentRef = useRef(null); - - // 2. Effects and lifecycle - useEffect(() => { - // Setup code - return () => { - // Cleanup code - }; - }, []); - - // 3. Event handlers - const handleUpdate = useCallback(() => { - // Handler code - }, []); - - // 4. Render - return ( -
- {/* Component JSX */} -
- ); -}; - -export default MyComponent; -``` - -### Best Practices - -1. **Component Design** - ```react - const ResponsiveComponent = () => { - return ( -
- - {/* Content adapts to container */} - -
- ); - }; - ``` - -2. **State Management** - ```react - const DataComponent = () => { - // Persistent data - const [savedData, setSavedData] = useStorage('data-key', []); - - // Temporary UI state - const [isLoading, setIsLoading] = useState(false); - - // Computed values - const processedData = useMemo(() => { - return savedData.map(item => /* process */); - }, [savedData]); - }; - ``` - -3. **Error Handling** - ```react - const SafeComponent = () => { - return ( - ( -
- Error: {error.message} -
- )} - > - {/* Protected content */} -
- ); - }; - ``` -1. **Error Checking**: - - Check browser console for errors - - Verify imports are working - - Ensure all required exports are present - -2. **Performance**: - - Keep components focused and minimal - - Use CDN imports sparingly - - Clean up resources in useEffect - -3. **Testing**: - - Test in both light and dark themes - - Verify mobile responsiveness (Hasn't been tested for mobile yet) - - Check CDN imports load correctly ## ๐Ÿ”ง Troubleshooting ### Common Issues 1. **Component not rendering** - - Verify default export is present - Check console for React errors - - Ensure all imports are available and supported - Validate JSX syntax 2. **CDN imports not working** @@ -624,7 +360,6 @@ export default MyComponent; - Confirm import syntax 3. **State persistence issues** - - Check frontmatter permissions - Verify storage key uniqueness - Validate data serialization - Monitor storage size limits @@ -634,22 +369,8 @@ export default MyComponent; - Implement proper cleanup in useEffect - Optimize re-renders with useMemo/useCallback - Monitor memory usage with large datasets - -## โš ๏ธ Important Notes - -### Mobile Compatibility -- Currently optimized for desktop use -- Mobile support is under development -- Test thoroughly on mobile devices - -### Performance and Resource Management -Best practices for optimal performance: - -- Clean up subscriptions and intervals -- Dispose of chart instances -- Release canvas resources -- Free up WebGL contexts -- Use persistent storage thoughtfully +Having issues or have questions? +Bring them to my attention by creating an issue. ### Security Considerations - CDN imports are restricted to cdnjs.cloudflare.com @@ -657,37 +378,10 @@ Best practices for optimal performance: - Component code runs in sandbox - No external network requests -## ๐Ÿ“‹ Technical Reference -### Available APIs - -1. **File System** - ```javascript - // File operations - let file = await readFile(path, extensions); - let content=file.content; - ``` - -2. **Theme Management** - ```javascript - // Theme utilities - const theme = getTheme(); - const isDark = theme === 'dark'; - ``` - -3. **Storage** - ```javascript - // Storage hooks - const [value, setValue] = useStorage(key, defaultValue); - const stored = useStorage(key, null, storage); - ``` - - ## Limitations 1. **Environment Constraints** - CDN imports limited to cdnjs.cloudflare.com - - Components must be self-contained in one code block - - Network requests follow Obsidian's security policies 2. **Performance Considerations** - Large datasets may impact performance @@ -696,30 +390,15 @@ Best practices for optimal performance: - Mobile performance varies 3. **Work in Progress** - - Mobile support still under development - - Some touch interactions need optimization - - Advanced debugging tools coming soon + - Mobile environment not yet tested -## ๐Ÿ”ฎ Future Plans +## ๐Ÿ”ฎ Future Plans & Upcoming Features -### Upcoming Features -1. Advanced Visualization - - More chart types - - Enhanced animations - - 3D visualization support - - Custom chart templates +* **Preset Component Templates**: Kickstart your development with a library of ready-to-use component templates for common use cases. +* **AI-Powered Component Generation**: Leverage AI (e.g., via MCP integration) to assist in generating boilerplate or even complete React components based on your descriptions. +* **GUI for Component Snippets**: An intuitive graphical user interface to easily save your favorite or frequently used component code snippets and load them into your notes. -2. Developer Experience - - Component templates - - Debug tools - - Performance monitoring - - Testing utilities - -3. Mobile Support - - Touch optimization - - Responsive layouts - - Performance improvements - - Mobile-specific components +* **Mobile-Specific Components & UI**: Introducing components and UI patterns specifically designed for the mobile experience. ## ๐Ÿค Contributing diff --git a/docs/03_STATE_MANAGEMENT.md b/docs/03_STATE_MANAGEMENT.md new file mode 100644 index 0000000..5b57ce9 --- /dev/null +++ b/docs/03_STATE_MANAGEMENT.md @@ -0,0 +1,219 @@ +# Feature: State Management in ReactiveNotes + +ReactiveNotes provides robust mechanisms for managing state within your components, allowing for both transient UI state and persistent data storage that travels with your notes. + +## 1. Local Component State (React `useState`) + +For temporary UI state that doesn't need to persist across sessions or be saved to the note, you can use React's standard `useState` hook. + +```javascript +// Example: A simple counter +const MyCounter = () => { + const [count, setCount] = React.useState(0); + + return ( + + ); +}; +export default MyCounter; +``` +This state is reset every time the component is unmounted or the note is reloaded. +## 2. Persistent State with `useStorage` (Frontmatter Integration) + +For state that you want to save with the note and persist across Obsidian sessions, ReactiveNotes provides the powerful `useStorage` hook. This hook directly interacts with the current note's frontmatter. + +### Basic Usage + +The `useStorage` hook is the primary way to create persistent state within your components. + +```tsx +const [storedValue, setStoredValue, error] = useStorage( + key, // String: Property name to store in frontmatter (under `react_data` by default) + defaultValue, // Any: Default value if the key doesn't exist in frontmatter + notePath = null, // Optional String: Path to another note (null = current note) + extProp = false // Optional Boolean: + // false (default): Store under `react_data.` in frontmatter + // true: Store directly as `` at the root level of frontmatter +); +``` + +- **`storedValue`**: The current value from frontmatter, or `defaultValue` if not found. + +- **`setStoredValue`**: A function to update the value. It automatically saves the new value to the note's frontmatter. + +- **`error`**: Contains an error message string if loading or saving failed, otherwise `null`. + + +**Example: A Persistent To-Do List Item** + +```jsx +const PersistentTask = () => { + // Uses 'myTask' as the key in frontmatter, defaults to an object if not found. + const [task, setTask, storageError] = useStorage('myTask', { text: 'Default Task', completed: false }); + const [componentError, setComponentError] = React.useState(null); // Local error for this component example + + const toggleComplete = () => { + try { + setTask(prevTask => ({ ...prevTask, completed: !prevTask.completed })); + setComponentError(null); // Clear local error on success + } catch (e) { + // This catch block might not be strictly necessary for setTask errors, + // as useStorage aims to handle errors internally and expose them via storageError. + // However, it can be useful for other logic within this function. + setComponentError("Failed to update task: " + e.message); + } + }; + + // Display any error from useStorage or local component logic + if (storageError || componentError) { + return
{storageError || componentError}
; + } + + return ( +
+ + + {/* You could add an input here to change task.text and call setTask with the new object */} +
+ ); +}; +export default PersistentTask; +``` + +### Storing at Root Level of Frontmatter + +If you want to store data directly at the root of the frontmatter (outside the default `react_data` object), set the `extProp` argument to `true`. + +```jsx +// Stores 'draft' under a top-level 'status' key in the current note's frontmatter +const [status, setStatus] = useStorage('status', 'draft', null, true); +``` + +This can be useful for interacting with frontmatter keys used by other plugins or for general note metadata. + +### Cross-Note State Management + +You can read and write state to _another_ note's frontmatter by providing the `notePath` argument. + +```jsx +// Reads/writes 'tags' array from/to 'Templates/MyProjectTemplate.md' frontmatter (at the root level) +const [tags, setTags] = useStorage('tags', ['react'], 'Templates/MyProjectTemplate.md', true); +``` + +**Important:** Ensure the target note exists. Writing to a non-existent note path may result in errors or unexpected behavior. + +### Deleting Keys from Frontmatter + +To remove a key managed by `useStorage` from the frontmatter, set its value to `undefined`. + +```jsx +setMyValue(undefined); // This will remove 'myValue' (or react_data.myValue) from the frontmatter +``` + +## 3. Direct Frontmatter Manipulation (Advanced) + +While `useStorage` is the recommended and most convenient way to interact with frontmatter from within React components, ReactiveNotes also provides global helper functions for more direct manipulation. These might be useful in utility scripts or more complex, non-component-based scenarios. + +- **`getFrontmatter(key?, defaultValue?, notePath?, extProp?)`**: Asynchronously retrieves values from frontmatter. + + - Returns the entire frontmatter object if `key` is null or undefined. + +- **`updateFrontmatter(key, value, notePath?, extProp?)`**: Asynchronously updates or sets values in frontmatter. + + +```jsx +// Example of using global helpers (less common within typical components) +// This function is NOT a React component. +async function updateGlobalProjectStatus(newStatus) { + try { + // Updates the 'projectStatus' key at the root of 'ProjectPlan.md' + await updateFrontmatter('projectStatus', newStatus, 'ProjectPlan.md', true); + new Notice('Project status updated in ProjectPlan.md!'); + } catch (e) { + new Notice('Failed to update project status: ' + e.message, 5000); + console.error("Error updating frontmatter:", e); + } +} + +// To read the status: +async function readGlobalProjectStatus() { + try { + const status = await getFrontmatter('projectStatus', 'unknown', 'ProjectPlan.md', true); + console.log('Current project status:', status); + return status; + } catch (e) { + console.error("Error reading frontmatter:", e); + return 'unknown'; + } +} +``` + +**Note:** These functions are asynchronous. For reactive updates that reflect in your UI, always prefer the `useStorage` hook within your React components. + +## 4. Browser `localStorage` (Global, Non-Note-Specific State) + +For state that needs to be shared across _all_ notes or persist independently of any specific note (e.g., global UI preferences for your plugin's components that aren't tied to a single file), you can use the browser's standard `localStorage` API. + +ReactiveNotes does not provide a specific hook for `localStorage` out-of-the-box (as it's a standard browser feature), but you can easily create a custom hook or use `localStorage` directly. + +Example: useLocalStorage Custom Hook + +(This is a common pattern for creating a React-friendly localStorage wrapper) + +```jsx +const useLocalStorage = (key, defaultValue) => { + const [state, setState] = React.useState(() => { + let storedValue; + try { + storedValue = localStorage.getItem(key); + return storedValue ? JSON.parse(storedValue) : defaultValue; + } catch (error) { + console.error(`Error reading localStorage key "${key}":`, error); + return defaultValue; + } + }); + + React.useEffect(() => { + try { + localStorage.setItem(key, JSON.stringify(state)); + } catch (error) { + console.error(`Error setting localStorage key "${key}":`, error); + } + }, [key, state]); + + return [state, setState]; +}; + +// Usage in a component: +const GlobalSettingsComponent = () => { + const [userThemePreference, setUserThemePreference] = useLocalStorage('reactiveNotesUserTheme', 'system'); + // ... component logic using userThemePreference ... + return ( + + ); +}; +export default GlobalSettingsComponent; +``` + +**Key Characteristics of `localStorage`:** + +- Data persists across browser/Obsidian sessions (Is not Vault specific). + +- Shared globally across all notes (not tied to a specific note's frontmatter). + +- Subject to browser storage limits (typically 5-10MB per domain). + +- Persists until browser data is explicitly cleared by the user (e.g., through browser settings like "Clear browsing data") or programmatically via JavaScript (localStorage.removeItem('key') or `localStorage.clear \ No newline at end of file diff --git a/docs/04_FILE_SYSTEM_ACCESS.md b/docs/04_FILE_SYSTEM_ACCESS.md new file mode 100644 index 0000000..0d67654 --- /dev/null +++ b/docs/04_FILE_SYSTEM_ACCESS.md @@ -0,0 +1,198 @@ +# Feature: File Reading Utility + +ReactiveNotes provides a convenient `readFile` utility that allows your components to interactively select and read files from your Obsidian vault, or to read a specific file by its path. + +This utility is essential for components that need to process data from various file types, such as text files, Markdown notes, CSV data, JSON configurations, and more. + +## How to Use + +The `readFile` function is available in the scope of your React components. You can call it using `await` as it returns a Promise. + +**Basic Syntax:** + +```javascript +async function loadAndProcessFile() { + const fileData = await readFile(path, extensions); + + if (fileData) { + // Process fileData.content, fileData.name, etc. + console.log(`Successfully read: ${fileData.name}`); + console.log(`Content snippet: ${fileData.content.substring(0, 100)}`); + } else { + // Handle cancellation or file not found/read error + console.log('File selection was cancelled or file could not be read.'); + } +} +``` +## Parameters + +The `readFile` function accepts two optional parameters: + +1. **`path`** (optional): + + - Type: `string | null` + + - Default: `null` + + - Description: If you provide a string representing the full path to a specific file within your vault (e.g., `'data/mydata.csv'` or `'Templates/My Template.md'`), the utility will attempt to read that file directly without showing the interactive file selection modal. + + - If `null` or not provided, the utility will open a suggestion modal allowing the user to search and select a file from the vault. + +2. **`extensions`** (optional): + + - Type: `string[]` + + - Default: `['txt',` 'md', 'json', 'csv'] + + - Description: An array of file extensions (without the leading dot) to filter the files shown in the suggestion modal. This helps users quickly find relevant files. This parameter is ignored if a direct `path` is provided. + + +## Return Value + +The `readFile` function returns a `Promise` that resolves to either: + +- **An object** containing file details if a file is successfully selected and read: + + - `path`: (string) The full path to the file in the vault (e.g., `folder/My File.md`). + + - `name`: (string) The base name of the file without the extension (e.g., `My File`). + + - `extension`: (string) The file extension without the leading dot (e.g., `md`). + + - `content`: (string) The raw text content of the file. + +- **`null`**: If: + + - The user cancels the file selection modal (e.g., by pressing Escape or closing it). + + - A direct `path` is provided but the file is not found or cannot be read. + + - An unexpected error occurs during the file reading process. + + +Your component should always check if the return value is `null` to handle these cases gracefully. +## Use Cases + +The `readFile` utility is versatile and can be used for: + +- Loading datasets for charts and visualizations (CSV, JSON). + +- Importing configurations or settings for components. + +- Displaying content from other notes or text files. + +- Building simple knowledge base explorers. + +- Creating components that process or analyze text from files. + +## Examples + +### 1. Interactive File Selection (Default Behavior) + +This will open a modal for the user to choose a file. By default, it filters for `.txt`, `.md`, `.json`, and `.csv` files. + +```jsx +const MyDataProcessor = () => { + const [fileContent, setFileContent] = React.useState(''); + const [fileName, setFileName] = React.useState(''); + + const handleLoadFile = async () => { + const fileData = await readFile(); // Uses default extensions + if (fileData) { + setFileName(fileData.name); + setFileContent(fileData.content); + // For CSV, you might parse it here: + // if (fileData.extension === 'csv') { + // const parsedData = Papa.parse(fileData.content, { header: true }); + // console.log(parsedData.data); + // } + } else { + new Notice('File selection cancelled.'); + } + }; + + return ( +
+ + {fileName &&

Displaying: {fileName}

} + {fileContent &&
{fileContent}
} +
+ ); +}; +export default MyDataProcessor; +``` + +### 2. Interactive Selection with Custom Extension Filters + +This will open a modal filtering for only Markdown (`.md`) and text (`.txt`) files. + +``` +const loadMarkdownOrTextFile = async () => { + const fileData = await readFile(null, ['md', 'txt']); + if (fileData) { + console.log(`Content of ${fileData.path}:`, fileData.content); + } +}; +``` + +### 3. Direct File Access by Path + +This will attempt to read `path/to/my/config.json` directly without showing a modal. + +``` +const loadSpecificConfig = async () => { + const filePath = 'configs/settings.json'; // Relative to vault root + const fileData = await readFile(filePath); + + if (fileData && fileData.extension === 'json') { + try { + const config = JSON.parse(fileData.content); + console.log('Configuration loaded:', config); + // Use the config object + } catch (e) { + new Notice(`Error parsing JSON from ${filePath}: ${e.message}`); + console.error("JSON parsing error:", e); + } + } else if (fileData) { + new Notice(`Expected a JSON file but got .${fileData.extension}`); + } else { + new Notice(`Could not read file: ${filePath}. Ensure it exists.`); + } +}; +``` + +### 4. Reading CSV Data for Charts + +``` +// (Assuming you have a chart component that takes data) +const CSVChartLoader = () => { + const [chartData, setChartData] = React.useState(null); + + const loadCSV = async () => { + const fileData = await readFile(null, ['csv']); + if (fileData && fileData.extension === 'csv') { + // Assuming PapaParse is available in scope + const parsed = Papa.parse(fileData.content, { header: true, dynamicTyping: true }); + if (parsed.errors.length > 0) { + new Notice("Errors found while parsing CSV: " + parsed.errors[0].message); + return; + } + setChartData(parsed.data); + new Notice(`Loaded ${parsed.data.length} rows from ${fileData.name}`); + } else if (fileData) { + new Notice(`Selected file was not a CSV: ${fileData.name}`); + } + }; + + return ( +
+ + {/* {chartData && } */} + {chartData &&
Data Loaded: {JSON.stringify(chartData.slice(0,2))}...
} +
+ ); +}; +export default CSVChartLoader; +``` + +By providing both interactive selection and direct path access, `readFile` offers flexibility for various component needs within ReactiveNotes. \ No newline at end of file diff --git a/docs/EXAMPLES/README.md b/docs/EXAMPLES/README.md new file mode 100644 index 0000000..d3e5718 --- /dev/null +++ b/docs/EXAMPLES/README.md @@ -0,0 +1 @@ +**(To be Populated)** \ No newline at end of file diff --git a/main.tsx b/main.tsx index 2631004..266a77b 100644 --- a/main.tsx +++ b/main.tsx @@ -1,4 +1,4 @@ -import { Plugin, MarkdownPostProcessorContext, MarkdownRenderChild, MarkdownRenderer, TFile, App, stringifyYaml, Notice, SuggestModal } from 'obsidian'; +import { Plugin, MarkdownPostProcessorContext, MarkdownRenderChild, MarkdownRenderer, TFile, App, stringifyYaml, Notice, SuggestModal, loadMathJax } from 'obsidian'; import { createRoot } from 'react-dom/client'; import { transform } from '@babel/standalone'; import * as React from 'react'; @@ -9,11 +9,15 @@ import { useStorage } from 'src/hooks/useStorage'; import { ComponentRegistry } from 'src/components/componentRegistry'; import { ErrorBoundary } from 'src/components/ErrorBoundary'; - import { read } from 'fs'; import { error } from 'console'; - +declare global { + interface Window { + MathJax: any; + } + } + class ReactComponentChild extends MarkdownRenderChild { private root: ReturnType; private storage: StorageManager; @@ -81,7 +85,7 @@ class ReactComponentChild extends MarkdownRenderChild { new Notice(errorMsg); return defaultValue; } - console.log('Frontmatter:', frontmatter); + //console.log('Frontmatter:', frontmatter); // Return specific key if requested if (key) { if(extProp&&!frontmatter[key]&&frontmatter.react_data[key]) new Notice(`Key "${key}" not found in outer frontmatter, But found in react_data. Set extProp to false to access it.`); @@ -132,260 +136,381 @@ class ReactComponentChild extends MarkdownRenderChild { } } -private RenderWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => { - - return ( - { - // The ErrorBoundary will catch the error and display a fallback UI. - // The console log for "Objects are not valid as a React child" should have been suppressed. - if (error.message?.includes('Objects are not valid as a React child')) { - const objectMatch = error.message.match(/found: object with keys {([^}]+)}/); - const keys = objectMatch ? objectMatch[1].split(',').map(k => k.trim()) : ['unknown']; + private RenderWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => { + // const containerRef = React.useRef(null); + const containerRef = React.useRef(null); + React.useEffect(() => { + if (!containerRef.current || !window.MathJax) return; + const container = containerRef.current; + // 1. Find math content in our component + const processMathInElement = (element: HTMLElement) => { + // Find all text nodes + const walker = document.createTreeWalker( + element, + NodeFilter.SHOW_TEXT, + null + ); + + const nodesToProcess = []; + let currentNode; + while ((currentNode = walker.nextNode())) { + const text = currentNode.nodeValue || ''; + + // Look for inline math: $...$ + if (text.includes('$') && !text.includes('$$')) { + nodesToProcess.push({node: currentNode, isDisplay: false}); + } + + // Look for display math: $$...$$ + if (text.includes('$$')) { + nodesToProcess.push({node: currentNode, isDisplay: true}); + } + } + + // 2. Process each node with math content + nodesToProcess.forEach(({node, isDisplay}) => { + const text = node.nodeValue || ''; + const parent = node.parentNode; + + if (!parent) return; + + if (isDisplay) { + // Handle display math: $$...$$ + const parts = text.split('$$'); + if (parts.length < 3) return; // Not enough delimiters + + // Create replacement fragment + const fragment = document.createDocumentFragment(); + + for (let i = 0; i < parts.length; i++) { + if (i % 2 === 0) { + // Text part + if (parts[i]) { + fragment.appendChild(document.createTextNode(parts[i])); + } + } else { + // Math part + try { + const mathNode = window.MathJax.tex2chtml(parts[i], {display: true}); + fragment.appendChild(mathNode); + } catch (e) { + console.error("MathJax display math error:", e); + fragment.appendChild(document.createTextNode(`$$${parts[i]}$$`)); + } + } + } + + // Replace original node with processed content + parent.replaceChild(fragment, node); + } else { + // Handle inline math: $...$ + const parts = text.split('$'); + if (parts.length < 3) return; // Not enough delimiters + + // Create replacement fragment + const fragment = document.createDocumentFragment(); + + for (let i = 0; i < parts.length; i++) { + if (i % 2 === 0) { + // Text part + if (parts[i]) { + fragment.appendChild(document.createTextNode(parts[i])); + } + } else { + // Math part + try { + const mathNode = window.MathJax.tex2chtml(parts[i], {display: false}); + fragment.appendChild(mathNode); + } catch (e) { + console.error("MathJax inline math error:", e); + fragment.appendChild(document.createTextNode(`$${parts[i]}$`)); + } + } + } + + // Replace original node with processed content + parent.replaceChild(fragment, node); + if (window.MathJax && typeof window.MathJax.typesetPromise === 'function') { + window.MathJax.typesetPromise([containerRef.current]).catch((err: any) => console.error("MathJax typesetPromise error:", err)); + } + } + }); + }; + + // Process the container + setTimeout(() => { + try { + processMathInElement(container); + } catch (e) { + console.error("MathJax processing error:", e); + } + }, 50); + // Cleanup function + return () => { + try { + //Need to explicitly tell MathJax to typeset new content if it hasn't already been configured to do so automatically. + if (window.MathJax && containerRef.current) { + window.MathJax.typesetClear([containerRef.current]); + } + } catch (e) { + console.warn("MathJax cleanup error:", e); + } + }; + }, [children]); + return ( + { + // The ErrorBoundary will catch the error and display a fallback UI. + // The console log for "Objects are not valid as a React child" should have been suppressed. + if (error.message?.includes('Objects are not valid as a React child')) { + const objectMatch = error.message.match(/found: object with keys {([^}]+)}/); + const keys = objectMatch ? objectMatch[1].split(',').map(k => k.trim()) : ['unknown']; + return ( +
+
+ ๐Ÿงฉ Component Rendered an Object +
+
A React component attempted to render a plain JavaScript object. Objects need to be mapped to renderable elements.
+
Object keys found:
+
    {keys.map(key =>
  • {key}
  • )}
+
+ ); + } + // Default error display for other types of errors return ( -
-
- ๐Ÿงฉ Component Rendered an Object -
-
A React component attempted to render a plain JavaScript object. Objects need to be mapped to renderable elements.
-
Object keys found:
-
    {keys.map(key =>
  • {key}
  • )}
+
+

Error in component:

+
{error.message}
+ {error.stack &&
Stack Trace
{error.stack}
}
); - } - // Default error display for other types of errors - return ( -
-

Error in component:

-
{error.message}
- {error.stack &&
Stack Trace
{error.stack}
} -
- ); - }} - > - {children} - - ); -}; + }} + > +
+ {children} +
+ + ); + }; -private needsThree(code: string): boolean { - // Check if the code contains any Three.js specific imports or usage - // More comprehensive detection of THREE usage - const hasThreeImports = /import\s+.*?three['"];?\s*$/gm.test(code) || - /import\s*{\s*[^}]*}\s*from\s*['"]three['"];?\s*$/gm.test(code) || - /import\s+.*?\s+as\s+(\w+)\s+from\s+['"]three['"];?\s*$/gm.test(code); - - // Save any custom import name from "import * as CustomName from 'three'" - const threeAliasMatch = code.match(/import\s+\*\s+as\s+(\w+)\s+from\s+['"]three['"];?\s*$/m); - const threeAlias = threeAliasMatch ? threeAliasMatch[1] : null; - - // Check for various THREE usage patterns - let hasThreeUsage = /\bTHREE\.|\bnew\s+THREE\.|\bextends\s+THREE\./.test(code) || // Direct THREE usage - /\bUtilities\.THREE\.|\bnew\s+Utilities\.THREE\./.test(code) || // Utilities.THREE usage - /\bComponentRegistry\.Utilities\.THREE\./.test(code); // Full path usage - - // If there's a custom alias, check for that too - if (threeAlias) { - hasThreeUsage = hasThreeUsage || new RegExp(`\\b${threeAlias}\\.`).test(code); + private needsThree(code: string): boolean { + // Check if the code contains any Three.js specific imports or usage + // More comprehensive detection of THREE usage + const hasThreeImports = /import\s+.*?three['"];?\s*$/gm.test(code) || + /import\s*{\s*[^}]*}\s*from\s*['"]three['"];?\s*$/gm.test(code) || + /import\s+.*?\s+as\s+(\w+)\s+from\s+['"]three['"];?\s*$/gm.test(code); + + // Save any custom import name from "import * as CustomName from 'three'" + const threeAliasMatch = code.match(/import\s+\*\s+as\s+(\w+)\s+from\s+['"]three['"];?\s*$/m); + const threeAlias = threeAliasMatch ? threeAliasMatch[1] : null; + + // Check for various THREE usage patterns + let hasThreeUsage = /\bTHREE\.|\bnew\s+THREE\.|\bextends\s+THREE\./.test(code) || // Direct THREE usage + /\bUtilities\.THREE\.|\bnew\s+Utilities\.THREE\./.test(code) || // Utilities.THREE usage + /\bComponentRegistry\.Utilities\.THREE\./.test(code); // Full path usage + + // If there's a custom alias, check for that too + if (threeAlias) { + hasThreeUsage = hasThreeUsage || new RegExp(`\\b${threeAlias}\\.`).test(code); + } + + // Also check for common THREE classes even without the THREE prefix + const commonThreeClasses = /\b(Scene|PerspectiveCamera|WebGLRenderer|Vector3|BoxGeometry|MeshBasicMaterial|Mesh|Object3D|Group|AmbientLight|DirectionalLight)\b/.test(code); + + // Combined check + return hasThreeImports || hasThreeUsage || commonThreeClasses; } - - // Also check for common THREE classes even without the THREE prefix - const commonThreeClasses = /\b(Scene|PerspectiveCamera|WebGLRenderer|Vector3|BoxGeometry|MeshBasicMaterial|Mesh|Object3D|Group|AmbientLight|DirectionalLight)\b/.test(code); - - // Combined check - return hasThreeImports || hasThreeUsage || commonThreeClasses; -} -private async preprocessCode(code: string): Promise { - - // Replace CDN imports with script loading - code = code.replace( - /import\s+(\w+)\s+from\s+['"]https:\/\/cdnjs\.cloudflare\.com\/([^'"]+)['"]/g, - (match, importName, cdnPath) => ` - const script = document.createElement('script'); - script.src = 'https://cdnjs.cloudflare.com/${cdnPath}'; - document.body.appendChild(script);`); - // Remove imports carefully - code = code.replace(/import\s+.*?['"].*$/gm, ''); - code = code.replace(/import\s*{[^}]*}\s*from\s*['"][^'"]*['"].*$/gm, ''); - code = code.replace(/import\s*\([^)]*\).*$/gm, ''); + private async preprocessCode(code: string): Promise { - // Handle both JS/TS exports - code = code.replace(/export\s+default\s+/gm, ''); - code = code.replace(/export\s+const\s+/gm, 'const '); - code = code.replace(/export\s+function\s+/gm, 'function '); - code = code.replace(/export\s+class\s+/gm, 'class '); - - - // Remove type annotations - //code = code.replace(/:\s*[A-Za-z<>[\]]+/g, ''); - //code = code.replace(/<[A-Za-z,\s]+>/g, ''); - - - // Find the component name - const componentMatch = code.match(/^(?![\s]*\/\/).*?(?:function\s+(\w+)|const\s+(\w+)\s*=\s*(?:(?:\([^)]*\)|)\s*=>|function\s*\(|React\.memo\(|React\.forwardRef\(|class\s+extends\s+React\.Component))/m); - const storeMatch = !componentMatch ? code.match(/(?:const\s+(\w+)\s*=\s*{|class\s+(\w+)\s*{)/) : null; - - if (!componentMatch) { - // If no component found, look for object literals or other exports - if (!storeMatch) { - throw new Error('No React component found'); + // Replace CDN imports with script loading + code = code.replace( + /import\s+(\w+)\s+from\s+['"]https:\/\/cdnjs\.cloudflare\.com\/([^'"]+)['"]/g, + (match, importName, cdnPath) => ` + const script = document.createElement('script'); + script.src = 'https://cdnjs.cloudflare.com/${cdnPath}'; + document.body.appendChild(script);`); + // Remove imports carefully + code = code.replace(/import\s+.*?['"].*$/gm, ''); + code = code.replace(/import\s*{[^}]*}\s*from\s*['"][^'"]*['"].*$/gm, ''); + code = code.replace(/import\s*\([^)]*\).*$/gm, ''); + + // Handle both JS/TS exports + code = code.replace(/export\s+default\s+/gm, ''); + code = code.replace(/export\s+const\s+/gm, 'const '); + code = code.replace(/export\s+function\s+/gm, 'function '); + code = code.replace(/export\s+class\s+/gm, 'class '); + + + // Remove type annotations + //code = code.replace(/:\s*[A-Za-z<>[\]]+/g, ''); + //code = code.replace(/<[A-Za-z,\s]+>/g, ''); + + + // Find the component name + const componentMatch = code.match(/^(?![\s]*\/\/).*?(?:function\s+(\w+)|const\s+(\w+)\s*=\s*(?:(?:\([^)]*\)|)\s*=>|function\s*\(|React\.memo\(|React\.forwardRef\(|class\s+extends\s+React\.Component))/m); + const storeMatch = !componentMatch ? code.match(/(?:const\s+(\w+)\s*=\s*{|class\s+(\w+)\s*{)/) : null; + + if (!componentMatch) { + // If no component found, look for object literals or other exports + if (!storeMatch) { + throw new Error('No React component found'); + } } - } - // Set safeName using either match - const componentName = componentMatch - ? (componentMatch[1] || componentMatch[2]) - : (storeMatch ? (storeMatch[1]|| storeMatch[2]) : 'EmptyComponent'); - console.log('Found component:', componentName); - - // Find component name and rename if it's 'WrappedComponent' - const safeName = componentName === 'WrappedComponent' ? 'UserComponent' : componentName; - - if (componentName === 'WrappedComponent') { - code = code.replace(/\bWrappedComponent\b/, safeName); - } - // Create a HOC wrapper for chart components - const chartWrapper = ` - const withChartContainer = (WrappedComponent) => { - return function ChartContainer(props) { - const [mounted, setMounted] = React.useState(false); - - React.useEffect(() => { - const timer = setTimeout(() => setMounted(true), 100); - return () => clearTimeout(timer); - }, []); - - return React.createElement( - 'div', - { style: { width: '100%', minHeight: '400px' } }, - mounted ? React.createElement(WrappedComponent, props) : null - ); + // Set safeName using either match + const componentName = componentMatch + ? (componentMatch[1] || componentMatch[2]) + : (storeMatch ? (storeMatch[1]|| storeMatch[2]) : 'EmptyComponent'); + console.log('Found component:', componentName); + + // Find component name and rename if it's 'WrappedComponent' + const safeName = componentName === 'WrappedComponent' ? 'UserComponent' : componentName; + + if (componentName === 'WrappedComponent') { + code = code.replace(/\bWrappedComponent\b/, safeName); + } + // Create a HOC wrapper for chart components + const chartWrapper = ` + const withChartContainer = (WrappedComponent) => { + return function ChartContainer(props) { + const [mounted, setMounted] = React.useState(false); + + React.useEffect(() => { + const timer = setTimeout(() => setMounted(true), 100); + return () => clearTimeout(timer); + }, []); + + return React.createElement( + 'div', + { style: { width: '100%', minHeight: '400px' } }, + mounted ? React.createElement(WrappedComponent, props) : null + ); + }; }; - }; - `; - // Combine everything - // added Component assignment - code = ` - ${chartWrapper} - ${code} - const WrappedComponent = (() => { - // Add error handling for component existence - if (typeof ${safeName} === 'undefined') { - throw new Error(\`Component "${safeName}" was matched but is undefined. Code context: ${code.slice(0, 100).replace(/`/g, '\\`')}...\`); - } - // Simple check - is it a valid React component? - const isValidComponent = (() => { - // Class component - if (${safeName}.prototype?.isReactComponent) return true; - - // Function that returns React elements - if (typeof ${safeName} === 'function') { - try { - const result = ${safeName}({}); - return React.isValidElement(result); - } catch { - // If it throws, check source code - return ${safeName}.toString().includes('createElement') || - ${safeName}.toString().includes('<'); - } - } - - // Direct objects are never valid components - return false; - })(); - - // If not a valid component, treat as a storage block - if (!isValidComponent) { - return function StorageBlockWrapper() { - // Get the definitions - handle all cases - let definitions; + `; + // Combine everything + // added Component assignment + code = ` + ${chartWrapper} + ${code} + const WrappedComponent = (() => { + // Add error handling for component existence + if (typeof ${safeName} === 'undefined') { + throw new Error(\`Component "${safeName}" was matched but is undefined. Code context: ${code.slice(0, 100).replace(/`/g, '\\`')}...\`); + } + // Simple check - is it a valid React component? + const isValidComponent = (() => { + // Class component + if (${safeName}.prototype?.isReactComponent) return true; + // Function that returns React elements if (typeof ${safeName} === 'function') { try { - // Try as function - definitions = ${safeName}({}); - } catch (e) { + const result = ${safeName}({}); + return React.isValidElement(result); + } catch { + // If it throws, check source code + return ${safeName}.toString().includes('createElement') || + ${safeName}.toString().includes('<'); + } + } + + // Direct objects are never valid components + return false; + })(); + + // If not a valid component, treat as a storage block + if (!isValidComponent) { + return function StorageBlockWrapper() { + // Get the definitions - handle all cases + let definitions; + + if (typeof ${safeName} === 'function') { try { - // Try as class - definitions = new ${safeName}(); - } catch (e2) { - // Last resort - definitions = ${safeName}; + // Try as function + definitions = ${safeName}({}); + } catch (e) { + try { + // Try as class + definitions = new ${safeName}(); + } catch (e2) { + // Last resort + definitions = ${safeName}; + } } + } else { + // Already an object (like IIFE or object literal) + definitions = ${safeName}; } - } else { - // Already an object (like IIFE or object literal) - definitions = ${safeName}; - } - - // Ensure it's an object - if (!definitions || typeof definitions !== 'object') { - definitions = { error: "Couldn't extract definitions" }; - } - - const keys = Object.keys(definitions); - return React.createElement('div', { - style: { - padding: '12px', - backgroundColor: 'var(--background-modifier-form-field)', - borderRadius: '6px', - border: '1px solid var(--background-modifier-border)', - fontFamily: 'var(--font-monospace)' + + // Ensure it's an object + if (!definitions || typeof definitions !== 'object') { + definitions = { error: "Couldn't extract definitions" }; } - }, [ - React.createElement('div', { - style: { - fontWeight: 'bold', - marginBottom: '8px', + + const keys = Object.keys(definitions); + return React.createElement('div', { + style: { + padding: '12px', + backgroundColor: 'var(--background-modifier-form-field)', + borderRadius: '6px', + border: '1px solid var(--background-modifier-border)', + fontFamily: 'var(--font-monospace)' + } + }, [ + React.createElement('div', { + style: { + fontWeight: 'bold', + marginBottom: '8px', + display: 'flex', + alignItems: 'center', + gap: '8px' + } + }, [ + React.createElement('span', null, '๐Ÿ“ฆ'), + React.createElement('span', null, 'Definitions Storage Container:') + ]), + React.createElement('div', { + style: { + padding: '8px', + marginBottom: '12px', + color: 'var(--text-on-accent)', + borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '8px' } }, [ - React.createElement('span', null, '๐Ÿ“ฆ'), - React.createElement('span', null, 'Definitions Storage Container:') + React.createElement('code', { + style: { + padding: '2px 6px', + backgroundColor: 'rgba(255,255,255,0.2)', + borderRadius: '3px', + fontWeight: 'bold' + } + }, '${safeName}') ]), React.createElement('div', { - style: { - padding: '8px', - marginBottom: '12px', - color: 'var(--text-on-accent)', - borderRadius: '4px', - display: 'flex', - alignItems: 'center', - gap: '8px' - } - }, [ - React.createElement('code', { - style: { - padding: '2px 6px', - backgroundColor: 'rgba(255,255,255,0.2)', - borderRadius: '3px', - fontWeight: 'bold' - } - }, '${safeName}') - ]), - React.createElement('div', { - style: { fontSize: '0.9em', opacity: 0.8 } - }, 'Exported definitions:'), - React.createElement('ul', { - style: { - margin: '8px 0', - paddingLeft: '20px' - } - }, keys.map(key => - React.createElement('li', { key }, - \`\${key}: \${typeof definitions[key]}\` - ) - )) - ]); - }; - } - const isChartComponent = ${safeName}.toString().includes('ResponsiveContainer') || - ${safeName}.toString().includes('svg'); - return isChartComponent ? withChartContainer(${safeName}) : ${safeName}; - })(); - `; + style: { fontSize: '0.9em', opacity: 0.8 } + }, 'Exported definitions:'), + React.createElement('ul', { + style: { + margin: '8px 0', + paddingLeft: '20px' + } + }, keys.map(key => + React.createElement('li', { key }, + \`\${key}: \${typeof definitions[key]}\` + ) + )) + ]); + }; + } + const isChartComponent = ${safeName}.toString().includes('ResponsiveContainer') || + ${safeName}.toString().includes('svg'); + return isChartComponent ? withChartContainer(${safeName}) : ${safeName}; + })(); + `; code = await this.processVaultImports(code); // Wrap code in async IIFE to allow for await return ` @@ -585,12 +710,11 @@ private async preprocessCode(code: string): Promise { ); return [value, updateValue, error] as const; }; - // Create scope with all required dependencies const scope = { ...ComponentRegistry, useStorage: boundUseStorage, - + //Not included MarketAnalysis functions getTheme: () => document.body.hasClass('theme-dark') ? 'dark' : 'light', // Add note context noteContext: { @@ -639,7 +763,7 @@ private async preprocessCode(code: string): Promise { }, Notice: (message:string, timeout = 4000) => new Notice(message, timeout), }; - + //console.log("MathJax version/config:", window.MathJax?.version, window.MathJax?.config); // Execute the code and get the component const Component = await new Function( ...Object.keys(scope), @@ -713,7 +837,7 @@ private async preprocessCode(code: string): Promise { } onChooseSuggestion(file:TFile, evt: MouseEvent|KeyboardEvent) { - console.log("File content:"); + //console.log("File content:"); if (cancelTimeoutHandle !== undefined) { clearTimeout(cancelTimeoutHandle); cancelTimeoutHandle = undefined; @@ -797,8 +921,10 @@ private async preprocessCode(code: string): Promise { export default class ReactNotesPlugin extends Plugin { private tailwindStyles: HTMLStyleElement | null = null; // Tailwind styles reference + async onload() { try { + await loadMathJax(); // Read the CSS file using Obsidian's API // - only left here for development purposes, // Users wont have this in production, we may use the build:css script to generate and add the css file in future @@ -849,6 +975,14 @@ private async preprocessCode(code: string): Promise { if (this.tailwindStyles) { this.tailwindStyles.remove(); } + // Reset MathJax state + if (window.MathJax) { + try { + window.MathJax.typesetClear(); + } catch (e) { + console.warn("MathJax cleanup error:", e); + } + } } private updateTheme = () => { // Update theme class on all react component containers @@ -864,6 +998,8 @@ private async preprocessCode(code: string): Promise { } }); }; + + private async parseMarkdownInHtml(container: HTMLElement) { // Query all divs or specific HTML blocks you want to process const htmlBlocks = Array.from(container.querySelectorAll('div:not(.markdown-rendered)')) as HTMLDivElement[]; diff --git a/manifest.json b/manifest.json index ac43720..c0771b3 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "reactive-notes", "name": "Reactive Notes", - "version": "1.0.4", + "version": "1.0.5", "minAppVersion": "1.4.0", "description": "Transform your vault into a reactive computational environment. Create dynamic React components directly in your notes.", "author": "Elias Noesis", diff --git a/package-lock.json b/package-lock.json index 2c18e0f..a24962b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "reactive-notes", - "version": "1.0.4", + "version": "1.0.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "reactive-notes", - "version": "1.0.4", + "version": "1.0.5", "dependencies": { "@codemirror/language": "^6.10.6", "@emotion/css": "^11.13.5", diff --git a/package.json b/package.json index 29d54d9..6984343 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "reactive-notes", - "version": "1.0.4", + "version": "1.0.5", "description": "Transform your vault into a reactive computational environment with React components.", "main": "main.js", "scripts": { diff --git a/versions.json b/versions.json index 08a5628..35e359e 100644 --- a/versions.json +++ b/versions.json @@ -1,5 +1,6 @@ { "1.0.2": "1.4.0", "1.0.3": "1.4.0", - "1.0.4": "1.4.0" + "1.0.4": "1.4.0", + "1.0.5": "1.4.0" } \ No newline at end of file