Skip to content

Implement OrderedListNode (Auto-Numbered Lists) #293

Closed

Description

@malibio

Overview

Implement OrderedListNode to support auto-numbered ordered lists using markdown `1. ` syntax. This completes basic markdown document support alongside existing text, header, quote-block, code-block, and task nodes.

Design Reference

IMPORTANT: Follow the established design specifications:

  • 🎨 Component Design - See "Ordered List Nodes" section for complete UI design
  • 🎨 Icon System - See "OrderedListNode Icon System" section for icon specifications

Reference Documentation

IMPORTANT: Before implementing, read these comprehensive guides:

Scope

In Scope:

  • Auto-numbered ordered lists with `1. ` prefix pattern
  • Pattern detection for auto-conversion
  • Slash command `/ordered-list` or `/ol`
  • CSS-based auto-numbering in view mode (1, 2, 3...)
  • Enter key creates new ordered list sibling
  • Backspace at start converts to text node

Out of Scope (Future Enhancement):

  • Nested/hierarchical ordered lists (`canHaveChildren: false`)
  • Starting at arbitrary numbers (e.g., `5. `)
  • Mixed numbering formats (e.g., `a.`, `i.`, `I.`)

Markdown Specification

CommonMark Standard:

  • Pattern: `1. ` (number, period, space)
  • Auto-numbering: All items use `1. ` in source, renderer provides sequential numbers
  • Reference: CommonMark Lists Tutorial

Complete Implementation Checklist

Phase 1: Backend Configuration

Step 1.1: Update ALLOWED_NODE_TYPES

File: `packages/desktop-app/src-tauri/src/constants.rs`

⚠️ CRITICAL: Forgetting this step causes HTTP 400 errors when creating nodes!

```rust
/// Allowed node types in the system
///
/// Currently supported node types:
/// - "text": Plain text nodes
/// - "header": Markdown headers (h1-h6)
/// - "task": Task/todo nodes with completion status
/// - "date": Date-based nodes for daily notes
/// - "code-block": Code blocks with language selection
/// - "quote-block": Quote block nodes with markdown styling
/// - "ordered-list": Auto-numbered ordered list items // ← ADD THIS LINE
///
/// Used by both Tauri IPC commands and HTTP dev server endpoints
/// to ensure consistent validation.
pub const ALLOWED_NODE_TYPES: &[&str] = &[
"text",
"header",
"task",
"date",
"code-block",
"quote-block",
"ordered-list", // ← ADD THIS
];
```

Phase 2: Frontend Icon System

Step 2.1: Icon Import and Registration

File: `packages/desktop-app/src/lib/design/icons/index.ts`

Add import and register icon:

```typescript
import { ListOrdered } from 'lucide-svelte'; // ← ADD THIS IMPORT

export const NODE_TYPE_ICONS: Record<NodeType, LucideIcon> = {
// ... existing icons
'quote-block': Quote,
'ordered-list': ListOrdered, // ← ADD THIS
};
```

Step 2.2: Icon Registry Configuration

File: `packages/desktop-app/src/lib/design/icons/registry.ts`

Register icon with proper configuration:

```typescript
class IconRegistry {
constructor() {
// ... existing registrations

// Ordered list - Auto-numbered list items
this.register('ordered-list', {
  component: ListOrderedIcon,  // Uses Lucide icon
  semanticClass: 'node-icon',
  colorVar: 'hsl(var(--node-text, 200 40% 45%))',
  hasState: false,
  hasRingEffect: false  // ← IMPORTANT: Leaf node, cannot have children
});

}
}
```

Key Decision: `hasRingEffect: false` because `canHaveChildren: false`

Design Reference: See Icon System - OrderedListNode Icon System for complete icon specifications including:

  • 16x16px filled circle with 2px offset in 20x20px container
  • Material Design numbered list icon overlay
  • Light/dark theme color specifications
  • No ring effect variant (leaf node only)

Phase 3: Node Component Implementation

Step 3.1: Create OrderedListNode Component

File: `packages/desktop-app/src/lib/design/components/ordered-list-node.svelte`

Create new file (copy structure from `quote-block-node.svelte`):

```svelte

<script lang=\"ts\"> import BaseNode from './base-node.svelte'; import type { Node } from '$lib/types/node'; import type { NodeUIState } from '$lib/types/node'; interface Props { node: Node; uiState: NodeUIState; } let { node, uiState }: Props = $props(); </script>

<BaseNode {node} {uiState} nodeTypeClass="ordered-list-node">
{#snippet viewContent()}

<span class="ordered-list-content">
{node.content.replace(/^1\.\s/, '')}

{/snippet}

<style> :global(.ordered-list-node) { position: relative; padding-left: 2rem; } /* Auto-numbering via CSS counter */ :global(.ordered-list-node::before) { counter-increment: ordered-list-counter; content: counter(ordered-list-counter) '. '; position: absolute; left: 0; font-weight: 600; color: hsl(var(--muted-foreground)); min-width: 1.5rem; text-align: right; } .ordered-list-content { display: inline; } </style>

```

Design Reference: See Components - Ordered List Nodes for complete component design including:

  • CSS counter auto-numbering implementation
  • 0.125rem (2px) spacing between items
  • Font weight 600 for numbers
  • Muted foreground color for numbers
  • Text wrapping behavior with `flex-shrink: 0`

Phase 4: Plugin System Integration

Step 4.1: Define Plugin

File: `packages/desktop-app/src/lib/plugins/core-plugins.ts`

Add plugin definition after `quoteBlockNodePlugin`:

```typescript
export const orderedListNodePlugin: PluginDefinition = {
id: 'ordered-list',
name: 'Ordered List Node',
description: 'Auto-numbered ordered list item',
version: '1.0.0',
config: {
slashCommands: [
{
id: 'ordered-list',
name: 'Ordered List',
description: 'Create an auto-numbered list item',
shortcut: '1.',
contentTemplate: '1. ',
nodeType: 'ordered-list',
desiredCursorPosition: 3 // Position cursor after "1. " prefix
}
],
// Pattern detection for "1. " auto-conversion
patternDetection: [
{
pattern: /^1\.\s/,
targetNodeType: 'ordered-list',
/**
* cleanContent: false - CRITICAL: Content MUST retain "1. " prefix
*
* Similar to quote-block ("> "), ordered lists store prefix in database.
* The "1. " prefix is:
* - Stored in database for round-trip consistency
* - Stripped in view mode for auto-numbering display
* - Shown in edit mode for user visibility
*
* Auto-numbering (1, 2, 3...) happens via CSS counters during rendering.
*/
cleanContent: false,
extractMetadata: () => ({}),
priority: 10,
desiredCursorPosition: 3 // Place cursor after "1. "
}
],
canHaveChildren: false, // ← IMPORTANT: Simple flat lists only (no nesting)
canBeChild: true
},
node: {
lazyLoad: () => import('../design/components/ordered-list-node.svelte'),
priority: 1
},
reference: {
component: BaseNodeReference as NodeReferenceComponent,
priority: 1
}
};
```

Step 4.2: Register Plugin

Register in `corePlugins` array:

```typescript
export const corePlugins = [
textNodePlugin,
headerNodePlugin,
taskNodePlugin,
aiChatNodePlugin,
dateNodePlugin,
codeBlockNodePlugin,
quoteBlockNodePlugin,
orderedListNodePlugin, // ← ADD THIS
userNodePlugin,
documentNodePlugin
];
```

Phase 5: Viewer Integration

Step 5.1: Add Counter Reset CSS

File: `packages/desktop-app/src/lib/components/viewers/base-node-viewer.svelte`

Add CSS to reset counter (find the existing `<style>` section and add):

```css
/* Reset ordered list counter at viewer level */
:global(.base-node-viewer) {
counter-reset: ordered-list-counter;
}

/* Also reset when ordered list sequence is broken by non-list nodes */
:global(.base-node-viewer > *:not(.ordered-list-node)) {
counter-reset: ordered-list-counter;
}
```

Counter Reset Behavior Example:
```

  1. First item (ordered-list)
  2. Second item (ordered-list)
    Some text (text) <- Breaks sequence
  3. New list starts (ordered-list) <- Counter resets
  4. Second in new list (ordered-list)
    ```

Phase 6: Testing

Step 6.1: Unit Tests

File: `packages/desktop-app/src/tests/components/ordered-list-node.test.ts`

```typescript
/**

  • OrderedListNode Tests
  • Tests for ordered list plugin functionality including:
    • Pattern detection
    • Plugin registration
    • View/edit mode rendering
    • CSS counter auto-numbering
      */

import { describe, it, expect } from 'vitest';
import { render } from '@testing-library/svelte';
import OrderedListNode from '$lib/design/components/ordered-list-node.svelte';
import { pluginRegistry } from '$lib/plugins/plugin-registry';

describe('OrderedListNode Component', () => {
it('should strip "1. " prefix in view mode', () => {
const node = {
id: 'test-1',
nodeType: 'ordered-list',
content: '1. First item',
parentId: null,
containerNodeId: null,
beforeSiblingId: null,
createdAt: new Date().toISOString(),
modifiedAt: new Date().toISOString(),
properties: {}
};

const uiState = {
  nodeId: 'test-1',
  depth: 0,
  expanded: false,
  autoFocus: false,
  inheritHeaderLevel: 0,
  isPlaceholder: false
};

const { container } = render(OrderedListNode, { props: { node, uiState } });

// View content should not show \"1. \"
expect(container.textContent).not.toContain('1. First item');
expect(container.textContent).toContain('First item');

});

it('should apply auto-numbering CSS counter', () => {
const { container } = render(OrderedListNode, { props: { node, uiState } });
const element = container.querySelector('.ordered-list-node');

expect(element).toBeTruthy();

});
});

describe('OrderedListNode Plugin', () => {
describe('Pattern Detection', () => {
it('should detect "1. " pattern', () => {
const content = '1. Test item';
const detection = pluginRegistry.detectPatternInContent(content);

  expect(detection).not.toBeNull();
  expect(detection?.config.targetNodeType).toBe('ordered-list');
});

it('should keep prefix in content (cleanContent: false)', () => {
  const plugin = pluginRegistry.getPlugin('ordered-list');
  const pattern = plugin?.config.patternDetection?.[0];
  
  expect(pattern?.cleanContent).toBe(false);
});

it('should position cursor after \"1. \" (position 3)', () => {
  const plugin = pluginRegistry.getPlugin('ordered-list');
  const pattern = plugin?.config.patternDetection?.[0];
  
  expect(pattern?.desiredCursorPosition).toBe(3);
});

});

describe('Plugin Registration', () => {
it('should have plugin registered', () => {
expect(pluginRegistry.hasPlugin('ordered-list')).toBe(true);
});

it('should have correct configuration', () => {
  const plugin = pluginRegistry.getPlugin('ordered-list');

  expect(plugin?.config.canHaveChildren).toBe(false);
  expect(plugin?.config.canBeChild).toBe(true);
});

});

describe('Slash Command', () => {
it('should register slash command', () => {
const commands = pluginRegistry.getAllSlashCommands();
const command = commands.find(c => c.nodeType === 'ordered-list');

  expect(command).toBeDefined();
  expect(command?.id).toBe('ordered-list');
  expect(command?.contentTemplate).toBe('1. ');
  expect(command?.desiredCursorPosition).toBe(3);
});

});
});
```

Step 6.2: Integration Tests

File: `packages/desktop-app/src/tests/integration/ordered-list-workflow.test.ts`

```typescript
import { describe, it, expect } from 'vitest';

describe('OrderedListNode Workflow', () => {
it('should auto-convert "1. " to ordered-list node', async () => {
// Type "1. " in text node
// Verify conversion to ordered-list nodeType
// Verify content retains "1. " prefix
});

it('should create new ordered list item on Enter', async () => {
// Press Enter in ordered list node
// Verify new sibling created with "1. " template
// Verify cursor at position 3
});

it('should convert to text on Backspace at start', async () => {
// Backspace at position 0 in ordered list
// Verify conversion to text and prefix stripped
});

it('should auto-number sequential ordered list items', async () => {
// Create 3 ordered list items as siblings
// Verify display shows "1.", "2.", "3." via CSS counters
});

it('should reset counter after non-list node', async () => {
// Create: ordered-list, ordered-list, text, ordered-list
// Verify last item shows "1." (counter reset)
});
});
```


Acceptance Criteria

  • `"ordered-list"` added to `ALLOWED_NODE_TYPES` in `constants.rs`
  • `ListOrdered` icon imported and registered in icon registry
  • `hasRingEffect: false` set (no children allowed)
  • `orderedListNodePlugin` added to `core-plugins.ts`
  • Plugin registered in `corePlugins` array
  • Pattern `/^1\.\s/` triggers auto-conversion to `ordered-list` nodeType
  • Slash command `/ordered-list` creates ordered list item
  • Content stored with `"1. "` prefix in database (`cleanContent: false`)
  • View mode strips `"1. "` prefix and displays auto-numbering via CSS
  • CSS counter provides sequential numbering (1, 2, 3...)
  • Counter resets when sequence broken by non-list nodes
  • Enter key creates new ordered list sibling with `"1. "` template
  • Backspace at position 0 converts to text node and strips prefix
  • `canHaveChildren: false` enforced (no nesting)
  • `desiredCursorPosition: 3` positions cursor after "1. "
  • Icon design matches specification in design system documentation
  • Component styling matches specification in design system documentation
  • Unit tests verify pattern detection and rendering
  • Integration tests verify workflow and counter behavior
  • Works alongside existing node types (text, header, quote-block, etc.)
  • Quality checks pass (`bun run quality:fix`)
  • All tests pass (`bun run test`)

Design Rationale

Why store `"1. "` prefix?

Following the quote-block pattern (`"> "`):

  • Round-trip consistency (content → database → content)
  • Backend can validate ordered list structure
  • Converting back to text preserves markdown syntax
  • Edit mode shows actual stored content for transparency

Why `canHaveChildren: false`?

  • Hierarchical ordered lists require complex counter management
    • Multi-level: `1.`, `1.1.`, `1.1.1.` OR
    • Different styles: `1.`, `a.`, `i.`
  • Node parent/child hierarchy already handles indentation visually
  • Keeps initial implementation simple and predictable
  • Can be enhanced in future with proper nested numbering design

Why CSS counters?

  • Automatic sequential numbering (1, 2, 3...)
  • No JavaScript required for numbering
  • Proper reset behavior when sequences break
  • Browser-native, performant
  • Works with print stylesheets

References

Metadata

Metadata

Assignees

Labels

enhancementfoundation

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions