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(client): add return types #20728

Merged
merged 8 commits into from
Jan 5, 2021
Merged
4 changes: 2 additions & 2 deletions packages/next/client/experimental-script.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ interface Props extends ScriptHTMLAttributes<HTMLScriptElement> {
preload?: boolean
}

const loadScript = (props: Props) => {
const loadScript = (props: Props): void => {
const {
src = '',
onLoad = () => {},
Expand Down Expand Up @@ -83,7 +83,7 @@ const loadScript = (props: Props) => {
document.body.appendChild(el)
}

export default function Script(props: Props) {
export default function Script(props: Props): JSX.Element | null {
const {
src = '',
onLoad = () => {},
Expand Down
7 changes: 5 additions & 2 deletions packages/next/client/head-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function reactElementToDOM({ type, props }: JSX.Element): HTMLElement {
return el
}

function updateElements(type: string, components: JSX.Element[]) {
function updateElements(type: string, components: JSX.Element[]): void {
const headEl = document.getElementsByTagName('head')[0]
const headCountEl: HTMLMetaElement = headEl.querySelector(
'meta[name=next-head-count]'
Expand Down Expand Up @@ -84,7 +84,10 @@ function updateElements(type: string, components: JSX.Element[]) {
headCountEl.content = (headCount - oldTags.length + newTags.length).toString()
}

export default function initHeadManager() {
export default function initHeadManager(): {
mountedInstances: Set<unknown>
updateHead: (head: JSX.Element[]) => void
} {
let updatePromise: Promise<void> | null = null

return {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/client/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ function prefetch(
prefetched[href + '%' + as + (curLocale ? '%' + curLocale : '')] = true
}

function isModifiedEvent(event: React.MouseEvent) {
function isModifiedEvent(event: React.MouseEvent): boolean {
const { target } = event.currentTarget as HTMLAnchorElement
return (
(target && target !== '_self') ||
Expand Down
5 changes: 3 additions & 2 deletions packages/next/client/page-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import createRouteLoader, {
RouteLoader,
} from './route-loader'

function normalizeRoute(route: string) {
function normalizeRoute(route: string): string {
if (route[0] !== '/') {
throw new Error(`Route name should start with a "/", got "${route}"`)
}
Expand Down Expand Up @@ -83,13 +83,14 @@ export default class PageLoader {
/**
* @param {string} href the route href (file-system path)
* @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes
* @returns {string}
*/
getDataHref(
href: string,
asPath: string,
ssg: boolean,
locale?: string | false
) {
): string {
const { pathname: hrefPathname, query, search } = parseRelativeUrl(href)
const { pathname: asPathname } = parseRelativeUrl(asPath)
const route = normalizeRoute(hrefPathname)
Expand Down
4 changes: 2 additions & 2 deletions packages/next/client/performance-relayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const initialHref = location.href
let isRegistered = false
let userReportHandler: ReportHandler | undefined

function onReport(metric: Metric) {
function onReport(metric: Metric): void {
if (userReportHandler) {
userReportHandler(metric)
}
Expand Down Expand Up @@ -57,7 +57,7 @@ function onReport(metric: Metric) {
}
}

export default (onPerfEntry?: ReportHandler) => {
export default (onPerfEntry?: ReportHandler): void => {
// Update function if it changes:
userReportHandler = onPerfEntry

Expand Down
4 changes: 3 additions & 1 deletion packages/next/client/request-idle-callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ declare global {

const requestIdleCallback =
(typeof self !== 'undefined' && self.requestIdleCallback) ||
function (cb: (deadline: RequestIdleCallbackDeadline) => void) {
function (
cb: (deadline: RequestIdleCallbackDeadline) => void
): NodeJS.Timeout {
let start = Date.now()
return setTimeout(function () {
cb({
Expand Down
20 changes: 11 additions & 9 deletions packages/next/client/route-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function withFuture<T>(
return Promise.resolve(entry)
}
let resolver: (entrypoint: T) => void
const prom = new Promise<T>((resolve) => {
const prom: Promise<T> = new Promise<T>((resolve) => {
resolver = resolve
})
map.set(key, (entry = { resolve: resolver!, future: prom }))
Expand Down Expand Up @@ -120,7 +120,7 @@ export function markAssetError(err: Error): Error {
return Object.defineProperty(err, ASSET_LOAD_ERROR, {})
}

export function isAssetError(err?: Error) {
export function isAssetError(err?: Error): boolean | undefined {
return err && ASSET_LOAD_ERROR in err
}

Expand Down Expand Up @@ -166,7 +166,9 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
return Promise.resolve(self.__BUILD_MANIFEST)
}

const onBuildManifest = new Promise<ClientBuildManifest>((resolve) => {
const onBuildManifest: Promise<ClientBuildManifest> = new Promise<
ClientBuildManifest
>((resolve) => {
// Mandatory because this is not concurrent safe:
const cb = self.__BUILD_MANIFEST_CB
self.__BUILD_MANIFEST_CB = () => {
Expand Down Expand Up @@ -229,7 +231,7 @@ function createRouteLoader(assetPrefix: string): RouteLoader {
> = new Map()

function maybeExecuteScript(src: string): Promise<unknown> {
let prom = loadedScripts.get(src)
let prom: Promise<unknown> | undefined = loadedScripts.get(src)
if (prom) {
return prom
}
Expand All @@ -244,7 +246,7 @@ function createRouteLoader(assetPrefix: string): RouteLoader {
}

function fetchStyleSheet(href: string): Promise<RouteStyleSheet> {
let prom = styleSheets.get(href)
let prom: Promise<RouteStyleSheet> | undefined = styleSheets.get(href)
if (prom) {
return prom
}
Expand All @@ -269,7 +271,7 @@ function createRouteLoader(assetPrefix: string): RouteLoader {
whenEntrypoint(route: string) {
return withFuture(route, entrypoints)
},
onEntrypoint(route, execute) {
onEntrypoint(route: string, execute: () => unknown) {
Promise.resolve(execute)
.then((fn) => fn())
.then(
Expand All @@ -285,7 +287,7 @@ function createRouteLoader(assetPrefix: string): RouteLoader {
if (old && 'resolve' in old) old.resolve(input)
})
},
loadRoute(route) {
loadRoute(route: string) {
return withFuture<RouteLoaderEntry>(route, routes, async () => {
try {
const { scripts, css } = await getFilesForRoute(assetPrefix, route)
Expand All @@ -296,7 +298,7 @@ function createRouteLoader(assetPrefix: string): RouteLoader {
Promise.all(css.map(fetchStyleSheet)),
] as const)

const entrypoint = await Promise.race([
const entrypoint: RouteEntrypoint = await Promise.race([
this.whenEntrypoint(route),
idleTimeout<RouteLoaderEntry>(
MS_MAX_IDLE_DELAY,
Expand All @@ -315,7 +317,7 @@ function createRouteLoader(assetPrefix: string): RouteLoader {
}
})
},
prefetch(route) {
prefetch(route: string): Promise<void> {
// https://github.com/GoogleChromeLabs/quicklink/blob/453a661fa1fa940e2d2e044452398e38c67a98fb/src/index.mjs#L115-L118
// License: Apache 2.0
let cn
Expand Down
6 changes: 3 additions & 3 deletions packages/next/client/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Object.defineProperty(singletonRouter, 'events', {
},
})

urlPropertyFields.forEach((field) => {
urlPropertyFields.forEach((field: string) => {
// Here we need to use Object.defineProperty because, we need to return
// the property assigned to the actual router
// The value might get changed as we change routes and this is the
Expand All @@ -79,15 +79,15 @@ urlPropertyFields.forEach((field) => {
})
})

coreMethodFields.forEach((field) => {
coreMethodFields.forEach((field: string) => {
// We don't really know the types here, so we add them later instead
;(singletonRouter as any)[field] = (...args: any[]) => {
const router = getRouter() as any
return router[field](...args)
}
})

routerEvents.forEach((event) => {
routerEvents.forEach((event: string) => {
singletonRouter.ready(() => {
Router.events.on(event, (...args) => {
const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(
Expand Down
22 changes: 10 additions & 12 deletions packages/next/client/use-intersection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ import requestIdleCallback from './request-idle-callback'
type UseIntersectionObserverInit = Pick<IntersectionObserverInit, 'rootMargin'>
type UseIntersection = { disabled?: boolean } & UseIntersectionObserverInit
type ObserveCallback = (isVisible: boolean) => void
type Observer = {
id: string
observer: IntersectionObserver
elements: Map<Element, ObserveCallback>
}

const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined'

export function useIntersection<T extends Element>({
rootMargin,
disabled,
}: UseIntersection): [(element: T | null) => void, boolean] {
const isDisabled = disabled || !hasIntersectionObserver
const isDisabled: boolean = disabled || !hasIntersectionObserver

const unobserve = useRef<Function>()
const [visible, setVisible] = useState(false)
Expand Down Expand Up @@ -49,12 +54,12 @@ function observe(
element: Element,
callback: ObserveCallback,
options: UseIntersectionObserverInit
) {
): () => void {
const { id, observer, elements } = createObserver(options)
elements.set(element, callback)

observer.observe(element)
return function unobserve() {
return function unobserve(): void {
elements.delete(element)
observer.unobserve(element)

Expand All @@ -66,15 +71,8 @@ function observe(
}
}

const observers = new Map<
string,
{
id: string
observer: IntersectionObserver
elements: Map<Element, ObserveCallback>
}
>()
function createObserver(options: UseIntersectionObserverInit) {
const observers = new Map<string, Observer>()
function createObserver(options: UseIntersectionObserverInit): Observer {
const id = options.rootMargin || ''
let instance = observers.get(id)
if (instance) {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/client/with-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function withRouter<
>(
ComposedComponent: NextComponentType<C, any, P>
): React.ComponentType<ExcludeRouterProps<P>> {
function WithRouterWrapper(props: any) {
function WithRouterWrapper(props: any): JSX.Element {
return <ComposedComponent router={useRouter()} {...props} />
}

Expand Down