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

feat: add notebook variable inspector panel #4186

Merged
merged 7 commits into from
Nov 28, 2024
Merged

Conversation

ensorrow
Copy link
Contributor

@ensorrow ensorrow commented Nov 26, 2024

Types

  • 🎉 New Features

Background or solution

支持快速 Notebook 文件内的变量

image

Changelog

feat: add notebook variable inspector panel

Summary by CodeRabbit

  • 新功能

    • 增加了变量面板的本地化字符串,改善用户界面。
    • 引入了 VariablePanel 组件,用于在笔记本界面中管理和显示变量。
    • 新增 LibroVariableComponent 组件,提供变量的显示和交互功能。
    • 新增 LibroVariableModule,整合多个变量管理组件。
    • 引入了语言模型接口和抽象类,支持多种编程语言的变量检查和操作。
  • 样式

    • 新增了变量管理界面的样式,提升用户体验。
  • 文档

    • 扩展了对不同编程语言的支持,增强了变量检查功能。

@opensumi opensumi bot added the 🎨 feature feature required label Nov 26, 2024
@ensorrow ensorrow requested a review from zhanba November 26, 2024 10:12
Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

此拉取请求引入了多个新本地化字符串,主要用于笔记本变量面板的用户界面,增强了对变量检查的支持。具体修改包括添加成功和失败的刷新操作消息、搜索变量名称的占位符以及查看详细信息的提示。此外,移除了与内核面板相关的多个组件和类,更新了模块的注册逻辑,并引入了新的变量管理界面和样式。整体结构保持不变,但功能得到了扩展。

Changes

文件路径 更改摘要
packages/i18n/src/common/en-US.lang.ts 添加了多个本地化字符串,包括变量检查器标题、刷新成功/失败消息等。
packages/i18n/src/common/zh-CN.lang.ts 添加了多个本地化字符串,包括变量检查器标题、刷新成功/失败消息等。
packages/notebook/src/browser/index.ts NotebookModuleproviders数组中移除了KernelPanelContribution
packages/notebook/src/browser/kernel-panel/index.ts 移除了kernel.panel.contributionkernel.panel.protocol的导出声明。
packages/notebook/src/browser/kernel-panel/kernel.panel.contribution.ts 删除了KernelPanelContribution类,移除与内核面板集成相关的功能。
packages/notebook/src/browser/libro.contribution.tsx 添加了LibroVariableModule,更新了LibroContribution类,增加了组件注册逻辑。
packages/notebook/src/browser/variables/index.less 新增了多个LESS样式类,用于变量管理界面的布局和样式。
packages/notebook/src/browser/variables/inspector-script.ts 新增了LanguageModel接口和Languages抽象类,管理多种编程语言的脚本和命令。
packages/notebook/src/browser/variables/libro-variable-color-registry.ts 新增了LibroVariableColorRegistry类,注册颜色定义。
packages/notebook/src/browser/variables/libro-variable-module.ts 新增了LibroVariableModule,注册LibroVariablePanelViewLibroVariableColorRegistry组件。
packages/notebook/src/browser/variables/variable-panel.tsx 新增了VariablePanel组件,用于在笔记本界面中管理和显示变量面板。
packages/notebook/src/browser/variables/variable-protocol.ts 新增了常量VARIABLE_ID,值为'variable'
packages/notebook/src/browser/variables/variable-view.tsx 新增了LibroVariableComponent组件,用于显示和交互变量,包含多个方法和状态管理。

Possibly related PRs

Suggested reviewers

  • Ricbet
  • zhanba
  • erha19

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

warning eslint@8.57.1: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/config-array@0.13.0: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/object-schema@2.0.3: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob@7.2.3: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning eslint-import-resolver-typescript > glob@7.2.3: Glob versions prior to v9 are no longer supported
error Couldn't find any versions for "@opensumi/ide-dev-tool" that matches "workspace:*"


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (13)
packages/notebook/src/browser/variables/index.less (2)

1-61: 建议改进容器样式的响应性和可访问性

以下几点建议:

  1. 建议避免使用固定的高度计算值(40px),考虑使用更灵活的方式
  2. 缺少键盘焦点状态样式,影响可访问性
  3. 变量名称过长时可能存在显示问题

建议应用以下修改:

.libro-variable-content {
-  height: calc(100% - 40px);
+  height: 100%;
+  padding-top: var(--mana-libro-header-height, 40px);
+  box-sizing: border-box;

  .libro-variable-list {
    .ant-list-item {
      &:hover,
+     &:focus-visible {
        border-radius: 6px;
-       background-color: var(--mana-libro-variable-background-hover-color);
+       background-color: var(--mana-libro-variable-interactive-color);
      }

      .libro-variable-name {
        color: var(--mana-libro-variable-name-color);
+       word-break: break-word;
      }
    }
  }
}

95-102: 优化空状态样式的实现方式

当前实现存在以下问题:

  1. 使用了 !important 标记,这通常不是最佳实践
  2. 空状态缺少适当的间距和文本样式定义

建议按照以下方式优化:

.libro-variable-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
-  margin: unset !important;
+  margin: 0;
+  padding: 16px;
+  color: var(--mana-libro-variable-description-color);
+  font-size: var(--mana-libro-font-size);
}
packages/notebook/src/browser/variables/libro-variable-color-registry.ts (3)

8-8: 请移除未使用的注释代码

代码中存在被注释掉的依赖注入语句,如果不再需要建议直接删除,以保持代码整洁。

-  // @inject(OpensumiInjector) injector: Injector;

11-130: 建议完善颜色注册的文档和结构

发现以下需要改进的地方:

  1. 所有颜色定义都缺少描述信息,建议添加清晰的说明。
  2. 颜色分组需要更清晰的结构和注释。
  3. 部分颜色值使用了硬编码的十六进制值。

建议按照以下方式重构:

  1. 为每个颜色添加有意义的描述:
 {
   id: 'libro.variable.search.background.color',
   defaults: {
     dark: '#ffffff0a',
     light: Color.rgba(0, 10, 26, 0.04),
   },
-  description: '',
+  description: '变量搜索框背景颜色',
 },
  1. 使用清晰的分组注释:
+ // #region 变量面板基础颜色
  {
    id: 'libro.variable.search.background.color',
    ...
  },
+ // #endregion

+ // #region 变量标签颜色
  {
    id: 'libro.variable.tag.background.color',
    ...
  },
+ // #endregion
  1. 考虑将常用的颜色值提取为常量:
const DARK_BACKGROUND = '#ffffff0a';
const LIGHT_TEXT = Color.rgba(0, 10, 26, 0.26);

12-12: region 注释不完整

代码中只有 region 开始注释,但缺少对应的 endregion。

-  // #region antd variable
+  // #region antd variables
+  // ... color definitions ...
+  // #endregion
packages/notebook/src/browser/variables/variable-panel.tsx (1)

30-44: 提取重复代码以提高代码可维护性

在处理 editorService.currentResourceeditorService.onActiveResourceChange 时,存在重复的逻辑。建议将重复的部分提取成一个独立的函数,以减少代码冗余,提升代码的可读性和维护性。

可以将重复的逻辑提取为一个函数,例如:

const handleResourceChange = (resource) => {
  if (resource?.uri.path.ext === `.${LIBRO_COMPONENTS_SCHEME_ID}`) {
    libroOpensumiService.getOrCreateLibroView(resource.uri).then((libro) => {
      const viewManager = manaContainer.get(ViewManager);
      viewManager
        .getOrCreateView<LibroVariablePanelView>(LibroVariablePanelView, {
          id: resource.uri.toString(),
        })
        .then((libroVariablePanelView) => {
          libroVariablePanelView?.pause();
          libroVariablePanelView.parent = libro;
          libroVariablePanelView.update();
          setLibroVariablePanelView(libroVariablePanelView);
        });
    });
  } else {
    setLibroVariablePanelView(undefined);
  }
};

然后在需要的地方调用:

- if (editorService.currentResource?.uri.path.ext === `.${LIBRO_COMPONENTS_SCHEME_ID}`) {
-   // 原有逻辑
- }
+ handleResourceChange(editorService.currentResource);

 editorService.onActiveResourceChange((e) => {
-   if (e?.uri.path.ext === `.${LIBRO_COMPONENTS_SCHEME_ID}`) {
-     // 原有逻辑
-   } else {
-     setLibroVariablePanelView(undefined);
-   }
+   handleResourceChange(e);
 });

这样可以减少代码重复,提升维护效率。

Also applies to: 48-61

packages/notebook/src/browser/libro.contribution.tsx (1)

132-134: 建议使用本地资源替换远程图标 URL

iconClass 中,使用了远程图标的 URL。如果这些外部资源不可用,可能导致图标无法显示。建议将图标资源本地化,或者确保外部资源的高可用性和稳定性。

packages/notebook/src/browser/variables/variable-view.tsx (3)

60-60: 修正组件名称的拼写错误

DesrendeItem 可能是拼写错误,建议修改为更具意义的名称,例如 DescRenderItem,以提高代码可读性。

-const DesrendeItem = () => <Tooltip title={item.varContent}>{item.varContent}</Tooltip>;
+const DescRenderItem = () => <Tooltip title={item.varContent}>{item.varContent}</Tooltip>;

118-123: 简化过滤条件逻辑

filteredList 方法中,过滤器内的 if 条件检查是多余的,建议直接返回过滤结果,以简化代码。

return this.list.filter((item) => {
-  if (!this.searchValue) {
-    return true;
-  }
  return item.varName.includes(this.searchValue);
});

可以进一步简化为:

return this.list.filter((item) => item.varName.includes(this.searchValue));

252-282: 提取重复的代码以减少代码重复

handleQueryResponse 方法中,处理 'execute_result''display_data' 消息类型的代码逻辑相似,建议提取公共部分到一个辅助函数,以提高代码的可维护性。

示例:

private parseResponseContent(response: KernelMessage.IIOPubMessage): void {
  const payload = response as KernelMessage.IExecuteResultMsg;
  let content: string = payload.content.data['text/plain'] as string;
  if (content.startsWith("'") || content.startsWith('"')) {
    content = content.slice(1, -1).replace(/\\"/g, '"').replace(/\\'/g, "'");
  }
  this.list = JSON.parse(content) as IVariable[];
}

protected handleQueryResponse = (response: KernelMessage.IIOPubMessage) => {
  const msgType = response.header.msg_type;
  switch (msgType) {
    case 'execute_result':
    case 'display_data':
      this.parseResponseContent(response);
      break;
    default:
      break;
  }
};
packages/notebook/src/browser/variables/inspector-script.ts (3)

327-329: 发现未完成的 'widgetQueryCommand' 实现

在 R 语言配置中,widgetQueryCommand 被设置为 'TODO',这表示该功能尚未实现。为了确保变量检查器的完整功能,需要提供 R 语言的 widgetQueryCommand 实现。

您是否需要帮助来实现此功能?我可以协助编写相应的命令,或者为此创建一个新的 GitHub issue。


334-336: 发现未完成的 Scala 语言配置项

在 Scala 配置中,matrixQueryCommandwidgetQueryCommanddeleteCommand 当前为空,且标有 // TODO。这表明这些功能尚未实现。

您是否需要帮助来完善这些配置项?我可以协助编写相应的命令,或者为此创建一个新的 GitHub issue。


340-348: 建议将 getScript 方法改为同步函数

getScript 方法中的操作是同步的,没有异步过程。建议将其改为同步函数,直接返回对应的 LanguageModel,以简化代码并提高性能。

示例修改:

-  public static getScript(lang: string): Promise<LanguageModel> {
-    return new Promise((resolve, reject) => {
-      if (lang in Languages.scripts) {
-        resolve(Languages.scripts[lang]);
-      } else {
-        reject('Language ' + lang + ' not supported yet!');
-      }
-    });
-  }
+  public static getScript(lang: string): LanguageModel {
+    if (lang in Languages.scripts) {
+      return Languages.scripts[lang];
+    } else {
+      throw new Error('Language ' + lang + ' not supported yet!');
+    }
+  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e0d9eb7 and 9d93357.

📒 Files selected for processing (13)
  • packages/i18n/src/common/en-US.lang.ts (1 hunks)
  • packages/i18n/src/common/zh-CN.lang.ts (1 hunks)
  • packages/notebook/src/browser/index.ts (0 hunks)
  • packages/notebook/src/browser/kernel-panel/index.ts (0 hunks)
  • packages/notebook/src/browser/kernel-panel/kernel.panel.contribution.ts (0 hunks)
  • packages/notebook/src/browser/libro.contribution.tsx (7 hunks)
  • packages/notebook/src/browser/variables/index.less (1 hunks)
  • packages/notebook/src/browser/variables/inspector-script.ts (1 hunks)
  • packages/notebook/src/browser/variables/libro-variable-color-registry.ts (1 hunks)
  • packages/notebook/src/browser/variables/libro-variable-module.ts (1 hunks)
  • packages/notebook/src/browser/variables/variable-panel.tsx (1 hunks)
  • packages/notebook/src/browser/variables/variable-protocol.ts (1 hunks)
  • packages/notebook/src/browser/variables/variable-view.tsx (1 hunks)
💤 Files with no reviewable changes (3)
  • packages/notebook/src/browser/index.ts
  • packages/notebook/src/browser/kernel-panel/index.ts
  • packages/notebook/src/browser/kernel-panel/kernel.panel.contribution.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/notebook/src/browser/variables/libro-variable-module.ts
  • packages/notebook/src/browser/variables/variable-protocol.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/notebook/src/browser/variables/inspector-script.ts

[error] 9-349: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)

packages/notebook/src/browser/variables/variable-view.tsx

[error] 26-26: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (4)
packages/i18n/src/common/zh-CN.lang.ts (1)

1277-1282: 变量检查器相关的翻译内容清晰完整!

这组翻译符合以下要求:

  • 术语使用准确,如"变量检查器"而不是直译的"变量检视器"
  • 提示信息简洁明了
  • 操作反馈信息清晰
  • 用语符合中文用户习惯
packages/i18n/src/common/en-US.lang.ts (1)

1516-1521: 新增的笔记本变量面板本地化字符串看起来不错!

这些字符串清晰地描述了变量检查器面板的各个功能,包括:

  • 面板标题
  • 文件格式不支持的提示
  • 刷新操作的成功/失败消息
  • 变量名搜索占位符
  • 查看详情的按钮文本

字符串的命名和格式与现有的本地化模式保持一致。

packages/notebook/src/browser/libro.contribution.tsx (2)

147-152: 确认组件注册时 weightpriority 属性的必要性

在注册 VariablePanel 时,同时设置了 weight: 2priority: 1。请确认这两个属性在组件排序或显示中的作用,是否需要同时设置,或者是否存在冲突。


128-160: 新增的 registerComponent 方法实现正确

registerComponent 方法成功地将 KernelPanelVariablePanel 注册到了组件注册表,符合预期功能。

Copy link

codecov bot commented Nov 26, 2024

Codecov Report

Attention: Patch coverage is 0% with 20 lines in your changes missing coverage. Please review.

Project coverage is 54.05%. Comparing base (e0d9eb7) to head (92cad82).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...notebook/src/browser/variables/inspector-script.ts 0.00% 9 Missing and 1 partial ⚠️
...browser/variables/libro-variable-color-registry.ts 0.00% 5 Missing ⚠️
...ook/src/browser/variables/libro-variable-module.ts 0.00% 4 Missing ⚠️
...otebook/src/browser/variables/variable-protocol.ts 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4186      +/-   ##
==========================================
- Coverage   54.06%   54.05%   -0.02%     
==========================================
  Files        1612     1616       +4     
  Lines       97925    97959      +34     
  Branches    20043    20046       +3     
==========================================
+ Hits        52942    52950       +8     
- Misses      37372    37397      +25     
- Partials     7611     7612       +1     
Flag Coverage Δ
jsdom 49.62% <0.00%> (-0.01%) ⬇️
node 15.55% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (5)
packages/notebook/src/browser/variables/variable-panel.tsx (2)

17-20: 建议将内联样式移至样式表

建议将 collapsePanelContainerStyle 对象移至样式表中,以保持代码的一致性和可维护性。这样可以:

  • 提高代码的可读性
  • 便于统一管理样式
  • 支持样式的复用
+ // index.less
+ .collapse-panel-container {
+   width: 100%;
+   height: 100%;
+ }

  // variable-panel.tsx
- const collapsePanelContainerStyle = {
-   width: viewState.width || '100%',
-   height: viewState.height,
- };
+ const containerStyle = {
+   ...viewState,
+ };

68-84: 建议简化渲染逻辑

当前的渲染逻辑包含了不必要的片段包装和冗余的返回语句,可以进行简化以提高代码的可读性。

- if (libroVariablePanelView) {
-   return (
-     <>
-       <div style={collapsePanelContainerStyle}>
-         {<ViewRender view={libroVariablePanelView}></ViewRender>}
-       </div>
-     </>
-   );
- } else {
-   return (
-     <>
-       <Empty
-         image={Empty.PRESENTED_IMAGE_SIMPLE}
-         description={localize('notebook.variable.panel.unsupported')}
-         className='libro-variable-empty'
-       />
-     </>
-   );
- }
+ return libroVariablePanelView ? (
+   <div style={collapsePanelContainerStyle}>
+     <ViewRender view={libroVariablePanelView} />
+   </div>
+ ) : (
+   <Empty
+     image={Empty.PRESENTED_IMAGE_SIMPLE}
+     description={localize('notebook.variable.panel.unsupported')}
+     className='libro-variable-empty'
+   />
+ );
packages/notebook/src/browser/libro.contribution.tsx (2)

18-19: 导入语句的组织需要优化

建议将相关的导入语句进行分组整理,提高代码的可读性:

  1. 将变量面板相关的导入(VariablePanel、VARIABLE_ID等)集中放置
  2. 将核心组件相关的导入(ComponentContribution、ComponentRegistry等)集中放置

建议按以下方式重组导入语句:

import {
  AppConfig,
  ClientAppContextContribution,
  ClientAppContribution,
  CommandContribution,
  CommandRegistry,
+ ComponentContribution,
+ ComponentRegistry,
  Disposable,
  Domain,
  IClientApp,
  IOpenerService,
  OpenerContribution,
  Schemes,
  URI,
+ localize,
} from '@opensumi/ide-core-browser';

// 变量面板相关导入
+import { LibroVariableModule } from './variables/libro-variable-module';
+import { VariablePanel } from './variables/variable-panel';
+import { VARIABLE_ID } from './variables/variable-protocol';

Also applies to: 27-27, 42-42, 52-54


65-65: 模块注册顺序建议调整

当前模块注册的顺序可能需要根据依赖关系进行优化。建议将核心模块放在前面,扩展模块放在后面。

-      modules={[ManaAppPreset, LibroJupyterNoEditorModule, LibroTOCModule, LibroOpensumiModule, LibroVariableModule]}
+      modules={[
+        // 核心模块
+        ManaAppPreset,
+        LibroJupyterNoEditorModule,
+        // 扩展模块
+        LibroOpensumiModule,
+        LibroTOCModule,
+        LibroVariableModule,
+      ]}
packages/notebook/src/browser/variables/variable-view.tsx (1)

252-282: 建议重构重复的响应处理逻辑

handleQueryResponse 方法中处理 'execute_result' 和 'display_data' 的逻辑存在重复。

建议提取共同逻辑到单独的方法:

protected parseContent(content: string): IVariable[] {
  if (content.slice(0, 1) === "'" || content.slice(0, 1) === '"') {
    content = content.slice(1, -1);
    content = content.replace(/\\"/g, '"').replace(/\\'/g, "'");
  }
  return JSON.parse(content);
}

protected handleQueryResponse = (response: KernelMessage.IIOPubMessage) => {
  const msgType = response.header.msg_type;
  if (msgType === 'execute_result' || msgType === 'display_data') {
    const payload = response as KernelMessage.IExecuteResultMsg;
    const content = payload.content.data['text/plain'] as string;
    this.list = this.parseContent(content);
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9d93357 and 92cad82.

📒 Files selected for processing (3)
  • packages/notebook/src/browser/libro.contribution.tsx (7 hunks)
  • packages/notebook/src/browser/variables/variable-panel.tsx (1 hunks)
  • packages/notebook/src/browser/variables/variable-view.tsx (1 hunks)
🔇 Additional comments (2)
packages/notebook/src/browser/libro.contribution.tsx (1)

74-75: 常量命名需要修正

此问题在之前的评审中已经提出,常量 NOTE_BOOK_PANEL_ID 的命名仍需要修正。

packages/notebook/src/browser/variables/variable-view.tsx (1)

87-95: 接口定义清晰完整

IVariable 接口的属性定义明确,类型完整,能够很好地描述变量的各个特征。

ensorrow and others added 4 commits November 28, 2024 09:38
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
packages/notebook/src/browser/variables/variable-view.tsx (1)

251-281: 建议提取重复代码到独立函数

handleQueryResponse 方法中存在重复的代码逻辑,建议重构以提高可维护性:

  1. 提取字符串处理逻辑
  2. 合并相似的消息处理逻辑
+private processContent(content: string): string {
+  if (content.slice(0, 1) === "'" || content.slice(0, 1) === '"') {
+    content = content.slice(1, -1);
+    return content.replace(/\\"/g, '"').replace(/\\'/g, "'");
+  }
+  return content;
+}

+private updateList(content: string): void {
+  const processedContent = this.processContent(content);
+  this.list = JSON.parse(processedContent) as IVariable[];
+}

 protected handleQueryResponse = (response: KernelMessage.IIOPubMessage) => {
   const msgType = response.header.msg_type;
   switch (msgType) {
     case 'execute_result': {
       const payload = response as KernelMessage.IExecuteResultMsg;
-      let content: string = payload.content.data['text/plain'] as string;
-      if (content.slice(0, 1) === "'" || content.slice(0, 1) === '"') {
-        content = content.slice(1, -1);
-        content = content.replace(/\\"/g, '"').replace(/\\'/g, "'");
-      }
-      const update = JSON.parse(content) as IVariable[];
-      this.list = update;
+      this.updateList(payload.content.data['text/plain'] as string);
       break;
     }
     case 'display_data': {
       const payloadDisplay = response as KernelMessage.IExecuteResultMsg;
-      let contentDisplay: string = payloadDisplay.content.data['text/plain'] as string;
-      if (contentDisplay.slice(0, 1) === "'" || contentDisplay.slice(0, 1) === '"') {
-        contentDisplay = contentDisplay.slice(1, -1);
-        contentDisplay = contentDisplay.replace(/\\"/g, '"').replace(/\\'/g, "'");
-      }
-      const updateDisplay = JSON.parse(contentDisplay) as IVariable[];
-      this.list = updateDisplay;
+      this.updateList(payloadDisplay.content.data['text/plain'] as string);
       break;
     }
     default:
       break;
   }
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a1838a7 and 81df759.

📒 Files selected for processing (2)
  • packages/notebook/src/browser/variables/libro-variable-color-registry.ts (1 hunks)
  • packages/notebook/src/browser/variables/variable-view.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/notebook/src/browser/variables/libro-variable-color-registry.ts
🔇 Additional comments (3)
packages/notebook/src/browser/variables/variable-view.tsx (3)

44-52: 建议避免使用硬编码的图片 URL

建议将图片资源本地化,避免依赖外部 CDN。


242-249: 建议添加空值检查而不是使用非空断言

在使用 this.languageModel 时直接使用非空断言 ! 可能导致运行时错误。


298-310: 建议增强错误处理

fetch 方法中的错误处理可以更加完善,特别是在处理内核连接和执行请求时的异常情况。

@ensorrow ensorrow merged commit 6290e8f into main Nov 28, 2024
11 checks passed
@ensorrow ensorrow deleted the feat/notebook-variables branch November 28, 2024 04:10
Aaaaash pushed a commit that referenced this pull request Dec 9, 2024
* feat: add notebook variable inspector panel

* fix: dispose event

* chore: simplify create logic

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: lint

* fix: missing deps

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🎨 feature feature required
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants