File size: 10,244 Bytes
55847d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import { useState, useMemo } from 'react'
import { ArrowLeftRight, Check, X } from 'lucide-react'
import { useTranslation } from 'react-i18next'

interface DiffViewerProps {
  /** 原始文本 */
  original: string
  /** 修改后文本 */
  modified: string
  /** 原始文本标签 */
  originalLabel?: string
  /** 修改后文本标签 */
  modifiedLabel?: string
  /** 接受修改回调 */
  onAccept?: (text: string) => void
  /** 拒绝修改回调 */
  onReject?: () => void
}

interface DiffLine {
  type: 'same' | 'add' | 'remove'
  content: string
  lineOld?: number
  lineNew?: number
}

/**
 * 文本对比查看器 — 并排显示原文和修改后的差异
 * 类似 VS Code 的 diff 视图
 */
export default function DiffViewer({
  original,
  modified,
  originalLabel,
  modifiedLabel,
  onAccept,
  onReject,
}: DiffViewerProps) {
  const { t } = useTranslation('editors')
  const resolvedOriginalLabel = originalLabel ?? t('diffViewer.original')
  const resolvedModifiedLabel = modifiedLabel ?? t('diffViewer.revised')
  const [mode, setMode] = useState<'side' | 'inline'>('side')

  // 计算差异
  const diffLines = useMemo(() => computeDiff(original, modified), [original, modified])

  // 统计
  const addCount = diffLines.filter((d) => d.type === 'add').length
  const removeCount = diffLines.filter((d) => d.type === 'remove').length

  return (
    <div className="flex flex-col h-full">
      {/* 头部工具栏 */}
      <div
        className="no-select flex items-center justify-between px-4 h-9 flex-shrink-0"
        style={{
          borderBottom: '1px solid var(--color-border)',
          backgroundColor: 'var(--color-sidebar)',
        }}
      >
        <div className="flex items-center gap-3">
          <ArrowLeftRight size={14} style={{ color: 'var(--color-accent)' }} />
          <span className="text-xs font-medium" style={{ color: 'var(--color-text)' }}>
            {t('diffViewer.title')}
          </span>
          <span className="text-xs" style={{ color: 'var(--color-text-muted)' }}>
            <span style={{ color: 'var(--color-success)' }}>+{addCount}</span>
            {' '}
            <span style={{ color: 'var(--color-error)' }}>-{removeCount}</span>
          </span>
        </div>
        <div className="flex items-center gap-2">
          {/* 视图切换 */}
          <button
            onClick={() => setMode(mode === 'side' ? 'inline' : 'side')}
            className="px-2 py-0.5 rounded text-xs"
            style={{
              backgroundColor: 'var(--color-hover)',
              color: 'var(--color-text-secondary)',
              border: '1px solid var(--color-border)',
            }}
          >
            {mode === 'side' ? t('diffViewer.sideBySide') : t('diffViewer.inline')}
          </button>
          {/* 操作按钮 */}
          {onReject && (
            <button
              onClick={onReject}
              className="flex items-center gap-1 px-2 py-0.5 rounded text-xs"
              style={{ color: 'var(--color-error)', border: '1px solid var(--color-border)' }}
            >
              <X size={12} /> {t('diffViewer.reject')}
            </button>
          )}
          {onAccept && (
            <button
              onClick={() => onAccept(modified)}
              className="flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium"
              style={{
                backgroundColor: 'var(--color-accent)',
                color: '#fff',
              }}
            >
              <Check size={12} /> {t('diffViewer.acceptChanges')}
            </button>
          )}
        </div>
      </div>

      {/* Diff 内容 */}
      {mode === 'side' ? (
        <SideBySideView diffLines={diffLines} originalLabel={resolvedOriginalLabel} modifiedLabel={resolvedModifiedLabel} />
      ) : (
        <InlineView diffLines={diffLines} />
      )}
    </div>
  )
}

/** 并排视图 */
function SideBySideView({ diffLines, originalLabel, modifiedLabel }: {
  diffLines: DiffLine[]; originalLabel: string; modifiedLabel: string
}) {
  return (
    <div className="flex flex-1 overflow-hidden">
      {/* 左侧:原文 */}
      <div className="flex-1 flex flex-col" style={{ borderRight: '1px solid var(--color-border)' }}>
        <div
          className="px-3 py-1 text-xs font-medium flex-shrink-0"
          style={{
            backgroundColor: 'color-mix(in srgb, var(--color-error) 6%, transparent)',
            color: 'var(--color-error)',
            borderBottom: '1px solid var(--color-border)',
          }}
        >
          {originalLabel}
        </div>
        <div className="flex-1 overflow-y-auto font-mono text-xs leading-5">
          {diffLines
            .filter((d) => d.type !== 'add')
            .map((d, i) => (
              <div
                key={i}
                className="px-3 py-0.5"
                style={{
                  backgroundColor: d.type === 'remove' ? 'color-mix(in srgb, var(--color-error) 8%, transparent)' : 'transparent',
                  color: d.type === 'remove' ? 'var(--color-error)' : 'var(--color-text)',
                }}
              >
                <span className="inline-block w-8 text-right mr-2 opacity-30">{d.lineOld ?? ''}</span>
                {d.type === 'remove' && <span className="mr-1">-</span>}
                {d.content}
              </div>
            ))}
        </div>
      </div>

      {/* 右侧:修改后 */}
      <div className="flex-1 flex flex-col">
        <div
          className="px-3 py-1 text-xs font-medium flex-shrink-0"
          style={{
            backgroundColor: 'color-mix(in srgb, var(--color-success) 6%, transparent)',
            color: 'var(--color-success)',
            borderBottom: '1px solid var(--color-border)',
          }}
        >
          {modifiedLabel}
        </div>
        <div className="flex-1 overflow-y-auto font-mono text-xs leading-5">
          {diffLines
            .filter((d) => d.type !== 'remove')
            .map((d, i) => (
              <div
                key={i}
                className="px-3 py-0.5"
                style={{
                  backgroundColor: d.type === 'add' ? 'color-mix(in srgb, var(--color-success) 8%, transparent)' : 'transparent',
                  color: d.type === 'add' ? 'var(--color-success)' : 'var(--color-text)',
                }}
              >
                <span className="inline-block w-8 text-right mr-2 opacity-30">{d.lineNew ?? ''}</span>
                {d.type === 'add' && <span className="mr-1">+</span>}
                {d.content}
              </div>
            ))}
        </div>
      </div>
    </div>
  )
}

/** 内联视图 */
function InlineView({ diffLines }: { diffLines: DiffLine[] }) {
  return (
    <div className="flex-1 overflow-y-auto font-mono text-xs leading-5 p-0">
      {diffLines.map((d, i) => (
        <div
          key={i}
          className="px-4 py-0.5"
          style={{
            backgroundColor:
              d.type === 'add' ? 'color-mix(in srgb, var(--color-success) 8%, transparent)'
              : d.type === 'remove' ? 'color-mix(in srgb, var(--color-error) 8%, transparent)'
              : 'transparent',
            color:
              d.type === 'add' ? 'var(--color-success)'
              : d.type === 'remove' ? 'var(--color-error)'
              : 'var(--color-text)',
          }}
        >
          <span className="inline-block w-8 text-right mr-1 opacity-30">{d.lineOld ?? ''}</span>
          <span className="inline-block w-8 text-right mr-2 opacity-30">{d.lineNew ?? ''}</span>
          <span className="mr-1">{d.type === 'add' ? '+' : d.type === 'remove' ? '-' : ' '}</span>
          {d.content}
        </div>
      ))}
    </div>
  )
}

/**
 * 简单行级 diff 算法(LCS-based)
 * 生产环境建议替换为 diff-match-patch 或类似库
 */
function computeDiff(original: string, modified: string): DiffLine[] {
  const oldLines = original.split('\n')
  const newLines = modified.split('\n')

  // 简化实现:逐行对比,使用 LCS 找出公共子序列
  const lcs = longestCommonSubsequence(oldLines, newLines)
  const result: DiffLine[] = []

  let oldIdx = 0
  let newIdx = 0
  let oldLineNum = 1
  let newLineNum = 1

  for (const common of lcs) {
    // 输出 old 中在 common 之前的删除行
    while (oldIdx < oldLines.length && oldLines[oldIdx] !== common) {
      result.push({ type: 'remove', content: oldLines[oldIdx], lineOld: oldLineNum++ })
      oldIdx++
    }
    // 输出 new 中在 common 之前的新增行
    while (newIdx < newLines.length && newLines[newIdx] !== common) {
      result.push({ type: 'add', content: newLines[newIdx], lineNew: newLineNum++ })
      newIdx++
    }
    // 公共行
    result.push({ type: 'same', content: common, lineOld: oldLineNum++, lineNew: newLineNum++ })
    oldIdx++
    newIdx++
  }

  // 处理尾部
  while (oldIdx < oldLines.length) {
    result.push({ type: 'remove', content: oldLines[oldIdx++], lineOld: oldLineNum++ })
  }
  while (newIdx < newLines.length) {
    result.push({ type: 'add', content: newLines[newIdx++], lineNew: newLineNum++ })
  }

  return result
}

/** 最长公共子序列(行级) */
function longestCommonSubsequence(a: string[], b: string[]): string[] {
  const m = a.length
  const n = b.length

  // 优化:对于大文本只取前后各 500 行
  if (m > 1000 || n > 1000) {
    return simpleFallback(a, b)
  }

  const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0))

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (a[i - 1] === b[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
      }
    }
  }

  // 回溯
  const result: string[] = []
  let i = m, j = n
  while (i > 0 && j > 0) {
    if (a[i - 1] === b[j - 1]) {
      result.unshift(a[i - 1])
      i--
      j--
    } else if (dp[i - 1][j] > dp[i][j - 1]) {
      i--
    } else {
      j--
    }
  }

  return result
}

/** 大文本降级:只保留完全相同的行 */
function simpleFallback(a: string[], b: string[]): string[] {
  const bSet = new Set(b)
  return a.filter((line) => bSet.has(line))
}