Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Lyra's Exporter
https://github.com/yalums/lyra-exporter
Admin
Lyra's Exporter是一个专业的AI对话导出器,支持统一管理和导出Claude、Gemini、NotebookLM等多平台对话记录。
Tokens:
5,276
Snippets:
27
Trust Score:
5.2
License:
MIT
Update:
1 year ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Get Dynamic Search Placeholder Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Generates a placeholder text for the search input field. The placeholder text varies dynamically based on the current view mode and file format, providing context-aware search guidance. ```javascript /** * Generates a dynamic placeholder for the search input. * Provides context-aware hints based on view and format. * @returns {string} The placeholder text. */ function getSearchPlaceholder() { // ... logic to determine placeholder based on viewMode and format ... return 'Search...'; } ``` -------------------------------- ### Get Statistics Data Source: https://github.com/yalums/lyra-exporter/blob/main/README.md A utility function to retrieve statistical data for the application. It relies on `calculateViewStats` to compute the necessary metrics based on the current view. ```javascript /** * Retrieves statistics data. * Calls calculateViewStats to get relevant metrics. * @returns {object} An object containing statistics. */ function getStats() { // return calculateViewStats(viewMode, ...); return {}; } ``` -------------------------------- ### Get Timeline Messages Source: https://github.com/yalums/lyra-exporter/blob/main/README.md A memoized function that filters and prepares messages for the timeline view. It uses `selectedConversationUuid` to fetch and display messages relevant to the current conversation. ```javascript /** * Retrieves and prepares messages for the timeline view, memoized. * Filters messages based on the selected conversation UUID. * @returns {Array} Array of messages for the timeline. */ const timelineMessages = useMemo(() => { // ... logic to filter messages based on selectedConversationUuid ... return []; }, [selectedConversationUuid, files]); ``` -------------------------------- ### Get Current Conversation Info Source: https://github.com/yalums/lyra-exporter/blob/main/README.md A memoized function that retrieves information about the currently active conversation. It augments the conversation data with additional details, such as its starred status. ```javascript /** * Retrieves and prepares information for the current conversation, memoized. * Includes augmented data like starred status. * @returns {object | null} The current conversation object or null. */ const currentConversation = useMemo(() => { // ... logic to find and augment current conversation data ... return null; }, [selectedConversationUuid, files]); ``` -------------------------------- ### Get Search Result Statistics Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Retrieves statistics specifically for search results. It considers the current view mode and filtered messages to provide relevant counts or summaries. ```javascript /** * Gets statistics for search results. * @param {string} viewMode - The current view mode. * @param {Array} filteredMessages - Messages that match the search query. * @param {...any} params - Additional parameters. * @returns {object} An object containing search result statistics. */ function getSearchResultStats(viewMode, filteredMessages, ...params) { // ... implementation to calculate stats for search results ... return {}; } ``` -------------------------------- ### Initialize Theme from Local Storage Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Sets up the application's theme by reading the user's preference from local storage. This effect runs once on component mount to apply the stored theme to the document's root element. ```javascript useEffect(() => { const savedTheme = localStorage.getItem('theme'); if (savedTheme) { document.documentElement.setAttribute('data-theme', savedTheme); } }, []); ``` -------------------------------- ### Set Up Post Message Listener Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Establishes a listener for 'message' events on the window object. This enables the application to receive data or commands from other windows or iframes, using a handler created by `createPostMessageHandler`. ```javascript useEffect(() => { const messageHandler = createPostMessageHandler(fileActions, setError); window.addEventListener('message', messageHandler); return () => { window.removeEventListener('message', messageHandler); }; }, [fileActions, setError]); ``` -------------------------------- ### Handle File Load Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Manages the process of loading files, typically triggered by user interaction like clicking a button or dragging files. It utilizes file action handlers to perform the actual loading. ```javascript /** * Handles the file loading process. * @param {Event} e - The file selection event. */ function handleFileLoad(e) { // Assuming fileActions is available in scope // fileActions.loadFiles(e.target.files); } ``` -------------------------------- ### Handle Export Operation Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Initiates the export process by calling the main export handler. It ensures all necessary state data is passed as arguments to the `exportHandler`. ```javascript /** * Executes the export operation. * Calls the main export handler with necessary state data. */ function handleExport() { // Assuming exportOptions and other state variables are available in scope // exportHandler(exportOptions, viewMode, processedData, currentFile, sortedMessages, hasCustomSort, marks, operatedFiles, files, currentFileIndex); } ``` -------------------------------- ### Handle Back to Conversations Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Provides functionality to navigate back to the conversation list view. It aims to restore the previous scroll position for a seamless user experience. ```javascript /** * Handles returning to the conversation list view. */ function handleBackToConversations() { // ... implementation to navigate back and restore scroll position ... } ``` -------------------------------- ### Unified Export Handler Source: https://github.com/yalums/lyra-exporter/blob/main/README.md The main entry point for handling export operations, accepting various configuration options and data parameters. It manages data collection, filtering, Markdown generation, and file saving. ```javascript /** * Unified export processing entry point. * @param {object} exportOptions - Export configuration options. * @param {string} viewMode - The current view mode (e.g., 'current', 'operated', 'all'). * @param {Array} processedData - The processed data to be exported. * @param {object} currentFile - The current file being processed. * @param {Array} sortedMessages - Sorted messages. * @param {boolean} hasCustomSort - Indicates if custom sorting is applied. * @param {Array} marks - Mark data. * @param {Set} operatedFiles - A set of operated files. * @param {Array} files - All loaded files. * @param {number} currentFileIndex - The index of the current file. */ function handleExport(exportOptions, viewMode, processedData, currentFile, sortedMessages, hasCustomSort, marks, operatedFiles, files, currentFileIndex) { // ... implementation details ... } // Specific export range handlers function exportCurrentFile() { /* ... */ } function exportOperatedFiles() { /* ... */ } function exportAllFiles() { /* ... */ } // Helper functions for export function generateMarkdownContent() { /* ... */ } function getFileMarks() { /* ... */ } function getCurrentDate() { /* ... */ } function getCurrentDateTime() { /* ... */ } ``` -------------------------------- ### Post Message Handler Creation Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Creates a handler for postMessage events to manage communication between different windows or iframes. It supports handshake, data loading, and error handling, with built-in security checks for message origin. ```javascript /** * Creates a postMessage event handler. * @param {object} fileActions - File action handlers. * @param {function} setError - Function to set error states. * @returns {function} The postMessage event listener. */ function createPostMessageHandler(fileActions, setError) { const allowedOrigins = ['http://localhost:3000']; // Example whitelist return (event) => { const { type, payload } = event.data; if (!allowedOrigins.includes(event.origin)) { console.warn(`Message received from unexpected origin: ${event.origin}`); return; } switch (type) { case 'LYRA_HANDSHAKE': console.log('Handshake received'); // Respond with handshake confirmation if needed break; case 'LYRA_LOAD_DATA': fileActions.loadFiles(payload.files); break; case 'LYRA_ERROR': setError(payload.error); break; default: console.warn(`Unknown message type: ${type}`); } }; } ``` -------------------------------- ### Calculate All Marks Statistics Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Calculates statistics for marks across all files. It takes the list of files and processed data as input to aggregate mark-related information. ```javascript /** * Calculates statistics for marks across all files. * @param {Array} files - The list of all files. * @param {Array} processedData - The processed data for all files. * @param {number} currentFileIndex - The index of the current file. * @returns {object} An object containing mark statistics. */ function getAllMarksStats(files, processedData, currentFileIndex) { // ... implementation to calculate stats based on marks ... return {}; } ``` -------------------------------- ### Service Worker Registration (JavaScript) Source: https://github.com/yalums/lyra-exporter/blob/main/public/index.html This script handles the registration of a Service Worker for Progressive Web Apps (PWAs). It only runs in production environments (not on localhost or 127.x.x.x) and includes logic for checking updates, skipping waiting for new versions, and reloading the page when a new controller is available. It also provides console logs for different stages of the process and logs an error if registration fails. ```javascript if ('serviceWorker' in navigator && window.location.hostname !== 'localhost' && !window.location.hostname.startsWith('127.')) { window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL || ''}/sw.js`; navigator.serviceWorker.register(swUrl) .then(registration => { console.log('SW注册成功:', registration); registration.addEventListener('updatefound', () => { const newWorker = registration.installing; console.log('发现新版本 Service Worker'); newWorker.addEventListener('statechange', () => { if (newWorker.state === 'installed' && navigator.serviceWorker.controller) { console.log('新版本已准备就绪'); newWorker.postMessage({ type: 'SKIP_WAITING' }); navigator.serviceWorker.addEventListener('controllerchange', () => { window.location.reload(); }); } }); }); setInterval(() => { registration.update(); }, 30000); }) .catch(error => { console.log('SW注册失败(生产环境):', error); }); }); } else { console.log('开发环境 - Service Worker 已禁用'); } ``` -------------------------------- ### Handle Card Selection Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Processes user selection of a card, which could represent a file or a conversation. The logic branches based on the card type to either switch the view mode or navigate to a specific conversation timeline. ```javascript /** * Handles the selection of a card (file or conversation). * @param {object} card - The selected card object. */ function handleCardSelect(card) { if (card.type === 'file') { // Logic for file card selection (e.g., switch view mode based on format) } else if (card.type === 'conversation') { // Logic for conversation card selection (e.g., set conversation UUID, navigate to timeline) } } ``` -------------------------------- ### Dynamic Theme Color Update (JavaScript) Source: https://github.com/yalums/lyra-exporter/blob/main/public/index.html This function updates the theme color of the HTML element and CSS variables based on system preference (dark/light mode) or a manual data-theme attribute. It also includes logic to update the meta theme-color tag and handles PWA startup background color. It's designed to be called immediately and on system theme changes, and is exposed globally. ```javascript function updateThemeColor() { const htmlElement = document.documentElement; const manualTheme = htmlElement.getAttribute('data-theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; const isDark = manualTheme ? manualTheme === 'dark' : prefersDark; const themeColorMeta = document.getElementById('theme-color-meta'); const newColor = isDark ? '#262624' : '#F2F0E9'; if (themeColorMeta) { themeColorMeta.setAttribute('content', newColor); } document.documentElement.style.setProperty('--pwa-bg-color', newColor); console.log('主题色已更新为:', newColor, '(是否深色:', isDark, ')'); } updateThemeColor(); window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateThemeColor); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') { updateThemeColor(); } }); }); observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); window.updatePWAThemeColor = updateThemeColor; ``` -------------------------------- ### Generate All Cards Data Source: https://github.com/yalums/lyra-exporter/blob/main/README.md A memoized function that generates the data required for all displayed cards. The output depends on the current `viewMode` and the format of the files, determining whether to show file cards or conversation cards. ```javascript /** * Generates data for all cards, memoized for performance. * Depends on viewMode and file format. * @returns {Array} Array of card data objects. */ const allCards = useMemo(() => { // ... logic to generate cards based on viewMode and file format ... return []; }, [viewMode, files]); ``` -------------------------------- ### Handle Post Message Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Processes incoming cross-window messages. This function is typically set up using `createPostMessageHandler` to handle various communication events. ```javascript /** * Handles cross-window messages. * This function is likely managed by a handler created via createPostMessageHandler. */ function handlePostMessage() { // Logic executed when a message is received, e.g.: // const messageHandler = createPostMessageHandler(fileActions, setError); // window.addEventListener('message', messageHandler); } ``` -------------------------------- ### Determine Search Target Source: https://github.com/yalums/lyra-exporter/blob/main/README.md A memoized function that defines the data source for search operations. It dynamically selects either file cards or messages based on the current `viewMode`. ```javascript /** * Determines the data target for search operations, memoized. * Selects either cards or messages based on the view mode. * @returns {Array} The data array to be searched. */ const searchTarget = useMemo(() => { // ... logic to determine search target based on viewMode ... return []; }, [viewMode, allCards, timelineMessages]); ``` -------------------------------- ### Data Parsing Engine (fileParser.js) - JavaScript Source: https://github.com/yalums/lyra-exporter/blob/main/README.md The fileParser.js module acts as the data parsing engine for Lyra's Exporter. It handles format detection for various AI conversation formats including Gemini/NotebookLM, Claude single conversation, and Claude full export. It then calls specific parsers to extract and standardize the chat data, supporting rich content like images, artifacts, and tool usage. ```javascript /** * Detects the format of the JSON data. * @param {object} jsonData - The JSON data to detect. * @returns {string} The detected format ('gemini_notebooklm', 'claude_full_export', 'claude', 'unknown'). */ function detectFileFormat(jsonData) { // Implementation to detect file format // ... return 'unknown'; } /** * Main entry point for extracting chat data. * @param {object} jsonData - The raw JSON data from the export file. * @param {string} fileName - The name of the file. * @returns {object} Standardized chat data. */ function extractChatData(jsonData, fileName) { const format = detectFileFormat(jsonData); switch (format) { case 'gemini_notebooklm': return extractGeminiNotebookLMData(jsonData, fileName); case 'claude_full_export': return extractClaudeFullExportData(jsonData, fileName); case 'claude': return extractClaudeData(jsonData); default: return { meta_info: {}, chat_history: [] }; } } /** * Parses Claude single conversation format. * @param {object} jsonData - The Claude JSON data. * @returns {object} Processed data with meta_info and chat_history. */ function extractClaudeData(jsonData) { // Implementation to parse Claude data // Handles messages, tool usage, artifacts, citations, attachments. // ... return { meta_info: {}, chat_history: [] }; } /** * Parses Gemini/NotebookLM export format. * @param {object} jsonData - The Gemini/NotebookLM JSON data. * @param {string} fileName - The name of the file. * @returns {object} Standardized chat data. */ function extractGeminiNotebookLMData(jsonData, fileName) { // Implementation to parse Gemini/NotebookLM data // Supports human/assistant pairs, base64 images. // ... return { meta_info: {}, chat_history: [] }; } /** * Parses Claude full export format. * @param {object} jsonData - The Claude full export JSON data. * @param {string} fileName - The name of the file. * @returns {object} Extended data structure with views. */ function extractClaudeFullExportData(jsonData, fileName) { // Implementation to parse Claude full export data // Handles multiple conversations, projects, conversation headers, star status. // ... return { views: { conversations: [], projects: [] } }; } /** * Detects message branches and branch points. * @param {object} processedData - The processed conversation data. * @returns {object} Data enhanced with branches and branch_points. */ function detectBranches(processedData) { // Implementation to detect branches // Builds parent-child relationship graph, marks branch points and paths. // ... return processedData; } // Helper functions (examples): function parseTimestamp(timestampStr) { // ...implementation... return 'formatted date'; } function formatFileSize(bytes) { // ...implementation... return 'formatted size'; } function getImageDisplayData(imageInfo) { // ...implementation... return {}; } function createMessage() { // ...implementation... return {}; } function processContentArray() { // ...implementation... } function processMessageImages() { // ...implementation... } function processGeminiImage() { // ...implementation... } function finalizeDisplayText() { // ...implementation... } function extractArtifact() { // ...implementation... } function extractToolUse() { // ...implementation... } function extractToolResult() { // ...implementation... } function markBranchPath() { // ...implementation... } function extractBranchInfo() { // ...implementation... } ``` -------------------------------- ### Automatic View Switching Based on File Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Automatically adjusts the application's view mode when a new file is loaded. This effect detects the format of the newly loaded file and switches to an appropriate view, such as the timeline or conversation list. ```javascript useEffect(() => { if (currentFile && currentFile.format) { // Logic to determine the best view mode based on currentFile.format // e.g., if (currentFile.format === 'claude_full_export') { setViewMode('conversations'); } } }, [currentFile]); ``` -------------------------------- ### Handle Mark Toggle Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Toggles a specific mark (e.g., completed, important) on a message. This action also has a side effect of adding the associated file to the `operatedFiles` set. ```javascript /** * Toggles a mark on a message. * @param {number} messageIndex - The index of the message. * @param {string} markType - The type of mark to toggle (e.g., 'completed', 'important'). */ function handleMarkToggle(messageIndex, markType) { // ... implementation to toggle mark ... // Example side effect: // operatedFiles.add(currentFile); } ``` -------------------------------- ### Handle File Removal Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Removes a specified file from the application's state. This action often involves resetting related view states to ensure consistency. ```javascript /** * Handles the removal of a file. * @param {number} fileIndex - The index of the file to remove. */ function handleFileRemove(fileIndex) { // ... implementation to remove file and reset related states ... } ``` -------------------------------- ### Handle Message Selection Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Manages the selection of a specific message, usually to display its detailed content in a modal or separate view. It updates the application state to reflect the selected message. ```javascript /** * Handles the selection of a message for detail view. * @param {number} messageIndex - The index of the message to select. */ function handleMessageSelect(messageIndex) { // ... implementation to set selected message index and potentially show detail modal ... } ``` -------------------------------- ### Export Management Module (exportModule.js) - JavaScript Source: https://github.com/yalums/lyra-exporter/blob/main/README.md The exportModule.js module provides functionality for exporting processed conversation data into various formats, primarily Markdown. It offers a range of configuration options to customize the export, such as including metadata, specific message types, timestamps, and Obsidian properties. It also includes a utility function for saving text content to a file. ```javascript /** * Exports processed chat data as Markdown. * @param {object} processedData - The standardized and processed chat data. * @param {object} config - Configuration options for the export. * @param {boolean} [config.exportObsidianMetadata=false] - Whether to include Obsidian metadata. * @param {boolean} [config.exportMarkedOnly=false] - Whether to export only marked messages. * @param {boolean} [config.includeTimestamps=true] - Whether to include timestamps. * @param {boolean} [config.includeThinking=false] - Whether to include thinking process. * @param {boolean} [config.includeArtifacts=false] - Whether to include artifacts. * @param {boolean} [config.includeTools=false] - Whether to include tool usage. * @param {boolean} [config.includeCitations=false] - Whether to include citations. * @param {object} [config.obsidianProperties={}] - Custom Obsidian properties. * @param {string[]} [config.obsidianTags=[]] - Obsidian tags. * @returns {string} The Markdown content. */ function exportChatAsMarkdown(processedData, config) { // Implementation to generate Markdown content // Supports branch marking, collapsible details, table formats. // ... let markdownContent = '# Conversation Export\n\n'; // Example: Iterating through messages and formatting them processedData.chat_history.forEach(message => { if (config.exportMarkedOnly && !message.isMarked) { return; } if (config.includeTimestamps) { markdownContent += `**${parseTimestamp(message.timestamp)}**\n`; } markdownContent += `**${message.sender}**: ${message.content}\n\n`; // Add logic for thinking, artifacts, tools, citations based on config }); return markdownContent; } /** * Saves text content to a file. * @param {string} text - The text content to save. * @param {string} fileName - The name of the file to save. * @returns {boolean} True if saved successfully, false otherwise. */ function saveTextFile(text, fileName) { try { const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); return true; } catch (error) { console.error('Error saving file:', error); return false; } } ``` -------------------------------- ### Calculate View Statistics Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Calculates statistics based on the current view mode. This function adapts its calculations depending on whether the user is viewing conversations, a timeline, or other modes. ```javascript /** * Calculates statistics based on the current view mode. * @param {string} viewMode - The current view mode (e.g., 'conversations', 'timeline'). * @param {...any} params - Additional parameters relevant to the view mode. * @returns {object} An object containing view-specific statistics. */ function calculateViewStats(viewMode, ...params) { // ... implementation to calculate stats based on viewMode ... return {}; } ``` -------------------------------- ### Handle Star Toggle Source: https://github.com/yalums/lyra-exporter/blob/main/README.md Toggles the starred status for a conversation, specifically for the 'claude_full_export' format. This function manages the starred state and potentially updates the UI or data accordingly. ```javascript /** * Toggles the starred status of a conversation (only for claude_full_export format). * @param {string} conversationUuid - The UUID of the conversation. * @param {boolean} nativeIsStarred - The current starred status of the conversation. */ function handleStarToggle(conversationUuid, nativeIsStarred) { // ... implementation to toggle star status ... } ```