You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "rusackas (via GitHub)" <gi...@apache.org> on 2026/10/01 05:00:59 UTC

[PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

rusackas opened a new pull request, #44858:
URL: https://github.com/apache/superset/pull/44858

   ### SUMMARY
   
   Follow-up to #39257, closing out two real bugs that were flagged in review but deliberately deferred rather than rushed into that PR:
   
   - `CollectionTable.handleTableChange()` reset rows from the `collection` prop on both sorting and clearing a sort, instead of the component's own live state. An inline edit whose `onChange` hadn't round-tripped back into the parent's state yet (the normal case, since that round trip is async relative to the keystroke) got silently discarded the moment the user touched a sortable column header, in the dataset editor's Columns/Calculated Columns/Metrics tables. It now sorts and restores order from the live `collection`/`collectionArray` state, tracking the pre-sort row order in a ref so clearing a sort still restores the original order rather than whatever the prop happened to look like.
   - `TextAreaControl`'s Ace editor used an uncontrolled `defaultValue`, so a later `initialValue` prop change (e.g. clicking "Sync columns from source" mid-edit) never reached an already-mounted editor; the SQL expression editor just kept showing stale text. It now diffs incoming values against what the editor itself last emitted, and imperatively pushes a genuinely external change into the live Ace instance while preserving cursor position, without remounting the editor or fighting the user's own typing on every keystroke.
   
   The third thing flagged in that review (the dataset modal's resize handle not actually changing the nested Ant modal's `vw` width) was deliberately left out here, it's a pre-existing `Modal` component limitation rather than a regression, and not a data-loss bug like the two above.
   
   ### TESTING INSTRUCTIONS
   
   ```bash
   npx jest src/components/Datasource/components/CollectionTable/CollectionTable.test.tsx
   npx jest src/explore/components/controls/TextAreaControl.test.tsx
   ```
   
   Manually: open a dataset's edit modal, go to Calculated Columns, sort by column name, edit an expression, then clear the sort โ€” the edit now survives. Separately, open a column's SQL expression editor, click "Sync columns from source," and confirm the editor picks up the refreshed expression instead of showing the stale one.
   
   ### ADDITIONAL INFORMATION
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [ ] Introduces new feature or API
   - [ ] Removes existing feature or API
   
   ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4153129901


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&
+      nextValue !== editor.getValue()
+    ) {
+      const cursorPos = editor.getCursorPosition();
+      editor.setValue(nextValue, 1);
+      editor.clearSelection();
+      editor.moveCursorToPosition(cursorPos);
+      lastEditorValueRef.current = nextValue;
+    }
+  }, [initialValue, value]);

Review Comment:
   <!-- Bito Reply -->
   The suggestion to track the main and modal editors separately is appropriate. It prevents the modal editor's `onLoad` from overwriting the `editorRef` used by the main editor, which currently causes the main editor to become stale when the modal is closed. Applying this change will ensure that `setValue` calls are correctly routed to the intended editor instance.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5925184363

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/44858?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `96.77419%` with `1 line` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 81.73%. Comparing base ([`4cdd680`](https://app.codecov.io/gh/apache/superset/commit/4cdd680f39918012bdfe254bc7ca938aa4cd6939?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`9c1d1be`](https://app.codecov.io/gh/apache/superset/commit/9c1d1bee4a4efd6bef52487a7ed704923cdc35c0?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/44858?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...ts/Datasource/components/CollectionTable/index.tsx](https://app.codecov.io/gh/apache/superset/pull/44858?src=pr&el=tree&filepath=superset-frontend%2Fsrc%2Fcomponents%2FDatasource%2Fcomponents%2FCollectionTable%2Findex.tsx&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2NvbXBvbmVudHMvRGF0YXNvdXJjZS9jb21wb25lbnRzL0NvbGxlY3Rpb25UYWJsZS9pbmRleC50c3g=) | 92.30% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44858?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #44858      +/-   ##
   ==========================================
   + Coverage   81.71%   81.73%   +0.02%     
   ==========================================
     Files        2978     2978              
     Lines      181613   181640      +27     
     Branches    41983    41992       +9     
   ==========================================
   + Hits       148402   148471      +69     
   + Misses      30489    30447      -42     
     Partials     2722     2722              
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/44858/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage ฮ” | |
   |---|---|---|
   | [javascript](https://app.codecov.io/gh/apache/superset/pull/44858/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `77.18% <96.77%> (+0.05%)` | :arrow_up: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/44858?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4178541170


##########
superset-frontend/src/components/Datasource/components/CollectionTable/CollectionTable.test.tsx:
##########
@@ -27,10 +28,242 @@ const props = {
   sortColumns: [],
 };
 
+test('keeps tie order stable when pagination reapplies a descending sort', () => {
+  const collection = Array.from({ length: 30 }, (_, i) => ({
+    id: i + 1,
+    column_name: `col_${i + 1}`,
+    verbose_name: '',
+  }));
+
+  const { container } = render(
+    <CollectionTable
+      collection={collection}
+      tableColumns={['column_name', 'verbose_name']}
+      sortColumns={['verbose_name']}
+      pagination={{ pageSize: 25 }}
+    />,
+  );
+
+  const sorters = container.querySelectorAll('.ant-table-column-sorters');
+  // ascend -> descend on the all-blank verbose_name column.
+  fireEvent.click(sorters[1]);

Review Comment:
   Only `verbose_name` is sortable here, so `.ant-table-column-sorters` contains one element and `sorters[1]` is undefined; the first click throws before the pagination assertions run. Could this select the sole sorter so the regression test reaches those assertions?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4179041458


##########
superset-frontend/src/components/Datasource/components/CollectionTable/CollectionTable.test.tsx:
##########
@@ -27,10 +28,242 @@ const props = {
   sortColumns: [],
 };
 
+test('keeps tie order stable when pagination reapplies a descending sort', () => {
+  const collection = Array.from({ length: 30 }, (_, i) => ({
+    id: i + 1,
+    column_name: `col_${i + 1}`,
+    verbose_name: '',
+  }));
+
+  const { container } = render(
+    <CollectionTable
+      collection={collection}
+      tableColumns={['column_name', 'verbose_name']}
+      sortColumns={['verbose_name']}
+      pagination={{ pageSize: 25 }}
+    />,
+  );
+
+  const sorters = container.querySelectorAll('.ant-table-column-sorters');
+  // ascend -> descend on the all-blank verbose_name column.
+  fireEvent.click(sorters[1]);

Review Comment:
   Good catch, @sadpandajoe. Switched to selecting the sole sorter, so the test reaches the pagination assertions now.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4152269544


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -137,15 +162,8 @@ function TextAreaControl({
   );
 
   const onEditorLoad = useCallback(
-    (editor: {
-      commands: {
-        addCommand: (cmd: {
-          name: string;
-          bindKey: { win: string; mac: string };
-          exec: () => void;
-        }) => void;
-      };
-    }) => {
+    (editor: AceEditorHandle) => {
+      editorRef.current = editor;

Review Comment:
   Yes, this is a valid issue. `editorRef` is overwritten whenever either Ace instance loads, and it is not cleared when the modal instance unmounts. Consequently, after closing the modal, an external `initialValue` update can target the destroyed modal editor and leave the visible inline editor stale.
   
   Track the mounted editors independently and update every live instance:
   
   ```tsx
   const inlineEditorRef = useRef<AceEditorHandle | null>(null);
   const modalEditorRef = useRef<AceEditorHandle | null>(null);
   
   const onEditorLoad = useCallback(
     (editor: AceEditorHandle, inModal: boolean) => {
       const ref = inModal ? modalEditorRef : inlineEditorRef;
       ref.current = editor;
   
       hotkeys?.forEach(keyConfig => {
         editor.commands.addCommand({
           name: keyConfig.name,
           bindKey: { win: keyConfig.key, mac: keyConfig.key },
           exec: keyConfig.func,
         });
       });
     },
     [hotkeys],
   );
   ```
   
   The modal renderer should clear its ref on unmount, and the synchronization effect should iterate over both refs, preserving each instanceโ€™s cursor position. A regression test should cover:
   
   1. Mount the inline editor.
   2. Open the modal, then close it.
   3. Change `initialValue` externally.
   4. Assert that the inline editor updates and no destroyed modal editor is accessed.
   
   This is worth fixing because the current single-ref implementation can cause exactly the stale inline editor behavior described in the comment.



##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +354,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet
+          // isn't dropped when a sort is applied.
+          sortedArray = [...collectionArray];
           sortedArray.sort((a: CollectionItem, b: CollectionItem) =>
             compareSort(a[col] as Sort, b[col] as Sort),
           );
           if (newSortOrder === SortOrderEnum.Desc) {
             sortedArray.reverse();
           }
         } else {
-          const { collectionArray: resetArray } =
-            createKeyedCollection(propsCollection);
-          sortedArray = resetArray;
+          // Restore the pre-sort order, but take each row's current value
+          // from the live `collection` map (not propsCollection) so an edit
+          // made while sorted survives clearing the sort. Any row not part
+          // of the tracked order (e.g. added while sorted) is appended.
+          const trackedIds = new Set(unsortedOrderRef.current);
+          sortedArray = unsortedOrderRef.current
+            .filter(id => collection[id])
+            .map(id => collection[id]);

Review Comment:
   Yes. The restore order should be refreshed when the underlying `propsCollection` changes while a sort is active. Otherwise, clearing the sort uses IDs from the pre-sync collection, which can restore stale ordering and mishandle added or removed rows.
   
   A minimal fix is to update `unsortedOrderRef` from the newly received collection whenever `propsCollection` changes, regardless of the current sort state:
   
   ```tsx
   useEffect(() => {
     const { collection: newCollection, collectionArray: newCollectionArray } =
       createKeyedCollection(propsCollection);
   
     setCollection(newCollection);
     setCollectionArray(newCollectionArray);
     unsortedOrderRef.current = newCollectionArray.map(item => item.id);
   }, [propsCollection]);
   ```
   
   The existing `collectionArray`/`sort` effect can remain for tracking local edits made while unsorted. This ensures a source sync establishes the new canonical row order, while the clear-sort path still reads current row values from `collection`, preserving edits made after the sync. A regression test should cover syncing a reordered/changed collection while sorted, then clearing the sort.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4178097059


##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +375,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet
+          // isn't dropped when a sort is applied.
+          sortedArray = [...collectionArray];
           sortedArray.sort((a: CollectionItem, b: CollectionItem) =>
             compareSort(a[col] as Sort, b[col] as Sort),
           );
           if (newSortOrder === SortOrderEnum.Desc) {
             sortedArray.reverse();
           }
         } else {
-          const { collectionArray: resetArray } =
-            createKeyedCollection(propsCollection);
-          sortedArray = resetArray;
+          // Restore the pre-sort order, but take each row's current value
+          // from the live `collection` map (not propsCollection) so an edit
+          // made while sorted survives clearing the sort. Any row not part
+          // of the tracked order (e.g. added while sorted) is appended.
+          const trackedIds = new Set(unsortedOrderRef.current);
+          sortedArray = unsortedOrderRef.current
+            .filter(id => collection[id])
+            .map(id => collection[id]);
+          collectionArray.forEach(item => {
+            if (!trackedIds.has(item.id)) {

Review Comment:
   With an echoing parent, `isEcho` now leaves a row added while sorted out of the restore order, so this loop alone keeps it after the sort is cleared; with the condition forced to `false` all 4 CollectionTable tests pass and the row disappears. A test adding a row while sorted would pin it.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4177675300


##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +375,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet

Review Comment:
   With a descending sort active, changing pages sorts the already-sorted rows and reverses every equal-key group again; with 30 metrics that have blank Labels and a page size of 25, page 2 repeats five metrics from page 1 and skips the remaining five. Could we keep tie ordering stable when pagination reapplies the existing sorter?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5929986872

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4160659280


##########
superset-frontend/src/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,143 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }

Review Comment:
   <!-- Bito Reply -->
   The update to use a shared SyncWrapper is a clean approach that addresses the redundancy identified in the review. This change simplifies the test structure and ensures that future modifications to the component props only need to be applied in one location.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4159084924


##########
superset-frontend/src/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,143 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Triplicated test Wrapper</b></div>
   <div id="fix">
   
   Tests at lines 66, 108, and 147 each re-declare a near-identical `Wrapper` (lines 67-85, 110-128, 148-166); only the `onChange` prop differs (`() => {}` vs the `onChange` mock). Extract one shared `Wrapper` taking `onChange` so future prop changes to `TextAreaControl` update a single site instead of three copies drifting apart.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #3966de</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/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&
+      nextValue !== editor.getValue()
+    ) {
+      const cursorPos = editor.getCursorPosition();
+      editor.setValue(nextValue, 1);
+      editor.clearSelection();
+      editor.moveCursorToPosition(cursorPos);
+      lastEditorValueRef.current = nextValue;
+    }
+  }, [initialValue, value]);

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>shared editorRef syncs wrong editor</b></div>
   <div id="fix">
   
   `onEditorLoad` (line 166) sets the single `editorRef.current`, but both the main editor (line 307) and the modal editor (line 298) pass it. antd `Modal` mounts children lazily, so after the user opens 'Edit in modal' once, the modal editor's `onLoad` overwrites `editorRef`. The new sync `useEffect` then calls `setValue` on the hidden modal editor, leaving the visible main editor stale. Track the two editors separately and sync the main one.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #6ca0d0</i></small>
   </div><div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Magic sentinel in setValue</b></div>
   <div id="fix">
   
   `setValue(nextValue, 1)` passes Ace's cursor-placement sentinel as a bare literal; its meaning is only recoverable from Ace's API docs, while the surrounding comment describes the intent in prose. Extract it to a named constant so the call site reads without external documentation and cannot be casually edited.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #3966de</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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #44858:
URL: https://github.com/apache/superset/pull/44858


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5933510806

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5937567388

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4152266692


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&

Review Comment:
   If initialValue changes from A to B while the async editor is loading, Ace mounts with B but this ref still holds A; a later external reset to A is then ignored and leaves B visible. Should onEditorLoad initialize the tracked value from the editor buffer so that reset is not mistaken for a typing echo?



##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +354,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet
+          // isn't dropped when a sort is applied.
+          sortedArray = [...collectionArray];
           sortedArray.sort((a: CollectionItem, b: CollectionItem) =>
             compareSort(a[col] as Sort, b[col] as Sort),
           );
           if (newSortOrder === SortOrderEnum.Desc) {
             sortedArray.reverse();
           }
         } else {
-          const { collectionArray: resetArray } =
-            createKeyedCollection(propsCollection);
-          sortedArray = resetArray;
+          // Restore the pre-sort order, but take each row's current value
+          // from the live `collection` map (not propsCollection) so an edit
+          // made while sorted survives clearing the sort. Any row not part
+          // of the tracked order (e.g. added while sorted) is appended.
+          const trackedIds = new Set(unsortedOrderRef.current);
+          sortedArray = unsortedOrderRef.current
+            .filter(id => collection[id])
+            .map(id => collection[id]);

Review Comment:
   Agreedโ€”after a source sync changes the column order while sorted, clearing the sort restores the old order, and the next edit sends that order back to the parent. Should the restore order track changes to the underlying collection as well?



##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -137,15 +162,8 @@ function TextAreaControl({
   );
 
   const onEditorLoad = useCallback(
-    (editor: {
-      commands: {
-        addCommand: (cmd: {
-          name: string;
-          bindKey: { win: string; mac: string };
-          exec: () => void;
-        }) => void;
-      };
-    }) => {
+    (editor: AceEditorHandle) => {
+      editorRef.current = editor;

Review Comment:
   Agreedโ€”opening and closing the modal leaves this ref pointing at its destroyed editor, so a later external update misses the visible inline editor. Should the two editor instances be tracked separately, with an open โ†’ close โ†’ external-update regression test?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4153125229


##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +354,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet
+          // isn't dropped when a sort is applied.
+          sortedArray = [...collectionArray];
           sortedArray.sort((a: CollectionItem, b: CollectionItem) =>
             compareSort(a[col] as Sort, b[col] as Sort),
           );
           if (newSortOrder === SortOrderEnum.Desc) {
             sortedArray.reverse();
           }
         } else {
-          const { collectionArray: resetArray } =
-            createKeyedCollection(propsCollection);
-          sortedArray = resetArray;
+          // Restore the pre-sort order, but take each row's current value
+          // from the live `collection` map (not propsCollection) so an edit
+          // made while sorted survives clearing the sort. Any row not part
+          // of the tracked order (e.g. added while sorted) is appended.
+          const trackedIds = new Set(unsortedOrderRef.current);
+          sortedArray = unsortedOrderRef.current
+            .filter(id => collection[id])
+            .map(id => collection[id]);

Review Comment:
   Good catch, fixed. `unsortedOrderRef` now refreshes from the synced collection whenever it changes, not just while unsorted, so clearing the sort after an external update uses the current order.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5985285350

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4159799623


##########
superset-frontend/src/components/Datasource/components/CollectionTable/CollectionTable.test.tsx:
##########
@@ -34,3 +34,99 @@ test('renders a table', () => {
   const rows = tableBody?.getElementsByTagName('tr');
   expect(rows).toHaveLength(mockDatasource['7__table'].columns.length);
 });
+
+test('preserves an edit made while sorted after the sort is cleared', () => {
+  const onChange = jest.fn();
+  const collection = [
+    { id: 1, column_name: 'b_col', type: 'VARCHAR' },
+    { id: 2, column_name: 'a_col', type: 'VARCHAR' },
+  ];
+
+  const { container } = render(
+    <CollectionTable
+      collection={collection}
+      tableColumns={['column_name', 'type']}
+      sortColumns={['column_name']}
+      itemRenderers={{
+        type: (val, onItemChange, _label, record) => (
+          <input
+            data-test={`type-input-${record.id}`}
+            value={val as string}
+            onChange={e => onItemChange(e.target.value)}
+          />
+        ),
+      }}
+      onChange={onChange}
+    />,
+  );
+
+  const sorter = container.querySelector('.ant-table-column-sorters');
+  expect(sorter).toBeInTheDocument();
+
+  // Ascending sort by column_name puts a_col (id 2) first.
+  fireEvent.click(sorter!);
+
+  const editedInput = container.querySelector(
+    '[data-test="type-input-2"]',
+  ) as HTMLInputElement;
+  expect(editedInput).toBeInTheDocument();
+  fireEvent.change(editedInput, { target: { value: 'EDITED' } });
+
+  // Cycle the sort back to unsorted (ascend -> descend -> cancel).
+  fireEvent.click(sorter!);

Review Comment:
   This only checks the edit after clearing the sort, which restores it from `collection`; reverting the active-sort path to `propsCollection` would still pass while the descending sort drops the displayed edit. Could we assert the edited value and sorted row order after the descending click, before clearing the sort?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4156904167


##########
superset-frontend/src/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,139 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const inlineEditorNode = container.querySelector(
+      '.ace_editor',
+    ) as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    // Open, then close, the "edit in modal" dialog. Its own Ace instance
+    // mounts and is destroyed (destroyOnHidden) in the process; this used
+    // to leave the single shared editor ref pointing at that destroyed
+    // instance instead of the still-visible inline editor.
+    // ModalTrigger wraps its triggerNode in its own role="button" element,
+    // so a <Button> triggerNode (as used here) yields two nested elements
+    // matching role "button" with the same accessible name; target the
+    // wrapper directly via its data-test id instead.
+    fireEvent.click(screen.getByTestId('span-modal-trigger'));
+    await waitFor(() => {
+      expect(container.querySelectorAll('.ace_editor')).toHaveLength(2);
+    });

Review Comment:
   Good catch, fixed โ€” querying `document` instead of `container` now, since the modal portals via antd's default `getContainer` (document.body).



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5925072738

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5943305936

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5945233350

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4177521095


##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -127,15 +127,32 @@ export default function CRUDCollection({
       : 10,
   );
   const [currentPage, setCurrentPage] = useState<number>(1);
+  // The row order to restore when a sort is cleared. Tracked from
+  // collectionArray itself (not propsCollection) so it reflects in-progress
+  // edits whose onChange round trip to the parent hasn't landed back in
+  // props yet.
+  const unsortedOrderRef = useRef<Array<string | number>>(
+    initialKeyed.current!.collectionArray.map(item => item.id),
+  );
 
   // Sync with props.collection changes
   useEffect(() => {
     const { collection: newCollection, collectionArray: newCollectionArray } =
       createKeyedCollection(propsCollection);
     setCollection(newCollection);
     setCollectionArray(newCollectionArray);
+    // Refresh the restore order too, so that clearing a sort after an
+    // external sync (e.g. a source-control-synced column set) reflects the
+    // synced order and row set instead of stale, pre-sync ids.
+    unsortedOrderRef.current = newCollectionArray.map(item => item.id);

Review Comment:
   Good catch @aminghadersohi. The sync effect now skips the restore-order refresh when the incoming row order matches what is already displayed while sorted, so an echoing parent no longer overwrites it. Added a round-tripping-parent test that fails without the change.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4178359812


##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +375,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet

Review Comment:
   Good catch, @sadpandajoe. Descending now uses a negated comparator instead of `reverse()`, and a pagination event that re-emits the current sorter no longer re-sorts. Added a 30-row, page-size-25 test with blank labels that checks all rows show up across both pages.



##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +375,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet
+          // isn't dropped when a sort is applied.
+          sortedArray = [...collectionArray];
           sortedArray.sort((a: CollectionItem, b: CollectionItem) =>
             compareSort(a[col] as Sort, b[col] as Sort),
           );
           if (newSortOrder === SortOrderEnum.Desc) {
             sortedArray.reverse();
           }
         } else {
-          const { collectionArray: resetArray } =
-            createKeyedCollection(propsCollection);
-          sortedArray = resetArray;
+          // Restore the pre-sort order, but take each row's current value
+          // from the live `collection` map (not propsCollection) so an edit
+          // made while sorted survives clearing the sort. Any row not part
+          // of the tracked order (e.g. added while sorted) is appended.
+          const trackedIds = new Set(unsortedOrderRef.current);
+          sortedArray = unsortedOrderRef.current
+            .filter(id => collection[id])
+            .map(id => collection[id]);
+          collectionArray.forEach(item => {
+            if (!trackedIds.has(item.id)) {

Review Comment:
   Thanks @aminghadersohi. Added a test that adds a row while sorted, clears the sort, and checks the row is still there.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4154832617


##########
superset-frontend/src/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,139 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const inlineEditorNode = container.querySelector(
+      '.ace_editor',
+    ) as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    // Open, then close, the "edit in modal" dialog. Its own Ace instance
+    // mounts and is destroyed (destroyOnHidden) in the process; this used
+    // to leave the single shared editor ref pointing at that destroyed
+    // instance instead of the still-visible inline editor.
+    // ModalTrigger wraps its triggerNode in its own role="button" element,

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Ambiguous role query</b></div>
   <div id="fix">
   
   This query matches two elements: `ModalTrigger` wraps `triggerNode` in its own div[role=button] (`ModalTrigger/index.tsx`), and the nested antd `Button` is also role button. Both have accessible name 'Edit sql in modal', so `getByRole` throws 'Found multiple elements'. Click the wrapper via its stable testid instead.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #e907e4</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/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,139 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const inlineEditorNode = container.querySelector(
+      '.ace_editor',
+    ) as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    // Open, then close, the "edit in modal" dialog. Its own Ace instance
+    // mounts and is destroyed (destroyOnHidden) in the process; this used
+    // to leave the single shared editor ref pointing at that destroyed
+    // instance instead of the still-visible inline editor.
+    // ModalTrigger wraps its triggerNode in its own role="button" element,
+    // so a <Button> triggerNode (as used here) yields two nested elements
+    // matching role "button" with the same accessible name; target the
+    // wrapper directly via its data-test id instead.
+    fireEvent.click(screen.getByTestId('span-modal-trigger'));
+    await waitFor(() => {
+      expect(container.querySelectorAll('.ace_editor')).toHaveLength(2);
+    });

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Portal outside container</b></div>
   <div id="fix">
   
   `ModalTrigger` renders antd `Modal`, which portals to `document.body` (`Modal.tsx` passes no `getContainer` override), so the modal's Ace editor never appears inside RTL's `container`; `toHaveLength(2)` times out. Query `document` (or `screen`) for the modal editor count.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #e907e4</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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4153128587


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&
+      nextValue !== editor.getValue()
+    ) {
+      const cursorPos = editor.getCursorPosition();
+      editor.setValue(nextValue, 1);
+      editor.clearSelection();
+      editor.moveCursorToPosition(cursorPos);
+      lastEditorValueRef.current = nextValue;
+    }
+  }, [initialValue, value]);

Review Comment:
   Same fix as the other `editorRef` thread, split into separate inline/modal refs.



##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&

Review Comment:
   Fixed, `onEditorLoad` now seeds the last-known value from `editor.getValue()` instead of the snapshot taken before the async load, so that case is not missed.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4153126811


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -137,15 +162,8 @@ function TextAreaControl({
   );
 
   const onEditorLoad = useCallback(
-    (editor: {
-      commands: {
-        addCommand: (cmd: {
-          name: string;
-          bindKey: { win: string; mac: string };
-          exec: () => void;
-        }) => void;
-      };
-    }) => {
+    (editor: AceEditorHandle) => {
+      editorRef.current = editor;

Review Comment:
   Fixed, split into separate inline/modal refs that null out on unmount, plus a test covering open close external sync.



##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&
+      nextValue !== editor.getValue()
+    ) {
+      const cursorPos = editor.getCursorPosition();
+      editor.setValue(nextValue, 1);

Review Comment:
   Good catch, fixed. The sync effect now flags its own `setValue()` call so the echoed `onChange` does not get treated as a real edit.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4152031466


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -137,15 +162,8 @@ function TextAreaControl({
   );
 
   const onEditorLoad = useCallback(
-    (editor: {
-      commands: {
-        addCommand: (cmd: {
-          name: string;
-          bindKey: { win: string; mac: string };
-          exec: () => void;
-        }) => void;
-      };
-    }) => {
+    (editor: AceEditorHandle) => {
+      editorRef.current = editor;

Review Comment:
   **Suggestion:** When the modal editor is open, `editorRef` points only to the last-loaded Ace instance, so external updates leave the other editor stale and may target an unmounted editor after closing.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Sometimes` ยท ๐Ÿท๏ธ `Stale reference`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4411ba8bccf1415dab4e2a3a126ac4de&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=4411ba8bccf1415dab4e2a3a126ac4de&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/src/explore/components/controls/TextAreaControl.tsx
   **Line:** 164:166
   **Comment:**
   	*Stale Reference: When the modal editor is open, `editorRef` points only to the last-loaded Ace instance, so external updates leave the other editor stale and may target an unmounted editor after closing.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44858&comment_hash=5f9c58927aaaefb5e3ed11d44da03b601695e6b930c99dee68280bba35e8100e&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44858&comment_hash=5f9c58927aaaefb5e3ed11d44da03b601695e6b930c99dee68280bba35e8100e&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -341,24 +354,38 @@ export default function CRUDCollection({
             return mStr.localeCompare(nStr);
           };
 
+          // Sort the live, edited collection rather than propsCollection, so
+          // an edit that hasn't round-tripped back through onChange yet
+          // isn't dropped when a sort is applied.
+          sortedArray = [...collectionArray];
           sortedArray.sort((a: CollectionItem, b: CollectionItem) =>
             compareSort(a[col] as Sort, b[col] as Sort),
           );
           if (newSortOrder === SortOrderEnum.Desc) {
             sortedArray.reverse();
           }
         } else {
-          const { collectionArray: resetArray } =
-            createKeyedCollection(propsCollection);
-          sortedArray = resetArray;
+          // Restore the pre-sort order, but take each row's current value
+          // from the live `collection` map (not propsCollection) so an edit
+          // made while sorted survives clearing the sort. Any row not part
+          // of the tracked order (e.g. added while sorted) is appended.
+          const trackedIds = new Set(unsortedOrderRef.current);
+          sortedArray = unsortedOrderRef.current
+            .filter(id => collection[id])
+            .map(id => collection[id]);

Review Comment:
   **Suggestion:** If `propsCollection` changes while sorted, `unsortedOrderRef` remains stale; clearing the sort then restores outdated order and can omit or append rows incorrectly.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Sometimes` ยท ๐Ÿท๏ธ `Stale reference`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c49b25e0a3764a78b06a1d3f2fe1e5d8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c49b25e0a3764a78b06a1d3f2fe1e5d8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx
   **Line:** 372:375
   **Comment:**
   	*Stale Reference: If `propsCollection` changes while sorted, `unsortedOrderRef` remains stale; clearing the sort then restores outdated order and can omit or append rows incorrectly.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44858&comment_hash=f996d0fd88f2bd91491562da2f1ee3d4b361f9728eabc3f1ba0366aa19e963a5&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44858&comment_hash=f996d0fd88f2bd91491562da2f1ee3d4b361f9728eabc3f1ba0366aa19e963a5&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&
+      nextValue !== editor.getValue()
+    ) {
+      const cursorPos = editor.getCursorPosition();
+      editor.setValue(nextValue, 1);

Review Comment:
   **Suggestion:** Ace's `setValue` emits its normal change event, so external synchronization calls `onChange` and can be mistaken for a user edit, triggering persistence or validation.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Sometimes` ยท ๐Ÿท๏ธ `Api mismatch`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0c6a32d6d9aa4e8abc413c67f677f944&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=0c6a32d6d9aa4e8abc413c67f677f944&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/src/explore/components/controls/TextAreaControl.tsx
   **Line:** 192:192
   **Comment:**
   	*Api Mismatch: Ace's `setValue` emits its normal change event, so external synchronization calls `onChange` and can be mistaken for a user edit, triggering persistence or validation.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44858&comment_hash=df35ea6661e7893ae4acd1ea022ebfeaca2b4922d58955a6dc1088a84662d1d5&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44858&comment_hash=df35ea6661e7893ae4acd1ea022ebfeaca2b4922d58955a6dc1088a84662d1d5&reaction=dislike'>๐Ÿ‘Ž</a>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4152092436


##########
superset-frontend/src/explore/components/controls/TextAreaControl.tsx:
##########
@@ -157,6 +175,27 @@ function TextAreaControl({
     [hotkeys],
   );
 
+  // Pick up an `initialValue` change that didn't originate from this
+  // editor's own typing (handleChange above would have already updated
+  // lastEditorValueRef for that case), without remounting the Ace instance
+  // or losing the user's current cursor position.
+  useEffect(() => {
+    const nextValue = initialValue ?? value;
+    const editor = editorRef.current;
+    if (
+      editor &&
+      nextValue !== undefined &&
+      nextValue !== lastEditorValueRef.current &&
+      nextValue !== editor.getValue()
+    ) {
+      const cursorPos = editor.getCursorPosition();
+      editor.setValue(nextValue, 1);
+      editor.clearSelection();
+      editor.moveCursorToPosition(cursorPos);
+      lastEditorValueRef.current = nextValue;
+    }
+  }, [initialValue, value]);

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>shared editorRef syncs wrong editor</b></div>
   <div id="fix">
   
   `onEditorLoad` (line 166) sets the single `editorRef.current`, but both the main editor (line 307) and the modal editor (line 298) pass it. antd `Modal` mounts children lazily, so after the user opens 'Edit in modal' once, the modal editor's `onLoad` overwrites `editorRef`. The new sync `useEffect` then calls `setValue` on the hidden modal editor, leaving the visible main editor stale. Track the two editors separately and sync the main one.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #6ca0d0</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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4160657715


##########
superset-frontend/src/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,143 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }

Review Comment:
   Done: the three copies are now one shared `SyncWrapper` taking `onChange`.



##########
superset-frontend/src/components/Datasource/components/CollectionTable/CollectionTable.test.tsx:
##########
@@ -34,3 +34,99 @@ test('renders a table', () => {
   const rows = tableBody?.getElementsByTagName('tr');
   expect(rows).toHaveLength(mockDatasource['7__table'].columns.length);
 });
+
+test('preserves an edit made while sorted after the sort is cleared', () => {
+  const onChange = jest.fn();
+  const collection = [
+    { id: 1, column_name: 'b_col', type: 'VARCHAR' },
+    { id: 2, column_name: 'a_col', type: 'VARCHAR' },
+  ];
+
+  const { container } = render(
+    <CollectionTable
+      collection={collection}
+      tableColumns={['column_name', 'type']}
+      sortColumns={['column_name']}
+      itemRenderers={{
+        type: (val, onItemChange, _label, record) => (
+          <input
+            data-test={`type-input-${record.id}`}
+            value={val as string}
+            onChange={e => onItemChange(e.target.value)}
+          />
+        ),
+      }}
+      onChange={onChange}
+    />,
+  );
+
+  const sorter = container.querySelector('.ant-table-column-sorters');
+  expect(sorter).toBeInTheDocument();
+
+  // Ascending sort by column_name puts a_col (id 2) first.
+  fireEvent.click(sorter!);
+
+  const editedInput = container.querySelector(
+    '[data-test="type-input-2"]',
+  ) as HTMLInputElement;
+  expect(editedInput).toBeInTheDocument();
+  fireEvent.change(editedInput, { target: { value: 'EDITED' } });
+
+  // Cycle the sort back to unsorted (ascend -> descend -> cancel).
+  fireEvent.click(sorter!);

Review Comment:
   Good catch @sadpandajoe. The test now asserts row order and the edited value after the descending click, before clearing the sort.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5981513661

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4174194370


##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -127,15 +127,32 @@ export default function CRUDCollection({
       : 10,
   );
   const [currentPage, setCurrentPage] = useState<number>(1);
+  // The row order to restore when a sort is cleared. Tracked from
+  // collectionArray itself (not propsCollection) so it reflects in-progress
+  // edits whose onChange round trip to the parent hasn't landed back in
+  // props yet.
+  const unsortedOrderRef = useRef<Array<string | number>>(
+    initialKeyed.current!.collectionArray.map(item => item.id),
+  );
 
   // Sync with props.collection changes
   useEffect(() => {
     const { collection: newCollection, collectionArray: newCollectionArray } =
       createKeyedCollection(propsCollection);
     setCollection(newCollection);
     setCollectionArray(newCollectionArray);
+    // Refresh the restore order too, so that clearing a sort after an
+    // external sync (e.g. a source-control-synced column set) reflects the
+    // synced order and row set instead of stale, pre-sync ids.
+    unsortedOrderRef.current = newCollectionArray.map(item => item.id);

Review Comment:
   With a parent that feeds onChange back into `collection`, as DatasourceEditor does, master and this head render identically: the edit survives on both. After an edit while sorted, this line stores the sorted array onCellChange emitted, so clearing the sort keeps sorted order.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5983379202

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #44858:
URL: https://github.com/apache/superset/pull/44858#issuecomment-5927306483

   ### <span aria-hidden="true">โœ…</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">๐Ÿ”จ</span> Latest commit | 1fe979c9a53951c75db420833a4574e028c54be1 |
   |<span aria-hidden="true">๐Ÿ”</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6abe12c87d64b7000961da9b |
   |<span aria-hidden="true">๐Ÿ˜Ž</span> Deploy Preview | [https://deploy-preview-44858--superset-docs-preview.netlify.app](https://deploy-preview-44858--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">๐Ÿ“ฑ</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQ0ODU4LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.BFnKnnktwIP4xbe3GIgW56X3JMvMNkYUhefKpUBuq1s)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">๐Ÿค–</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DctRCoMwDADQu-TbQB2jTm-wY6RNZEI1Nc3AMXb39e_9vC9U0706LAADJKMjv7rX7UImp6Zvy4LCm6thU3Okg7E5FcF2ln5YatHPk_uKlGS85cfE8Z6mEMIcR6Y5we8P) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-44858--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(dataset-editor): preserve edits across sort and sync external SQL changes [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44858:
URL: https://github.com/apache/superset/pull/44858#discussion_r4156906370


##########
superset-frontend/src/explore/components/controls/TextAreaControl.test.tsx:
##########
@@ -61,4 +62,139 @@ describe('TextArea', () => {
     fireEvent.change(textArea, { target: { value: 'x' } });
     expect(defaultProps.onChange).toHaveBeenCalledWith('x');
   });
+
+  test('picks up an externally changed initialValue without remounting the AceEditor', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    // react-ace keeps a reference to the live editor instance on the
+    // container node's `env`, which lets us read the underlying Ace
+    // document directly; jsdom doesn't paint Ace's text layer, so the
+    // rendered DOM has no visible text to assert against.
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+    expect(editorNode.env.editor.getValue()).toBe('first');
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Same editor instance picked up the new value; it was not remounted.
+    expect(container.querySelector('.ace_editor')).toBe(editorNode);
+  });
+
+  test('does not re-notify onChange when an external sync sets the editor value', async () => {
+    const onChange = jest.fn();
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={onChange}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const editorNode = container.querySelector('.ace_editor') as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    fireEvent.click(screen.getByText('sync'));
+
+    await waitFor(() => {
+      expect(editorNode.env.editor.getValue()).toBe('synced-from-source');
+    });
+    // Ace's setValue() fires its own change event; that echo must not be
+    // mistaken for the user typing and bounced back up through onChange.
+    expect(onChange).not.toHaveBeenCalled();
+  });
+
+  test('keeps syncing the inline editor after the edit-in-modal dialog is opened and closed', async () => {
+    function Wrapper() {
+      const [initialValue, setInitialValue] = useState('first');
+      return (
+        <>
+          <button
+            type="button"
+            onClick={() => setInitialValue('synced-from-source')}
+          >
+            sync
+          </button>
+          <TextAreaControl
+            name="expr"
+            language="sql"
+            initialValue={initialValue}
+            onChange={() => {}}
+          />
+        </>
+      );
+    }
+    const { container } = render(<Wrapper />);
+    await waitFor(() => {
+      expect(container.querySelector('.ace_text-input')).toBeInTheDocument();
+    });
+    const inlineEditorNode = container.querySelector(
+      '.ace_editor',
+    ) as HTMLElement & {
+      env: { editor: { getValue: () => string } };
+    };
+
+    // Open, then close, the "edit in modal" dialog. Its own Ace instance
+    // mounts and is destroyed (destroyOnHidden) in the process; this used
+    // to leave the single shared editor ref pointing at that destroyed
+    // instance instead of the still-visible inline editor.
+    // ModalTrigger wraps its triggerNode in its own role="button" element,
+    // so a <Button> triggerNode (as used here) yields two nested elements
+    // matching role "button" with the same accessible name; target the
+    // wrapper directly via its data-test id instead.
+    fireEvent.click(screen.getByTestId('span-modal-trigger'));
+    await waitFor(() => {
+      expect(container.querySelectorAll('.ace_editor')).toHaveLength(2);
+    });

Review Comment:
   <!-- Bito Reply -->
   The change to query `document` instead of `container` is appropriate. Since the modal is rendered via a portal to `document.body`, it exists outside the standard React Testing Library `container` node, making it inaccessible to queries scoped to that container. This adjustment ensures the test correctly detects the modal's editor instance.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org