import type {ReactFunctionLocation, ReactCallSite} from 'shared/ReactTypes';
import {useCallback, useContext, useSyncExternalStore} from 'react';
import ViewElementSourceContext from './Components/ViewElementSourceContext';
import {getAlwaysOpenInEditor} from '../../utils';
import useEditorURL from './useEditorURL';
import {LOCAL_STORAGE_ALWAYS_OPEN_IN_EDITOR} from '../../constants';
import {checkConditions} from './Editor/utils';
const useOpenResource = (
source: null | ReactFunctionLocation | ReactCallSite,
symbolicatedSource: null | ReactFunctionLocation | ReactCallSite,
): [
boolean,
() => void,
] => {
const {canViewElementSourceFunction, viewElementSourceFunction} = useContext(
ViewElementSourceContext,
);
const editorURL = useEditorURL();
const alwaysOpenInEditor = useSyncExternalStore(
useCallback(function subscribe(callback) {
window.addEventListener(LOCAL_STORAGE_ALWAYS_OPEN_IN_EDITOR, callback);
return function unsubscribe() {
window.removeEventListener(
LOCAL_STORAGE_ALWAYS_OPEN_IN_EDITOR,
callback,
);
};
}, []),
getAlwaysOpenInEditor,
);
const openInEditor =
alwaysOpenInEditor && source !== null
? checkConditions(editorURL, symbolicatedSource || source)
: null;
const linkIsEnabled =
(openInEditor !== null && !openInEditor.shouldDisableButton) ||
(viewElementSourceFunction != null &&
source != null &&
(canViewElementSourceFunction == null ||
canViewElementSourceFunction(source, symbolicatedSource)));
const viewSource = useCallback(() => {
if (openInEditor !== null && !openInEditor.shouldDisableButton) {
window.open(openInEditor.url);
} else if (viewElementSourceFunction != null && source != null) {
viewElementSourceFunction(source, symbolicatedSource);
}
}, [openInEditor, source, symbolicatedSource]);
return [linkIsEnabled, viewSource];
};
export default useOpenResource;