Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

6.6 KB
Raw Blame
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router';
import { Plus, Film, Trash2, Clock } from 'lucide-react';
import PageSkeleton from '../components/ui/PageSkeleton';
import ListLoadError from '../components/ui/ListLoadError';
import toast from '../components/ui/Toast';
import useListResource from '../hooks/useListResource';
import * as api from '../services/api';
import { formatDurationSec } from '../utils/formatters';
import { projectSummary, historySourceDuration, CLIP_CATALOG_QUERY } from '../lib/videoTimelineModel';

const loadTimelineProjects = () => api.listTimelineProjects({ silent: true });
const loadVideoHistory = () => api.listVideoHistory({ silent: true, query: CLIP_CATALOG_QUERY });

export default function VideoTimeline() {
  const navigate = useNavigate();
  const projectsResource = useListResource(loadTimelineProjects);
  const {
    items: projects, state: projectsState, error: projectsError, retry: retryProjects, setItems: setProjects,
  } = projectsResource;
  const historyResource = useListResource(loadVideoHistory);
  const {
    items: history, state: historyState, error: historyError, retry: retryHistory,
  } = historyResource;
  const loading = projectsState === 'loading' || historyState === 'loading';
  const [creating, setCreating] = useState(false);
  const [name, setName] = useState('');

  const handleCreate = async (e) => {
    e.preventDefault();
    const trimmed = name.trim();
    if (!trimmed) return;
    setCreating(true);
    const created = await api.createTimelineProject(trimmed, { silent: true }).catch((err) => {
      toast.error(`Failed to create: ${err.message}`);
      return null;
    });
    setCreating(false);
    if (created) {
      setName('');
      navigate(`/media/timeline/${created.id}`);
    }
  };

  const handleDelete = async (project) => {
    setProjects((prev) => prev.filter((p) => p.id !== project.id));
    await api.deleteTimelineProject(project.id, { silent: true }).catch((err) => {
      toast.error(`Failed to delete: ${err.message}`);
      retryProjects();
    });
  };

  const projectStats = useMemo(() => {
    const historyMap = new Map(history.map((h) => [h.id, h]));
    const thumbnailFor = (clipId) => historyMap.get(clipId)?.thumbnail;
    const sourceDurationFor = (clipId) => historySourceDuration(historyMap.get(clipId));
    return new Map(projects.map((p) => [p.id, projectSummary(p, thumbnailFor, sourceDurationFor)]));
  }, [projects, history]);

  return (
    <div className="space-y-4">
      <form onSubmit={handleCreate} className="flex gap-2 items-center">
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="New project name…"
          aria-label="New project name"
          className="flex-1 max-w-sm px-3 py-2 bg-port-card border border-port-border rounded-md text-white text-sm placeholder-gray-500 focus:outline-none focus:border-port-accent"
          disabled={creating}
        />
        <button
          type="submit"
          disabled={!name.trim() || creating}
          className="flex items-center gap-2 px-3 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm rounded-md transition-colors"
        >
          <Plus size={16} /> New project
        </button>
      </form>

      {loading && <PageSkeleton header="none" label="Loading timeline projects" layout="grid" cards={3} gridColsClass="sm:grid-cols-2 lg:grid-cols-3" />}

      {projectsState === 'error' && (
        <ListLoadError what="timeline projects" error={projectsError} onRetry={retryProjects} />
      )}

      {historyState === 'error' && (
        <ListLoadError what="video history" error={historyError} onRetry={retryHistory} />
      )}

      {!loading && projectsState === 'ready' && projects.length === 0 && (
        <div className="text-center py-12 text-gray-500">
          <Film className="w-10 h-10 mx-auto mb-3 opacity-40" />
          <p className="text-sm">No timeline projects yet. Create one above to start compositing clips.</p>
        </div>
      )}

      {!loading && projectsState === 'ready' && projects.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {projects.map((project) => {
            const { totalSec, blockCount, firstThumb } = projectStats.get(project.id) || { totalSec: 0, blockCount: 0, firstThumb: null };
            return (
              <div key={project.id} className="bg-port-card border border-port-border rounded-xl overflow-hidden hover:border-port-accent/50 transition-colors">
                <button
                  type="button"
                  onClick={() => navigate(`/media/timeline/${project.id}`)}
                  className="block w-full aspect-video bg-port-bg relative"
                >
                  {firstThumb ? (
                    <img src={firstThumb} alt={project.name} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-gray-600">
                      <Film className="w-10 h-10" />
                    </div>
                  )}
                </button>
                <div className="p-3 space-y-1.5">
                  <div className="flex items-start justify-between gap-2">
                    <button
                      type="button"
                      onClick={() => navigate(`/media/timeline/${project.id}`)}
                      className="flex-1 text-left text-sm font-medium text-white hover:text-port-accent transition-colors truncate"
                    >
                      {project.name}
                    </button>
                    <button
                      type="button"
                      onClick={() => handleDelete(project)}
                      className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-port-error transition-colors"
                      title="Delete project" aria-label="Delete project"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                  <div className="flex items-center gap-3 text-xs text-gray-400">
                    <span className="flex items-center gap-1"><Film className="w-3 h-3" />{blockCount} blocks</span>
                    <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{formatDurationSec(totalSec)}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}