Manual
Almnck.
Price: 50ⓐ

Interactive Figures Framework Implementation Plan

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Build an interactive figures framework for Almanack, starting with three interconnected moon visualizations for “Regolith with Latitude.”

Architecture: Self-contained figure modules in assets/figures/ communicate via capability-based pub/sub. A minimal runtime handles figure discovery and wiring. The moon-renderer component provides WebGL visualization with static fallback.

Tech Stack: Vanilla ES modules, WebGL, Canvas 2D, Pointer Events API, ResizeObserver, IntersectionObserver (for lazy loading).

Reference: See doc/plans/2026-01-11-interactive-figures-design.md for full design rationale.


Phase 1: Project Structure

Task 1.1: Create figures directory structure

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/ - Create: editorial/articles/regolith-with-latitude/assets/figures/data/ - Create: editorial/articles/regolith-with-latitude/assets/figures/textures/ - Create: editorial/articles/regolith-with-latitude/assets/figures/fallback/ - Create: editorial/articles/regolith-with-latitude/assets/figures/fallback/frames/

Step 1: Create directory structure

mkdir -p editorial/articles/regolith-with-latitude/assets/figures/{data,textures,fallback/frames}

Step 2: Verify structure

tree editorial/articles/regolith-with-latitude/assets/figures/

Expected:

figures/
├── data/
├── fallback/
│   └── frames/
└── textures/

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/.gitkeep 2>/dev/null || true
git commit --allow-empty -m "chore: create figures directory structure for regolith-with-latitude"

Task 1.2: Create figures Makefile

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/Makefile

Step 1: Write the Makefile

# Makefile for regolith-with-latitude interactive figures

.PHONY: sync clean test test-local test-browser help

help:
    @echo "Available targets:"
    @echo "  sync         - Fetch NASA moon data and fallback frames"
    @echo "  clean        - Remove generated data files"
    @echo "  test         - Run all tests"
    @echo "  test-local   - Run fast local tests (Node/Deno)"
    @echo "  test-browser - Run headless browser tests"

sync:
    ./sync.sh

clean:
    rm -rf data/*.json fallback/frames/*.jpg

test: test-local test-browser

test-local:
    @echo "Running local tests..."
    node --test tests/*.test.js 2>/dev/null || deno test tests/*.test.js 2>/dev/null || echo "No local tests yet"

test-browser:
    @echo "Browser tests not yet implemented"

Step 2: Verify Makefile syntax

make -C editorial/articles/regolith-with-latitude/assets/figures/ help

Expected output includes “Available targets:” and the list.

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/Makefile
git commit -m "chore: add figures Makefile with sync, clean, test targets"

Task 1.3: Create manifest.json

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/manifest.json

Step 1: Write the manifest

{
  "version": "1.0.0",
  "description": "Interactive figures for Regolith with Latitude",
  "figures": {
    "three-moons": {
      "module": "./three-moons.js",
      "publishes": [],
      "subscribes": []
    },
    "latitude-picker": {
      "module": "./latitude-picker.js",
      "publishes": ["latitude"],
      "subscribes": []
    },
    "moon-timeline": {
      "module": "./moon-timeline.js",
      "publishes": ["date"],
      "subscribes": ["latitude"]
    }
  },
  "topics": {
    "latitude": {
      "description": "Viewer's Earth latitude in degrees (-90 to 90)",
      "initialValue": 0
    },
    "date": {
      "description": "Selected date as ISO string",
      "initialValue": null
    }
  }
}

Step 2: Validate JSON syntax

python3 -c "import json; json.load(open('editorial/articles/regolith-with-latitude/assets/figures/manifest.json'))" && echo "Valid JSON"

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/manifest.json
git commit -m "chore: add figures manifest with topic wiring"

Task 1.4: Create README.md

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/README.md

Step 1: Write the README

# Regolith with Latitude - Interactive Figures

Interactive visualizations showing how the Moon's appearance changes with observer latitude.

## Figures

| Name | Description | Publishes | Subscribes |
|------|-------------|-----------|------------|
| `three-moons` | Static comparison of three moon sizes | - | - |
| `latitude-picker` | Earth map with draggable latitude selector | `latitude` | - |
| `moon-timeline` | Animated moon with date scrubber | `date` | `latitude` |

## Quick Start

```bash
# Fetch NASA data (required before first use)
make sync

# Run tests
make test

Development

Each figure is a self-contained ES module exporting: - meta - Name, description, version - setup(container, capabilities) - Initialization function

See runtime.js for the pub/sub and loader implementation.

Data Sources

  • Moon ephemeris: NASA SVS 5587
  • Fallback frames: NASA SVS pre-rendered moon images

**Step 2: Commit**

```bash
git add editorial/articles/regolith-with-latitude/assets/figures/README.md
git commit -m "docs: add figures README"

Phase 2: Runtime Implementation

Task 2.1: Write pub/sub test

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/tests/pubsub.test.js

Step 1: Create tests directory and write test

mkdir -p editorial/articles/regolith-with-latitude/assets/figures/tests
// tests/pubsub.test.js
import { test } from 'node:test';
import assert from 'node:assert';
import { createPubSub } from '../runtime.js';

test('pubsub: subscribe receives published values', () => {
  const topic = createPubSub();
  const received = [];

  topic.subscribe((value) => received.push(value));
  topic.publish(42);
  topic.publish('hello');

  assert.deepStrictEqual(received, [42, 'hello']);
});

test('pubsub: sticky last value delivered to new subscribers', () => {
  const topic = createPubSub();
  topic.publish(100);

  const received = [];
  topic.subscribe((value) => received.push(value));

  assert.deepStrictEqual(received, [100]);
});

test('pubsub: unsubscribe stops delivery', () => {
  const topic = createPubSub();
  const received = [];

  const handler = (value) => received.push(value);
  topic.subscribe(handler);
  topic.publish(1);
  topic.unsubscribe(handler);
  topic.publish(2);

  assert.deepStrictEqual(received, [1]);
});

test('pubsub: subscribers() returns current handlers', () => {
  const topic = createPubSub();
  const handler1 = () => {};
  const handler2 = () => {};

  topic.subscribe(handler1);
  topic.subscribe(handler2);

  assert.strictEqual(topic.subscribers().length, 2);
});

test('pubsub: no sticky value if never published', () => {
  const topic = createPubSub();
  const received = [];

  topic.subscribe((value) => received.push(value));

  assert.deepStrictEqual(received, []);
});

Step 2: Run test to verify it fails

cd editorial/articles/regolith-with-latitude/assets/figures && node --test tests/pubsub.test.js

Expected: FAIL with error about missing runtime.js or createPubSub

Step 3: Commit failing test

git add editorial/articles/regolith-with-latitude/assets/figures/tests/
git commit -m "test: add pub/sub tests (failing)"

Task 2.2: Implement pub/sub

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/runtime.js

Step 1: Write minimal pub/sub implementation

// runtime.js - Almanack Interactive Figures Runtime

/**
 * Create a pub/sub topic with sticky last value.
 * Interface mirrors Spritely Goblins ^pubsub for future OCapN compatibility.
 */
export function createPubSub() {
  const handlers = new Set();
  let lastValue = undefined;
  let hasPublished = false;

  return {
    subscribe(handler) {
      handlers.add(handler);
      // Deliver sticky last value to new subscriber
      if (hasPublished) {
        handler(lastValue);
      }
    },

    unsubscribe(handler) {
      handlers.delete(handler);
    },

    publish(value) {
      lastValue = value;
      hasPublished = true;
      for (const handler of handlers) {
        handler(value);
      }
    },

    subscribers() {
      return Array.from(handlers);
    },
  };
}

Step 2: Run tests to verify they pass

cd editorial/articles/regolith-with-latitude/assets/figures && node --test tests/pubsub.test.js

Expected: All 5 tests PASS

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/runtime.js
git commit -m "feat: implement pub/sub with sticky last value"

Task 2.3: Write figure loader test

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/tests/loader.test.js

Step 1: Write test (browser-oriented, will mock DOM)

// tests/loader.test.js
import { test, mock } from 'node:test';
import assert from 'node:assert';
import { parseCapabilities, wireCapabilities } from '../runtime.js';

test('parseCapabilities: extracts publish and subscribe lists', () => {
  const result = parseCapabilities({
    publishes: 'latitude',
    subscribes: 'date,time',
  });

  assert.deepStrictEqual(result.publishes, ['latitude']);
  assert.deepStrictEqual(result.subscribes, ['date', 'time']);
});

test('parseCapabilities: handles empty attributes', () => {
  const result = parseCapabilities({
    publishes: '',
    subscribes: '',
  });

  assert.deepStrictEqual(result.publishes, []);
  assert.deepStrictEqual(result.subscribes, []);
});

test('parseCapabilities: handles missing attributes', () => {
  const result = parseCapabilities({});

  assert.deepStrictEqual(result.publishes, []);
  assert.deepStrictEqual(result.subscribes, []);
});

test('wireCapabilities: creates publish functions for declared topics', () => {
  const topics = {
    latitude: { publish: mock.fn(), subscribe: mock.fn() },
  };

  const caps = wireCapabilities(['latitude'], [], topics);

  assert.ok(typeof caps.publish.latitude === 'function');
  caps.publish.latitude(45);
  assert.strictEqual(topics.latitude.publish.mock.calls.length, 1);
});

test('wireCapabilities: creates subscribe functions for declared topics', () => {
  const topics = {
    date: { publish: mock.fn(), subscribe: mock.fn() },
  };

  const caps = wireCapabilities([], ['date'], topics);
  const handler = () => {};

  assert.ok(typeof caps.subscribe.date === 'function');
  caps.subscribe.date(handler);
  assert.strictEqual(topics.date.subscribe.mock.calls.length, 1);
});

Step 2: Run test to verify it fails

cd editorial/articles/regolith-with-latitude/assets/figures && node --test tests/loader.test.js

Expected: FAIL with error about missing parseCapabilities or wireCapabilities

Step 3: Commit failing test

git add editorial/articles/regolith-with-latitude/assets/figures/tests/loader.test.js
git commit -m "test: add figure loader tests (failing)"

Task 2.4: Implement capability parsing and wiring

Files: - Modify: editorial/articles/regolith-with-latitude/assets/figures/runtime.js

Step 1: Add parsing and wiring functions

Add to runtime.js after the createPubSub function:

/**
 * Parse capability declarations from data attributes.
 * @param {Object} attrs - Object with publishes and subscribes strings
 * @returns {Object} - { publishes: string[], subscribes: string[] }
 */
export function parseCapabilities(attrs) {
  const parse = (str) =>
    str ? str.split(',').map((s) => s.trim()).filter(Boolean) : [];

  return {
    publishes: parse(attrs.publishes || ''),
    subscribes: parse(attrs.subscribes || ''),
  };
}

/**
 * Create capability objects for a figure based on its declarations.
 * @param {string[]} publishes - Topic names this figure can publish to
 * @param {string[]} subscribes - Topic names this figure can subscribe to
 * @param {Object} topics - Map of topic name to pubsub instance
 * @returns {Object} - { publish: { [name]: fn }, subscribe: { [name]: fn } }
 */
export function wireCapabilities(publishes, subscribes, topics) {
  const publish = {};
  const subscribe = {};

  for (const name of publishes) {
    if (topics[name]) {
      publish[name] = (value) => topics[name].publish(value);
    }
  }

  for (const name of subscribes) {
    if (topics[name]) {
      subscribe[name] = (handler) => topics[name].subscribe(handler);
    }
  }

  return { publish, subscribe };
}

Step 2: Run tests to verify they pass

cd editorial/articles/regolith-with-latitude/assets/figures && node --test tests/loader.test.js

Expected: All 5 tests PASS

Step 3: Run all tests

cd editorial/articles/regolith-with-latitude/assets/figures && node --test tests/*.test.js

Expected: All 10 tests PASS

Step 4: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/runtime.js
git commit -m "feat: add capability parsing and wiring"

Task 2.5: Implement initFigures (browser-only)

Files: - Modify: editorial/articles/regolith-with-latitude/assets/figures/runtime.js

Step 1: Add initFigures function

Add to the end of runtime.js:

/**
 * Resolve asset paths relative to the figures directory.
 * @param {string} base - Base URL of the figures directory
 * @returns {Object} - Asset path helpers
 */
function createAssetResolver(base) {
  return {
    data: (path) => `${base}/data/${path}`,
    textures: (path) => `${base}/textures/${path}`,
    fallback: (path) => `${base}/fallback/${path}`,
  };
}

/**
 * Initialize all interactive figures on the page.
 * Finds [data-interactive] elements, loads their modules, wires capabilities.
 */
export async function initFigures() {
  // Determine base path from this script's location
  const scriptUrl = import.meta.url;
  const base = scriptUrl.substring(0, scriptUrl.lastIndexOf('/'));

  // Load manifest
  const manifestUrl = `${base}/manifest.json`;
  const manifest = await fetch(manifestUrl).then((r) => r.json());

  // Create topics from manifest
  const topics = {};
  for (const [name, config] of Object.entries(manifest.topics || {})) {
    topics[name] = createPubSub();
    // Set initial value if specified
    if (config.initialValue !== undefined && config.initialValue !== null) {
      topics[name].publish(config.initialValue);
    }
  }

  // Find all interactive figures
  const figures = document.querySelectorAll('[data-interactive]');
  const assets = createAssetResolver(base);

  // Initialize each figure
  for (const container of figures) {
    const name = container.dataset.interactive;
    const figureConfig = manifest.figures[name];

    if (!figureConfig) {
      console.warn(`Unknown figure: ${name}`);
      continue;
    }

    // Check for lazy loading
    if (container.dataset.lazy !== undefined) {
      setupLazyFigure(container, figureConfig, manifest, topics, assets, base);
    } else {
      await initializeFigure(container, figureConfig, manifest, topics, assets, base);
    }
  }
}

/**
 * Set up IntersectionObserver for lazy-loaded figure.
 */
function setupLazyFigure(container, figureConfig, manifest, topics, assets, base) {
  const observer = new IntersectionObserver(
    (entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          observer.unobserve(container);
          initializeFigure(container, figureConfig, manifest, topics, assets, base);
        }
      }
    },
    { rootMargin: '100px' }
  );
  observer.observe(container);
}

/**
 * Initialize a single figure.
 */
async function initializeFigure(container, figureConfig, manifest, topics, assets, base) {
  // Parse capability overrides from HTML, fallback to manifest
  const attrs = {
    publishes: container.dataset.publishes ?? figureConfig.publishes.join(','),
    subscribes: container.dataset.subscribes ?? figureConfig.subscribes.join(','),
  };
  const { publishes, subscribes } = parseCapabilities(attrs);

  // Ensure topics exist for all declared capabilities
  for (const name of [...publishes, ...subscribes]) {
    if (!topics[name]) {
      topics[name] = createPubSub();
    }
  }

  // Wire capabilities
  const capabilities = wireCapabilities(publishes, subscribes, topics);

  // Import and initialize the figure module
  const moduleUrl = new URL(figureConfig.module, `${base}/`).href;
  try {
    const module = await import(moduleUrl);
    if (typeof module.setup === 'function') {
      const cleanup = await module.setup(container, { ...capabilities, assets });
      // Store cleanup function for potential teardown
      container._figureCleanup = cleanup;
    }
  } catch (err) {
    console.error(`Failed to initialize figure "${figureConfig.module}":`, err);
  }
}

Step 2: Verify syntax (can’t fully test without browser)

node -c editorial/articles/regolith-with-latitude/assets/figures/runtime.js && echo "Syntax OK"

Expected: “Syntax OK”

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/runtime.js
git commit -m "feat: implement initFigures with lazy loading support"

Phase 3: Moon Renderer Component

Task 3.1: Create moon-renderer stub

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/moon-renderer.js

Step 1: Write stub returning capability object

// moon-renderer.js - Shared moon display component
// Returns a capability object for controlling the moon visualization.

/**
 * Create a moon renderer in the given container.
 * Handles progressive enhancement: static fallback → WebGL.
 *
 * @param {HTMLElement} container - DOM element to render into
 * @param {Object} options
 * @param {Object} options.assets - Asset path resolver
 * @returns {Object} Moon capability object
 */
export function createMoon(container, { assets }) {
  // Internal state
  let currentParams = {
    size: 100,
    brightness: 1,
    latitude: 0,
    date: new Date().toISOString().split('T')[0],
  };

  let canvas = null;
  let ctx = null;

  // Create canvas
  function ensureCanvas() {
    if (!canvas) {
      canvas = document.createElement('canvas');
      canvas.setAttribute('role', 'img');
      canvas.setAttribute('aria-label', 'Moon visualization');
      container.appendChild(canvas);
      ctx = canvas.getContext('2d');
    }
    return canvas;
  }

  // Render placeholder (will be replaced with actual implementation)
  function renderPlaceholder() {
    ensureCanvas();
    const size = currentParams.size;
    canvas.width = size;
    canvas.height = size;

    // Draw placeholder circle
    ctx.fillStyle = '#1a1a2e';
    ctx.fillRect(0, 0, size, size);

    ctx.beginPath();
    ctx.arc(size / 2, size / 2, size / 2 - 4, 0, Math.PI * 2);
    ctx.fillStyle = '#c9c9c9';
    ctx.fill();

    // Show current state as text (for debugging)
    ctx.fillStyle = '#333';
    ctx.font = `${Math.max(10, size / 10)}px sans-serif`;
    ctx.textAlign = 'center';
    ctx.fillText(`${currentParams.latitude}°`, size / 2, size / 2);
  }

  // Initial render
  renderPlaceholder();

  // Return capability object
  return {
    /**
     * Update moon appearance.
     * @param {Object} params
     * @param {number} params.size - Pixel diameter
     * @param {number} params.brightness - 0-1 intensity
     * @param {number} params.latitude - Viewer latitude (-90 to 90)
     * @param {string} params.date - ISO date string
     */
    render(params) {
      currentParams = { ...currentParams, ...params };
      renderPlaceholder();
    },

    /**
     * Get current parameters.
     */
    getState() {
      return { ...currentParams };
    },

    /**
     * Clean up resources.
     */
    destroy() {
      if (canvas && canvas.parentNode) {
        canvas.parentNode.removeChild(canvas);
      }
      canvas = null;
      ctx = null;
    },
  };
}

Step 2: Verify syntax

node -c editorial/articles/regolith-with-latitude/assets/figures/moon-renderer.js && echo "Syntax OK"

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/moon-renderer.js
git commit -m "feat: add moon-renderer stub with placeholder rendering"

Task 3.2: Write moon-renderer test

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/tests/moon-renderer.test.js

Step 1: Write test (mocking DOM)

// tests/moon-renderer.test.js
import { test } from 'node:test';
import assert from 'node:assert';

// Minimal DOM mock for Node testing
globalThis.document = {
  createElement: (tag) => ({
    tagName: tag.toUpperCase(),
    style: {},
    width: 0,
    height: 0,
    setAttribute: function(k, v) { this[k] = v; },
    getAttribute: function(k) { return this[k]; },
    appendChild: function() {},
    getContext: () => ({
      fillStyle: '',
      font: '',
      textAlign: '',
      fillRect: () => {},
      beginPath: () => {},
      arc: () => {},
      fill: () => {},
      fillText: () => {},
    }),
  }),
};

// Import after DOM mock is set up
const { createMoon } = await import('../moon-renderer.js');

test('createMoon: returns capability object with required methods', () => {
  const container = { appendChild: () => {} };
  const moon = createMoon(container, { assets: {} });

  assert.ok(typeof moon.render === 'function');
  assert.ok(typeof moon.getState === 'function');
  assert.ok(typeof moon.destroy === 'function');
});

test('createMoon: getState returns current parameters', () => {
  const container = { appendChild: () => {} };
  const moon = createMoon(container, { assets: {} });

  const state = moon.getState();
  assert.ok('size' in state);
  assert.ok('brightness' in state);
  assert.ok('latitude' in state);
  assert.ok('date' in state);
});

test('createMoon: render updates state', () => {
  const container = { appendChild: () => {} };
  const moon = createMoon(container, { assets: {} });

  moon.render({ latitude: 45, size: 200 });
  const state = moon.getState();

  assert.strictEqual(state.latitude, 45);
  assert.strictEqual(state.size, 200);
});

test('createMoon: render preserves unspecified params', () => {
  const container = { appendChild: () => {} };
  const moon = createMoon(container, { assets: {} });

  moon.render({ size: 150 });
  moon.render({ latitude: 30 });
  const state = moon.getState();

  assert.strictEqual(state.size, 150);
  assert.strictEqual(state.latitude, 30);
});

Step 2: Run tests

cd editorial/articles/regolith-with-latitude/assets/figures && node --test tests/moon-renderer.test.js

Expected: All 4 tests PASS

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/tests/moon-renderer.test.js
git commit -m "test: add moon-renderer capability tests"

Phase 4: Figure Implementations (Stubs)

Task 4.1: Implement three-moons.js stub

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/three-moons.js

Step 1: Write stub figure

// three-moons.js - Static comparison of three moons at different sizes

import { createMoon } from './moon-renderer.js';

export const meta = {
  name: 'three-moons',
  description: 'Static comparison of three moons at different apparent sizes',
  version: '1.0.0',
};

export function setup(container, { assets }) {
  // Respect reduced motion preference
  const prefersReducedMotion = window.matchMedia(
    '(prefers-reduced-motion: reduce)'
  ).matches;

  // Find or create moon containers
  const moonContainers = [
    container.querySelector('.moon-1') || createMoonContainer(container, 'moon-1'),
    container.querySelector('.moon-2') || createMoonContainer(container, 'moon-2'),
    container.querySelector('.moon-3') || createMoonContainer(container, 'moon-3'),
  ];

  // Create moon renderers
  const moons = moonContainers.map((el) => createMoon(el, { assets }));

  // Render at different sizes (simulating distance/apparent size)
  moons[0].render({ size: 80, brightness: 1.0, latitude: 0, date: '2026-03-20' });
  moons[1].render({ size: 120, brightness: 0.9, latitude: 0, date: '2026-03-20' });
  moons[2].render({ size: 160, brightness: 0.8, latitude: 0, date: '2026-03-20' });

  // Cleanup
  return () => {
    moons.forEach((m) => m.destroy());
  };
}

function createMoonContainer(parent, className) {
  const div = document.createElement('div');
  div.className = className;
  parent.appendChild(div);
  return div;
}

Step 2: Verify syntax

node -c editorial/articles/regolith-with-latitude/assets/figures/three-moons.js && echo "Syntax OK"

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/three-moons.js
git commit -m "feat: add three-moons figure stub"

Task 4.2: Implement latitude-picker.js stub

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/latitude-picker.js

Step 1: Write stub with pointer events and accessibility

// latitude-picker.js - Earth map with draggable latitude selector

import { createMoon } from './moon-renderer.js';

export const meta = {
  name: 'latitude-picker',
  description: 'Mercator Earth projection with draggable latitude line',
  version: '1.0.0',
};

export function setup(container, { publish, subscribe, assets }) {
  // State
  let latitude = 0;

  // Find or create elements
  const mapContainer =
    container.querySelector('.earth-map') || createDiv(container, 'earth-map');
  const moonContainer =
    container.querySelector('.moon-preview') || createDiv(container, 'moon-preview');
  const valueDisplay =
    container.querySelector('.latitude-value') || createValueDisplay(container);

  // Create moon preview
  const moon = createMoon(moonContainer, { assets });

  // Create canvas for Earth map
  const canvas = document.createElement('canvas');
  canvas.setAttribute('role', 'slider');
  canvas.setAttribute('aria-label', 'Latitude selector');
  canvas.setAttribute('aria-valuemin', '-90');
  canvas.setAttribute('aria-valuemax', '90');
  canvas.setAttribute('aria-valuenow', '0');
  canvas.setAttribute('tabindex', '0');
  mapContainer.appendChild(canvas);

  // Responsive sizing
  const ro = new ResizeObserver(() => resize());
  ro.observe(mapContainer);

  function resize() {
    const rect = mapContainer.getBoundingClientRect();
    canvas.width = rect.width || 300;
    canvas.height = rect.height || 150;
    render();
  }

  function render() {
    const ctx = canvas.getContext('2d');
    const { width, height } = canvas;

    // Draw placeholder Earth (blue rectangle for now)
    ctx.fillStyle = '#1a5276';
    ctx.fillRect(0, 0, width, height);

    // Draw latitude line
    const y = ((90 - latitude) / 180) * height;
    ctx.strokeStyle = '#e74c3c';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(0, y);
    ctx.lineTo(width, y);
    ctx.stroke();

    // Update ARIA
    canvas.setAttribute('aria-valuenow', String(latitude));

    // Update display
    valueDisplay.textContent = `${latitude.toFixed(1)}°${latitude >= 0 ? 'N' : 'S'}`;

    // Update moon
    moon.render({ latitude });
  }

  function setLatitude(newLat) {
    latitude = Math.max(-90, Math.min(90, newLat));
    render();
    if (publish.latitude) {
      publish.latitude(latitude);
    }
  }

  // Pointer events for drag
  let dragging = false;

  function handlePointerDown(e) {
    dragging = true;
    canvas.setPointerCapture(e.pointerId);
    updateFromPointer(e);
  }

  function handlePointerMove(e) {
    if (dragging) {
      updateFromPointer(e);
    }
  }

  function handlePointerUp(e) {
    dragging = false;
    canvas.releasePointerCapture(e.pointerId);
  }

  function updateFromPointer(e) {
    const rect = canvas.getBoundingClientRect();
    const y = e.clientY - rect.top;
    const lat = 90 - (y / rect.height) * 180;
    setLatitude(lat);
  }

  canvas.addEventListener('pointerdown', handlePointerDown);
  canvas.addEventListener('pointermove', handlePointerMove);
  canvas.addEventListener('pointerup', handlePointerUp);
  canvas.addEventListener('pointercancel', handlePointerUp);

  // Keyboard controls
  canvas.addEventListener('keydown', (e) => {
    switch (e.key) {
      case 'ArrowUp':
        setLatitude(latitude + 5);
        e.preventDefault();
        break;
      case 'ArrowDown':
        setLatitude(latitude - 5);
        e.preventDefault();
        break;
      case 'Home':
        setLatitude(90);
        e.preventDefault();
        break;
      case 'End':
        setLatitude(-90);
        e.preventDefault();
        break;
    }
  });

  // Initial render
  resize();

  // Cleanup
  return () => {
    ro.disconnect();
    moon.destroy();
    canvas.removeEventListener('pointerdown', handlePointerDown);
    canvas.removeEventListener('pointermove', handlePointerMove);
    canvas.removeEventListener('pointerup', handlePointerUp);
    canvas.removeEventListener('pointercancel', handlePointerUp);
  };
}

function createDiv(parent, className) {
  const div = document.createElement('div');
  div.className = className;
  parent.appendChild(div);
  return div;
}

function createValueDisplay(parent) {
  const span = document.createElement('span');
  span.className = 'latitude-value';
  span.setAttribute('aria-live', 'polite');
  parent.appendChild(span);
  return span;
}

Step 2: Verify syntax

node -c editorial/articles/regolith-with-latitude/assets/figures/latitude-picker.js && echo "Syntax OK"

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/latitude-picker.js
git commit -m "feat: add latitude-picker figure with pointer/keyboard controls"

Task 4.3: Implement moon-timeline.js stub

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/moon-timeline.js

Step 1: Write stub with date slider

// moon-timeline.js - Animated moon with date scrubber

import { createMoon } from './moon-renderer.js';

export const meta = {
  name: 'moon-timeline',
  description: 'Moon phase and libration viewer with timeline slider',
  version: '1.0.0',
};

export function setup(container, { publish, subscribe, assets }) {
  // State
  let latitude = 0;
  let dayOfYear = 1;
  const year = 2026;

  // Find or create elements
  const moonContainer =
    container.querySelector('.moon-display') || createDiv(container, 'moon-display');
  const slider =
    container.querySelector('.timeline') || createSlider(container);
  const dateDisplay =
    container.querySelector('.date-display') || createDateDisplay(container);

  // Create moon renderer
  const moon = createMoon(moonContainer, { assets });

  // Responsive sizing
  const ro = new ResizeObserver(() => {
    const rect = moonContainer.getBoundingClientRect();
    const size = Math.min(rect.width, rect.height) || 200;
    moon.render({ size, latitude, date: dayToDate(dayOfYear) });
  });
  ro.observe(moonContainer);

  function dayToDate(day) {
    const date = new Date(year, 0, day);
    return date.toISOString().split('T')[0];
  }

  function formatDate(day) {
    const date = new Date(year, 0, day);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  }

  function render() {
    const dateStr = dayToDate(dayOfYear);
    moon.render({ latitude, date: dateStr });
    dateDisplay.textContent = formatDate(dayOfYear);
    slider.value = dayOfYear;

    if (publish.date) {
      publish.date(dateStr);
    }
  }

  // Subscribe to latitude changes
  if (subscribe.latitude) {
    subscribe.latitude((lat) => {
      latitude = lat;
      render();
    });
  }

  // Slider events
  slider.addEventListener('input', (e) => {
    dayOfYear = parseInt(e.target.value, 10);
    render();
  });

  // Keyboard on slider (already handled by range input)

  // Respect reduced motion - disable auto-play animations
  const prefersReducedMotion = window.matchMedia(
    '(prefers-reduced-motion: reduce)'
  ).matches;

  // Initial render
  render();

  // Cleanup
  return () => {
    ro.disconnect();
    moon.destroy();
  };
}

function createDiv(parent, className) {
  const div = document.createElement('div');
  div.className = className;
  parent.appendChild(div);
  return div;
}

function createSlider(parent) {
  const input = document.createElement('input');
  input.type = 'range';
  input.className = 'timeline';
  input.min = '1';
  input.max = '365';
  input.value = '1';
  input.setAttribute('aria-label', 'Day of year');
  parent.appendChild(input);
  return input;
}

function createDateDisplay(parent) {
  const span = document.createElement('span');
  span.className = 'date-display';
  span.setAttribute('aria-live', 'polite');
  parent.appendChild(span);
  return span;
}

Step 2: Verify syntax

node -c editorial/articles/regolith-with-latitude/assets/figures/moon-timeline.js && echo "Syntax OK"

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/moon-timeline.js
git commit -m "feat: add moon-timeline figure with date slider"

Phase 5: Data Pipeline

Task 5.1: Create sync.sh script

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/sync.sh

Step 1: Write sync script

#!/bin/bash
# sync.sh - Fetch NASA moon data for figures
# Run from the figures/ directory

set -euo pipefail
cd "$(dirname "$0")"

YEAR="${1:-2026}"
DATA_DIR="data"
FALLBACK_DIR="fallback/frames"

echo "Syncing moon data for year $YEAR..."

# Create directories if needed
mkdir -p "$DATA_DIR" "$FALLBACK_DIR"

# For now, create placeholder data
# TODO: Replace with actual NASA SVS fetch once we determine the exact data format
cat > "$DATA_DIR/moon-$YEAR.json" << 'PLACEHOLDER'
{
  "year": 2026,
  "epoch": "2026-01-01",
  "source": "placeholder - replace with NASA SVS 5587 data",
  "days": []
}
PLACEHOLDER

echo "Created placeholder $DATA_DIR/moon-$YEAR.json"
echo ""
echo "TODO: Implement NASA SVS data fetching from https://svs.gsfc.nasa.gov/5587/"
echo "      - Ephemeris data: phase, libration, position angle"
echo "      - Fallback frames: subset of pre-rendered images"
echo ""
echo "Sync complete (placeholder data only)"

Step 2: Make executable and test

chmod +x editorial/articles/regolith-with-latitude/assets/figures/sync.sh
cd editorial/articles/regolith-with-latitude/assets/figures && ./sync.sh

Expected: Creates placeholder JSON file, prints TODO message

Step 3: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/sync.sh
git add editorial/articles/regolith-with-latitude/assets/figures/data/
git commit -m "feat: add sync.sh with placeholder data generation"

Phase 6: Article Integration

Task 6.1: Create test HTML page

Files: - Create: editorial/articles/regolith-with-latitude/assets/figures/test.html

Step 1: Write test page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Figures Test - Regolith with Latitude</title>
  <style>
    * { box-sizing: border-box; }
    body {
      font-family: system-ui, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 2rem;
      background: #f5f5f5;
    }
    figure {
      background: white;
      border: 1px solid #ddd;
      padding: 1rem;
      margin: 2rem 0;
    }
    figcaption {
      font-style: italic;
      color: #666;
      margin-top: 0.5rem;
    }
    .earth-map {
      width: 100%;
      height: 200px;
      background: #eee;
    }
    .moon-preview, .moon-display {
      width: 200px;
      height: 200px;
      margin: 1rem auto;
    }
    .moon-1, .moon-2, .moon-3 {
      display: inline-block;
      margin: 0.5rem;
    }
    .latitude-value, .date-display {
      display: block;
      text-align: center;
      font-size: 1.2rem;
      margin: 0.5rem 0;
    }
    .timeline {
      width: 100%;
    }
  </style>
</head>
<body>
  <h1>Interactive Figures Test</h1>

  <figure data-interactive="three-moons">
    <div style="text-align: center;">
      <div class="moon-1"></div>
      <div class="moon-2"></div>
      <div class="moon-3"></div>
    </div>
    <figcaption>Three moons at different apparent sizes</figcaption>
  </figure>

  <figure data-interactive="latitude-picker">
    <div class="earth-map"></div>
    <div class="moon-preview"></div>
    <figcaption>Drag the line to change your viewing latitude</figcaption>
  </figure>

  <figure data-interactive="moon-timeline" data-lazy>
    <div class="moon-display"></div>
    <input type="range" class="timeline" min="1" max="365" value="1">
    <figcaption>The Moon through 2026, as seen from your latitude</figcaption>
  </figure>

  <script type="module">
    import { initFigures } from './runtime.js';

    initFigures().then(() => {
      console.log('Figures initialized');
    }).catch((err) => {
      console.error('Figure initialization failed:', err);
    });
  </script>
</body>
</html>

Step 2: Commit

git add editorial/articles/regolith-with-latitude/assets/figures/test.html
git commit -m "feat: add test.html for local figure development"

Task 6.2: Test in browser

Step 1: Start a local server

cd editorial/articles/regolith-with-latitude/assets/figures && python3 -m http.server 8000

Step 2: Open in browser

Navigate to: http://localhost:8000/test.html

Step 3: Verify

  • [ ] Three-moons figure shows three gray circles
  • [ ] Latitude-picker shows blue rectangle with red line, draggable
  • [ ] Moon-timeline appears when scrolled into view (lazy loading)
  • [ ] Dragging latitude updates moon-timeline’s moon
  • [ ] No JavaScript errors in console

Step 4: Stop server, commit any fixes


Phase 7: Documentation

Task 7.1: Create central figures catalog

Files: - Create: doc/figures.md

Step 1: Write catalog

# Almanack Interactive Figures Catalog

Central listing of all interactive figures across Almanack articles.

## Articles with Figures

| Article | Figures | Status |
|---------|---------|--------|
| [Regolith with Latitude](../editorial/articles/regolith-with-latitude/) | three-moons, latitude-picker, moon-timeline | In Development |

## Shared Components

| Component | Location | Description |
|-----------|----------|-------------|
| runtime.js | Per-article | Pub/sub + figure loader (~150 lines) |
| moon-renderer.js | regolith-with-latitude | WebGL moon with fallback |

## Creating New Figures

See any article's `assets/figures/README.md` for local documentation.

General pattern:
1. Create `assets/figures/` directory in your article
2. Copy `runtime.js` from an existing article (or symlink)
3. Create `manifest.json` defining your figures
4. Write figure modules exporting `meta` and `setup()`
5. Add `<figure data-interactive="name">` elements to article
6. Add `<script type="module">` to initialize

## Design Documentation

- [Interactive Figures Design](/manual/process/plans/plans/2026-01-11-interactive-figures-design/)
- [Implementation Plan](/manual/process/plans/plans/2026-01-11-interactive-figures-implementation/)

Step 2: Commit

git add doc/figures.md
git commit -m "docs: add central figures catalog"

Summary

Phases completed: 1. Project structure (directories, Makefile, manifest, README) 2. Runtime (pub/sub, capability wiring, figure loader) 3. Moon renderer (stub with placeholder) 4. Figure stubs (three-moons, latitude-picker, moon-timeline) 5. Data pipeline (sync.sh placeholder) 6. Article integration (test.html) 7. Documentation (figures catalog)

Remaining work (future tasks): - Implement actual NASA data fetching in sync.sh - Add WebGL rendering to moon-renderer - Add static fallback frame loading to moon-renderer - Add Earth map image to latitude-picker - Style figures for Almanack theme - Browser testing with Playwright - Integration into actual article markdown