Skip to content

Commit

Permalink
chore: housekeeping & make eslint happy
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Oct 11, 2024
1 parent dcf6a8e commit 2fffd88
Show file tree
Hide file tree
Showing 27 changed files with 1,197 additions and 1,387 deletions.
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const { resolve } = require('node:path');

const tsconfigPath = resolve(__dirname, 'tsconfig.json');

module.exports = require('eslint-config-sukka').sukka({
Expand Down
32 changes: 16 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,29 @@
"server-only": "^0.0.1"
},
"devDependencies": {
"@eslint-sukka/node": "^6.4.3",
"@eslint-sukka/react": "^6.4.3",
"@eslint-sukka/node": "^6.7.0",
"@eslint-sukka/react": "^6.7.0",
"@napi-rs/magic-string": "^0.3.4",
"@package-json/types": "^0.0.10",
"@package-json/types": "^0.0.11",
"@swc-node/register": "^1.10.9",
"@swc/core": "^1.7.26",
"@types/node": "^20.16.5",
"@types/react": "^18.3.7",
"@swc/core": "^1.7.35",
"@types/node": "^22.7.5",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0",
"brotli-size": "^4.0.0",
"browserslist": "^4.23.3",
"eslint": "^9.10.0",
"eslint-config-sukka": "^6.4.3",
"eslint-formatter-sukka": "^6.4.3",
"fdir": "^6.3.0",
"browserslist": "^4.24.0",
"eslint": "^9.12.0",
"eslint-config-sukka": "^6.7.0",
"eslint-formatter-sukka": "^6.7.0",
"fdir": "^6.4.0",
"gzip-size": "6.0.0",
"next": "^14.2.11",
"next": "^14.2.15",
"react-router-dom": "^6.26.2",
"rollup": "^4.21.3",
"rollup": "^4.24.0",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-swc3": "^0.11.2",
"rollup-preserve-directives": "^1.1.1",
"typescript": "^5.6.2"
"rollup-plugin-swc3": "^0.12.1",
"rollup-preserve-directives": "^1.1.2",
"typescript": "^5.6.3"
},
"peerDependencies": {
"react": "*"
Expand Down
2,384 changes: 1,099 additions & 1,285 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ const externalModules = Object.keys(pkgJson.dependencies)
'react-router-dom',
'next'
]);
const external = (id: string) => {
function external(id: string) {
return externalModules.some((name) => id === name || id.startsWith(`${name}/`));
};
}

// Same target as Next.js 13
const targets = browserslist([
Expand Down
12 changes: 6 additions & 6 deletions src/create-fixed-array/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
const arrayMap = new Map<number, readonly number[]>();

const makeArray = (length: number) => {
function makeArray(length: number) {
const arr = Array.from(new Array(length).keys());
if (process.env.NODE_ENV === 'development') {
Object.freeze(arr);
}

return arr;
};
}

export const createFixedArrayWithoutGC = (length: number): readonly number[] => {
export function createFixedArrayWithoutGC(length: number): readonly number[] {
if (arrayMap.has(length)) {
return arrayMap.get(length)!;
}
const arr = makeArray(length);
arrayMap.set(length, arr);
return arr;
};
}

const arrayWeakRefMap = new Map<number, WeakRef<readonly number[]>>();

export const createFixedArrayWithGC = (length: number): readonly number[] => {
export function createFixedArrayWithGC(length: number): readonly number[] {
let ref: WeakRef<readonly number[]> | undefined;
let array: readonly number[] | undefined;
if (arrayWeakRefMap.has(length)) {
Expand All @@ -37,6 +37,6 @@ export const createFixedArrayWithGC = (length: number): readonly number[] => {
}

return array;
};
}

export const createFixedArray = typeof WeakRef === 'function' ? createFixedArrayWithGC : createFixedArrayWithoutGC;
4 changes: 2 additions & 2 deletions src/create-storage-hook/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ export interface UseStorageParserOption<T> {
deserializer: Deserializer<T>
}

const getServerSnapshotWithoutServerValue = () => {
function getServerSnapshotWithoutServerValue() {
throw noSSRError('useLocalStorage cannot be used on the server without a serverValue');
};
}

export function createStorage(type: StorageType) {
const FOXACT_LOCAL_STORAGE_EVENT_KEY = type === 'localStorage' ? 'foxact-use-local-storage' : 'foxact-use-session-storage';
Expand Down
8 changes: 4 additions & 4 deletions src/no-ssr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const stlProp = Object.getOwnPropertyDescriptor(
const hasSTL = stlProp?.writable && typeof stlProp.value === 'number';

/** @private */
export const noSSRError = (errorMessage?: string, nextjsDigest = 'BAILOUT_TO_CLIENT_SIDE_RENDERING') => {
export function noSSRError(errorMessage?: string, nextjsDigest = 'BAILOUT_TO_CLIENT_SIDE_RENDERING') {
const originalStackTraceLimit = Error.stackTraceLimit;

/**
Expand Down Expand Up @@ -35,11 +35,11 @@ export const noSSRError = (errorMessage?: string, nextjsDigest = 'BAILOUT_TO_CLI
(error as any).recoverableError = 'NO_SSR';

return error;
};
}

/** @see https://foxact.skk.moe/no-ssr */
export const noSSR = (extraMessage?: string) => {
export function noSSR(extraMessage?: string) {
if (typeof window === 'undefined') {
throw noSSRError(extraMessage);
}
};
}
4 changes: 2 additions & 2 deletions src/nullthrow/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// TODO: https://github.com/microsoft/TypeScript/issues/40562

/** @see https://foxact.skk.moe/invariant-nullthrow */
export const nullthrow = <T>(value: T, message = '[foxact/invariant] "value" is null or undefined'): NonNullable<T> => {
export function nullthrow<T>(value: T, message = '[foxact/invariant] "value" is null or undefined'): NonNullable<T> {
if (value === null || value === undefined) {
throw new TypeError(message);
}
return value;
};
}
4 changes: 2 additions & 2 deletions src/rem/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const SIXTEEN_PX = '16px';

const scaleRem = (remValue: string, shouldScaleTo: '16px' | (string & {}) | null = null) => {
function scaleRem(remValue: string, shouldScaleTo: '16px' | (string & {}) | null = null) {
if (shouldScaleTo && shouldScaleTo !== SIXTEEN_PX) {
return `calc(${remValue} * ${shouldScaleTo})`;
}
return remValue;
};
}

export function createConverter(units: string, shouldScaleTo: '16px' | (string & {}) | null = null, htmlFontSize = 16) {
return function converter(this: void, value: number | string | number[]): string {
Expand Down
7 changes: 4 additions & 3 deletions src/use-abortable-effect/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import 'client-only';
import { type EffectCallback, useEffect as useEffectFromReact, type DependencyList } from 'react';
import { useEffect as useEffectFromReact } from 'react';
import type { EffectCallback, DependencyList } from 'react';

/** @see https://foxact.skk.moe/use-abortable-effect */
export const useAbortableEffect = (callback: (signal: AbortSignal) => ReturnType<EffectCallback>, deps: DependencyList) => {
export function useAbortableEffect(callback: (signal: AbortSignal) => ReturnType<EffectCallback>, deps: DependencyList) {
useEffectFromReact(() => {
const controller = new AbortController();
const signal = controller.signal;
Expand All @@ -12,5 +13,5 @@ export const useAbortableEffect = (callback: (signal: AbortSignal) => ReturnType
f?.();
};
}, deps);
};
}
export const useEffect = useAbortableEffect;
4 changes: 2 additions & 2 deletions src/use-array/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'client-only';
import { useCallback, useState } from 'react';

export const useArray = <T>(initialState: T[] | (() => T[]) = () => []) => {
export function useArray<T>(initialState: T[] | (() => T[]) = () => []) {
const [array, setArray] = useState<T[]>(initialState);

const add = useCallback((v: T) => setArray((prevArray) => prevArray.concat(v)), []);
Expand All @@ -17,4 +17,4 @@ export const useArray = <T>(initialState: T[] | (() => T[]) = () => []) => {
}), []);

return [array, add, reset, removeByIndex] as const;
};
}
12 changes: 7 additions & 5 deletions src/use-composition-input/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ export interface UseCompositionInputReturn<T extends HTMLInputElement | HTMLText
onCompositionEnd: React.CompositionEventHandler<T>
}

const getInitialRef = () => ({
function getInitialRef() {
return {
/** is"C"ompositioning */ c: false,
/** is"E"mitted */ e: false
});
/** is"E"mitted */ e: false
};
}

/** @see https://foxact.skk.moe/use-composition-input */
export const useCompositionInput = <T extends HTMLInputElement | HTMLTextAreaElement = HTMLInputElement>(cb: UseCompositionInputCallback): UseCompositionInputReturn<T> => {
export function useCompositionInput<T extends HTMLInputElement | HTMLTextAreaElement = HTMLInputElement>(cb: UseCompositionInputCallback): UseCompositionInputReturn<T> {
const internalState = useSingleton(getInitialRef);

const onChange = useCallback((e: React.ChangeEvent<T> | React.CompositionEvent<T>) => {
Expand Down Expand Up @@ -55,4 +57,4 @@ export const useCompositionInput = <T extends HTMLInputElement | HTMLTextAreaEle
onCompositionStart,
onCompositionEnd
};
};
}
13 changes: 5 additions & 8 deletions src/use-error-boundary/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@ import { useState } from 'react';

type ErrorLike = Error | undefined | null | boolean;

const isTruthy = (value: ErrorLike): value is Error => {
if (value === false) return false;
if (value == null) return false;

return true;
};
function isTruthy(value: ErrorLike): value is Error {
return !(value === false || value == null);
}

/** @see https://foxact.skk.moe/use-error-boundary */
export const useErrorBoundary = (givenError: ErrorLike = false) => {
export function useErrorBoundary(givenError: ErrorLike = false) {
const [error, setError] = useState<ErrorLike>(false);

if (isTruthy(givenError)) throw givenError;
if (isTruthy(error)) throw error;
return setError;
};
}
4 changes: 2 additions & 2 deletions src/use-is-client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'client-only';
import { useEffect, useState } from 'react';

/** @see https://foxact.skk.moe/use-is-client */
export const useIsClient = () => {
export function useIsClient() {
const [mounted, setMounted] = useState(false);

useEffect(() => {
Expand All @@ -13,4 +13,4 @@ export const useIsClient = () => {
}, []);

return mounted;
};
}
4 changes: 2 additions & 2 deletions src/use-map/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'client-only';
import { useCallback, useState } from 'react';

export const useMap = <K, T>(initialState: Map<K, T> | (() => Map<K, T>) = () => new Map<K, T>()) => {
export function useMap<K, T>(initialState: Map<K, T> | (() => Map<K, T>) = () => new Map<K, T>()) {
const [map, setMap] = useState<Map<K, T>>(initialState);

const add = useCallback((k: K, v: T) => setMap((prevMap) => {
Expand All @@ -21,4 +21,4 @@ export const useMap = <K, T>(initialState: Map<K, T> | (() => Map<K, T>) = () =>
const setAll = useCallback((m: Map<K, T>) => setMap(m), []);

return [map, add, remove, reset, setAll] as const;
};
}
13 changes: 7 additions & 6 deletions src/use-media-query/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useCallback, useSyncExternalStore } from 'react';

const externalStore = new Map<string, boolean>(); // External store to hold the state of each media query

const subscribeToMediaQuery = (mq: string, callback: VoidFunction) => {
function subscribeToMediaQuery(mq: string, callback: VoidFunction) {
if (typeof window === 'undefined') return noop;

const mediaQueryList = window.matchMedia(mq);
Expand All @@ -23,14 +23,15 @@ const subscribeToMediaQuery = (mq: string, callback: VoidFunction) => {
return () => {
mediaQueryList.removeEventListener('change', handleChange); // Cleanup function to remove listener
};
};
}

const getServerSnapshotWithoutServerValue = () => {
function getServerSnapshotWithoutServerValue(): never {
throw noSSRError('useMediaQuery cannot be used on the server without a serverValue');
};
}

/** @see https://foxact.skk.moe/use-media-query */
export const useMediaQuery = (mq: string, serverValue?: boolean): boolean => {
// eslint-disable-next-line sukka/bool-param-default -- serveValue is intentionally optional
export function useMediaQuery(mq: string, serverValue?: boolean): boolean {
if (typeof window !== 'undefined' && !externalStore.has(mq)) {
// This part of the code should only run once per media query, on client-side only
// since we are on the client-side, let's get initial value directly from DOM
Expand All @@ -51,4 +52,4 @@ export const useMediaQuery = (mq: string, serverValue?: boolean): boolean => {
: () => serverValue;

return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); // Use useSyncExternalStore to manage the subscription and state
};
}
20 changes: 8 additions & 12 deletions src/use-next-link/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export interface UseNextLinkReturnProps extends Partial<React.JSX.IntrinsicEleme
href?: string
}

const isModifiedEvent = (event: React.MouseEvent<HTMLAnchorElement>) => {
function isModifiedEvent(event: React.MouseEvent<HTMLAnchorElement>) {
const eventTarget = event.currentTarget;
const target = eventTarget.getAttribute('target');
return (
Expand All @@ -58,17 +58,15 @@ const isModifiedEvent = (event: React.MouseEvent<HTMLAnchorElement>) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-deprecated -- back compat
|| (event.nativeEvent && event.nativeEvent.which === 2)
);
};
}

// https://github.com/vercel/next.js/blob/39589ff35003ba73f92b7f7b349b3fdd3458819f/packages/next/src/client/components/router-reducer/router-reducer-types.ts#L148
const PREFETCH_APPROUTER_AUTO = 'auto';
const PREFETCH_APPROUTER_FULL = 'full';

const prefetch = (
router: ReturnType<typeof useRouter>,
function prefetch(router: ReturnType<typeof useRouter>,
href: string,
options: AppRouterPrefetchOptions
) => {
options: AppRouterPrefetchOptions) {
if (typeof window === 'undefined') {
return;
}
Expand All @@ -83,11 +81,10 @@ const prefetch = (
throw err;
}
});
};
}

/** @see https://foxact.skk.moe/use-next-link */
const useNextLink = (
hrefProp: string | UrlObject,
function useNextLink(hrefProp: string | UrlObject,
{
prefetch: prefetchProp,
ref,
Expand All @@ -97,8 +94,7 @@ const useNextLink = (
scroll: routerScroll = true,
replace = false,
...restProps // Record<string, never>
}: UseNextLinkOptions
): [isPending: boolean, linkProps: UseNextLinkReturnProps] => {
}: UseNextLinkOptions): [isPending: boolean, linkProps: UseNextLinkReturnProps] {
// Type guard to make sure there is no more props left in restProps
if (process.env.NODE_ENV === 'development') {
const _: Record<string, never> = restProps;
Expand Down Expand Up @@ -239,6 +235,6 @@ const useNextLink = (
isPending,
childProps
] as const;
};
}

export const unstable_useNextLink = useNextLink;
4 changes: 2 additions & 2 deletions src/use-next-pathname/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useRouter } from 'next/router.js';
import { useMemo } from 'react';

/** @see https://foxact.skk.moe/use-next-pathname */
export const useNextPathname = (ensureTrailingSlash = false) => {
export function useNextPathname(ensureTrailingSlash = false) {
const { asPath } = useRouter();
return useMemo(() => {
const path = asPath.split(/[#?]/)[0];
Expand All @@ -13,4 +13,4 @@ export const useNextPathname = (ensureTrailingSlash = false) => {
}
return path;
}, [ensureTrailingSlash, asPath]);
};
}
Loading

0 comments on commit 2fffd88

Please sign in to comment.