Skip to content

Commit

Permalink
style(projects): optimize code style
Browse files Browse the repository at this point in the history
  • Loading branch information
mufeng889 committed Aug 31, 2024
1 parent f27d4c3 commit 0eded8d
Show file tree
Hide file tree
Showing 44 changed files with 164 additions and 207 deletions.
2 changes: 1 addition & 1 deletion ErrorBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const ErrorPage: FC<Props> = ({ error, resetErrorBoundary }) => {
// 可以在这里根据不同的业务逻辑处理错误或者上报给日志服务
const hook = HookSupportChecker()

console.error(error, 999);
console.error(error);

return (
<div className="size-full min-h-520px flex-col-center gap-16px overflow-hidden">
Expand Down
11 changes: 5 additions & 6 deletions build/plugins/auto-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function setupAutoImport(viteEnv: Env.ImportMeta) {
return AutoImport({
imports: ['react', 'react-router-dom', 'react-i18next', 'ahooks', { from: 'react', imports: ['FC'], type: true }],
include: [/\.[tj]sx?$/],
dirs: ['src/hooks/**','src/components/**'],
dirs: ['src/hooks/**', 'src/components/**'],
dts: 'src/types/auto-imports.d.ts',
resolvers: [
IconsResolver({
Expand All @@ -20,11 +20,10 @@ export function setupAutoImport(viteEnv: Env.ImportMeta) {
});
}


function autoImportAntd(componentName:string)
{
function autoImportAntd(componentName: string) {
const pattern = /^A[A-Z]/;
if (pattern.test(componentName)) {
return { name: componentName.slice(1), from: 'antd' }
if (!pattern.test(componentName)) {
return { name: componentName.slice(1), from: 'antd' };
}
return null;
}
2 changes: 1 addition & 1 deletion build/plugins/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function setupElegantRouter() {
base: 'src/layouts/base-layout/index.tsx',
blank: 'src/layouts/blank-layout/index.tsx'
},
log:false,
log: false,
customRoutes: {
names: [
'exception_403',
Expand Down
4 changes: 2 additions & 2 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ export default defineConfig(
singleAttributePerLine: true,
trailingCommas: 'none'
},
ignores: ['src/layouts/modules/global-tab/index.tsx']
ignores: ['src/layouts/modules/global-tab/index.tsx', 'ErrorBoundary.tsx']
},
{
rules: {
'no-underscore-dangle': 'off',
'react/jsx-no-undef': [true, { allowGlobals: true }]
'react/jsx-no-undef': 'off'
}
}
);
2 changes: 1 addition & 1 deletion packages/simple-router/src/hooks/useRouter/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createContext, useContext } from 'react';

import Router from '../../router'
import type Router from '../../router';

export const RouterContext = createContext<Router>({} as Router);
export function useRouter() {
Expand Down
4 changes: 1 addition & 3 deletions packages/simple-router/src/matcher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ class CreateRouterMatcher {
const parentPath = parent.record.path as string;
const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/';
normalizedRecord.path = parent.record.path + (path && connectingSlash + path);

}

// create the object beforehand, so it can be passed to children
Expand Down Expand Up @@ -204,7 +203,7 @@ class CreateRouterMatcher {
* @returns An array of route names.
*/
getAllRouteNames() {
return Array.from(this.matcherMap.keys())
return Array.from(this.matcherMap.keys());
}

/**
Expand All @@ -213,7 +212,6 @@ class CreateRouterMatcher {
* @param matcher - The matcher object to insert.
*/
insertMatcher(matcher: RouteRecordRaw) {

if (matcher.record.path === '*') {
this.matchers.unshift(matcher);
} else {
Expand Down
2 changes: 1 addition & 1 deletion packages/simple-router/src/matcher/pathMatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export function createRouteRecordMatcher(record: RouteRecordNormalized, parent?:
parent,
// these needs to be populated by the parent
children: [],
name:record.name
name: record.name
};

if (parent) {
Expand Down
12 changes: 6 additions & 6 deletions packages/simple-router/src/matcher/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,16 @@ export function generatePath(pathTemplate: string, params: { [key: string]: stri
* @returns the normalized version
*/
export function normalizeRouteRecord(record: ElegantConstRoute): RouteRecordNormalized {

return {
redirect: record.redirect||record.children&&record.children[0].path,
redirect: record.redirect || (record.children && record.children[0].path),
path: record.path || '',
name: record.name,
meta: record.meta || {},
children: record.children?.map(child => {
child.redirect=child.redirect||child.children&&child.children[0].path
return child
}) || [],
children:
record.children?.map(child => {
child.redirect ||= child.children && child.children[0].path;
return child;
}) || [],
component: record.component
};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/simple-router/src/matcher/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ export interface RouteRecordRaw {
record: RouteRecordNormalized;
children: RouteRecordRaw[];
parent: RouteRecordRaw | undefined;
name?:string
name?: string;
}
63 changes: 25 additions & 38 deletions packages/simple-router/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
import React from 'react';
import type { RouteLocationNamedRaw, RouteLocationNormalizedLoaded, RouterOptions } from './types';
import CreateRouterMatcher from './matcher';
import type { RouteRecordNormalized } from './matcher/types';
import type { RouteRecordNormalized, RouteRecordRaw } from './matcher/types';
import { START_LOCATION_NORMALIZED } from './types';
import { RouterContext } from './hooks/useRouter';
import { RouteContext } from './hooks/useRoute';
import { warn } from './warning';
import type { RouteRecordRaw } from './matcher/types'

const historyCreatorMap: Record<
'hash' | 'history' | 'memory',
Expand Down Expand Up @@ -90,33 +89,30 @@ class CreateRouter {
});

// Update react-router's routes
this.#changeRoutes()
this.#changeRoutes();
}

#changeRoutes() {
this.reactRouter._internalSetRoutes([...this.initReactRoutes, ...this.reactRoutes]);
}

removeRoute(name: string) {
const matched = this.matcher.getRecordMatcher(name)
if (!matched) return
const matched = this.matcher.getRecordMatcher(name);
if (!matched) return;
if (matched.parent) {
const parentNames = findParentNames(matched.parent);
let routes = this.reactRoutes;

const parentNames = findParentNames(matched.parent)
let routes = this.reactRoutes

parentNames.forEach(name => {
const finalRoute = routes.find(route => route.id === name)
if (finalRoute && finalRoute.children) routes = finalRoute.children
})
removeElement(routes, matched.name)

parentNames.forEach(parentName => {
const finalRoute = routes.find(route => route.id === parentName);
if (finalRoute && finalRoute.children) routes = finalRoute.children;
});
removeElement(routes, matched.name);
} else {
this.reactRoutes = this.reactRoutes.filter(route => route.id !== matched.record.name)
this.reactRoutes = this.reactRoutes.filter(route => route.id !== matched.record.name);
}
this.#changeRoutes()
this.#changeRoutes();
this.matcher.removeRoute(name);

}

#onBeforeRouteChange = (
Expand All @@ -142,22 +138,20 @@ class CreateRouter {
if (to.redirect) {
if (to.redirect.startsWith('/')) {
if (to.redirect === this.currentRoute.fullPath) {
return true
return true;
}
} else {
const finalRoute = to.matched[to.matched.length - 1]

const finalRoute = to.matched[to.matched.length - 1];

const finalPath = getFullPath(finalRoute)
const finalPath = getFullPath(finalRoute);

if (finalPath === this.currentRoute.fullPath) return true
if (finalPath === this.currentRoute.fullPath) return true;
}
}

return beforeEach(to, this.currentRoute, this.#next);
};


#next(param?: boolean | string | Location | RouteLocationNamedRaw) {
if (!param) return false;
if (typeof param === 'string') {
Expand Down Expand Up @@ -319,26 +313,21 @@ function cleanParams(params: Record<string, any> | undefined): Record<string, an
return Object.fromEntries(Object.entries(params).filter(([_, value]) => value !== null));
}





function findParentNames(matched: RouteRecordRaw | undefined): (string | undefined)[] {
const parentNames: (string | undefined)[] = []
const parentNames: (string | undefined)[] = [];

function helper(current: RouteRecordRaw | undefined) {
if (current?.parent) {
helper(current.parent)
helper(current.parent);
}
parentNames.push(current?.name)
parentNames.push(current?.name);
}

helper(matched)
helper(matched);

return parentNames
return parentNames;
}


function removeElement(arr: RouteObject[], name: string | undefined) {
const index = arr.findIndex(route => route.id === name);
if (index !== -1) {
Expand All @@ -347,15 +336,13 @@ function removeElement(arr: RouteObject[], name: string | undefined) {
return arr;
}


function getFullPath(route: RouteRecordNormalized | ElegantConstRoute ): string {
function getFullPath(route: RouteRecordNormalized | ElegantConstRoute): string {
// 如果当前 route 存在并且有 children
if (route && route.redirect && route.children && route.children.length > 0) {
// 获取第一个子路由
const firstChild = route.children.find(child => child.path === route.redirect)
const firstChild = route.children.find(child => child.path === route.redirect);
// 递归调用,继续拼接子路由的 path
if (firstChild)
return `${route.path}/${getFullPath(firstChild)}`;
if (firstChild) return `${route.path}/${getFullPath(firstChild)}`;
}
// 如果没有 children,返回当前 route 的 path
return route.path;
Expand Down
4 changes: 2 additions & 2 deletions packages/simple-router/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ export interface Router {
back: () => void;
forwardRef: () => void;
go: (delta: number) => void;
removeRoute:(name:string)=>void;
removeRoute: (name: string) => void;
}
export interface HistoryStateArray extends Array<HistoryStateValue> { }
export interface HistoryStateArray extends Array<HistoryStateValue> {}

export type HistoryStateValue = string | number | boolean | null | undefined | HistoryState | HistoryStateArray;

Expand Down
4 changes: 1 addition & 3 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
},
"typesVersions": {
"*": {
"*": [
"./src/*"
]
"*": ["./src/*"]
}
},
"dependencies": {
Expand Down
24 changes: 12 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { useUpdateEffect } from 'ahooks';
import type { WatermarkProps } from 'antd';
import { localStg } from '@/utils/storage';
import { getLocale } from '@/store/slice/app';
import { getAntdTheme, setupThemeVarsToHtml, toggleCssDarkMode } from '@/store/slice/theme/shared.ts';
import { getDarkMode, themeColors, getThemeSettings } from '@/store/slice/theme';
import { getDarkMode, getThemeSettings, themeColors } from '@/store/slice/theme';
import MenuProvider from '@/components/stateful/MenuProvider.tsx';
import { router } from '@/router';
import { info } from '@/constants/app.ts';
import { antdLocales } from './locales/antd';
import AppProvider from './components/stateful/AppProvider.tsx';
import { info } from '@/constants/app.ts'
import type { WatermarkProps } from 'antd'

const watermarkProps: WatermarkProps = {
font: {
fontSize: 16,
fontSize: 16
},
width: 240,
height: 128,
Expand All @@ -26,7 +26,6 @@ function useTheme() {
const darkMode = useAppSelector(getDarkMode);
const antdTheme = getAntdTheme(colors, darkMode);


useEffect(() => {
setupThemeVarsToHtml(colors);
localStg.set('themeColor', colors.primary);
Expand All @@ -38,16 +37,15 @@ function useTheme() {

console.info(`%c${info}`, `color: ${colors.primary}`);

return antdTheme
return antdTheme;
}

const App = () => {
const locale = useAppSelector(getLocale);

const themeSettings = useAppSelector(getThemeSettings);

const antdTheme=useTheme()

const antdTheme = useTheme();

return (
<AConfigProvider
Expand All @@ -56,10 +54,12 @@ const App = () => {
button={{ classNames: { icon: 'align-1px text-icon' } }}
>
<AppProvider>
<AWatermark content={themeSettings.watermark.visible ? themeSettings.watermark?.text || 'Soybean' : ''} className='h-full' {...watermarkProps} >
<MenuProvider>
{router.CustomRouterProvider(<GlobalLoading />)}
</MenuProvider>
<AWatermark
content={themeSettings.watermark.visible ? themeSettings.watermark?.text || 'Soybean' : ''}
className="h-full"
{...watermarkProps}
>
<MenuProvider>{router.CustomRouterProvider(<GlobalLoading />)}</MenuProvider>
</AWatermark>
</AppProvider>
</AConfigProvider>
Expand Down
7 changes: 1 addition & 6 deletions src/components/stateful/MenuProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,7 @@ export default MenuProvider;
*/
function getGlobalMenuByBaseRoute(route: ElegantConstRoute): MenuItemType {
const { name } = route;
const {
title,
i18nKey,
icon = import.meta.env.VITE_MENU_ICON,
localIcon
} = route.meta ?? {};
const { title, i18nKey, icon = import.meta.env.VITE_MENU_ICON, localIcon } = route.meta ?? {};

const label = i18nKey ? $t(i18nKey) : title!;
const menu: MenuItemType = {
Expand Down
5 changes: 2 additions & 3 deletions src/components/stateful/SoybeanAvatar.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import ClassNames from 'classnames';
import soybeanAvatar from '@/assets/imgs/soybean.jpg';


const SoybeanAvatar: FC<React.ComponentProps<'div'>> = ({ className, ...props }) => {
const SoybeanAvatar: FC<React.ComponentProps<'div'>> = memo(({ className, ...props }) => {
return (
<div
{...props}
Expand All @@ -14,6 +13,6 @@ const SoybeanAvatar: FC<React.ComponentProps<'div'>> = ({ className, ...props })
/>
</div>
);
};
});

export default SoybeanAvatar;
Loading

0 comments on commit 0eded8d

Please sign in to comment.