Unverified Commit dcb69ee9 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Strictly type `react-dev-overlay` (#15669)

Fixes #15668
parent 3caa9960
......@@ -15,7 +15,7 @@ function onUnhandledError(ev: ErrorEvent) {
Bus.emit({
type: Bus.TYPE_UNHANDLED_ERROR,
reason: error,
frames: parseStack(e.stack),
frames: parseStack(e.stack!),
})
}
......@@ -34,7 +34,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) {
Bus.emit({
type: Bus.TYPE_UNHANDLED_REJECTION,
reason: reason,
frames: parseStack(e.stack),
frames: parseStack(e.stack!),
})
}
......
......@@ -41,7 +41,9 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
}
}
function ReactDevOverlay({ children }) {
const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
children,
}) {
const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, { nextId: 1, buildError: null, errors: [] })
......@@ -76,7 +78,7 @@ function ReactDevOverlay({ children }) {
<ComponentStyles />
{hasBuildError ? (
<BuildError message={state.buildError} />
<BuildError message={state.buildError!} />
) : hasRuntimeErrors ? (
<Errors errors={state.errors} />
) : undefined}
......
......@@ -45,7 +45,7 @@ function drain() {
// event(s)
Boolean(handlers.size)
) {
const ev = queue.shift()
const ev = queue.shift()!
handlers.forEach((handler) => handler(ev))
}
}, 1)
......
......@@ -16,7 +16,7 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({
const prefixLength = lines
.map((line) => /^>? +\d+ +\| ( *)/.exec(stripAnsi(line)))
.filter(Boolean)
.map((v) => v.pop())
.map((v) => v!.pop()!)
.reduce((c, n) => (isNaN(c) ? n.length : Math.min(c, n.length)), NaN)
if (prefixLength > 1) {
......@@ -43,7 +43,7 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({
const open = React.useCallback(() => {
const params = new URLSearchParams()
for (const key in stackFrame) {
params.append(key, (stackFrame[key] ?? '').toString())
params.append(key, ((stackFrame as any)[key] ?? '').toString())
}
self
......
......@@ -14,7 +14,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({
onClose,
...props
}) {
const [dialog, setDialog] = React.useState<HTMLDivElement>(null)
const [dialog, setDialog] = React.useState<HTMLDivElement | null>(null)
const onDialog = React.useCallback((node) => {
setDialog(node)
}, [])
......@@ -47,8 +47,9 @@ const Dialog: React.FC<DialogProps> = function Dialog({
}
}
shadowRoot.addEventListener('keydown', handler)
return () => shadowRoot.removeEventListener('keydown', handler)
shadowRoot.addEventListener('keydown', handler as EventListener)
return () =>
shadowRoot.removeEventListener('keydown', handler as EventListener)
}, [dialog])
return (
......
......@@ -14,9 +14,9 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
next,
close,
}) {
const buttonLeft = React.useRef<HTMLButtonElement>()
const buttonRight = React.useRef<HTMLButtonElement>()
const buttonClose = React.useRef<HTMLButtonElement>()
const buttonLeft = React.useRef<HTMLButtonElement | null>(null)
const buttonRight = React.useRef<HTMLButtonElement | null>(null)
const buttonClose = React.useRef<HTMLButtonElement | null>(null)
const [nav, setNav] = React.useState<HTMLElement | null>(null)
const onNav = React.useCallback((el: HTMLElement) => {
......@@ -54,16 +54,18 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
}
}
close()
if (close) {
close()
}
}
}
root.addEventListener('keydown', handler)
root.addEventListener('keydown', handler as EventListener)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler)
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
......@@ -83,11 +85,11 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
const a = root.activeElement
if (previous == null) {
if (a === buttonLeft.current) {
if (buttonLeft.current && a === buttonLeft.current) {
buttonLeft.current.blur()
}
} else if (next == null) {
if (a === buttonRight.current) {
if (buttonRight.current && a === buttonRight.current) {
buttonRight.current.blur()
}
}
......@@ -142,7 +144,7 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
&nbsp;
{children}
</nav>
{close && (
{close ? (
<button
ref={buttonClose}
type="button"
......@@ -174,7 +176,7 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
</svg>
</span>
</button>
)}
) : null}
</div>
)
}
......
// @ts-ignore
import allyDisable from 'ally.js/maintain/disabled'
// @ts-ignore
import allyTrap from 'ally.js/maintain/tab-focus'
import * as React from 'react'
import { lock, unlock } from './body-locker'
......@@ -17,8 +19,8 @@ const Overlay: React.FC<OverlayProps> = function Overlay({
}
}, [])
const [overlay, setOverlay] = React.useState<HTMLElement | null>(null)
const onOverlay = React.useCallback((el: HTMLElement) => {
const [overlay, setOverlay] = React.useState<HTMLDivElement | null>(null)
const onOverlay = React.useCallback((el: HTMLDivElement) => {
setOverlay(el)
}, [])
......
......@@ -14,7 +14,7 @@ export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({
let [, forceUpdate] = React.useState()
React.useLayoutEffect(() => {
const ownerDocument = mountNode.current.ownerDocument
const ownerDocument = mountNode.current!.ownerDocument!
portalNode.current = ownerDocument.createElement('nextjs-portal')
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current)
......
......@@ -209,7 +209,7 @@ export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) {
// This component shouldn't be rendered with no errors, but if it is, let's
// handle it gracefully by rendering nothing.
if (errors.length < 1) {
if (errors.length < 1 || activeError == null) {
return null
}
......@@ -252,14 +252,14 @@ export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) {
type="error"
aria-labelledby="nextjs__container_errors_label"
aria-describedby="nextjs__container_errors_desc"
onClose={!isServerError && minimize}
onClose={isServerError ? undefined : minimize}
>
<DialogContent>
<DialogHeader className="nextjs-container-errors-header">
<LeftRightDialogHeader
previous={activeIdx > 0 ? previous : null}
next={activeIdx < readyErrors.length - 1 ? next : null}
close={!isServerError && minimize}
close={isServerError ? undefined : minimize}
>
<small>
<span>{activeIdx + 1}</span> of{' '}
......
......@@ -21,7 +21,7 @@ const CallStackFrame: React.FC<{
const params = new URLSearchParams()
for (const key in f) {
params.append(key, (f[key] ?? '').toString())
params.append(key, ((f as any)[key] ?? '').toString())
}
self
......@@ -134,8 +134,8 @@ const RuntimeError: React.FC<RuntimeErrorProps> = function RuntimeError({
/>
))}
<CodeFrame
stackFrame={firstFrame.originalStackFrame}
codeFrame={firstFrame.originalCodeFrame}
stackFrame={firstFrame.originalStackFrame!}
codeFrame={firstFrame.originalCodeFrame!}
/>
</React.Fragment>
) : undefined}
......
......@@ -35,7 +35,7 @@ export function getNodeError(error: Error): Error {
n.name = error.name
try {
n.stack = parse(error.stack)
n.stack = parse(error.stack!)
.map(getFilesystemFrame)
.map((f) => {
let str = ` at ${f.methodName}`
......
......@@ -6,14 +6,14 @@ export function parseStack(stack: string): StackFrame[] {
const frames = parse(stack)
return frames.map((frame) => {
try {
const url = new URL(frame.file)
const url = new URL(frame.file!)
const res = regexNextStatic.exec(url.pathname)
if (res) {
const distDir = process.env.__NEXT_DIST_DIR
?.replace(/\\/g, '/')
?.replace(/\/$/, '')
if (distDir) {
frame.file = 'file://' + distDir.concat(res.pop())
frame.file = 'file://' + distDir.concat(res.pop()!)
}
}
} catch {}
......
......@@ -47,7 +47,7 @@ export function getOriginalStackFrame(
const params = new URLSearchParams()
params.append('isServerSide', String(isServerSide))
for (const key in source) {
params.append(key, (source[key] ?? '').toString())
params.append(key, ((source as any)[key] ?? '').toString())
}
const controller = new AbortController()
......@@ -114,7 +114,7 @@ export function getOriginalStackFrame(
export function getFrameSource(frame: StackFrame): string {
let str = ''
try {
const u = new URL(frame.file)
const u = new URL(frame.file!)
// Strip the origin for same-origin scripts.
if (
......
......@@ -2,10 +2,10 @@ import * as React from 'react'
export function useOnClickOutside(
el: Node | null,
handler: (e: MouseEvent | TouchEvent) => void
handler: ((e: MouseEvent | TouchEvent) => void) | undefined
) {
React.useEffect(() => {
if (el == null) {
if (el == null || handler == null) {
return
}
......@@ -19,11 +19,11 @@ export function useOnClickOutside(
}
const root = el.getRootNode()
root.addEventListener('mousedown', listener)
root.addEventListener('touchstart', listener)
root.addEventListener('mousedown', listener as EventListener)
root.addEventListener('touchstart', listener as EventListener)
return function () {
root.removeEventListener('mousedown', listener)
root.removeEventListener('touchstart', listener)
root.removeEventListener('mousedown', listener as EventListener)
root.removeEventListener('touchstart', listener as EventListener)
}
}, [handler, el])
}
......@@ -10,6 +10,7 @@ import {
import { StackFrame } from 'stacktrace-parser'
import url from 'url'
// eslint-disable-next-line import/no-extraneous-dependencies
// @ts-ignore
import webpack from 'webpack'
import { getRawSourceMap } from './internal/helpers/getRawSourceMap'
import { launchEditor } from './internal/helpers/launchEditor'
......@@ -97,6 +98,10 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const compilation = isServerSide
? options.serverStats()?.compilation
: options.stats()?.compilation
if (compilation == null) {
return null
}
const module = [...compilation.modules].find(
(searchModule) => searchModule.id === id
)
......@@ -112,7 +117,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
res: ServerResponse,
next: Function
) {
const { pathname, query } = url.parse(req.url, true)
const { pathname, query } = url.parse(req.url!, true)
if (pathname === '/__nextjs_original-stack-frame') {
const frame = (query as unknown) as StackFrame & {
......@@ -171,7 +176,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const consumer = await new SourceMapConsumer(source.map())
pos = consumer.originalPositionFor({
line: frameLine,
column: frameColumn,
column: frameColumn ?? 0,
})
if (pos.source) {
posSourceContent =
......@@ -215,7 +220,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
pos.line
? (codeFrameColumns(
posSourceContent,
{ start: { line: pos.line, column: pos.column } },
{ start: { line: pos.line, column: pos.column ?? 0 } },
{ forceColor: true }
) as string)
: null
......
{
"compilerOptions": {
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"target": "es3",
"lib": ["dom"],
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment