Skip to content

Commit

Permalink
[CodeEditor] Explicitly call the latest props.onChange (elastic#176296
Browse files Browse the repository at this point in the history
)

## Summary

fix elastic#175684

Refer to the issue elastic#175684 for
the problem and reproduction


I tested that this fixes the issue using the story from the reproduction
elastic#175670 and the URL drilldown's
placeholder issue explained in
elastic#175684
  • Loading branch information
Dosant authored and CoenWarmer committed Feb 15, 2024
1 parent 6af1136 commit 06701a4
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion packages/shared-ux/code_editor/impl/code_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export interface CodeEditorProps {
export const CodeEditor: React.FC<CodeEditorProps> = ({
languageId,
value,
onChange,
onChange: _onChange,
width,
height,
options,
Expand Down Expand Up @@ -206,6 +206,8 @@ export const CodeEditor: React.FC<CodeEditorProps> = ({

const [isHintActive, setIsHintActive] = useState(true);

const onChange = useBug175684OnChange(_onChange);

const startEditing = useCallback(() => {
setIsHintActive(false);
_editor?.focus();
Expand Down Expand Up @@ -676,3 +678,20 @@ const useFitToContent = ({
};
}, [editor, isFitToContent, minLines, maxLines, isFullScreen]);
};

// https://github.com/elastic/kibana/issues/175684
// 'react-monaco-editor' has a bug that it always calls the initial onChange callback, so the closure might become stale
// we work this around by calling the latest onChange from props
const useBug175684OnChange = (onChange: CodeEditorProps['onChange']) => {
const onChangePropRef = useRef<CodeEditorProps['onChange']>(onChange);
useEffect(() => {
onChangePropRef.current = onChange;
}, [onChange]);
const onChangeWrapper = useCallback<NonNullable<CodeEditorProps['onChange']>>((_value, event) => {
if (onChangePropRef.current) {
onChangePropRef.current(_value, event);
}
}, []);

return onChangeWrapper;
};

0 comments on commit 06701a4

Please sign in to comment.