Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[CodeEditor] Explicitly call the latest props.onChange #176296

Merged
merged 2 commits into from
Feb 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
};