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

Highlight erroring line #954

Merged
merged 7 commits into from
Mar 28, 2023
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
Next Next commit
Highlight erroring line
  • Loading branch information
samdev-7 committed Mar 11, 2023
commit 608974c52ec46802713fb26035c5fbcc20b22a01
19 changes: 13 additions & 6 deletions src/components/big-interactive-pages/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Help from '../popups-etc/help'
import { collapseRanges } from '../../lib/codemirror/util'
import { defaultExampleCode } from '../../lib/examples'
import MigrateToast from '../popups-etc/migrate-toast'
import { highlightError, clearErrorHighlight } from '../../lib/engine/3-editor/error'

interface EditorProps {
persistenceState: Signal<PersistenceState>
Expand Down Expand Up @@ -85,7 +86,7 @@ export default function Editor({ persistenceState, cookies }: EditorProps) {
return () => window.removeEventListener('resize', updateMaxSize)
}, [])
const realOutputAreaSize = useComputed(() => Math.min(maxOutputAreaSize.value, Math.max(minOutputAreaSize, outputAreaSize.value)))

// Resize bar logic
const resizeState = useSignal<ResizeState | null>(null)
useEffect(() => {
Expand All @@ -105,15 +106,15 @@ export default function Editor({ persistenceState, cookies }: EditorProps) {
const onRun = async () => {
foldAllTemplateLiterals()
if (!screen.current) return

if (cleanup.current) cleanup.current()
errorLog.value = []

const code = codeMirror.value?.state.doc.toString() ?? ''
const res = runGame(code, screen.current, (error) => {
errorLog.value = [ ...errorLog.value, error ]
})

screen.current.focus()
screenShake.value++
setTimeout(() => screenShake.value--, 200)
Expand All @@ -122,6 +123,12 @@ export default function Editor({ persistenceState, cookies }: EditorProps) {
if (res.error) {
console.error(res.error.raw)
errorLog.value = [ ...errorLog.value, res.error ]

if (res.error.line) {
highlightError(res.error.line);
}
} else {
clearErrorHighlight();
}
}
useEffect(() => () => cleanup.current?.(), [])
Expand Down Expand Up @@ -168,7 +175,7 @@ export default function Editor({ persistenceState, cookies }: EditorProps) {
return (
<div class={styles.page}>
<Navbar persistenceState={persistenceState} />

<div class={styles.pageMain}>
<div className={styles.codeContainer}>
<CodeMirror
Expand Down Expand Up @@ -198,7 +205,7 @@ export default function Editor({ persistenceState, cookies }: EditorProps) {
<button class={styles.errorClose} onClick={() => errorLog.value = []}>
<IoClose />
</button>

{errorLog.value.map((error, i) => (
<div key={`${i}-${error.description}`}>{error.description}</div>
))}
Expand Down Expand Up @@ -248,7 +255,7 @@ export default function Editor({ persistenceState, cookies }: EditorProps) {
{persistenceState.value.kind === 'IN_MEMORY' && persistenceState.value.showInitialWarning && (
<DraftWarningModal persistenceState={persistenceState} />
)}

<Help initialVisible={!cookies.hideHelp} />
<MigrateToast persistenceState={persistenceState} />
</div>
Expand Down
4 changes: 4 additions & 0 deletions src/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,8 @@ a:hover {

.grecaptcha-badge {
visibility: hidden;
}

.cm-lineNumbers > .cm-gutterElement[err-line] {
background: #ecb2b2!important;
}
59 changes: 53 additions & 6 deletions src/lib/engine/3-editor/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type EsprimaError = Error & {
column: number
}

export type GameError =
export type GameError =
| { kind: 'parse', error: EsprimaError }
| { kind: 'runtime', error: unknown }
| { kind: 'page', error: unknown }
Expand Down Expand Up @@ -52,7 +52,7 @@ const normalizeStack = (stack: string): StackItem[] | null => {
let fileUrl = match[2]!
while (chromeStackUrlRegex.test(fileUrl))
fileUrl = fileUrl.match(chromeStackUrlRegex)![1]!

return {
callSite,
fileUrl,
Expand Down Expand Up @@ -82,22 +82,27 @@ export const normalizeGameError = (gameError: GameError): NormalizedError => {
const line = lineNumber - 1
return {
description: `SyntaxError: ${description}\n at <game>:${line}:${column}`,
raw: gameError.error
raw: gameError.error,
line: line,
column: column
}
} else if (gameError.error instanceof Error) {
const descriptionLines: string[] = []

const stack = (gameError.error.stack ? normalizeStack(gameError.error.stack) : null) ?? []

let [line, col] = findErrorLineCol(gameError.error.stack)

stack.reverse()

let foundEval = false
for (const item of stack) {
if (!foundEval && [ 'eval', 'anonymous' ].includes(item.callSite)) {
if (!foundEval && ['eval', 'anonymous'].includes(item.callSite)) {
foundEval = true
if (item.lineNumber) item.lineNumber -= lineOffset
}
if (!foundEval) continue

let fileName
try {
const url = new URL(item.fileUrl)
Expand All @@ -118,9 +123,51 @@ export const normalizeGameError = (gameError: GameError): NormalizedError => {
descriptionLines.unshift(`${gameError.error.name}: ${gameError.error.message}`)
return {
description: descriptionLines.join('\n'),
raw: gameError.error
raw: gameError.error,
line: line,
column: col
}
} else {
return { description: `Runtime Error: ${gameError.error}`, raw: gameError.error }
}
}

function findErrorLineCol(stack: string | undefined): [number | null, number | null] {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please add a comment that explains what this function does at a high level?

if (!stack) return [null, null]

let line = null
let col = null
let location = stack.match(/<anonymous>:(.+)\)/)
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please add a comment that explains what this function does at a high level?


if (location) {
let lineCol = location[1].split(":").map(Number)
line = lineCol[0] - 2 - 1
col = lineCol[1]
}

return [line, col]
}


export function highlightError(line: number) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please add a comment that explains what this function does at a high level?

console.log(line)
const cmLineGutters = document.querySelectorAll(".cm-lineNumbers > .cm-gutterElement")
for (let i = 0; i < cmLineGutters.length; i++) {
const cmLineGutter = cmLineGutters[i] as HTMLElement;
const innerNumber = cmLineGutter.innerText;
const height = cmLineGutter.style.height;
if (Number(innerNumber) !== line || height === "0px") {
cmLineGutter.removeAttribute("err-line");
continue;
};
cmLineGutter.setAttribute("err-line", "");
}
}

export function clearErrorHighlight() {
const cmLineGutters = document.querySelectorAll(".cm-lineNumbers > .cm-gutterElement")
for (let i = 0; i < cmLineGutters.length; i++) {
const cmLineGutter = cmLineGutters[i] as HTMLElement;
cmLineGutter.removeAttribute("err-line");
}
}
2 changes: 2 additions & 0 deletions src/lib/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import type { Game, SessionInfo } from './game-saving/account'
export interface NormalizedError {
raw: unknown
description: string
line?: number | null
column?: number | null
}

// Editor types
Expand Down