bito-code-review[bot] commented on code in PR #37499:
URL: https://github.com/apache/superset/pull/37499#discussion_r2733975976


##########
superset-frontend/src/core/editors/AceEditorProvider.tsx:
##########
@@ -0,0 +1,321 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * @fileoverview Default Ace Editor provider implementation.
+ *
+ * This module wraps the existing Ace editor components to implement the
+ * standard EditorProps interface, serving as the default editor when no
+ * extension provides a custom implementation.
+ */
+
+import {
+  useRef,
+  useEffect,
+  useCallback,
+  useImperativeHandle,
+  forwardRef,
+  type Ref,
+} from 'react';
+import type AceEditor from 'react-ace';
+import type { editors } from '@apache-superset/core';
+import {
+  FullSQLEditor,
+  JsonEditor,
+  MarkdownEditor,
+  CssEditor,
+  ConfigEditor,
+  type AceCompleterKeyword,
+} from '@superset-ui/core/components';
+import { Disposable } from '../models';
+
+type EditorKeyword = editors.EditorKeyword;
+type EditorProps = editors.EditorProps;
+type EditorHandle = editors.EditorHandle;
+type Position = editors.Position;
+type Range = editors.Range;
+type Selection = editors.Selection;
+type EditorAnnotation = editors.EditorAnnotation;
+type CompletionProvider = editors.CompletionProvider;
+
+/**
+ * Maps EditorLanguage to the corresponding Ace editor component.
+ */
+const getEditorComponent = (language: string) => {
+  switch (language) {
+    case 'sql':
+      return FullSQLEditor;
+    case 'json':
+      return JsonEditor;
+    case 'markdown':
+      return MarkdownEditor;
+    case 'css':
+      return CssEditor;
+    case 'yaml':
+      return ConfigEditor;
+    default:
+      return FullSQLEditor;
+  }
+};
+
+/**
+ * Converts EditorAnnotation to Ace annotation format.
+ */
+const toAceAnnotation = (annotation: EditorAnnotation) => ({
+  row: annotation.line,
+  column: annotation.column ?? 0,
+  text: annotation.message,
+  type: annotation.severity,
+});
+
+/**
+ * Creates an EditorHandle implementation backed by an Ace editor instance.
+ */
+const createAceEditorHandle = (
+  aceEditorRef: React.RefObject<AceEditor>,
+  completionProviders: React.MutableRefObject<Map<string, CompletionProvider>>,
+): EditorHandle => ({
+  focus: () => {
+    aceEditorRef.current?.editor?.focus();
+  },
+
+  getValue: () => aceEditorRef.current?.editor?.getValue() ?? '',
+
+  setValue: (value: string) => {
+    aceEditorRef.current?.editor?.setValue(value, -1);
+  },
+
+  getCursorPosition: (): Position => {
+    const pos = aceEditorRef.current?.editor?.getCursorPosition();
+    return {
+      line: pos?.row ?? 0,
+      column: pos?.column ?? 0,
+    };
+  },
+
+  moveCursorToPosition: (position: Position) => {
+    aceEditorRef.current?.editor?.moveCursorToPosition({
+      row: position.line,
+      column: position.column,
+    });
+  },
+
+  getSelections: (): Selection[] => {
+    const selection = aceEditorRef.current?.editor?.getSelection();
+    if (!selection) return [];
+    const range = selection.getRange();
+    return [
+      {
+        start: { line: range.start.row, column: range.start.column },
+        end: { line: range.end.row, column: range.end.column },
+      },
+    ];
+  },
+
+  setSelection: (range: Range) => {
+    const editor = aceEditorRef.current?.editor;
+    if (editor) {
+      editor.selection.setSelectionRange({
+        start: { row: range.start.line, column: range.start.column },
+        end: { row: range.end.line, column: range.end.column },
+      });
+    }
+  },
+
+  getSelectedText: () => aceEditorRef.current?.editor?.getSelectedText() ?? '',
+
+  insertText: (text: string) => {
+    aceEditorRef.current?.editor?.insert(text);
+  },
+
+  executeCommand: (commandName: string) => {
+    const editor = aceEditorRef.current?.editor;
+    if (editor?.commands) {
+      editor.commands.exec(commandName, editor, {});
+    }
+  },
+
+  scrollToLine: (line: number) => {
+    aceEditorRef.current?.editor?.scrollToLine(line, true, true);
+  },
+
+  setAnnotations: (annotations: EditorAnnotation[]) => {
+    const session = aceEditorRef.current?.editor?.getSession();
+    if (session) {
+      session.setAnnotations(annotations.map(toAceAnnotation));
+    }
+  },
+
+  clearAnnotations: () => {
+    const session = aceEditorRef.current?.editor?.getSession();
+    if (session) {
+      session.clearAnnotations();
+    }
+  },
+
+  registerCompletionProvider: (provider: CompletionProvider): Disposable => {
+    completionProviders.current.set(provider.id, provider);
+    return new Disposable(() => {
+      completionProviders.current.delete(provider.id);
+    });
+  },
+});
+
+/**
+ * Converts generic EditorKeyword to Ace's AceCompleterKeyword format.
+ */
+const toAceKeyword = (keyword: EditorKeyword): AceCompleterKeyword => ({
+  name: keyword.name,
+  value: keyword.value ?? keyword.name,
+  score: keyword.score ?? 0,
+  meta: keyword.meta ?? '',
+});
+
+/**
+ * Default Ace-based editor provider component.
+ * Implements the standard EditorProps interface while wrapping the existing
+ * Ace editor components.
+ */
+const AceEditorProvider = forwardRef<EditorHandle, EditorProps>(
+  (props, ref) => {
+    const {
+      id,
+      value,
+      onChange,
+      onBlur,
+      onCursorPositionChange,
+      onSelectionChange,
+      language,
+      readOnly,
+      tabSize,
+      lineNumbers,
+      wordWrap,
+      annotations,
+      hotkeys,
+      keywords,
+      height = '100%',
+      width = '100%',
+      onReady,
+    } = props;
+
+    const aceEditorRef = useRef<AceEditor>(null);
+    const completionProviders = useRef<Map<string, CompletionProvider>>(
+      new Map(),
+    );
+
+    // Create the handle
+    const handle = createAceEditorHandle(aceEditorRef, completionProviders);
+
+    // Expose handle via ref
+    useImperativeHandle(ref, () => handle, []);
+
+    // Notify when ready
+    useEffect(() => {
+      if (onReady && aceEditorRef.current?.editor) {
+        onReady(handle);
+      }
+    }, [onReady, handle]);
+
+    // Handle editor load
+    const onEditorLoad = useCallback(
+      (editor: AceEditor['editor']) => {
+        // Register hotkeys
+        if (hotkeys) {
+          hotkeys.forEach(hotkey => {
+            editor.commands.addCommand({
+              name: hotkey.name,
+              bindKey: { win: hotkey.key, mac: hotkey.key },
+              exec: () => hotkey.exec(handle),
+            });
+          });
+        }
+
+        // Set up cursor position change listener
+        if (onCursorPositionChange) {
+          editor.selection.on('changeCursor', () => {
+            const cursor = editor.getCursorPosition();
+            onCursorPositionChange({
+              line: cursor.row,
+              column: cursor.column,
+            });
+          });
+        }
+
+        // Set up selection change listener
+        if (onSelectionChange) {
+          editor.selection.on('changeSelection', () => {
+            const range = editor.getSelection().getRange();
+            onSelectionChange([
+              {
+                start: { line: range.start.row, column: range.start.column },
+                end: { line: range.end.row, column: range.end.column },
+              },
+            ]);
+          });
+        }
+
+        // Focus the editor
+        editor.focus();
+      },
+      [hotkeys, onCursorPositionChange, onSelectionChange, handle],
+    );
+
+    // Handle blur
+    const handleBlur = useCallback(() => {
+      if (onBlur) {
+        onBlur(value);
+      }
+    }, [onBlur, value]);
+
+    // Get the appropriate editor component
+    const EditorComponent = getEditorComponent(language);
+
+    // Convert annotations to Ace format
+    const aceAnnotations = annotations?.map(toAceAnnotation);
+
+    // Convert generic keywords to Ace format
+    const aceKeywords = keywords?.map(toAceKeyword);
+
+    return (
+      <EditorComponent
+        ref={aceEditorRef as Ref<never>}
+        name={id}
+        value={value}

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Incorrect syntax highlighting for yaml</b></div>
   <div id="fix">
   
   For yaml language, ConfigEditor is used but mode defaults to 'json' since 
it's the first inferred mode. This causes yaml content to be syntax highlighted 
as json instead of yaml. Pass mode={language} to ensure correct highlighting.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
           name={id}
           mode={language}
           value={value}
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #b00531</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset-frontend/src/dashboard/components/gridComponents/Markdown/Markdown.jsx:
##########
@@ -282,20 +287,26 @@ class Markdown extends PureComponent {
 
   renderEditMode() {
     return (
-      <MarkdownEditor
+      <EditorHost
+        id={`markdown-editor-${this.props.id}`}
         onChange={this.handleMarkdownChange}
         width="100%"
         height="100%"
-        showGutter={false}
-        editorProps={{ $blockScrolling: true }}
         value={
           // this allows "select all => delete" to give an empty editor
           typeof this.state.markdownSource === 'string'
             ? this.state.markdownSource
             : MARKDOWN_PLACE_HOLDER
         }
+        language="markdown"
         readOnly={false}
-        onLoad={this.setEditor}
+        lineNumbers={false}

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Word Wrap in Editor Migration</b></div>
   <div id="fix">
   
   The migration to EditorHost omits word wrapping, which was enabled in the 
old MarkdownEditor via setUseWrapMode(true). This affects the editing 
experience for long lines in markdown components.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
         lineNumbers={false}
         wordWrap={true}
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #b00531</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset-frontend/src/core/editors/EditorHost.tsx:
##########
@@ -0,0 +1,122 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * @fileoverview EditorHost component for dynamic editor resolution.
+ *
+ * This component resolves and renders the appropriate editor implementation
+ * based on the language and any registered extension providers. If an 
extension
+ * has registered an editor for the language, it uses that; otherwise, it falls
+ * back to the default Ace editor.
+ */
+
+import { useState, useEffect, forwardRef } from 'react';
+import type { editors, contributions } from '@apache-superset/core';
+import { useTheme } from '@apache-superset/core/ui';
+import EditorProviders from './EditorProviders';
+import AceEditorProvider from './AceEditorProvider';
+
+type EditorLanguage = contributions.EditorLanguage;
+type EditorProps = editors.EditorProps;
+type EditorHandle = editors.EditorHandle;
+
+/**
+ * Props for EditorHost component.
+ * Uses the generic EditorProps interface that all editor implementations 
support.
+ */
+export type EditorHostProps = EditorProps;
+
+/**
+ * Hook to track editor provider changes.
+ * Returns the provider for the specified language and re-renders when it 
changes.
+ */
+const useEditorProvider = (language: EditorLanguage) => {
+  const manager = EditorProviders.getInstance();
+  const [provider, setProvider] = useState(() => 
manager.getProvider(language));
+
+  useEffect(() => {
+    // Subscribe to provider changes
+    const registerDisposable = manager.onDidRegister(event => {
+      if (event.provider.contribution.languages.includes(language)) {
+        setProvider(event.provider);
+      }
+    });
+
+    const unregisterDisposable = manager.onDidUnregister(event => {
+      if (event.contribution.languages.includes(language)) {
+        setProvider(manager.getProvider(language));
+      }
+    });
+
+    // Check for provider on mount (in case it was registered before this 
component mounted)
+    const currentProvider = manager.getProvider(language);
+    if (currentProvider !== provider) {
+      setProvider(currentProvider);
+    }
+
+    return () => {
+      registerDisposable.dispose();
+      unregisterDisposable.dispose();
+    };
+  }, [language, manager, provider]);
+
+  return provider;

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Incorrect useEffect dependencies</b></div>
   <div id="fix">
   
   The useEffect dependency array includes 'provider', which is set inside the 
effect. This can cause the effect to re-run every time 'provider' changes, 
leading to performance issues or infinite loops. It should only depend on 
'language' and 'manager'.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
     }, [language, manager]);
    
     return provider;
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #b00531</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to