Obsidian Link Embed

repository·main·Indexed 42 days ago

https://github.com/seraphli/obsidian-link-embed

An Obsidian plugin that converts URLs into rich, Notion-style visual embedded preview cards. It supports multiple parsing methods including Local, JSONLink, MicroLink, Iframely, and LinkPreview. Version 2.10.5 utilizes MarkdownCodeBlockProcessor for structured metadata storage and offers features such as auto-embedding, favicon support for markdown links, and the ability to save preview images directly to the vault.

Tokens
4.9K
Snippets
16
Records
21
Agent score
54%

What's inside Obsidian Link Embed

  1. Understand the Embed Format (v2.0.0+)

    main

    Starting from version 2.0.0, embeds are stored as MarkdownCodeBlockProcessor blocks using the embed language identifier. This format allows for structured metadata storage.

    Key fields include:

    • title: The title of the linked content.
    • image: The URL of the preview image.
    • description: A brief description of the content.
    • url: The original link URL.
    • favicon: The website's favicon URL.
    • aspectRatio: Optional parameter to maintain image dimensions.
    • metadata: Optional field for custom user data.
    • parser: The parser used to generate the embed.
    • date: The date of the embed.
    • custom_date: A formatted date string.
    title: "Example Title"
    image: "https://example.com/image.jpg"
    description: "This is an example description"
    url: "https://example.com"
    favicon: "https://example.com/favicon.ico"
    aspectRatio: "1.5"
    metadata: "Additional custom metadata can be included here"
    parser: "local"
    date: "2023-04-01"
    custom_date: "2023-04-01 13:45:22"
  2. Migrate old embeds to the new code block format

    main

    If you are upgrading from a version prior to 2.0.0, your old embeds may not render correctly with the new MarkdownCodeBlockProcessor.

    To convert existing embeds to the new code block format, use the Convert button located in the plugin settings.

  3. Use Obsidian Link Embed to create link previews

    main

    The plugin converts URLs into rich embedded previews. You can trigger the embedding process in several ways:

    1. Using the Popup Menu

    When pasting a URL, a popup menu may appear (if enabled) with these options:

    • Create Embed: Converts the URL into an embedded preview.
    • Create Markdown Link: Converts the URL into a standard markdown link [title](url).
    • Dismiss: Closes the popup.

    2. Using the Command Palette

    To manually trigger an embed, ensure the URL is available via one of these methods:

    • The URL is currently selected in the editor.
    • Your cursor is placed within the URL text.
    • The URL is copied to your clipboard.

    Then, open the Command Palette and select:

    • Link Embed: Embed link

    If you want to force a specific parser, use:

    • Link Embed: Embed link with ...

    3. Auto Embed

    If Auto Embed is enabled in settings, the plugin will automatically replace a link with an embed preview when you paste a link into an empty line.

  4. Configure Obsidian Link Embed settings

    main

    The plugin offers several configuration categories:

    Parser Settings

    • Default Parser: Set the primary parser. You can also configure a secondary parser to act as a fallback if the primary fails.
    • Supported Parsers:
      • Local (Default): Parses HTML directly without an API.
      • JSONLink: Requires an API key.
      • MicroLink: Limited to 50 requests per day.
      • Iframely: Limited to 1000 requests per month.
      • LinkPreview: Requires an API key.

    Embed Behavior

    • In Place: When enabled, the selected URL is removed and replaced by the embed. When disabled, the embed is inserted on the next line.

    Advanced Settings

    • Save Images to Vault: Downloads images from embedded links into your vault.
    • Image Folder Path: The directory for saved images (default: link-embed-images).
    • Respect Aspect Ratio: Preserves original image dimensions.
    • Use Cache: Caches favicons and aspect ratios for performance.
    • Enable Favicon: Displays website favicons in embeds.
    • Max Concurrent Local Parsers: Limits simultaneous local parsing operations to manage system load.
    • Metadata: Enables custom information (notes, tags) to be associated with embeds.
    • Metadata Template: Customize metadata using variables:
      • {{parser}}: The parser type used.
      • {{date}}: The date.
      • {{#formatDate}}YYYY-MM-DD HH:mm:ss{{/formatDate}}: Custom date formatting.

    Allows displaying favicons next to standard markdown links:

    • Enable Markdown Link Favicon: Shows favicons in Reading and Live Preview modes.
    • Favicon Position: Choose to display before or after link text.
    • Show on Aliased Links: Toggle for [text](url).
    • Show on Plain Links: Toggle for https://url.com.
  5. Extend the Parser class to create custom parsers

    main

    To add support for new URL types, you must extend the abstract Parser class and implement the process method. The Parser class provides a lifecycle for fetching and processing data.

    Lifecycle of a Parse Operation:

    1. parse(url): The entry point. It calls parseUrl and then process.
    2. parseUrl(url): Fetches raw data from an API using Mustache to render the api template. It supports GET and POST methods.
    3. process(data): (Required Implementation) An abstract method where you transform the raw API response into a basic object containing title, image, description, and optionally favicon.
    4. handleImageProcessing(...): A built-in utility that automatically handles favicon fetching, image downloading to the vault (if configured), and aspect ratio calculation.

    Parser Configuration Properties:

    • api: A Mustache template string used to construct the request URL.
    • debug: Boolean to enable/disable debug logging.
    • location: String used for error reporting (e.g., file:line).
    • method: HTTP method (defaults to 'GET').
    • headers: A Record<string, string> for request headers.
    • body: A string for POST requests. Use {{{url}}} as a placeholder for the target URL.
    • vault: Reference to the Obsidian vault.
    • saveImagesToVault: Boolean indicating if images should be downloaded locally.
    • imageFolderPath: The path within the vault where images will be saved.
    export abstract class Parser {
        // ... properties
        abstract process(data: any): {
            title: string;
            image: string;
            description: string;
            favicon?: string;
        };
    }
  6. Manage plugin settings with loadSettings and saveSettings

    main

    The ObsidianLinkEmbedPlugin provides methods to manage its configuration state.

    • loadSettings(): Asynchronously loads the plugin settings, merging them with DEFAULT_SETTINGS to ensure all keys are present.
    • saveSettings(): Persists the current settings object to disk using this.saveData(). It also re-initializes the LocalParser limiter if maxConcurrentLocalParsers has changed.
    async loadSettings() {
        this.settings = Object.assign(
            {},
            DEFAULT_SETTINGS,
            await this.loadData(),
        );
    }
    
    async saveSettings() {
        await this.saveData(this.settings);
        LocalParser.initLimiter(this.settings.maxConcurrentLocalParsers);
    }
  7. Generate embed markdown with `generateEmbedMarkdown()`

    main

    Creates the actual Markdown code block string for an embed based on parsed data and plugin settings. It handles metadata templates, escaping special characters in titles/descriptions, and includes favicons if enabled.

    const markdown = generateEmbedMarkdown(
        { title: 'Title', image: 'img.jpg', description: 'Desc', url: 'https://ex.com', aspectRatio: 1.5, favicon: 'fav.ico' },
        settings,
        'primary'
    );
  8. Create a parser instance with createParser()

    main

    Use the createParser factory function to instantiate a specific parser implementation based on a parserType string. The function handles API key validation for external services and configures image saving settings.

    Supported parserType values:

    • jsonlink: Requires settings.jsonlinkApiKey.
    • microlink: No API key required.
    • iframely: Requires settings.iframelyApiKey.
    • local: For local file parsing.
    • linkpreview: Requires settings.linkpreviewApiKey.

    Configuration via settings:

    • saveImagesToVault: Boolean (defaults to false).
    • imageFolderPath: String (defaults to 'link-embed-images').

    Vault Integration: If a vault object is provided, it is assigned to the parser instance to enable local file operations.

    import { createParser } from './parsers';
    
    const settings = {
        jsonlinkApiKey: 'YOUR_API_KEY',
        saveImagesToVault: true,
        imageFolderPath: 'my-custom-images'
    };
    
    // Create a JSONLink parser
    const parser = createParser('jsonlink', settings, myVaultInstance);
  9. Try multiple parsers with `tryParsers()`

    main

    Iterates through a list of selectedParsers to find the first one that successfully parses the metadata for a given URL. It provides visual feedback via Obsidian Notice during the process.

    Returns: A Promise resolving to { data: any; selectedParser: string }.

    Throws: An error if all provided parsers fail.

    const { data, selectedParser } = await tryParsers(
        'https://example.com',
        ['primary', 'backup'],
        settings,
        'context-info',
        vault
    );
  10. Handle UI interactions for embeds

    main

    The library provides utility functions to attach event listeners to the buttons rendered within an embed UI:

    • addRefreshButtonHandler(element, embedInfo, ctx, settings, vault): Attaches a click listener to the .refresh-button to trigger refreshEmbed.
    • addCopyButtonHandler(element, embedInfo, ctx, vault, settings): Attaches a click listener to the .copy-button to copy the raw embed Markdown code to the clipboard.
    • addDeleteButtonHandler(element, embedInfo, ctx, vault, settings): Attaches a click listener to the .delete-button to remove the entire embed code block from the current file.
  11. Convert a URL to a Markdown link with `convertUrlToMarkdownLink()`

    main

    Converts a raw URL into a standard Markdown link format [title](url) by attempting to fetch the page title using the provided parsers. If all parsers fail or no title is found, it returns null.

    const markdownLink = await convertUrlToMarkdownLink(
        'https://example.com',
        ['primary', 'backup'],
        settings,
        vault
    );