Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

2.0 KB
Raw Blame
import { useEffect, useMemo, useState } from 'react';

import type { FileDiff } from '@/lib/gitReview.types';
import type { DiffRenderRow } from './diffRows';
import {
  collectHighlightLines,
  highlightLine,
  languageFromPath,
  shouldSkipHighlightDiff,
} from './highlight';

interface HighlightState {
  signature: string;
  values: Map<string, string>;
}

const EMPTY_HIGHLIGHTS = new Map<string, string>();

export function useDiffHighlights(diff: FileDiff, rows: readonly DiffRenderRow[]): ReadonlyMap<string, string> {
  const language = useMemo(() => languageFromPath(diff.path), [diff.path]);
  const signature = useMemo(
    () => `${diff.id}:${hashRowsForHighlight(rows)}`,
    [diff.id, rows],
  );
  const [state, setState] = useState<HighlightState>({ signature: '', values: EMPTY_HIGHLIGHTS });

  useEffect(() => {
    if (typeof Worker === 'undefined' || shouldSkipHighlightDiff(rows)) return;

    const lines = collectHighlightLines(rows);
    if (lines.length === 0) return;

    let cancelled = false;
    void (async () => {
      const entries = await Promise.all(lines.map(async (line) => {
        const html = await highlightLine(language, line.content);
        return html ? [line.key, html] as const : null;
      }));
      if (cancelled) return;
      const values = new Map<string, string>();
      for (const entry of entries) {
        if (entry) values.set(entry[0], entry[1]);
      }
      setState({ signature, values });
    })();

    return () => {
      cancelled = true;
    };
  }, [language, rows, signature]);

  return state.signature === signature ? state.values : EMPTY_HIGHLIGHTS;
}

function hashRowsForHighlight(rows: readonly DiffRenderRow[]): string {
  let hash = 5381;
  const lines = collectHighlightLines(rows);
  for (const line of lines) {
    for (let i = 0; i < line.key.length; i += 1) {
      hash = ((hash << 5) + hash) ^ line.key.charCodeAt(i);
    }
    for (let i = 0; i < line.content.length; i += 1) {
      hash = ((hash << 5) + hash) ^ line.content.charCodeAt(i);
    }
  }
  return `${lines.length}:${hash >>> 0}`;
}