Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error when highlighting an empty file #225

Open
jclem opened this issue Sep 5, 2024 · 1 comment
Open

Error when highlighting an empty file #225

jclem opened this issue Sep 5, 2024 · 1 comment

Comments

@jclem
Copy link

jclem commented Sep 5, 2024

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.

@xyJen
Copy link
Contributor

xyJen commented Dec 9, 2024

@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,可以吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants