### Render embed preview from markdown code block Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt This code snippet shows how the `handleEmbedCodeBlock` function processes `embed` code blocks in markdown files, converting them into interactive HTML previews. It parses the YAML content within the code block, then uses other services like `parseYaml`, `handleEmbedCodeBlock`, and a cache to render an interactive card. The example demonstrates the required input (the source code block and an HTML element) and describes the resulting interactive HTML output. ```TypeScript import { parseYaml, MarkdownPostProcessorContext } from 'obsidian'; import { handleEmbedCodeBlock } from './eventHandlers'; // This is automatically registered by the plugin, but here's how it works: // In your markdown file: // ```embed // title: "GitHub" // image: "https://github.com/images/og-image.png" // description: "Where the world builds software" // url: "https://github.com" // favicon: "https://github.com/favicon.ico" // aspectRatio: "1.91" // ``` // The processor renders it as interactive HTML const source = ` title: "GitHub" image: "https://github.com/images/og-image.png" description: "Where the world builds software" url: "https://github.com" favicon: "https://github.com/favicon.ico" aspectRatio: "1.91" `; const el = document.createElement('div'); const ctx: MarkdownPostProcessorContext = /* context from Obsidian */; const settings = { enableFavicon: true, respectImageAspectRatio: true, useCache: true, debug: false }; const cache = new Map(); const vault = app.vault; const imageLoadAttempts = new Map(); await handleEmbedCodeBlock(source, el, ctx, settings, cache, vault, imageLoadAttempts); // Result: el contains an interactive card with: // - Clickable image and title linking to URL // - Refresh button to update metadata // - Copy button to copy embed code // - Delete button to remove embed from file // - Favicon displayed next to URL ``` -------------------------------- ### Refresh an existing embed's metadata Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt This code shows how to refresh the metadata of an existing embed using the `refreshEmbed` function. It takes a URL, the embed element, and other contextual information to update the embed's content by fetching fresh data. The example includes error handling and shows how the function can be triggered by a user action, such as clicking a refresh button. It also demonstrates the before and after state of the markdown code block. ```TypeScript import { refreshEmbed } from './embedUtils'; import { MarkdownPostProcessorContext } from 'obsidian'; // Example: Refresh an embed when user clicks the refresh button const element: HTMLElement = /* the embed element */; const ctx: MarkdownPostProcessorContext = /* from processor */; const settings = { primary: 'local', backup: 'microlink', debug: true }; const vault = app.vault; const url = 'https://example.com'; try { const success = await refreshEmbed(url, element, ctx, settings, vault); if (success) { console.log('Embed refreshed successfully'); // The code block in the file is now updated with fresh metadata // Previous content: // ```embed // title: "Old Title" // description: "Old description" // ... // ``` // // Updated content: // ```embed // title: "New Title" // description: "Updated description from latest fetch" // ... // ``` } } catch (error) { console.error('Refresh failed:', error); } ``` -------------------------------- ### Define default plugin settings and load configuration (TypeScript) Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt This snippet declares the default settings structure for the Obsidian Link Embed plugin, specifying user options, image handling, API keys, metadata templates, and performance limits. It also shows how to enable image saving, caching, and adjust concurrency before persisting the settings. The code requires the plugin instance and the settings interfaces from the plugin's codebase. ```TypeScript import { ObsidianLinkEmbedPluginSettings, DEFAULT_SETTINGS } from './settings'; // Default settings structure const settings: ObsidianLinkEmbedPluginSettings = { // User Options popup: true, // Show popup menu on paste rmDismiss: false, // Remove dismiss option from popup autoEmbedWhenEmpty: false, // Auto-embed on empty lines defaultPasteAction: 'embed', // 'embed' or 'markdown' primary: 'local', // Primary parser backup: 'microlink', // Fallback parser inPlace: false, // Replace selection vs new line // Image Settings saveImagesToVault: false, // Download images locally imageFolderPath: 'link-embed-images', // Where to save images respectImageAspectRatio: true, // Maintain image proportions useCache: true, // Cache images and favicons enableFavicon: false, // Show website favicons // API Keys linkpreviewApiKey: '', jsonlinkApiKey: '', iframelyApiKey: '', // Metadata useMetadataTemplate: false, metadataTemplate: 'parser: "{{parser}}"\ndate: "{{date}}"', // Performance maxConcurrentLocalParsers: 1, // Limit concurrent requests // Developer debug: false, delay: 0 // Delay before replacing preview }; // Example: Enable image saving and caching await plugin.loadSettings(); plugin.settings.saveImagesToVault = true; plugin.settings.imageFolderPath = 'attachments/embeds'; plugin.settings.useCache = true; plugin.settings.enableFavicon = true; plugin.settings.maxConcurrentLocalParsers = 3; await plugin.saveSettings(); // Updates LocalParser limiter automatically // Images will be saved to vault/attachments/embeds/ ``` -------------------------------- ### Parse a URL and extract metadata Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt This code demonstrates how to use the `LocalParser` class to extract metadata from a given URL. It first initializes a concurrency limiter, then configures the parser with settings like debugging, image saving, and the target vault. Finally, it demonstrates how to parse a URL and print the extracted title and image aspect ratio to the console, with error handling for failed requests. ```TypeScript import { LocalParser } from './parsers/LocalParser'; // Initialize the concurrency limiter (important for performance) LocalParser.initLimiter(3); // Max 3 concurrent requests const parser = new LocalParser(); parser.debug = true; parser.saveImagesToVault = true; parser.vault = app.vault; parser.imageFolderPath = 'my-images'; // Parse a URL const url = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript'; try { const metadata = await parser.parse(url); // Output: // { // title: "JavaScript | MDN", // image: "https://developer.mozilla.org/mdn-social-share.png", // description: "JavaScript (JS) is a lightweight interpreted...", // url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript", // aspectRatio: 2.0, // favicon: "https://developer.mozilla.org/favicon.ico" // } console.log('Title:', metadata.title); console.log('Image aspect ratio:', metadata.aspectRatio); } catch (error) { console.error('Failed to parse URL:', error); // Falls back to backup parser if configured } ``` -------------------------------- ### API Functions - TypeScript Implementation Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt Core API functions for the Obsidian Link Embed Plugin including embedUrl for creating link previews and createParser for initializing parsers. Shows TypeScript integration with Obsidian Editor API, multiple parser fallback strategies, and error handling. Supports local HTML parsing and external API parsers with configuration options. ```typescript import { Editor } from 'obsidian'; import { embedUrl } from './embedUtils'; import { ObsidianLinkEmbedPluginSettings } from './settings'; // Example: Embed a URL using primary and backup parsers const editor: Editor = /* your editor instance */; const url = 'https://example.com'; const settings: ObsidianLinkEmbedPluginSettings = { primary: 'local', backup: 'microlink', debug: true, inPlace: false, // ... other settings }; await embedUrl( editor, { can: true, text: url, boundary: { start: { line: 5, ch: 0 }, end: { line: 5, ch: url.length } } }, [settings.primary, settings.backup], settings, false // inPlace: if true, replaces selection instead of inserting new line ); // Result: Creates a code block in the editor: // ```embed // title: "Example Domain" // image: "https://example.com/image.jpg" // description: "Example domain for documentation" // url: "https://example.com" // favicon: "https://example.com/favicon.ico" // aspectRatio: "1.5" // parser: "local" // date: "2024-01-15" // ``` ``` ```typescript import { createParser } from './parsers'; import { ObsidianLinkEmbedPluginSettings } from './settings'; // Example: Create a local parser (no API key needed) const settings = { saveImagesToVault: true, imageFolderPath: 'link-embed-images', jsonlinkApiKey: 'your-api-key', // ... other settings }; const vault = app.vault; try { // Local parser - no API key required const localParser = createParser('local', settings, vault); localParser.debug = true; const result = await localParser.parse('https://example.com'); console.log(result); // Output: // { // title: "Example Domain", // image: "https://example.com/image.jpg", // description: "Example domain for documentation", // url: "https://example.com", // aspectRatio: 1.5, // favicon: "https://example.com/favicon.ico" // } // JSONLink parser - requires API key const jsonlinkParser = createParser('jsonlink', settings, vault); const jsonResult = await jsonlinkParser.parse('https://github.com'); } catch (error) { console.error('Parser failed:', error.message); // Error: "JSONLink API key is not set" } ``` -------------------------------- ### Register embed and markdown link commands for parsers (TypeScript) Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt This snippet registers multiple commands in the Obsidian plugin, allowing users to create embed blocks or markdown links using default or specific parsers. It demonstrates adding generic commands, parser‑specific commands, and handling editor callbacks with asynchronous functions. The code depends on the Obsidian API's addCommand method and custom handler functions. ```TypeScript // Main embed command - uses primary/backup parsers this.addCommand({ id: 'embed-link', name: 'Create Embed Block', editorCallback: async (editor: Editor) => { await handleEmbedLinkCommand(editor, this.settings); } }); // Markdown link command this.addCommand({ id: 'create-markdown-link', name: 'Create Markdown Link', editorCallback: async (editor: Editor) => { await handleCreateMarkdownLinkCommand( editor, this.settings, this.app.vault ); } }); // Parser-specific commands const parseOptions = { jsonlink: 'JSONLink', microlink: 'MicroLink', iframely: 'Iframely', local: 'Local', linkpreview: 'LinkPreview' }; Object.keys(parseOptions).forEach((name) => { // Embed command for specific parser this.addCommand({ id: `embed-link-${name}`, name: `Create Embed Block with ${parseOptions[name]}`, editorCallback: createParserCommandHandler(name, this.settings) }); // Markdown link command for specific parser this.addCommand({ id: `create-markdown-link-${name}`, name: `Create Markdown Link with ${parseOptions[name]}`, editorCallback: async (editor: Editor) => { await handleCreateMarkdownLinkCommand( editor, this.settings, this.app.vault, [name] // Use only this parser ); } }); }); // Usage: User opens command palette and types: // - "Link Embed: Create Embed Block" -> Uses primary/backup // - "Link Embed: Create Embed Block with Local" -> Forces local parser // - "Link Embed: Create Markdown Link with MicroLink" -> Markdown with MicroLink ``` -------------------------------- ### Calculate Image Aspect Ratio (TypeScript) Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt Loads an image from a URL and calculates its dimensions (width, height) and aspect ratio. It includes support for caching fetched dimensions and tracking failed load attempts to optimize subsequent requests. This is crucial for maintaining image proportions within embeds. ```typescript import { getImageDimensions } from './parsers'; const imageUrl = 'https://example.com/image.jpg'; const cache = new Map(); // Optional cache const imageLoadAttempts = new Map(); // Optional tracking try { const dimensions = await getImageDimensions( imageUrl, cache, imageLoadAttempts ); if (dimensions) { console.log('Width:', dimensions.width); // 800 console.log('Height:', dimensions.height); // 600 console.log('Aspect Ratio:', dimensions.aspectRatio); // 133.33 // Aspect ratio is calculated as (width / height) * 100 // Used to maintain image proportions in CSS // Cache is automatically populated const cached = cache.get(imageUrl); console.log('Cached:', cached); // Same dimensions object } } catch (error) { console.error('Failed to load image:', error); // Attempt is tracked in imageLoadAttempts map // Future attempts will be limited based on failure count } ``` -------------------------------- ### Auto-Popup Embed Suggest Menu Handler (TypeScript) Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt Handles the editor suggestion menu that automatically appears when pasting URLs. It provides options to create embeds, Markdown links, or dismiss the menu. The handler supports auto-embedding on empty lines based on plugin settings and can be manually triggered. ```typescript import { App, Editor, EditorPosition } from 'obsidian'; import EmbedSuggest from './suggest'; // Registered automatically by the plugin const plugin = /* your plugin instance */; const suggest = new EmbedSuggest(app, plugin); // Configuration through plugin settings plugin.settings = { popup: true, // Show popup menu on paste rmDismiss: false, // Show dismiss option autoEmbedWhenEmpty: true, // Auto-embed on empty lines defaultPasteAction: 'embed', // 'embed' or 'markdown' primary: 'local', backup: 'microlink' }; // When user pastes "https://example.com": // 1. Plugin detects URL in clipboard via handleEditorPaste // 2. If popup enabled, EmbedSuggest shows menu with: // - "Create Embed Block" (default) // - "Create Markdown Link" // - "Dismiss" // // 3. If autoEmbedWhenEmpty and line is empty: // - Automatically creates embed without showing popup // - Uses defaultPasteAction to determine embed vs markdown // Manual trigger example this.registerEditorSuggest(suggest); ``` -------------------------------- ### Create Markdown Link from URL (TypeScript) Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt Converts a given URL into a standard Markdown link format `[title](url)`. It fetches the page title using specified parsers and settings, supporting fallback mechanisms. This function is useful for simple text references without rich previews and returns a string containing the Markdown link or null if all parsers fail. ```typescript import { convertUrlToMarkdownLink } from './embedUtils'; const url = 'https://obsidian.md'; const selectedParsers = ['local', 'microlink']; const settings = { primary: 'local', backup: 'microlink', debug: true, jsonlinkApiKey: '', // ... other settings }; const vault = app.vault; try { const markdownLink = await convertUrlToMarkdownLink( url, selectedParsers, settings, vault ); console.log(markdownLink); // Output: "[Obsidian - Sharpen your thinking](https://obsidian.md)" if (markdownLink) { // Insert into editor at cursor position editor.replaceSelection(markdownLink); } } catch (error) { console.error('Failed to create markdown link:', error); // Falls back to null if all parsers fail } ``` -------------------------------- ### Detect URL Paste Event Handler (TypeScript) Source: https://context7.com/seraphli/obsidian-link-embed/llms.txt An event handler designed to detect when a URL is pasted into the editor. Upon detection, it updates internal paste information to trigger suggestion menus or auto-embed features. This handler is essential for initiating the embed suggestion workflow. ```typescript import { handleEditorPaste } from './eventHandlers'; // Registered in plugin onload: this.registerEvent( this.app.workspace.on('editor-paste', (evt: ClipboardEvent) => { handleEditorPaste(evt, this.pasteInfo); }) ); // Plugin maintains pasteInfo state: const pasteInfo = { trigger: false, text: '' }; // When user pastes "https://example.com": // 1. handleEditorPaste checks clipboard content // 2. If valid URL detected: // pasteInfo.trigger = true // pasteInfo.text = "https://example.com" // 3. EmbedSuggest.onTrigger is called // 4. Shows popup menu or auto-embeds based on settings // Invalid pastes (non-URL text): // pasteInfo.trigger remains false // No popup shown ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.