Better multi-window updates

This commit is contained in:
Gregory Schier
2023-03-29 21:53:20 -07:00
parent bc40e22008
commit dab2df7e79
16 changed files with 180 additions and 136 deletions

View File

@@ -51,33 +51,6 @@ await listen(
}, UPDATE_DEBOUNCE_MILLIS),
);
await listen(
'updated_request',
debounce(({ payload: request }: { payload: HttpRequest }) => {
if (request.updatedBy === appWindow.label) return;
queryClient.setQueryData(
requestsQueryKey(request.workspaceId),
(requests: HttpRequest[] = []) => {
const newRequests = [];
let found = false;
for (const r of requests) {
if (r.id === request.id) {
found = true;
newRequests.push(request);
} else {
newRequests.push(r);
}
}
if (!found) {
newRequests.push(request);
}
return newRequests;
},
);
}, UPDATE_DEBOUNCE_MILLIS),
);
await listen('updated_response', ({ payload: response }: { payload: HttpResponse }) => {
queryClient.setQueryData(
responsesQueryKey(response.requestId),

View File

@@ -1,6 +1,5 @@
import type { Extension } from '@codemirror/state';
import { useEffect, useMemo, useState } from 'react';
import { useUniqueKey } from '../hooks/useUniqueKey';
import type { HttpRequest } from '../lib/models';
import { sendEphemeralRequest } from '../lib/sendEphemeralRequest';
import type { EditorProps } from './core/Editor';
@@ -13,7 +12,10 @@ import {
} from './core/Editor';
import { Separator } from './core/Separator';
type Props = Pick<EditorProps, 'heightMode' | 'onChange' | 'defaultValue' | 'className'> & {
type Props = Pick<
EditorProps,
'heightMode' | 'onChange' | 'defaultValue' | 'className' | 'forceUpdateKey'
> & {
baseRequest: HttpRequest;
};
@@ -24,7 +26,6 @@ interface GraphQLBody {
}
export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEditorProps }: Props) {
const queryKey = useUniqueKey();
const { query, variables } = useMemo<GraphQLBody>(() => {
if (!defaultValue) {
return { query: '', variables: {} };
@@ -79,7 +80,6 @@ export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEdi
return (
<div className="pb-2 h-full grid grid-rows-[minmax(0,100%)_auto_auto_minmax(0,auto)]">
<Editor
key={queryKey.key}
heightMode="auto"
defaultValue={query ?? ''}
languageExtension={graphqlExtension}

View File

@@ -9,15 +9,17 @@ import type { PairEditorProps } from './core/PairEditor';
import { PairEditor } from './core/PairEditor';
type Props = {
forceUpdateKey: string;
headers: HttpRequest['headers'];
onChange: (headers: HttpRequest['headers']) => void;
};
export function HeaderEditor({ headers, onChange }: Props) {
export function HeaderEditor({ headers, onChange, forceUpdateKey }: Props) {
return (
<PairEditor
pairs={headers}
onChange={onChange}
forceUpdateKey={forceUpdateKey}
nameValidate={validateHttpHeader}
nameAutocomplete={nameAutocomplete}
valueAutocomplete={valueAutocomplete}

View File

@@ -2,10 +2,18 @@ import type { HttpRequest } from '../lib/models';
import { PairEditor } from './core/PairEditor';
type Props = {
forceUpdateKey: string;
parameters: { name: string; value: string }[];
onChange: (headers: HttpRequest['headers']) => void;
};
export function ParametersEditor({ parameters, onChange }: Props) {
return <PairEditor pairs={parameters} onChange={onChange} namePlaceholder="name" />;
export function ParametersEditor({ parameters, forceUpdateKey, onChange }: Props) {
return (
<PairEditor
forceUpdateKey={forceUpdateKey}
pairs={parameters}
onChange={onChange}
namePlaceholder="name"
/>
);
}

View File

@@ -3,8 +3,8 @@ import type { CSSProperties } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useActiveRequest } from '../hooks/useActiveRequest';
import { useKeyValue } from '../hooks/useKeyValue';
import { useRequestUpdateKey } from '../hooks/useRequestUpdateKey';
import { useUpdateRequest } from '../hooks/useUpdateRequest';
import { useWindowFocus } from '../hooks/useWindowFocus';
import { tryFormatJson } from '../lib/formatters';
import type { HttpHeader, HttpRequest } from '../lib/models';
import {
@@ -125,13 +125,7 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
[],
);
const visible = useWindowFocus();
const multiWindowKey = useMemo(() => {
// If the window has focus, don't ever force an update
if (visible) return undefined;
// If the window is not focused, force an update if the request has been updated
return activeRequest?.updatedAt;
}, [visible, activeRequest?.updatedAt]);
const { updateKey: forceUpdateKey } = useRequestUpdateKey(activeRequest?.id ?? null);
return (
<div
@@ -140,12 +134,7 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
>
{activeRequest && (
<>
<UrlBar
key={multiWindowKey}
id={activeRequest.id}
url={activeRequest.url}
method={activeRequest.method}
/>
<UrlBar id={activeRequest.id} url={activeRequest.url} method={activeRequest.method} />
<Tabs
value={activeTab.value}
onChangeValue={activeTab.set}
@@ -156,13 +145,13 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
<TabContent value="auth">
{activeRequest.authenticationType === AUTH_TYPE_BASIC ? (
<BasicAuth
key={multiWindowKey}
key={forceUpdateKey}
requestId={activeRequest.id}
authentication={activeRequest.authentication}
/>
) : activeRequest.authenticationType === AUTH_TYPE_BEARER ? (
<BearerAuth
key={multiWindowKey}
key={forceUpdateKey}
requestId={activeRequest.id}
authentication={activeRequest.authentication}
/>
@@ -174,18 +163,22 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
</TabContent>
<TabContent value="headers">
<HeaderEditor
key={`${forceUpdateHeaderEditorKey}::${multiWindowKey}`}
forceUpdateKey={`${forceUpdateHeaderEditorKey}::${forceUpdateKey}`}
headers={activeRequest.headers}
onChange={handleHeadersChange}
/>
</TabContent>
<TabContent value="params">
<ParametersEditor key={multiWindowKey} parameters={[]} onChange={() => null} />
<ParametersEditor
forceUpdateKey={forceUpdateKey}
parameters={[]}
onChange={() => null}
/>
</TabContent>
<TabContent value="body" className="pl-3 mt-1">
{activeRequest.bodyType === BODY_TYPE_JSON ? (
<Editor
key={multiWindowKey}
forceUpdateKey={forceUpdateKey}
useTemplating
placeholder="..."
className="!bg-gray-50"
@@ -197,7 +190,7 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
/>
) : activeRequest.bodyType === BODY_TYPE_XML ? (
<Editor
key={multiWindowKey}
forceUpdateKey={forceUpdateKey}
useTemplating
placeholder="..."
className="!bg-gray-50"
@@ -208,7 +201,7 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
/>
) : activeRequest.bodyType === BODY_TYPE_GRAPHQL ? (
<GraphQLEditor
key={multiWindowKey}
forceUpdateKey={forceUpdateKey}
baseRequest={activeRequest}
className="!bg-gray-50"
defaultValue={activeRequest?.body ?? ''}

View File

@@ -122,7 +122,7 @@ export const ResponsePane = memo(function ResponsePane({ style, className }: Pro
) : viewMode === 'pretty' && contentType.includes('json') ? (
<Editor
readOnly
key={`${contentType}:${activeResponse.updatedAt}:pretty`}
forceUpdateKey={activeResponse.updatedAt}
className="bg-gray-50 dark:!bg-gray-100"
defaultValue={tryFormatJson(activeResponse?.body)}
contentType={contentType}
@@ -130,7 +130,7 @@ export const ResponsePane = memo(function ResponsePane({ style, className }: Pro
) : activeResponse?.body ? (
<Editor
readOnly
key={`${contentType}:${activeResponse.updatedAt}`}
forceUpdateKey={activeResponse.updatedAt}
className="bg-gray-50 dark:!bg-gray-100"
defaultValue={activeResponse?.body}
contentType={contentType}

View File

@@ -2,6 +2,7 @@ import classnames from 'classnames';
import type { FormEvent } from 'react';
import { memo, useCallback } from 'react';
import { useIsResponseLoading } from '../hooks/useIsResponseLoading';
import { useRequestUpdateKey } from '../hooks/useRequestUpdateKey';
import { useSendRequest } from '../hooks/useSendRequest';
import { useUpdateRequest } from '../hooks/useUpdateRequest';
import type { HttpRequest } from '../lib/models';
@@ -19,6 +20,7 @@ export const UrlBar = memo(function UrlBar({ id: requestId, url, method, classNa
const handleMethodChange = useCallback((method: string) => updateRequest.mutate({ method }), []);
const handleUrlChange = useCallback((url: string) => updateRequest.mutate({ url }), []);
const loading = useIsResponseLoading(requestId);
const { updateKey } = useRequestUpdateKey(requestId);
const handleSubmit = useCallback(
async (e: FormEvent) => {
@@ -32,13 +34,13 @@ export const UrlBar = memo(function UrlBar({ id: requestId, url, method, classNa
<form onSubmit={handleSubmit} className={classnames('url-bar', className)}>
<Input
size="sm"
key={requestId}
hideLabel
useTemplating
contentType="url"
className="px-0"
name="url"
label="Enter URL"
forceUpdateKey={updateKey}
containerClassName="shadow shadow-gray-100 dark:shadow-gray-50"
onChange={handleUrlChange}
defaultValue={url}

View File

@@ -1,6 +1,7 @@
import { defaultKeymap } from '@codemirror/commands';
import type { Extension } from '@codemirror/state';
import { Compartment, EditorState } from '@codemirror/state';
import { Compartment, EditorState, Transaction } from '@codemirror/state';
import type { ViewUpdate } from '@codemirror/view';
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
import classnames from 'classnames';
import { EditorView } from 'codemirror';
@@ -19,6 +20,7 @@ export { formatSdl } from 'format-graphql';
export interface EditorProps {
id?: string;
forceUpdateKey?: string;
readOnly?: boolean;
type?: 'text' | 'password';
className?: string;
@@ -42,6 +44,7 @@ export function Editor({
type = 'text',
heightMode,
contentType,
forceUpdateKey,
autoFocus,
placeholder,
useTemplating,
@@ -87,6 +90,15 @@ export function Editor({
view.dispatch({ effects: languageCompartment.reconfigure(ext) });
}, [contentType, autocomplete]);
useEffect(() => {
if (cm.current === null) return;
const { view, languageCompartment } = cm.current;
const newDoc = defaultValue;
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: newDoc ?? '' } });
const ext = getLanguageExtension({ contentType, useTemplating, autocomplete });
view.dispatch({ effects: languageCompartment.reconfigure(ext) });
}, [forceUpdateKey]);
// Initialize the editor when ref mounts
useEffect(() => {
if (wrapperRef.current === null || cm.current !== null) return;
@@ -218,13 +230,27 @@ function getExtensions({
// Handle onChange
EditorView.updateListener.of((update) => {
if (onChange && update.docChanged) {
if (onChange && update.docChanged && isViewUpdateFromUserInput(update)) {
onChange.current?.(update.state.doc.toString());
}
}),
];
}
function isViewUpdateFromUserInput(viewUpdate: ViewUpdate) {
// Make sure document has changed, ensuring user events like selections don't count.
if (viewUpdate.docChanged) {
// Check transactions for any that are direct user input, not changes from Y.js or another extension.
for (const transaction of viewUpdate.transactions) {
// Not using Transaction.isUserEvent because that only checks for a specific User event type ( "input", "delete", etc.). Checking the annotation directly allows for any type of user event.
const userEventType = transaction.annotation(Transaction.userEvent);
if (userEventType) return userEventType;
}
}
return false;
}
const syncGutterBg = ({
parent,
className = '',

View File

@@ -7,7 +7,7 @@ import { IconButton } from './IconButton';
import { HStack, VStack } from './Stacks';
export type InputProps = Omit<HTMLAttributes<HTMLInputElement>, 'onChange' | 'onFocus'> &
Pick<EditorProps, 'contentType' | 'useTemplating' | 'autocomplete'> & {
Pick<EditorProps, 'contentType' | 'useTemplating' | 'autocomplete' | 'forceUpdateKey'> & {
name: string;
type?: 'text' | 'password';
label: string;

View File

@@ -14,6 +14,7 @@ import { Input } from './Input';
export type PairEditorProps = {
pairs: Pair[];
onChange: (pairs: Pair[]) => void;
forceUpdateKey?: string;
className?: string;
namePlaceholder?: string;
valuePlaceholder?: string;
@@ -36,6 +37,7 @@ type PairContainer = {
export const PairEditor = memo(function PairEditor({
pairs: originalPairs,
forceUpdateKey,
nameAutocomplete,
valueAutocomplete,
namePlaceholder,
@@ -53,6 +55,15 @@ export const PairEditor = memo(function PairEditor({
return [...pairs, newPairContainer()];
});
useEffect(() => {
// Remove empty headers on initial render
// TODO: Make this not refresh the entire editor when forceUpdateKey changes, using some
// sort of diff method or deterministic IDs based on array index and update key
const nonEmpty = originalPairs.filter((h) => !(h.name === '' && h.value === ''));
const pairs = nonEmpty.map((pair) => newPairContainer(pair));
setPairs([...pairs, newPairContainer()]);
}, [forceUpdateKey]);
const setPairsAndSave = useCallback(
(fn: (pairs: PairContainer[]) => PairContainer[]) => {
setPairs((oldPairs) => {
@@ -139,6 +150,7 @@ export const PairEditor = memo(function PairEditor({
pairContainer={p}
className="py-1"
isLast={isLast}
forceUpdateKey={forceUpdateKey}
nameAutocomplete={nameAutocomplete}
valueAutocomplete={valueAutocomplete}
namePlaceholder={namePlaceholder}
@@ -179,6 +191,7 @@ type FormRowProps = {
| 'valuePlaceholder'
| 'nameValidate'
| 'valueValidate'
| 'forceUpdateKey'
>;
const FormRow = memo(function FormRow({
@@ -190,6 +203,7 @@ const FormRow = memo(function FormRow({
onMove,
onEnd,
isLast,
forceUpdateKey,
nameAutocomplete,
valueAutocomplete,
namePlaceholder,
@@ -287,6 +301,7 @@ const FormRow = memo(function FormRow({
require={!isLast && !!pairContainer.pair.enabled && !!pairContainer.pair.value}
validate={nameValidate}
useTemplating
forceUpdateKey={forceUpdateKey}
containerClassName={classnames(isLast && 'border-dashed')}
defaultValue={pairContainer.pair.name}
label="Name"
@@ -301,6 +316,7 @@ const FormRow = memo(function FormRow({
size="sm"
containerClassName={classnames(isLast && 'border-dashed')}
validate={valueValidate}
forceUpdateKey={forceUpdateKey}
defaultValue={pairContainer.pair.value}
label="Value"
name="value"

View File

@@ -0,0 +1,14 @@
import { createGlobalState } from 'react-use';
import { generateId } from '../lib/generateId';
const useGlobalState = createGlobalState<Record<string, string>>({});
export function useRequestUpdateKey(requestId: string | null) {
const [keys, setKeys] = useGlobalState();
return {
updateKey: `${requestId}::${keys[requestId ?? 'n/a']}`,
wasUpdatedExternally: (changedRequestId: string) => {
setKeys((m) => ({ ...m, [changedRequestId]: generateId() }));
},
};
}

View File

@@ -1,23 +1,62 @@
import { listen } from '@tauri-apps/api/event';
import { useQueryClient } from '@tanstack/react-query';
import { appWindow } from '@tauri-apps/api/window';
import { useEffect } from 'react';
import { debounce } from '../lib/debounce';
import type { HttpRequest } from '../lib/models';
import { requestsQueryKey } from './useRequests';
import { useRequestUpdateKey } from './useRequestUpdateKey';
import { useSidebarDisplay } from './useSidebarDisplay';
const unsubFns: (() => void)[] = [];
const UPDATE_DEBOUNCE_MILLIS = 500;
export function useTauriListeners() {
const sidebarDisplay = useSidebarDisplay();
const queryClient = useQueryClient();
const { wasUpdatedExternally } = useRequestUpdateKey(null);
useEffect(() => {
let unmounted = false;
listen('toggle_sidebar', async () => {
sidebarDisplay.toggle();
}).then((fn) => {
if (unmounted) {
fn();
} else {
unsubFns.push(fn);
}
});
appWindow
.listen('toggle_sidebar', async () => {
sidebarDisplay.toggle();
})
.then((unsub) => {
if (unmounted) unsub();
else unsubFns.push(unsub);
});
appWindow
.listen(
'updated_request',
debounce(({ payload: request }: { payload: HttpRequest }) => {
queryClient.setQueryData(
requestsQueryKey(request.workspaceId),
(requests: HttpRequest[] = []) => {
const newRequests = [];
let found = false;
for (const r of requests) {
if (r.id === request.id) {
found = true;
newRequests.push(request);
} else {
newRequests.push(r);
}
}
if (!found) {
newRequests.push(request);
}
setTimeout(() => wasUpdatedExternally(request.id), 50);
return newRequests;
},
);
}, UPDATE_DEBOUNCE_MILLIS),
)
.then((unsub) => {
if (unmounted) unsub();
else unsubFns.push(unsub);
});
return () => {
unmounted = true;

View File

@@ -2,7 +2,7 @@ import { useState } from 'react';
export function useUniqueKey(len = 10): { key: string; regenerate: () => void } {
const [key, setKey] = useState<string>(() => generate(len));
return { key, regenerate: () => setKey(generate(len)) };
return { key, wasUpdatedExternally: () => setKey(generate(len)) };
}
const CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

View File

@@ -0,0 +1,3 @@
export function generateId(): string {
return Math.random().toString(36).slice(2);
}