refactor(typescript): use generic instead of simple array type (#205)

This commit is contained in:
Marco Pasqualetti
2024-12-07 11:58:58 +01:00
committed by GitHub
parent 08b75b1a79
commit c76464bf8a
20 changed files with 41 additions and 37 deletions
@@ -9,7 +9,7 @@ interface Breadcrumb {
label: string
}
interface BreadcrumbsProps {
breadcrumbs: Breadcrumb[]
breadcrumbs: Array<Breadcrumb>
}
export default function TuonoBreadcrumbs({
@@ -8,8 +8,8 @@ export interface Heading {
getNode: () => HTMLHeadingElement
}
function getHeadingsData(headings: HTMLHeadingElement[]): Heading[] {
const result: Heading[] = []
function getHeadingsData(headings: Array<HTMLHeadingElement>): Array<Heading> {
const result: Array<Heading> = []
for (const heading of headings) {
if (heading.id) {
@@ -26,7 +26,7 @@ function getHeadingsData(headings: HTMLHeadingElement[]): Heading[] {
return result
}
export function getHeadings(): Heading[] {
export function getHeadings(): Array<Heading> {
const root = document.getElementById('mdx-root')
console.log(root)
@@ -14,7 +14,7 @@ interface TableOfContentsProps {
withTabs: boolean
}
function getActiveElement(rects: DOMRect[]): number {
function getActiveElement(rects: Array<DOMRect>): number {
if (rects.length === 0) {
return -1
}
@@ -40,8 +40,8 @@ export function TableOfContents({
withTabs,
}: TableOfContentsProps): JSX.Element | null {
const [active, setActive] = useState(0)
const [headings, setHeadings] = useState<Heading[]>([])
const headingsRef = useRef<Heading[]>([])
const [headings, setHeadings] = useState<Array<Heading>>([])
const headingsRef = useRef<Array<Heading>>([])
const router = useRouter()
const filteredHeadings = headings.filter((heading) => heading.depth > 1)
+1 -1
View File
@@ -48,7 +48,7 @@ export default tseslint.config(
},
rules: {
// #region @typescript-eslint
'@typescript-eslint/array-type': 'error',
'@typescript-eslint/array-type': ['error', { default: 'generic' }],
'@typescript-eslint/no-wrapper-object-types': 'error',
'@typescript-eslint/no-empty-object-type': 'error',
'@typescript-eslint/no-unsafe-function-type': 'error',
@@ -1,4 +1,5 @@
import { Link } from 'tuono'
import styles from './PokemonView.module.css'
interface Pokemon {
+1 -1
View File
@@ -9,7 +9,7 @@ interface Pokemon {
}
interface IndexProps {
results: Pokemon[]
results: Array<Pokemon>
}
export default function IndexPage({
@@ -1,7 +1,7 @@
import { spaces } from './utils'
import type { RouteNode } from './types'
export function buildRouteConfig(nodes: RouteNode[], depth = 1): string {
export function buildRouteConfig(nodes: Array<RouteNode>, depth = 1): string {
const children = nodes.map((node) => {
const route = `${node.variableName}Route`
@@ -36,9 +36,9 @@ let skipMessage = false
async function getRouteNodes(
config = defaultConfig,
): Promise<{ routeNodes: RouteNode[]; rustHandlersNodes: string[] }> {
const routeNodes: RouteNode[] = []
const rustHandlersNodes: string[] = []
): Promise<{ routeNodes: Array<RouteNode>; rustHandlersNodes: Array<string> }> {
const routeNodes: Array<RouteNode> = []
const rustHandlersNodes: Array<string> = []
async function recurse(dir: string): Promise<void> {
const fullDir = path.resolve(config.folderName, dir)
@@ -127,7 +127,7 @@ export async function routeGenerator(config = defaultConfig): Promise<void> {
const preRouteNodes = sortRouteNodes(beforeRouteNodes)
const routeNodes: RouteNode[] = []
const routeNodes: Array<RouteNode> = []
// Loop over the flat list of routeNodes and
// build up a tree based on the routeNodes' routePath
@@ -3,7 +3,7 @@ import { multiSortBy } from './utils'
import type { RouteNode } from './types'
export function hasParentRoute(
routes: RouteNode[],
routes: Array<RouteNode>,
node: RouteNode,
routePathToCheck = '/',
): RouteNode | null {
@@ -4,7 +4,7 @@ import { ROOT_PATH_ID } from './constants'
// Routes need to be sorted in order to iterate over the handleNode fn
// with first the items that might be parent routes
export const sortRouteNodes = (routes: RouteNode[]): RouteNode[] =>
export const sortRouteNodes = (routes: Array<RouteNode>): Array<RouteNode> =>
multiSortBy(routes, [
(d): number => (d.routePath === '/' ? -1 : 1),
(d): number => d.routePath.split('/').length,
+1 -1
View File
@@ -5,7 +5,7 @@ export interface RouteNode {
path?: string
cleanedPath?: string
isLayout?: boolean
children?: RouteNode[]
children?: Array<RouteNode>
parent?: RouteNode
variableName?: string
}
+3 -3
View File
@@ -34,9 +34,9 @@ export function routePathToVariable(routePath: string): string {
}
export function multiSortBy<T>(
arr: T[],
accessors: ((item: T) => unknown)[] = [(d): unknown => d],
): T[] {
arr: Array<T>,
accessors: Array<(item: T) => unknown> = [(d): unknown => d],
): Array<T> {
return arr
.map((d, i) => [d, i] as const)
.sort(([a, ai], [b, bi]) => {
@@ -36,7 +36,7 @@ interface ParentProps<TData = unknown> {
}
interface TraverseRootComponentsProps<TData = unknown> {
routes: Route[]
routes: Array<Route>
data: TData
isLoading: boolean
children?: React.ReactNode
@@ -84,7 +84,10 @@ const TraverseRootComponents = React.memo(
},
)
const loadParentComponents = (route: Route, loader: Route[] = []): Route[] => {
const loadParentComponents = (
route: Route,
loader: Array<Route> = [],
): Array<Route> => {
const parentComponent = route.options.getParentRoute?.() as Route
loader.push(parentComponent)
+1 -1
View File
@@ -47,7 +47,7 @@ export default function useRoute(pathname?: string): Route | undefined {
for (const dynamicRoute of dynamicRoutes) {
const dynamicRouteSegments = dynamicRoute.split('/').filter(Boolean)
const routeSegmentsCollector: string[] = []
const routeSegmentsCollector: Array<string> = []
for (let i = 0; i < dynamicRouteSegments.length; i++) {
if (
+3 -3
View File
@@ -16,9 +16,9 @@ interface RouterState {
isTransitioning: boolean
status: 'idle'
location: ParsedLocation
matches: string[]
pendingMatches: string[]
cachedMatches: string[]
matches: Array<string>
pendingMatches: Array<string>
cachedMatches: Array<string>
statusCode: 200
updateLocation: (loc: ParsedLocation) => void
}
+2 -2
View File
@@ -24,7 +24,7 @@ export class Route {
path?: string
fullPath!: string
children?: Route[]
children?: Array<Route>
parentRoute?: Route
originalIndex?: number
component: RouteComponent
@@ -77,7 +77,7 @@ export class Route {
this.fullPath = fullPath || ''
}
addChildren(routes: Route[]): Route {
addChildren(routes: Array<Route>): Route {
this.children = routes
return this
}
+1 -1
View File
@@ -59,7 +59,7 @@ export class Router {
}
#buildRouteTree = (): void => {
const recurseRoutes = (childRoutes: Route[]): void => {
const recurseRoutes = (childRoutes: Array<Route>): void => {
childRoutes.forEach((route: Route, i: number) => {
route.init(i)
+3 -3
View File
@@ -1,6 +1,6 @@
import type { Segment } from './types'
export function joinPaths(paths: (string | undefined)[]): string {
export function joinPaths(paths: Array<string | undefined>): string {
return cleanPath(paths.filter(Boolean).join('/'))
}
@@ -9,14 +9,14 @@ function cleanPath(path: string): string {
return path.replace(/\/{2,}/g, '/')
}
export function parsePathname(pathname?: string): Segment[] {
export function parsePathname(pathname?: string): Array<Segment> {
if (!pathname) {
return []
}
pathname = cleanPath(pathname)
const segments: Segment[] = []
const segments: Array<Segment> = []
if (pathname.slice(0, 1) === '/') {
pathname = pathname.substring(1)
+1 -1
View File
@@ -45,7 +45,7 @@ const normalizeViteAlias = (alias?: AliasOptions): AliasOptions | undefined => {
if (!alias) return
if (Array.isArray(alias)) {
return (alias as Extract<AliasOptions, readonly unknown[]>).map(
return (alias as Extract<AliasOptions, ReadonlyArray<unknown>>).map(
({ replacement, ...userAliasDefinition }) => ({
...userAliasDefinition,
replacement: normalizeAliasPath(replacement),
+4 -4
View File
@@ -22,14 +22,14 @@ window.__vite_plugin_react_preamble_installed__ = true
<script type="module" src="http://localhost:${TUONO_DEV_SERVER_PORT}${VITE_PROXY_PATH}/@vite/client"></script>
<script type="module" src="http://localhost:${TUONO_DEV_SERVER_PORT}${VITE_PROXY_PATH}/client-main.tsx"></script>`
function generateCssLinks(cssBundles: string[], mode: Mode): string {
function generateCssLinks(cssBundles: Array<string>, mode: Mode): string {
if (mode === 'Dev') return ''
return cssBundles.reduce((acc, value) => {
return acc + `<link rel="stylesheet" type="text/css" href="/${value}" />`
}, '')
}
function generateJsScripts(jsBundles: string[], mode: Mode): string {
function generateJsScripts(jsBundles: Array<string>, mode: Mode): string {
if (mode === 'Dev') return ''
return jsBundles.reduce((acc, value) => {
return acc + `<script type="module" src="/${value}"></script>`
@@ -44,8 +44,8 @@ export function serverSideRendering(routeTree: RouteTree) {
>
const mode = serverProps.mode as Mode
const jsBundles = serverProps.jsBundles as string[]
const cssBundles = serverProps.cssBundles as string[]
const jsBundles = serverProps.jsBundles as Array<string>
const cssBundles = serverProps.cssBundles as Array<string>
const router = createRouter({ routeTree }) // Render the app
const helmetContext = {}