2021-06-29 04:03:36 -05:00
|
|
|
/////////////////////////////////////////////////////////////
|
|
|
|
//
|
|
|
|
// pgAdmin 4 - PostgreSQL Tools
|
|
|
|
//
|
|
|
|
// Copyright (C) 2013 - 2021, The pgAdmin Development Team
|
|
|
|
// This software is released under the PostgreSQL Licence
|
|
|
|
//
|
|
|
|
//////////////////////////////////////////////////////////////
|
|
|
|
|
|
|
|
import React, { useEffect, useRef } from 'react';
|
|
|
|
import {default as OrigCodeMirror} from 'bundled_codemirror';
|
2021-07-07 07:47:16 -05:00
|
|
|
import {useOnScreen} from 'sources/custom_hooks';
|
2021-06-29 04:03:36 -05:00
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
|
|
|
|
/* React wrapper for CodeMirror */
|
2021-08-16 09:18:08 -05:00
|
|
|
export default function CodeMirror({currObj, name, value, options, events, ...props}) {
|
2021-06-29 04:03:36 -05:00
|
|
|
const taRef = useRef();
|
|
|
|
const cmObj = useRef();
|
2021-07-07 07:47:16 -05:00
|
|
|
const cmWrapper = useRef();
|
|
|
|
const isVisibleTrack = useRef();
|
2021-06-29 04:03:36 -05:00
|
|
|
|
|
|
|
useEffect(()=>{
|
|
|
|
/* Create the object only once on mount */
|
|
|
|
cmObj.current = new OrigCodeMirror.fromTextArea(
|
|
|
|
taRef.current, options);
|
2021-07-07 07:47:16 -05:00
|
|
|
|
2021-08-16 09:18:08 -05:00
|
|
|
currObj && currObj(cmObj.current);
|
|
|
|
|
2021-07-07 07:47:16 -05:00
|
|
|
if(cmObj.current) {
|
|
|
|
try {
|
|
|
|
cmWrapper.current = cmObj.current.getWrapperElement();
|
|
|
|
} catch(e) {
|
|
|
|
cmWrapper.current = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Object.keys(events||{}).forEach((eventName)=>{
|
|
|
|
cmObj.current.on(eventName, events[eventName]);
|
|
|
|
});
|
2021-06-29 04:03:36 -05:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(()=>{
|
2021-07-07 07:47:16 -05:00
|
|
|
/* Refresh when value changes async */
|
|
|
|
if(props.isAsync) {
|
|
|
|
if(cmObj.current) {
|
|
|
|
cmObj.current.setValue(value);
|
|
|
|
cmObj.current.refresh();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [value]);
|
|
|
|
|
|
|
|
const onScreenVisible = useOnScreen(cmWrapper);
|
|
|
|
if(!isVisibleTrack.current && onScreenVisible) {
|
|
|
|
isVisibleTrack.current = true;
|
|
|
|
|
2021-06-29 04:03:36 -05:00
|
|
|
/* Refresh when value changes */
|
|
|
|
if(cmObj.current) {
|
|
|
|
cmObj.current.setValue(value);
|
|
|
|
cmObj.current.refresh();
|
|
|
|
}
|
2021-07-07 07:47:16 -05:00
|
|
|
cmObj.current.refresh();
|
|
|
|
} else if(!onScreenVisible) {
|
|
|
|
isVisibleTrack.current = false;
|
|
|
|
}
|
2021-06-29 04:03:36 -05:00
|
|
|
|
|
|
|
return <textarea ref={taRef} name={name} />;
|
|
|
|
}
|
|
|
|
|
|
|
|
CodeMirror.propTypes = {
|
2021-08-16 09:18:08 -05:00
|
|
|
currObj: PropTypes.func,
|
2021-06-29 04:03:36 -05:00
|
|
|
name: PropTypes.string,
|
|
|
|
value: PropTypes.string,
|
2021-07-07 07:47:16 -05:00
|
|
|
options: PropTypes.object,
|
|
|
|
change: PropTypes.func,
|
|
|
|
events: PropTypes.object,
|
|
|
|
isAsync: PropTypes.bool
|
2021-06-29 04:03:36 -05:00
|
|
|
};
|