Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(laboratory): rename preflight-script to just preflight #6470

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions cypress/e2e/laboratory-preflight-script.cy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { dedent } from '../support/testkit';

const selectors = {
buttonPreflightScript: '[aria-label*="Preflight Script"]',
buttonPreflight: '[aria-label*="Preflight Script"]',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we change the label value also?

buttonModalCy: 'preflight-script-modal-button',
buttonToggleCy: 'toggle-preflight-script',
buttonHeaders: '[data-name="headers"]',
Expand All @@ -27,7 +27,7 @@ beforeEach(() => {
cy.setCookie('sRefreshToken', refreshToken);
data.slug = slug;
cy.visit(`/${slug}/laboratory`);
cy.get(selectors.buttonPreflightScript).click();
cy.get(selectors.buttonPreflight).click();
});
});
});
Expand Down Expand Up @@ -60,7 +60,7 @@ describe('Laboratory > Preflight Script', () => {
it('regression: loads even if local storage is set to {}', () => {
window.localStorage.setItem('hive:laboratory:environment', '{}');
cy.visit(`/${data.slug}/laboratory`);
cy.get(selectors.buttonPreflightScript).click();
cy.get(selectors.buttonPreflight).click();
});
it('mini script editor is read only', () => {
cy.dataCy('toggle-preflight-script').click();
Expand Down
2 changes: 1 addition & 1 deletion packages/web/app/preflight-worker-embed.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
<a href="https://www.youtube.com/watch?v=CMNry4PE93Y" rel="nofollow">I like turtles</a>
<a href="https://www.youtube.com/watch?v=XOi2jFIhZhA" rel="nofollow">Wheatherboi</a>

<script type="module" src="./src/lib/preflight-sandbox/preflight-worker-embed.ts"></script>
<script type="module" src="./src/lib/preflight/preflight-worker-embed.ts"></script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,9 @@ import { cn } from '../utils';
import labApiDefinitionRaw from './lab-api-declaration?raw';
import { IFrameEvents, LogMessage } from './shared-types';

export type PreflightScriptResultData = Omit<
IFrameEvents.Outgoing.EventData.Result,
'type' | 'runId'
>;
export type PreflightResultData = Omit<IFrameEvents.Outgoing.EventData.Result, 'type' | 'runId'>;

export const preflightScriptPlugin: GraphiQLPlugin = {
export const preflightPlugin: GraphiQLPlugin = {
icon: () => (
<svg
viewBox="0 0 256 256"
Expand All @@ -59,7 +56,7 @@ export const preflightScriptPlugin: GraphiQLPlugin = {
</svg>
),
title: 'Preflight Script',
content: PreflightScriptContent,
content: PreflightContent,
};

const classes = {
Expand Down Expand Up @@ -111,7 +108,7 @@ const monacoProps = {
},
} satisfies Record<'script' | 'env', ComponentPropsWithoutRef<typeof MonacoEditor>>;

const UpdatePreflightScriptMutation = graphql(`
const UpdatePreflightMutation = graphql(`
mutation UpdatePreflightScript($input: UpdatePreflightScriptInput!) {
updatePreflightScript(input: $input) {
ok {
Expand All @@ -130,7 +127,7 @@ const UpdatePreflightScriptMutation = graphql(`
}
`);

const PreflightScript_TargetFragment = graphql(`
const Preflight_TargetFragment = graphql(`
fragment PreflightScript_TargetFragment on Target {
id
preflightScript {
Expand All @@ -147,14 +144,16 @@ export const enum PreflightWorkerState {
ready,
}

export function usePreflightScript(args: {
target: FragmentType<typeof PreflightScript_TargetFragment> | null;
export function usePreflight(args: {
target: FragmentType<typeof Preflight_TargetFragment> | null;
}) {
const iframeRef = useRef<HTMLIFrameElement>(null);
const prompt = usePromptManager();

const target = useFragment(PreflightScript_TargetFragment, args.target);
const [isPreflightScriptEnabled, setIsPreflightScriptEnabled] = useLocalStorageJson(
const target = useFragment(Preflight_TargetFragment, args.target);
const [isPreflightEnabled, setIsPreflightEnabled] = useLocalStorageJson(
// todo: ability to pass historical keys for seamless gradual migration to new key names.
// 'hive:laboratory:isPreflightEnabled',
'hive:laboratory:isPreflightScriptEnabled',
z.boolean().default(false),
);
Expand All @@ -175,8 +174,8 @@ export function usePreflightScript(args: {
async function execute(
script = target?.preflightScript?.sourceCode ?? '',
isPreview = false,
): Promise<PreflightScriptResultData> {
const resultEnvironmentVariablesDecoded: PreflightScriptResultData['environmentVariables'] =
): Promise<PreflightResultData> {
const resultEnvironmentVariablesDecoded: PreflightResultData['environmentVariables'] =
Kit.tryOr(
() => JSON.parse(latestEnvironmentVariablesRef.current),
// todo: find a better solution than blowing away the user's
Expand All @@ -192,14 +191,14 @@ export function usePreflightScript(args: {
//
() => ({}),
);
const result: PreflightScriptResultData = {
const result: PreflightResultData = {
request: {
headers: [],
},
environmentVariables: resultEnvironmentVariablesDecoded,
};

if (isPreview === false && !isPreflightScriptEnabled) {
if (isPreview === false && !isPreflightEnabled) {
return result;
}

Expand Down Expand Up @@ -422,9 +421,9 @@ export function usePreflightScript(args: {
return {
execute,
abort,
isPreflightScriptEnabled,
setIsPreflightScriptEnabled,
script: target?.preflightScript?.sourceCode ?? '',
isPreflightEnabled,
setIsPreflightEnabled,
content: target?.preflightScript?.sourceCode ?? '',
environmentVariables,
setEnvironmentVariables,
state,
Expand All @@ -447,27 +446,27 @@ export function usePreflightScript(args: {
} as const;
}

type PreflightScriptObject = ReturnType<typeof usePreflightScript>;
type PreflightObject = ReturnType<typeof usePreflight>;

const PreflightScriptContext = createContext<PreflightScriptObject | null>(null);
export const PreflightScriptProvider = PreflightScriptContext.Provider;
const PreflightContext = createContext<PreflightObject | null>(null);
export const PreflightProvider = PreflightContext.Provider;

function PreflightScriptContent() {
const preflightScript = useContext(PreflightScriptContext);
if (preflightScript === null) {
throw new Error('PreflightScriptContent used outside PreflightScriptContext.Provider');
function PreflightContent() {
const preflight = useContext(PreflightContext);
if (preflight === null) {
throw new Error('PreflightContent used outside PreflightContext.Provider');
}

const [showModal, toggleShowModal] = useToggle();
const params = useParams({
from: '/authenticated/$organizationSlug/$projectSlug/$targetSlug',
});

const [, mutate] = useMutation(UpdatePreflightScriptMutation);
const [, mutate] = useMutation(UpdatePreflightMutation);

const { toast } = useToast();

const handleScriptChange = useCallback(async (newValue = '') => {
const handleContentChange = useCallback(async (newValue = '') => {
const { data, error } = await mutate({
input: {
selector: params,
Expand All @@ -494,24 +493,24 @@ function PreflightScriptContent() {

return (
<>
<PreflightScriptModal
<PreflightModal
// to unmount on submit/close
key={String(showModal)}
isOpen={showModal}
toggle={toggleShowModal}
scriptValue={preflightScript.script}
executeScript={value =>
preflightScript.execute(value, true).catch(err => {
preflight.execute(value, true).catch(err => {
console.error(err);
})
}
state={preflightScript.state}
abortScriptRun={preflightScript.abort}
logs={preflightScript.logs}
clearLogs={preflightScript.clearLogs}
onScriptValueChange={handleScriptChange}
envValue={preflightScript.environmentVariables}
onEnvValueChange={preflightScript.setEnvironmentVariables}
state={preflight.state}
abortScriptRun={preflight.abort}
logs={preflight.logs}
clearLogs={preflight.clearLogs}
content={preflight.content}
onContentChange={handleContentChange}
envValue={preflight.environmentVariables}
onEnvValueChange={preflight.setEnvironmentVariables}
/>
<div className="graphiql-doc-explorer-title flex items-center justify-between gap-4">
Preflight Script
Expand All @@ -536,13 +535,11 @@ function PreflightScriptContent() {
size="sm"
variant="outline"
className="mt-3"
onClick={() =>
preflightScript.setIsPreflightScriptEnabled(!preflightScript.isPreflightScriptEnabled)
}
onClick={() => preflight.setIsPreflightEnabled(!preflight.isPreflightEnabled)}
data-cy="toggle-preflight-script"
>
<PowerIcon className="mr-2 size-4" />
{preflightScript.isPreflightScriptEnabled ? 'On' : 'Off'}
{preflight.isPreflightEnabled ? 'On' : 'Off'}
</Button>
</div>

Expand All @@ -554,7 +551,7 @@ function PreflightScriptContent() {
</EditorTitle>
<Subtitle className="mb-3 cursor-not-allowed">Read-only view of the script</Subtitle>
<div className="relative">
{preflightScript.isPreflightScriptEnabled ? null : (
{preflight.isPreflightEnabled ? null : (
<div className="absolute inset-0 z-20 flex items-center justify-center bg-[#030711]/90 p-4 text-white">
<div className="rounded-md bg-[#0f1520] p-4 text-sm">
Preflight Script is disabled and will not be executed
Expand All @@ -563,7 +560,7 @@ function PreflightScriptContent() {
)}
<MonacoEditor
height={128}
value={preflightScript.script}
value={preflight.content}
{...monacoProps.script}
className={cn(classes.monacoMini, 'z-10')}
wrapperProps={{
Expand Down Expand Up @@ -592,8 +589,8 @@ function PreflightScriptContent() {
</Subtitle>
<MonacoEditor
height={128}
value={preflightScript.environmentVariables}
onChange={value => preflightScript.setEnvironmentVariables(value ?? '')}
value={preflight.environmentVariables}
onChange={value => preflight.setEnvironmentVariables(value ?? '')}
{...monacoProps.env}
className={classes.monacoMini}
wrapperProps={{
Expand All @@ -604,28 +601,28 @@ function PreflightScriptContent() {
);
}

function PreflightScriptModal({
function PreflightModal({
isOpen,
toggle,
scriptValue,
content,
executeScript,
state,
abortScriptRun,
logs,
clearLogs,
onScriptValueChange,
onContentChange,
envValue,
onEnvValueChange,
}: {
isOpen: boolean;
toggle: () => void;
scriptValue?: string;
content?: string;
executeScript: (script: string) => void;
state: PreflightWorkerState;
abortScriptRun: () => void;
logs: Array<LogRecord>;
clearLogs: () => void;
onScriptValueChange: (value: string) => void;
onContentChange: (value: string) => void;
envValue: string;
onEnvValueChange: (value: string) => void;
}) {
Expand Down Expand Up @@ -653,7 +650,7 @@ function PreflightScriptModal({
}, []);

const handleSubmit = useCallback(() => {
onScriptValueChange(scriptEditorRef.current?.getValue() ?? '');
onContentChange(scriptEditorRef.current?.getValue() ?? '');
onEnvValueChange(envEditorRef.current?.getValue() ?? '');
toggle();
}, []);
Expand Down Expand Up @@ -729,7 +726,7 @@ function PreflightScriptModal({
</Button>
</div>
<MonacoEditor
value={scriptValue}
value={content}
beforeMount={handleMonacoEditorBeforeMount}
onMount={handleScriptEditorDidMount}
{...monacoProps.script}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Kit } from '../kit';
import PreflightWorker from './preflight-script-worker?worker&inline';
import PreflightWorker from './preflight-worker?worker&inline';
import { IFrameEvents, WorkerEvents } from './shared-types';

function postMessage(data: IFrameEvents.Outgoing.EventData) {
Expand Down
Loading
Loading