Move some things around

This commit is contained in:
Gregory Schier
2023-03-08 23:20:15 -08:00
parent 92ec514442
commit d1b5b9c371
19 changed files with 617 additions and 705 deletions

View File

@@ -137,7 +137,7 @@ const DropdownMenuContent = forwardRef<HTMLDivElement, D.DropdownMenuContentProp
align="start"
className={classnames(
className,
'bg-background rounded-md shadow-lg p-1.5 border border-gray-200',
'bg-gray-50 rounded-md shadow-lg p-1.5 border border-gray-200',
'overflow-auto m-1',
)}
style={styles}

View File

@@ -144,7 +144,7 @@
/* NOTE: Extra selector required to override default styles */
.cm-tooltip.cm-tooltip {
@apply shadow-lg bg-background rounded overflow-hidden text-gray-900 border border-gray-200 z-50 pointer-events-auto;
@apply shadow-lg bg-gray-50 rounded overflow-hidden text-gray-900 border border-gray-200 z-50 pointer-events-auto;
* {
@apply transition-none;

View File

@@ -1,194 +1,4 @@
import { defaultKeymap } from '@codemirror/commands';
import { Compartment, EditorState } from '@codemirror/state';
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
import classnames from 'classnames';
import { EditorView } from 'codemirror';
import type { HTMLAttributes } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import './Editor.css';
import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions';
import { singleLineExt } from './singleLine';
export interface EditorProps extends Omit<HTMLAttributes<HTMLDivElement>, 'onChange'> {
readOnly?: boolean;
heightMode?: 'auto' | 'full';
contentType?: string;
autoFocus?: boolean;
valueKey?: string | number;
defaultValue?: string;
placeholder?: string;
tooltipContainer?: HTMLElement;
useTemplating?: boolean;
onChange?: (value: string) => void;
singleLine?: boolean;
}
export default function Editor({
readOnly,
heightMode,
contentType,
autoFocus,
placeholder,
valueKey,
useTemplating,
defaultValue,
onChange,
className,
singleLine,
...props
}: EditorProps) {
const [cm, setCm] = useState<{ view: EditorView; langHolder: Compartment } | null>(null);
const ref = useRef<HTMLDivElement>(null);
const extensions = useMemo(
() =>
getExtensions({
container: ref.current,
readOnly,
placeholder,
singleLine,
onChange,
contentType,
useTemplating,
}),
[contentType, ref.current],
);
const syncGutterBg = () => {
if (ref.current === null) return;
if (singleLine) return;
const gutterEl = ref.current.querySelector<HTMLDivElement>('.cm-gutters');
const classList = className?.split(/\s+/) ?? [];
const bgClasses = classList
.filter((c) => c.match(/(^|:)?bg-.+/)) // Find bg-* classes
.map((c) => c.replace(/^bg-/, '!bg-')) // !important
.map((c) => c.replace(/^dark:bg-/, 'dark:!bg-')); // !important
if (gutterEl) {
gutterEl?.classList.add(...bgClasses);
}
};
// Create codemirror instance when ref initializes
useEffect(() => {
if (ref.current === null) return;
// console.log('INIT EDITOR');
let view: EditorView | null = null;
try {
const langHolder = new Compartment();
const langExt = getLanguageExtension({ contentType, useTemplating });
const state = EditorState.create({
doc: `${defaultValue ?? ''}`,
extensions: [...extensions, langHolder.of(langExt)],
});
view = new EditorView({
state,
parent: ref.current,
});
setCm({ view, langHolder });
syncGutterBg();
if (autoFocus && view) view.focus();
} catch (e) {
console.log('Failed to initialize Codemirror', e);
}
return () => view?.destroy();
}, [ref.current, valueKey]);
// Update value when valueKey changes
// TODO: This would be more efficient but the onChange handler gets fired on update
// useEffect(() => {
// if (cm === null) return;
// console.log('NEW DOC', valueKey, defaultValue);
// cm.view.dispatch({
// changes: { from: 0, to: cm.view.state.doc.length, insert: `${defaultValue ?? ''}` },
// });
// }, [valueKey]);
// Update language extension when contentType changes
useEffect(() => {
if (cm === null) return;
// console.log('UPDATE LANG');
const ext = getLanguageExtension({ contentType, useTemplating });
cm.view.dispatch({ effects: cm.langHolder.reconfigure(ext) });
}, [contentType]);
return (
<div
ref={ref}
dangerouslySetInnerHTML={{ __html: '' }}
className={classnames(
className,
'cm-wrapper text-base bg-background',
heightMode === 'auto' ? 'cm-auto-height' : 'cm-full-height',
singleLine ? 'cm-singleline' : 'cm-multiline',
readOnly && 'cm-readonly',
)}
{...props}
/>
);
}
function getExtensions({
container,
readOnly,
singleLine,
placeholder,
onChange,
contentType,
useTemplating,
}: Pick<
EditorProps,
'singleLine' | 'onChange' | 'contentType' | 'useTemplating' | 'placeholder' | 'readOnly'
> & { container: HTMLDivElement | null }) {
const ext = getLanguageExtension({ contentType, useTemplating });
// TODO: Ensure tooltips render inside the dialog if we are in one.
const parent =
container?.closest<HTMLDivElement>('[role="dialog"]') ??
document.querySelector<HTMLDivElement>('#cm-portal') ??
undefined;
return [
...baseExtensions,
tooltips({ parent }),
keymap.of(singleLine ? defaultKeymap.filter((k) => k.key !== 'Enter') : defaultKeymap),
...(singleLine ? [singleLineExt()] : []),
...(!singleLine ? [multiLineExtensions] : []),
...(ext ? [ext] : []),
...(readOnly ? [EditorState.readOnly.of(true)] : []),
...(placeholder ? [placeholderExt(placeholder)] : []),
...(singleLine
? [
EditorView.domEventHandlers({
focus: (e, view) => {
// select all text on focus, like a regular input does
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
},
keydown: (e) => {
// Submit nearest form on enter if there is one
if (e.key === 'Enter') {
const el = e.currentTarget as HTMLElement;
const form = el.closest('form');
form?.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
}
},
}),
]
: []),
// Clear selection on blur
EditorView.domEventHandlers({
blur: (e, view) => {
setTimeout(() => {
view.dispatch({ selection: { anchor: 0, head: 0 } });
}, 100);
},
}),
// Handle onChange
EditorView.updateListener.of((update) => {
if (typeof onChange === 'function' && update.docChanged) {
onChange(update.state.doc.toString());
}
}),
];
}
import type { EditorProps } from './_Editor';
const { default: Editor } = await import('./_Editor');
export { Editor };
export type { EditorProps };

View File

@@ -0,0 +1,196 @@
import { defaultKeymap } from '@codemirror/commands';
import { Compartment, EditorState } from '@codemirror/state';
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
import classnames from 'classnames';
import { EditorView } from 'codemirror';
import type { HTMLAttributes } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
const { baseExtensions, getLanguageExtension, multiLineExtensions } = await import('./extensions');
import { singleLineExt } from './singleLine';
import './Editor.css';
export interface EditorProps extends Omit<HTMLAttributes<HTMLDivElement>, 'onChange'> {
readOnly?: boolean;
heightMode?: 'auto' | 'full';
contentType?: string;
autoFocus?: boolean;
valueKey?: string | number;
defaultValue?: string;
placeholder?: string;
tooltipContainer?: HTMLElement;
useTemplating?: boolean;
onChange?: (value: string) => void;
singleLine?: boolean;
}
export default function Editor({
readOnly,
heightMode,
contentType,
autoFocus,
placeholder,
valueKey,
useTemplating,
defaultValue,
onChange,
className,
singleLine,
...props
}: EditorProps) {
const [cm, setCm] = useState<{ view: EditorView; langHolder: Compartment } | null>(null);
const ref = useRef<HTMLDivElement>(null);
const extensions = useMemo(
() =>
getExtensions({
container: ref.current,
readOnly,
placeholder,
singleLine,
onChange,
contentType,
useTemplating,
}),
[contentType, ref.current],
);
// Create codemirror instance when ref initializes
useEffect(() => {
const parent = ref.current;
if (parent === null) return;
// console.log('INIT EDITOR');
let view: EditorView | null = null;
try {
const langHolder = new Compartment();
const langExt = getLanguageExtension({ contentType, useTemplating });
const state = EditorState.create({
doc: `${defaultValue ?? ''}`,
extensions: [...extensions, langHolder.of(langExt)],
});
view = new EditorView({ state, parent });
syncGutterBg({ parent, className });
setCm({ view, langHolder });
if (autoFocus && view) view.focus();
} catch (e) {
console.log('Failed to initialize Codemirror', e);
}
return () => view?.destroy();
}, [ref.current, valueKey]);
// Update value when valueKey changes
// TODO: This would be more efficient but the onChange handler gets fired on update
// useEffect(() => {
// if (cm === null) return;
// console.log('NEW DOC', valueKey, defaultValue);
// cm.view.dispatch({
// changes: { from: 0, to: cm.view.state.doc.length, insert: `${defaultValue ?? ''}` },
// });
// }, [valueKey]);
// Update language extension when contentType changes
useEffect(() => {
if (cm === null) return;
// console.log('UPDATE LANG');
const ext = getLanguageExtension({ contentType, useTemplating });
cm.view.dispatch({ effects: cm.langHolder.reconfigure(ext) });
}, [contentType]);
return (
<div
ref={ref}
className={classnames(
className,
'cm-wrapper text-base bg-gray-50',
heightMode === 'auto' ? 'cm-auto-height' : 'cm-full-height',
singleLine ? 'cm-singleline' : 'cm-multiline',
readOnly && 'cm-readonly',
)}
{...props}
/>
);
}
function getExtensions({
container,
readOnly,
singleLine,
placeholder,
onChange,
contentType,
useTemplating,
}: Pick<
EditorProps,
'singleLine' | 'onChange' | 'contentType' | 'useTemplating' | 'placeholder' | 'readOnly'
> & { container: HTMLDivElement | null }) {
const ext = getLanguageExtension({ contentType, useTemplating });
// TODO: Ensure tooltips render inside the dialog if we are in one.
const parent =
container?.closest<HTMLDivElement>('[role="dialog"]') ??
document.querySelector<HTMLDivElement>('#cm-portal') ??
undefined;
return [
...baseExtensions,
tooltips({ parent }),
keymap.of(singleLine ? defaultKeymap.filter((k) => k.key !== 'Enter') : defaultKeymap),
...(singleLine ? [singleLineExt()] : []),
...(!singleLine ? [multiLineExtensions] : []),
...(ext ? [ext] : []),
...(readOnly ? [EditorState.readOnly.of(true)] : []),
...(placeholder ? [placeholderExt(placeholder)] : []),
...(singleLine
? [
EditorView.domEventHandlers({
focus: (e, view) => {
// select all text on focus, like a regular input does
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
},
keydown: (e) => {
// Submit nearest form on enter if there is one
if (e.key === 'Enter') {
const el = e.currentTarget as HTMLElement;
const form = el.closest('form');
form?.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
}
},
}),
]
: []),
// Clear selection on blur
EditorView.domEventHandlers({
blur: (e, view) => {
setTimeout(() => {
view.dispatch({ selection: { anchor: 0, head: 0 } });
}, 100);
},
}),
// Handle onChange
EditorView.updateListener.of((update) => {
if (typeof onChange === 'function' && update.docChanged) {
onChange(update.state.doc.toString());
}
}),
];
}
const syncGutterBg = ({
parent,
className = '',
}: {
parent: HTMLDivElement;
className?: string;
}) => {
const gutterEl = parent.querySelector<HTMLDivElement>('.cm-gutters');
const classList = className?.split(/\s+/) ?? [];
const bgClasses = classList
.filter((c) => c.match(/(^|:)?bg-.+/)) // Find bg-* classes
.map((c) => c.replace(/^bg-/, '!bg-')) // !important
.map((c) => c.replace(/^dark:bg-/, 'dark:!bg-')); // !important
if (gutterEl) {
gutterEl?.classList.add(...bgClasses);
}
};

View File

@@ -1,6 +1,6 @@
import { closeCompletion, startCompletion } from '@codemirror/autocomplete';
import { EditorView } from 'codemirror';
import { debounce } from 'lodash';
import { debounce } from '../../lib/debounce';
/*
* Debounce autocomplete until user stops typing for `millis` milliseconds.

View File

@@ -1,7 +1,7 @@
import classnames from 'classnames';
import type { InputHTMLAttributes, ReactNode } from 'react';
import type { EditorProps } from './Editor/Editor';
import Editor from './Editor/Editor';
import { Editor } from './Editor/Editor';
import { HStack, VStack } from './Stacks';
interface Props

View File

@@ -2,7 +2,7 @@ import classnames from 'classnames';
import { useRequestUpdate, useSendRequest } from '../hooks/useRequest';
import type { HttpRequest } from '../lib/models';
import { Button } from './Button';
import Editor from './Editor/Editor';
import { Editor } from './Editor/Editor';
import { ScrollArea } from './ScrollArea';
import { HStack } from './Stacks';
import { UrlBar } from './UrlBar';

View File

@@ -2,11 +2,12 @@ import classnames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import { useDeleteAllResponses, useDeleteResponse, useResponses } from '../hooks/useResponses';
import { Dropdown } from './Dropdown';
import Editor from './Editor/Editor';
import { Editor } from './Editor/Editor';
import { Icon } from './Icon';
import { IconButton } from './IconButton';
import { HStack } from './Stacks';
import { StatusColor } from './StatusColor';
import { Webview } from './Webview';
interface Props {
requestId: string;
@@ -33,15 +34,6 @@ export function ResponsePane({ requestId, className }: Props) {
[response],
);
const contentForIframe: string | null = useMemo(() => {
if (!contentType.includes('html')) return null;
if (response == null) return null;
if (response.body.includes('<head>')) {
return response.body.replace(/<head>/gi, `<head><base href="${response.url}"/>`);
}
return response.body;
}, [response?.body, contentType]);
if (!response) {
return null;
}
@@ -119,15 +111,8 @@ export function ResponsePane({ requestId, className }: Props) {
<div className="p-1">
<div className="text-white bg-red-500 px-3 py-2 rounded">{response.error}</div>
</div>
) : viewMode === 'pretty' && contentForIframe !== null ? (
<div className="px-2 pb-2">
<iframe
title="Response preview"
srcDoc={contentForIframe}
sandbox="allow-scripts allow-same-origin"
className="h-full w-full rounded-md border border-gray-100/20"
/>
</div>
) : viewMode === 'pretty' ? (
<Webview body={response.body} contentType={contentType} url={response.url} />
) : response?.body ? (
<Editor
readOnly

View File

@@ -1,7 +1,6 @@
import classnames from 'classnames';
import type { HTMLAttributes } from 'react';
import React, { useState } from 'react';
import { SketchPicker } from 'react-color';
import { useRequestCreate } from '../hooks/useRequest';
import useTheme from '../hooks/useTheme';
import type { HttpRequest } from '../lib/models';
@@ -21,10 +20,8 @@ interface Props extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
export function Sidebar({ className, activeRequestId, workspaceId, requests, ...props }: Props) {
const createRequest = useRequestCreate({ workspaceId, navigateAfter: true });
const { appearance, toggleAppearance, forceSetTheme } = useTheme();
const { appearance, toggleAppearance } = useTheme();
const [open, setOpen] = useState<boolean>(false);
const [color, setColor] = useState<string>('blue');
const [showPicker, setShowPicker] = useState<boolean>(false);
return (
<div
className={classnames(
@@ -63,17 +60,6 @@ export function Sidebar({ className, activeRequestId, workspaceId, requests, ...
<IconButton icon={appearance === 'dark' ? 'moon' : 'sun'} onClick={toggleAppearance} />
<IconButton icon="rows" onClick={() => setOpen(true)} />
</HStack>
{showPicker && (
<SketchPicker
className="fixed z-10 bottom-2 right-2"
color={color}
onChange={(c) => {
setColor(c.hex);
forceSetTheme(c.hex);
}}
/>
)}
</VStack>
</div>
);
@@ -86,7 +72,12 @@ function SidebarItem({ request, active }: { request: HttpRequest; active: boolea
color="custom"
to={`/workspaces/${request.workspaceId}/requests/${request.id}`}
disabled={active}
className={classnames('w-full', active ? 'bg-gray-200/70 text-gray-900' : 'text-gray-600')}
className={classnames(
'w-full',
active
? 'bg-gray-200/70 text-gray-900'
: 'text-gray-600 hover:text-gray-800 active:bg-gray-200/50',
)}
size="sm"
justify="start"
>

View File

@@ -0,0 +1,28 @@
import { useMemo } from 'react';
interface Props {
body: string;
contentType: string;
url: string;
}
export function Webview({ body, url, contentType }: Props) {
const contentForIframe: string | undefined = useMemo(() => {
if (!contentType.includes('html')) return;
if (body.includes('<head>')) {
return body.replace(/<head>/gi, `<head><base href="${url}"/>`);
}
return body;
}, [body, contentType]);
return (
<div className="px-2 pb-2">
<iframe
title="Response preview"
srcDoc={contentForIframe}
sandbox="allow-scripts allow-same-origin"
className="h-full w-full rounded-md border border-gray-100/20"
/>
</div>
);
}