Skip to content

Backlinks UI Panel - Display 'Mentioned By' References #318

Closed

Description

@malibio

Backlinks UI Panel - Display "Mentioned By" References

Overview

Create a UI panel component that displays all incoming mentions (backlinks) for a given node. This allows users to see which other nodes reference the current node, enabling bi-directional navigation through the knowledge graph.

Dependencies

Problem Statement

Currently, users can create mentions/links from one node to another using the [@text](nodespace://node-id) format. However, there's no UI to see the reverse direction - which nodes link TO the current node.

This "backlinks" or "mentioned by" feature is critical for:

  • Understanding node relationships and context
  • Discovering related content
  • Building a bi-directional knowledge graph
  • Navigation patterns similar to Roam Research and Obsidian

Key Design Decisions

Container-Level Backlinks

Rule: Backlinks are resolved and displayed at the container level, not individual node level.

Rationale:

  • The @mention system already filters to only show container nodes (+ exceptions like task/ai-chat)
  • When you create a mention, you're always linking to a container node
  • Multiple child nodes within the same container may mention the same target
  • Users want to see "which pages/documents mention this" not "which paragraphs mention this"

Implementation:

  • New backend method: get_mentioning_containers(node_id)
  • Returns container node IDs that contain mentions to the target node
  • Automatically deduplicates (if 5 nodes in Container X mention Node Y, show Container X once)
  • Handles exceptions: task and ai-chat nodes are treated as their own containers

Example:

Date 2025-01-15 (container, id: date-1)
  ├─ Text Node A: "See [@2025-01-20](nodespace://date-2)"
  └─ Text Node C: "Also [@2025-01-20](nodespace://date-2)"

Date 2025-01-20 (container, id: date-2)
  └─ Text Node B

Backlinks displayed on date-2:
  - "2025-01-15" (shown once, not "Node A" and "Node C" separately)

Implementation Scope

What This Issue Includes:

  1. Backend: get_mentioning_containers() Rust function with Tauri command
  2. Frontend: getMentioningContainers() adapter method
  3. UI: BacklinksPanel.svelte component
  4. Integration: Add to DateNodeViewer and BaseNodeViewer
  5. Tests: Unit and integration tests
  6. Documentation: Update ADR-022 with container-level backlinks decision

What This Issue Does NOT Include:

Technical Specifications

Backend API

Rust Function (packages/desktop-app/src-tauri/src/commands/nodes.rs):

/// Get containers of nodes that mention the target node (backlinks at container level)
///
/// This resolves incoming mentions to their container nodes and deduplicates.
/// 
/// Example: If nodes A and B (both children of Container X) mention target node,
/// returns ['container-x-id'] (deduplicated).
///
/// Exceptions: Task and ai-chat nodes are treated as their own containers.
#[tauri::command]
pub async fn get_mentioning_containers(
    service: State<'_, NodeService>,
    node_id: String,
) -> Result<Vec<String>, CommandError> {
    service
        .get_mentioning_containers(&node_id)
        .await
        .map_err(Into::into)
}

Implementation approach:

  1. Query node_mentions table for all incoming mentions
  2. JOIN with nodes table to get each mentioning node's container_node_id
  3. For task/ai-chat nodes: use the node's own ID (they are their own containers)
  4. For other nodes: use their container_node_id
  5. Deduplicate container IDs
  6. Return unique list

SQL Query (approximate):

-- Get unique containers of nodes that mention target_node_id
SELECT DISTINCT 
  CASE 
    WHEN n.node_type IN ('task', 'ai-chat') THEN n.id
    ELSE COALESCE(n.container_node_id, n.id)
  END as container_id
FROM node_mentions nm
JOIN nodes n ON nm.node_id = n.id
WHERE nm.mentions_node_id = ?

Frontend API

Backend Adapter (packages/desktop-app/src/lib/services/backend-adapter.ts):

/**
 * Get containers of nodes that mention this node (backlinks at container level).
 * 
 * Unlike getIncomingMentions() which returns individual mentioning nodes,
 * this resolves to their container nodes and deduplicates.
 * 
 * Example: If nodes A and B (both children of Container X) mention this node,
 * returns ['container-x-id'] instead of ['node-a-id', 'node-b-id'].
 * 
 * Exceptions: Task and ai-chat nodes are treated as their own containers.
 * 
 * @param nodeId - The node to find backlinks for
 * @returns Array of unique container node IDs
 */
async getMentioningContainers(nodeId: string): Promise<string[]> {
  try {
    return await invoke<string[]>('get_mentioning_containers', { nodeId });
  } catch (error) {
    const err = toError(error);
    throw new NodeOperationError(err.message, nodeId, 'getMentioningContainers');
  }
}

Component Implementation

File: packages/desktop-app/src/lib/design/components/backlinks-panel.svelte

<script lang="ts">
  import { backendAdapter } from '$lib/services/backend-adapter';
  import { sharedNodeStore } from '$lib/services/shared-node-store';
  import { onMount } from 'svelte';
  import type { Node } from '$lib/types/node';

  let { nodeId }: { nodeId: string } = $props();
  
  let backlinks = $state<Node[]>([]);
  let loading = $state(true);
  let error = $state<string | null>(null);

  onMount(async () => {
    try {
      // Get container IDs that mention this node
      const containerIds = await backendAdapter.getMentioningContainers(nodeId);
      
      // Fetch full node data for each container
      backlinks = containerIds
        .map(id => sharedNodeStore.getNode(id))
        .filter((node): node is Node => node !== undefined);
      
    } catch (err) {
      console.error('Failed to load backlinks:', err);
      error = err instanceof Error ? err.message : 'Failed to load backlinks';
    } finally {
      loading = false;
    }
  });
  
  function getPreviewText(content: string): string {
    // Extract first 100 chars, strip markdown formatting
    return content
      .replace(/\[@[^\]]+\]\([^)]+\)/g, '') // Remove mention links
      .replace(/[#*_`]/g, '') // Remove basic markdown
      .trim()
      .substring(0, 100);
  }
</script>

<div class="backlinks-panel">
  <h3 class="backlinks-header">
    Mentioned by
    {#if !loading && backlinks.length > 0}
      <span class="backlinks-count">({backlinks.length})</span>
    {/if}
  </h3>
  
  {#if loading}
    <div class="backlinks-loading">Loading backlinks...</div>
  {:else if error}
    <div class="backlinks-error">{error}</div>
  {:else if backlinks.length === 0}
    <div class="backlinks-empty">No pages mention this one yet.</div>
  {:else}
    <ul class="backlinks-list">
      {#each backlinks as backlink}
        <li class="backlink-item">
          <a href="nodespace://{backlink.id}" class="backlink-link">
            <div class="backlink-type">{backlink.nodeType}</div>
            <div class="backlink-preview">
              {getPreviewText(backlink.content)}
            </div>
          </a>
        </li>
      {/each}
    </ul>
  {/if}
</div>

<style>
  /* Design system compliant styles */
  .backlinks-panel {
    padding: var(--spacing-md);
    background: hsl(var(--surface));
    border-radius: var(--radius-md);
    border: 1px solid hsl(var(--border));
  }

  .backlinks-header {
    font-size: var(--font-size-md);
    font-weight: 600;
    margin-bottom: var(--spacing-sm);
    color: hsl(var(--foreground));
  }

  .backlinks-count {
    font-weight: 400;
    color: hsl(var(--muted-foreground));
  }

  .backlinks-loading,
  .backlinks-empty,
  .backlinks-error {
    padding: var(--spacing-sm);
    color: hsl(var(--muted-foreground));
    font-size: var(--font-size-sm);
  }

  .backlinks-error {
    color: hsl(var(--destructive));
  }

  .backlinks-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: var(--spacing-xs);
  }

  .backlink-item {
    border-radius: var(--radius-sm);
    overflow: hidden;
  }

  .backlink-link {
    display: block;
    padding: var(--spacing-sm);
    background: hsl(var(--background));
    border: 1px solid hsl(var(--border));
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: hsl(var(--foreground));
    transition: all 0.15s ease;
  }

  .backlink-link:hover {
    background: hsl(var(--accent));
    border-color: hsl(var(--accent-foreground) / 0.2);
  }

  .backlink-type {
    font-size: var(--font-size-xs);
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: hsl(var(--muted-foreground));
    margin-bottom: var(--spacing-xs);
  }

  .backlink-preview {
    font-size: var(--font-size-sm);
    color: hsl(var(--foreground));
    line-height: 1.4;
  }
</style>

Integration with Node Viewers

DateNodeViewer (packages/desktop-app/src/lib/components/viewers/date-node-viewer.svelte):

<script lang="ts">
  import BacklinksPanel from '$lib/design/components/backlinks-panel.svelte';
  // ... existing imports
  
  let { nodeId }: { nodeId: string } = $props();
</script>

<div class="date-node-viewer">
  <!-- Existing content -->
  <BaseNodeViewer {containerNodeId} />
  
  <!-- Backlinks panel -->
  <div class="viewer-sidebar">
    <BacklinksPanel {nodeId} />
  </div>
</div>

<style>
  .viewer-sidebar {
    margin-top: var(--spacing-lg);
    max-width: 600px;
  }
</style>

BaseNodeViewer: Similar integration for container nodes

Navigation

Uses existing nodespace:// protocol handler from #297 (no additional code needed).

Testing Requirements

Unit Tests

File: packages/desktop-app/src/tests/components/backlinks-panel.test.ts

Test scenarios:

  • ✅ Loading state displays initially
  • ✅ Container backlinks display when loaded
  • ✅ Empty state shows when no backlinks
  • ✅ Error handling for backend failures
  • ✅ Correct nodespace:// link generation
  • ✅ Deduplication verification (mock multiple nodes in same container)

Integration Tests

Manual Testing Checklist:

  • Create mentions from multiple nodes in Container A to Node B
  • Verify Container A appears once in Node B's backlinks
  • Test with task nodes (should appear directly, not their container)
  • Test navigation by clicking backlinks
  • Test Cmd+Click for new tab
  • Verify empty state when no backlinks
  • Test error handling (backend unavailable)

Acceptance Criteria

  • get_mentioning_containers() Rust function implemented and tested
  • getMentioningContainers() frontend adapter method added
  • BacklinksPanel component implemented with all states
  • Component integrated into DateNodeViewer
  • Component integrated into BaseNodeViewer
  • Deduplication works correctly (multiple mentions → single container)
  • Task/ai-chat exception handling works
  • Unit tests pass with >90% coverage
  • Manual integration tests completed
  • ADR-022 updated with container-level backlinks decision
  • Code passes bun run quality:fix

Future Enhancements (Not in Scope)

  • Real-time updates when mentions change (requires event system)
  • Filtering/searching backlinks
  • Grouping backlinks by node type
  • Showing context (surrounding text where mention appears)
  • Backlink preview on hover
  • Click to scroll to specific mention within container

Related Issues

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions