Finally fix the editor!

This commit is contained in:
Gregory Schier
2023-03-31 15:56:35 -07:00
parent 94a3ae3696
commit d36623ebc9
4 changed files with 70 additions and 80 deletions

View File

@@ -215,7 +215,9 @@ async fn actually_send_ephemeral_request(
response = models::update_response_if_id(response, pool) response = models::update_response_if_id(response, pool)
.await .await
.expect("Failed to update response"); .expect("Failed to update response");
emit_side_effect(app_handle, "updated_model", &response); if request.id != "" {
emit_side_effect(app_handle, "updated_model", &response);
}
Ok(response) Ok(response)
} }
Err(e) => response_err(response, e.to_string(), app_handle, pool).await, Err(e) => response_err(response, e.to_string(), app_handle, pool).await,

View File

@@ -1,15 +1,10 @@
import type { Extension } from '@codemirror/state'; import { updateSchema } from 'cm6-graphql';
import { useEffect, useMemo, useState } from 'react'; import type { EditorView } from 'codemirror';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import type { HttpRequest } from '../lib/models'; import type { HttpRequest } from '../lib/models';
import { sendEphemeralRequest } from '../lib/sendEphemeralRequest'; import { sendEphemeralRequest } from '../lib/sendEphemeralRequest';
import type { EditorProps } from './core/Editor'; import type { EditorProps } from './core/Editor';
import { import { buildClientSchema, Editor, formatGraphQL, getIntrospectionQuery } from './core/Editor';
buildClientSchema,
Editor,
formatGraphQL,
getIntrospectionQuery,
graphql,
} from './core/Editor';
import { Separator } from './core/Separator'; import { Separator } from './core/Separator';
type Props = Pick< type Props = Pick<
@@ -41,23 +36,28 @@ export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEdi
} }
}, [defaultValue]); }, [defaultValue]);
const handleChange = (b: GraphQLBody) => { const handleChange = useCallback(
onChange?.(JSON.stringify(b, null, 2)); (b: GraphQLBody) => onChange?.(JSON.stringify(b, null, 2)),
}; [onChange],
);
const handleChangeQuery = (query: string) => { const handleChangeQuery = useCallback(
handleChange({ query, variables }); (query: string) => handleChange({ query, variables }),
}; [handleChange],
);
const handleChangeVariables = (variables: string) => { const handleChangeVariables = useCallback(
try { (variables: string) => {
handleChange({ query, variables: JSON.parse(variables) }); try {
} catch (e) { handleChange({ query, variables: JSON.parse(variables) });
// Meh, not much we can do here } catch (e) {
} // Meh, not much we can do here
}; }
},
[handleChange],
);
const [graphqlExtension, setGraphqlExtension] = useState<Extension>(); const editorViewRef = useRef<EditorView>(null);
useEffect(() => { useEffect(() => {
const body = JSON.stringify({ const body = JSON.stringify({
@@ -67,9 +67,11 @@ export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEdi
const req: HttpRequest = { ...baseRequest, body, id: '' }; const req: HttpRequest = { ...baseRequest, body, id: '' };
sendEphemeralRequest(req).then((response) => { sendEphemeralRequest(req).then((response) => {
try { try {
const { data } = JSON.parse(response.body); if (editorViewRef.current) {
const schema = buildClientSchema(data); const { data } = JSON.parse(response.body);
setGraphqlExtension(graphql(schema, {})); const schema = buildClientSchema(data);
updateSchema(editorViewRef.current, schema);
}
} catch (err) { } catch (err) {
console.log('Failed to parse introspection query', err); console.log('Failed to parse introspection query', err);
return; return;
@@ -80,9 +82,9 @@ export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEdi
return ( return (
<div className="pb-2 h-full grid grid-rows-[minmax(0,100%)_auto_auto_minmax(0,auto)]"> <div className="pb-2 h-full grid grid-rows-[minmax(0,100%)_auto_auto_minmax(0,auto)]">
<Editor <Editor
ref={editorViewRef}
heightMode="auto" heightMode="auto"
defaultValue={query ?? ''} defaultValue={query ?? ''}
languageExtension={graphqlExtension}
onChange={handleChangeQuery} onChange={handleChangeQuery}
contentType="application/graphql" contentType="application/graphql"
placeholder="..." placeholder="..."

View File

@@ -1,13 +1,11 @@
import { defaultKeymap } from '@codemirror/commands'; import { defaultKeymap } from '@codemirror/commands';
import type { Extension } from '@codemirror/state';
import { Compartment, EditorState, Transaction } from '@codemirror/state'; import { Compartment, EditorState, Transaction } from '@codemirror/state';
import type { ViewUpdate } from '@codemirror/view'; import type { ViewUpdate } from '@codemirror/view';
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view'; import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
import classnames from 'classnames'; import classnames from 'classnames';
import { EditorView } from 'codemirror'; import { EditorView } from 'codemirror';
import type { MutableRefObject } from 'react'; import type { MutableRefObject } from 'react';
import { memo, useEffect, useRef } from 'react'; import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react';
import { useUnmount } from 'react-use';
import { IconButton } from '../IconButton'; import { IconButton } from '../IconButton';
import './Editor.css'; import './Editor.css';
import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions'; import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions';
@@ -26,7 +24,6 @@ export interface EditorProps {
className?: string; className?: string;
heightMode?: 'auto' | 'full'; heightMode?: 'auto' | 'full';
contentType?: string; contentType?: string;
languageExtension?: Extension;
forceUpdateKey?: string; forceUpdateKey?: string;
autoFocus?: boolean; autoFocus?: boolean;
defaultValue?: string; defaultValue?: string;
@@ -40,45 +37,28 @@ export interface EditorProps {
autocomplete?: GenericCompletionConfig; autocomplete?: GenericCompletionConfig;
} }
export function Editor({ defaultValue, forceUpdateKey, ...props }: EditorProps) { export const Editor = forwardRef<EditorView | undefined, EditorProps>(function Editor(
// In order to not have the editor render too much, we combine forceUpdateKey {
// here with default value so that we only send new props to the editor when readOnly,
// forceUpdateKey changes. The editor can then use the defaultValue to force type = 'text',
// update instead of using both forceUpdateKey and defaultValue. heightMode,
// contentType,
// NOTE: This was originally done to fix a bug where the editor would unmount autoFocus,
// and remount after the first change event, something to do with React placeholder,
// StrictMode. This fixes it, though, and actually makes more sense useTemplating,
// const fixedDefaultValue = useMemo(() => defaultValue, [forceUpdateKey, props.type]); defaultValue,
return <_Editor defaultValue={defaultValue} forceUpdateKey={forceUpdateKey} {...props} />; forceUpdateKey,
} onChange,
onFocus,
const _Editor = memo(function _Editor({ className,
readOnly, singleLine,
type = 'text', format,
heightMode, autocomplete,
contentType, }: EditorProps,
autoFocus, ref,
placeholder, ) {
useTemplating,
defaultValue,
forceUpdateKey,
languageExtension,
onChange,
onFocus,
className,
singleLine,
format,
autocomplete,
}: EditorProps) {
const cm = useRef<{ view: EditorView; languageCompartment: Compartment } | null>(null); const cm = useRef<{ view: EditorView; languageCompartment: Compartment } | null>(null);
const wrapperRef = useRef<HTMLDivElement | null>(null); useImperativeHandle(ref, () => cm.current?.view);
// Unmount editor when we're done
useUnmount(() => {
cm.current?.view.destroy();
cm.current = null;
});
// Use ref so we can update the onChange handler without re-initializing the editor // Use ref so we can update the onChange handler without re-initializing the editor
const handleChange = useRef<EditorProps['onChange']>(onChange); const handleChange = useRef<EditorProps['onChange']>(onChange);
@@ -117,13 +97,18 @@ const _Editor = memo(function _Editor({
}, [forceUpdateKey]); }, [forceUpdateKey]);
// Initialize the editor when ref mounts // Initialize the editor when ref mounts
useEffect(() => { const initEditorRef = useCallback((container: HTMLDivElement | null) => {
if (wrapperRef.current === null || cm.current !== null) return; if (container === null) {
cm.current?.view.destroy();
cm.current = null;
return;
}
let view: EditorView; let view: EditorView;
try { try {
const languageCompartment = new Compartment(); const languageCompartment = new Compartment();
const langExt = const langExt = getLanguageExtension({ contentType, useTemplating, autocomplete });
languageExtension ?? getLanguageExtension({ contentType, useTemplating, autocomplete });
const state = EditorState.create({ const state = EditorState.create({
doc: `${defaultValue ?? ''}`, doc: `${defaultValue ?? ''}`,
extensions: [ extensions: [
@@ -132,7 +117,7 @@ const _Editor = memo(function _Editor({
placeholderExt(placeholderElFromText(placeholder ?? '')), placeholderExt(placeholderElFromText(placeholder ?? '')),
), ),
...getExtensions({ ...getExtensions({
container: wrapperRef.current, container,
onChange: handleChange, onChange: handleChange,
onFocus: handleFocus, onFocus: handleFocus,
readOnly, readOnly,
@@ -140,18 +125,19 @@ const _Editor = memo(function _Editor({
}), }),
], ],
}); });
view = new EditorView({ state, parent: wrapperRef.current });
view = new EditorView({ state, parent: container });
cm.current = { view, languageCompartment }; cm.current = { view, languageCompartment };
syncGutterBg({ parent: wrapperRef.current, className }); syncGutterBg({ parent: container, className });
if (autoFocus) view.focus(); if (autoFocus) view.focus();
} catch (e) { } catch (e) {
console.log('Failed to initialize Codemirror', e); console.log('Failed to initialize Codemirror', e);
} }
}, [wrapperRef.current, languageExtension]); }, []);
const cmContainer = ( const cmContainer = (
<div <div
ref={wrapperRef} ref={initEditorRef}
className={classnames( className={classnames(
className, className,
'cm-wrapper text-base bg-gray-50', 'cm-wrapper text-base bg-gray-50',

View File

@@ -144,7 +144,7 @@ export const TabContent = memo(function TabContent({
<div <div
tabIndex={-1} tabIndex={-1}
data-tab={value} data-tab={value}
className={classnames(className, 'tab-content', 'w-full h-full')} className={classnames(className, 'tab-content', 'hidden w-full h-full')}
> >
{children} {children}
</div> </div>