react-diff-view icon indicating copy to clipboard operation
react-diff-view copied to clipboard

Error when highlighting an empty file

Open jclem opened this issue 1 year ago • 1 comments

This code assumes at least one token is in an array. When highlighting things like an empty file diff, this may not be the case, which leads to an error.

Here is a reproduction:

import { tokenize } from "react-diff-view";
import refractor from "refractor";

const tokens = tokenize(
  [
    {
      changes: [
        {
          content: "",
          type: "insert",
          isInsert: true,
          lineNumber: 1,
        },
      ],

      content: "@@ -0,0 +1,1 @@",

      isPlain: false,

      newLines: 1,
      newStart: 1,
      oldLines: 1,
      oldStart: 0,
    },
  ],
  {
    highlight: true,
    language: "js",
    refractor,
  },
);

function isEmptyToken(tokens) {
  if (tokens.length > 1) {
    return false;
  }

  const [token] = tokens;
  return token.type === "text" && !token.value;
}

tokens.new.map(isEmptyToken);
// Throws `TypeError: Cannot read properties of undefined (reading 'type')`

The issue doesn't happen when not highlighting.

jclem avatar Sep 05 '24 21:09 jclem

@otakustay 这里有个逻辑问题。CodeCell 中为了 解决 210 的问题,将 token 的判空条件从 (tokens.length ? tokens.map(actualRenderToken) : ' ') 改为 (isEmptyToken(tokens) ? ' ' : tokens.map(actualRenderToken))

但是,从 Hunks 组件 -> SplitHunk -> SplitChange -> CodeCell 这条链路上。 SplitHunk 在 renderRow 时,传递给 SplitChange 组件的 tokens 是 null。会导致 isEmptyToken 抛错。

const oldTokens = (oldValue && tokens) ? tokens.old[computeOldLineNumber(oldValue) - 1] : null;  // 这里的 token 类型可能为 数组或者 null
const newTokens = (newValue && tokens) ? tokens.new[computeNewLineNumber(newValue) - 1] : null;

我觉得,isEmptyToken 应支持是否是数组的判断,如果不是数组(可能为 null),则认为 isEmptyToken 为true。

你看看有没有什么问题,没问题的话,我下午发起一个 pr,可以吗?

xyJen avatar Dec 09 '24 05:12 xyJen

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 26 '25 01:04 stale[bot]