Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion e2e/tests/visual.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ class TryPlaywrightPage {
constructor(private readonly page: Page) { }
async executeExample(nth: number): Promise<void> {
await this.page.goto('/?l=javascript');
await this.page.locator(`.rs-panel-group > .rs-panel:nth-child(${nth})`).click();
const panel = this.page.locator('.rs-panel-group > .rs-panel').nth(nth - 1);
await panel.getByRole('link').click();
await expect(panel).toHaveClass(/rs-panel-in/);
const responsePromise = this.page.waitForResponse("**/service/control/run");
await Promise.all([
responsePromise,
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import useDarkMode from '../../hooks/useDarkMode';
const VITE_TURNSTILE_SITEKEY = '0x4AAAAAAA_K0T_2LZ0rgUtv';

const App: React.FunctionComponent = () => {
const { code, onChangeRightPanelMode, codeLanguage, onLanguageChange } = useContext(CodeContext)
const { getCode, onChangeRightPanelMode, codeLanguage, onLanguageChange } = useContext(CodeContext)
const [loading, setLoading] = useState<boolean>(false)
const [resp, setResponse] = useState<ExecutionResponse|null>(null)
const handleExecutionRef = useRef<() => Promise<void>>(undefined)
Expand All @@ -37,7 +37,7 @@ const App: React.FunctionComponent = () => {
'error-callback': () => resolve(''),
});
});
setResponse(await runCode(code, codeLanguage, turnstileToken))
setResponse(await runCode(getCode(), codeLanguage, turnstileToken))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Snapshot the code before awaiting Turnstile

When Turnstile completion is delayed and the user selects another example from the still-active examples panel after clicking Run, getCode() reads the mutated ref only after that selection, so this execution unexpectedly submits the later example rather than the code associated with the Run click. Capture getCode() before awaiting the Turnstile token, then pass that snapshot to runCode.

Useful? React with 👍 / 👎.

setLoading(false)
onChangeRightPanelMode(false)
}
Expand Down
17 changes: 13 additions & 4 deletions frontend/src/components/CodeContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect, createContext } from 'react'
import { useState, useEffect, useRef, createContext } from 'react'
import { CodeLanguage } from '../constants'
import { Example, Examples } from '../examples'

Expand All @@ -8,6 +8,7 @@ import { determineCode, determineLanguage, pushNewURL } from '../utils'

interface CodeContextContent {
code: string;
getCode: () => string;
codeLanguage: CodeLanguage
onLanguageChange: (language: CodeLanguage) => void,
examples: Example[],
Expand All @@ -18,6 +19,7 @@ interface CodeContextContent {

export const CodeContext = createContext<CodeContextContent>({
code: "",
getCode: () => "",
codeLanguage: CodeLanguage.JAVASCRIPT,
onLanguageChange: () => {},
examples: [],
Expand All @@ -32,9 +34,15 @@ type CodeContextProviderProps = {

const CodeContextProvider: React.FC<CodeContextProviderProps> = ({ children }) => {
const [code, setCode] = useState<string>("")
const latestCode = useRef(code)
const [rightPanelMode, setRightPanelMode] = useState(true)
const [codeLanguage, setCodeLanguage] = useState<CodeLanguage>(determineLanguage())

const updateCode = (next: string) => {
latestCode.current = next
setCode(next)
}

// Store the code in localstorage with a 500ms debounce on change
const handleLazyStore = ()=>{
if (window.localStorage) {
Expand All @@ -51,7 +59,7 @@ const CodeContextProvider: React.FC<CodeContextProviderProps> = ({ children }) =

// determine the code which should be loaded on the application start
useEffect(() => {
determineCode(code => setCode(code), examples)
determineCode(next => updateCode(next), examples)
}, [examples])

const handleSetLanguage = (language: CodeLanguage) => {
Expand All @@ -61,7 +69,7 @@ const CodeContextProvider: React.FC<CodeContextProviderProps> = ({ children }) =
params.set("l", language)
pushNewURL(params)
setCodeLanguage(language)
setCode("")
updateCode("")
if (window.localStorage) {
window.localStorage.removeItem("code")
}
Expand All @@ -71,10 +79,11 @@ const CodeContextProvider: React.FC<CodeContextProviderProps> = ({ children }) =
return (
<CodeContext.Provider value={{
code,
getCode: () => latestCode.current,
codeLanguage: codeLanguage,
onLanguageChange: handleSetLanguage,
examples,
onChange: setCode,
onChange: updateCode,
rightPanelMode,
onChangeRightPanelMode: setRightPanelMode
}}>
Expand Down
9 changes: 9 additions & 0 deletions frontend/src/components/staleCodeRef.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { test, expect } from '@playwright/experimental-ct-react'
import { StaleCodeRefRepro } from './staleCodeRef'

test('render state is stale in the same click as onChange; getCode is not', async ({ mount }) => {
const component = await mount(<StaleCodeRefRepro />)
await component.getByRole('button', { name: 'select-and-read' }).click()
await expect(component.getByTestId('from-render')).toHaveText('')
await expect(component.getByTestId('from-ref')).toHaveText('example-8-code')
})
55 changes: 55 additions & 0 deletions frontend/src/components/staleCodeRef.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { createContext, useContext, useRef, useState, type ReactNode } from 'react'

type LatestCode = {
code: string
getCode: () => string
onChange: (value: string) => void
}

const Ctx = createContext<LatestCode>({
code: '',
getCode: () => '',
onChange: (_value: string) => {},
})

const Provider = ({ children }: { children: ReactNode }) => {
const [code, setCode] = useState('')
const latestCode = useRef(code)
const onChange = (next: string) => {
latestCode.current = next
setCode(next)
}
return (
<Ctx.Provider value={{ code, getCode: () => latestCode.current, onChange }}>
{children}
</Ctx.Provider>
)
}

const Probe = () => {
const { code, getCode, onChange } = useContext(Ctx)
const [fromRender, setFromRender] = useState('unset')
const [fromRef, setFromRef] = useState('unset')
return (
<div>
<button
onClick={() => {
onChange('example-8-code')
setFromRender(code)
setFromRef(getCode())
}}
>
select-and-read
</button>
<div data-testid="from-render">{fromRender}</div>
<div data-testid="from-ref">{fromRef}</div>
</div>
)
}

/** Story used by staleCodeRef.spec.tsx — not production UI. */
export const StaleCodeRefRepro = () => (
<Provider>
<Probe />
</Provider>
)
Loading