Skip to content

Commit

Permalink
refactor(typescript): use generic instead of simple array type (#205)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcalexiei authored Dec 7, 2024
1 parent 08b75b1 commit c76464b
Show file tree
Hide file tree
Showing 20 changed files with 41 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ interface Breadcrumb {
label: string
}
interface BreadcrumbsProps {
breadcrumbs: Breadcrumb[]
breadcrumbs: Array<Breadcrumb>
}

export default function TuonoBreadcrumbs({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions examples/tuono-tutorial/src/components/PokemonView.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Link } from 'tuono'

import styles from './PokemonView.module.css'

interface Pokemon {
Expand Down
2 changes: 1 addition & 1 deletion examples/tuono-tutorial/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ interface Pokemon {
}

interface IndexProps {
results: Pokemon[]
results: Array<Pokemon>
}

export default function IndexPage({
Expand Down
2 changes: 1 addition & 1 deletion packages/fs-router-vite-plugin/src/build-route-config.ts
Original file line number Diff line number Diff line change
@@ -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`

Expand Down
8 changes: 4 additions & 4 deletions packages/fs-router-vite-plugin/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/fs-router-vite-plugin/src/has-parent-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion packages/fs-router-vite-plugin/src/sort-route-nodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/fs-router-vite-plugin/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export interface RouteNode {
path?: string
cleanedPath?: string
isLayout?: boolean
children?: RouteNode[]
children?: Array<RouteNode>
parent?: RouteNode
variableName?: string
}
Expand Down
6 changes: 3 additions & 3 deletions packages/fs-router-vite-plugin/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]) => {
Expand Down
7 changes: 5 additions & 2 deletions packages/router/src/components/RouteMatch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ interface ParentProps<TData = unknown> {
}

interface TraverseRootComponentsProps<TData = unknown> {
routes: Route[]
routes: Array<Route>
data: TData
isLoading: boolean
children?: React.ReactNode
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion packages/router/src/hooks/useRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
6 changes: 3 additions & 3 deletions packages/router/src/hooks/useRouterStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions packages/router/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class Route {
path?: string
fullPath!: string

children?: Route[]
children?: Array<Route>
parentRoute?: Route
originalIndex?: number
component: RouteComponent
Expand Down Expand Up @@ -77,7 +77,7 @@ export class Route {
this.fullPath = fullPath || ''
}

addChildren(routes: Route[]): Route {
addChildren(routes: Array<Route>): Route {
this.children = routes
return this
}
Expand Down
2 changes: 1 addition & 1 deletion packages/router/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
6 changes: 3 additions & 3 deletions packages/router/src/utils.ts
Original file line number Diff line number Diff line change
@@ -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('/'))
}

Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion packages/tuono/src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 4 additions & 4 deletions packages/tuono/src/ssr/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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>`
Expand All @@ -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 = {}
Expand Down

0 comments on commit c76464b

Please sign in to comment.