From 9b80a834455e568b212831022cb8d578ede6ceea Mon Sep 17 00:00:00 2001 From: Coki <92775570+HashCookie@users.noreply.github.com> Date: Tue, 21 May 2024 00:47:08 +0800 Subject: [PATCH] refactor: reformat the code via eslint rules (#104) * refactor(useIndex): simplify retur statement * chore: update eslint rules and prettier config --- .eslintrc.json | 10 +- .prettierrc.json | 4 +- .../editor/casbin-mode/casbin-conf.ts | 29 +-- .../editor/casbin-mode/casbin-csv.ts | 13 +- app/components/editor/hooks/useIndex.tsx | 55 +----- app/components/editor/hooks/useRunTest.tsx | 44 +---- .../editor/hooks/useSetupEnforceContext.tsx | 16 +- app/components/editor/index.tsx | 172 +++--------------- 8 files changed, 62 insertions(+), 281 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index fc64e1f..521bd13 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,15 +1,13 @@ { - "plugins": [ - ], - "extends": [ - "next/core-web-vitals" - ], + "plugins": [], + "extends": ["next/core-web-vitals"], "rules": { "@typescript-eslint/no-unused-vars": "off", "@typescript-eslint/no-explicit-any": "off", "no-empty-pattern": "off", "no-unused-vars": "off", "arrow-parens": ["error", "always"], - "arrow-body-style": ["error", "always"] + "arrow-body-style": ["error", "always"], + "max-len": ["error", { "code": 150 }] } } diff --git a/.prettierrc.json b/.prettierrc.json index 937375d..b512db8 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,4 +1,6 @@ { "semi": true, - "singleQuote": true + "singleQuote": true, + "printWidth": 150, + "tabWidth": 2 } diff --git a/app/components/editor/casbin-mode/casbin-conf.ts b/app/components/editor/casbin-mode/casbin-conf.ts index 465acda..b15fed7 100755 --- a/app/components/editor/casbin-mode/casbin-conf.ts +++ b/app/components/editor/casbin-mode/casbin-conf.ts @@ -12,12 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { - IndentContext, - LanguageSupport, - StreamLanguage, - StringStream, -} from '@codemirror/language'; +import { IndentContext, LanguageSupport, StreamLanguage, StringStream } from '@codemirror/language'; import { tags as t } from '@lezer/highlight'; const token = (stream: StringStream, state) => { @@ -77,10 +72,7 @@ const token = (stream: StringStream, state) => { if (stream.sol()) { if (state.sec !== '') { - if ( - (state.sec === 'g' && stream.match(new RegExp('^g[2-9]?'))) || - stream.match(state.sec) - ) { + if ((state.sec === 'g' && stream.match(new RegExp('^g[2-9]?'))) || stream.match(state.sec)) { if (stream.peek() === ' ' || stream.peek() === '=') { return 'builtin'; } else { @@ -136,11 +128,7 @@ const token = (stream: StringStream, state) => { } // Match: e = [some]([where] (p.eft == allow)) - if ( - stream.match('some') || - stream.match('where') || - stream.match('priority') - ) { + if (stream.match('some') || stream.match('where') || stream.match('priority')) { return 'keyword'; } @@ -167,10 +155,7 @@ const token = (stream: StringStream, state) => { } // Match: m = [g](r.sub, p.sub) && r.obj == p.obj && r.act == p.act - if ( - stream.match(new RegExp('^[_a-zA-Z][_a-zA-Z0-9]*')) && - stream.peek() === '(' - ) { + if (stream.match(new RegExp('^[_a-zA-Z][_a-zA-Z0-9]*')) && stream.peek() === '(') { return 'def'; } } @@ -187,11 +172,7 @@ export const CasbinConfLang = StreamLanguage.define({ token: token, blankLine: (state: {}, indentUnit: number): void => {}, copyState: (state: {}) => {}, - indent: ( - state: {}, - textAfter: string, - context: IndentContext, - ): number | null => { + indent: (state: {}, textAfter: string, context: IndentContext): number | null => { return 0; }, languageData: { diff --git a/app/components/editor/casbin-mode/casbin-csv.ts b/app/components/editor/casbin-mode/casbin-csv.ts index 563806b..9523262 100755 --- a/app/components/editor/casbin-mode/casbin-csv.ts +++ b/app/components/editor/casbin-mode/casbin-csv.ts @@ -12,12 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { - IndentContext, - LanguageSupport, - StreamLanguage, - StringStream, -} from '@codemirror/language'; +import { IndentContext, LanguageSupport, StreamLanguage, StringStream } from '@codemirror/language'; import { tags as t } from '@lezer/highlight'; const token = (stream: StringStream, state) => { @@ -56,11 +51,7 @@ export const CasbinPolicyLang = StreamLanguage.define({ token: token, blankLine: (state: {}, indentUnit: number): void => {}, copyState: (state: {}) => {}, - indent: ( - state: {}, - textAfter: string, - context: IndentContext, - ): number | null => { + indent: (state: {}, textAfter: string, context: IndentContext): number | null => { return 0; }, languageData: { diff --git a/app/components/editor/hooks/useIndex.tsx b/app/components/editor/hooks/useIndex.tsx index 7998f32..7252d80 100644 --- a/app/components/editor/hooks/useIndex.tsx +++ b/app/components/editor/hooks/useIndex.tsx @@ -1,10 +1,5 @@ import React, { isValidElement, ReactNode, useEffect, useState } from 'react'; -import { - defaultCustomConfig, - defaultEnforceContext, - example, - ModelKind, -} from '@/app/components/editor/casbin-mode/example'; +import { defaultCustomConfig, defaultEnforceContext, example, ModelKind } from '@/app/components/editor/casbin-mode/example'; import { ShareFormat } from '@/app/components/editor/hooks/useShareInfo'; import { defaultEnforceContextData } from '@/app/components/editor/hooks/useSetupEnforceContext'; @@ -17,9 +12,7 @@ export default function useIndex() { const [requestResult, setRequestResult] = useState(''); const [customConfig, setCustomConfig] = useState(''); const [share, setShare] = useState(''); - const [enforceContextData, setEnforceContextData] = useState( - new Map(defaultEnforceContextData), - ); + const [enforceContextData, setEnforceContextData] = useState(new Map(defaultEnforceContextData)); function setPolicyPersistent(text: string): void { setPolicy(text); @@ -58,9 +51,7 @@ export default function useIndex() { setRequestPersistent(sharedContent.request); setRequestPersistent(sharedContent.request); if (sharedContent.enforceContext) { - setEnforceContextDataPersistent( - new Map(Object.entries(sharedContent.enforceContext)), - ); + setEnforceContextDataPersistent(new Map(Object.entries(sharedContent.enforceContext))); } setRequestResult(''); window.location.hash = ''; // prevent duplicate load @@ -77,15 +68,7 @@ export default function useIndex() { setModelText(example[modelKind].model); setRequest(example[modelKind].request); setCustomConfig(defaultCustomConfig); - setEnforceContextData( - new Map( - Object.entries( - JSON.parse( - example[modelKind].enforceContext || defaultEnforceContext, - ), - ), - ), - ); + setEnforceContextData(new Map(Object.entries(JSON.parse(example[modelKind].enforceContext || defaultEnforceContext)))); }, [modelKind]); function handleShare(v: ReactNode | string) { @@ -98,29 +81,9 @@ export default function useIndex() { } } return { - modelKind, - setModelKind, - modelText, - setModelText, - policy, - setPolicy, - request, - setRequest, - echo, - setEcho, - requestResult, - setRequestResult, - customConfig, - setCustomConfig, - share, - setShare, - enforceContextData, - setEnforceContextData, - setPolicyPersistent, - setModelTextPersistent, - setCustomConfigPersistent, - setRequestPersistent, - setEnforceContextDataPersistent, - handleShare, - }; + modelKind, setModelKind, modelText, setModelText, policy, setPolicy, request, + setRequest, echo, setEcho, requestResult, setRequestResult, customConfig, setCustomConfig, share, setShare, + enforceContextData, setEnforceContextData, setPolicyPersistent, setModelTextPersistent, + setCustomConfigPersistent, setRequestPersistent, setEnforceContextDataPersistent, handleShare, + } ; } diff --git a/app/components/editor/hooks/useRunTest.tsx b/app/components/editor/hooks/useRunTest.tsx index 5456de4..21879c5 100755 --- a/app/components/editor/hooks/useRunTest.tsx +++ b/app/components/editor/hooks/useRunTest.tsx @@ -13,13 +13,7 @@ // limitations under the License. import React from 'react'; -import { - DefaultRoleManager, - newEnforcer, - newModel, - StringAdapter, - Util, -} from 'casbin'; +import { DefaultRoleManager, newEnforcer, newModel, StringAdapter, Util } from 'casbin'; import { newEnforceContext } from '@/app/components/editor/hooks/useSetupEnforceContext'; interface RunTestProps { @@ -92,10 +86,7 @@ async function enforcer(props: RunTestProps) { const startTime = performance.now(); const result = []; try { - const e = await newEnforcer( - newModel(props.model), - props.policy ? new StringAdapter(props.policy) : undefined, - ); + const e = await newEnforcer(newModel(props.model), props.policy ? new StringAdapter(props.policy) : undefined); const customConfigCode = props.customConfig; if (customConfigCode) { @@ -133,15 +124,9 @@ async function enforcer(props: RunTestProps) { } if (typeof matchingForGFunction === 'string') { if (matchingForGFunction in config.functions) { - await rm.addMatchingFunc( - config.functions[matchingForGFunction], - ); + await rm.addMatchingFunc(config.functions[matchingForGFunction]); } else { - props.onResponse( -
- Must sure the {matchingForGFunction}() in config.functions -
, - ); + props.onResponse(
Must sure the {matchingForGFunction}() in config.functions
); return; } } @@ -154,27 +139,16 @@ async function enforcer(props: RunTestProps) { } if (typeof matchingDomainForGFunction === 'string') { if (matchingDomainForGFunction in config.functions) { - await rm.addDomainMatchingFunc( - config.functions[matchingDomainForGFunction], - ); + await rm.addDomainMatchingFunc(config.functions[matchingDomainForGFunction]); } else { - props.onResponse( -
- Must sure the {matchingDomainForGFunction}() in - config.functions -
, - ); + props.onResponse(
Must sure the {matchingDomainForGFunction}() in config.functions
); return; } } } } } catch (e) { - props.onResponse( -
- Please check syntax in Custom Function Editor: {(e as any).message} -
, - ); + props.onResponse(
Please check syntax in Custom Function Editor: {(e as any).message}
); return; } } @@ -204,9 +178,7 @@ async function enforcer(props: RunTestProps) { const stopTime = performance.now(); - props.onResponse( -
{'Done in ' + (stopTime - startTime).toFixed(2) + 'ms'}
, - ); + props.onResponse(
{'Done in ' + (stopTime - startTime).toFixed(2) + 'ms'}
); props.onResponse(result); } catch (e) { props.onResponse(
{(e as any).message}
); diff --git a/app/components/editor/hooks/useSetupEnforceContext.tsx b/app/components/editor/hooks/useSetupEnforceContext.tsx index a8a348d..63bdf4e 100644 --- a/app/components/editor/hooks/useSetupEnforceContext.tsx +++ b/app/components/editor/hooks/useSetupEnforceContext.tsx @@ -33,21 +33,11 @@ export const defaultEnforceContextData = new Map([ ]); export const newEnforceContext = (data: Map) => { - return new EnforceContext( - data.get(r)!, - data.get(p)!, - data.get(e)!, - data.get(m)!, - ); + return new EnforceContext(data.get(r)!, data.get(p)!, data.get(e)!, data.get(m)!); }; -export default function useSetupEnforceContext({ - onChange, - data, -}: SetupEnforceContextProps) { - const [enforceContextData, setEnforceContextData] = useState( - new Map(defaultEnforceContextData), - ); +export default function useSetupEnforceContext({ onChange, data }: SetupEnforceContextProps) { + const [enforceContextData, setEnforceContextData] = useState(new Map(defaultEnforceContextData)); const handleEnforceContextChange = (key: string, value: string) => { onChange(data.set(key, value)); }; diff --git a/app/components/editor/index.tsx b/app/components/editor/index.tsx index 64f7dde..b4fc4fa 100755 --- a/app/components/editor/index.tsx +++ b/app/components/editor/index.tsx @@ -15,12 +15,7 @@ 'use client'; import React, { isValidElement, useState, useEffect } from 'react'; import { example, ModelKind } from './casbin-mode/example'; -import { - e, - m, - p, - r, -} from '@/app/components/editor/hooks/useSetupEnforceContext'; +import { e, m, p, r } from '@/app/components/editor/hooks/useSetupEnforceContext'; // prettier-ignore import { clsx } from 'clsx'; import CodeMirror from '@uiw/react-codemirror'; import { monokai } from '@uiw/codemirror-theme-monokai'; @@ -40,41 +35,19 @@ import useIndex from '@/app/components/editor/hooks/useIndex'; export const EditorScreen = () => { const { - modelKind, - setModelKind, - modelText, - setModelText, - policy, - setPolicy, - request, - setRequest, - echo, - setEcho, - requestResult, - setRequestResult, - customConfig, - setCustomConfig, - share, - setShare, - enforceContextData, - setEnforceContextData, - setPolicyPersistent, - setModelTextPersistent, - setCustomConfigPersistent, - setRequestPersistent, - setEnforceContextDataPersistent, - handleShare, - } = useIndex(); - + modelKind, setModelKind, modelText, setModelText, policy, setPolicy, request, + setRequest, echo, setEcho, requestResult, setRequestResult, customConfig, setCustomConfig, share, setShare, + enforceContextData, setEnforceContextData, setPolicyPersistent, setModelTextPersistent, + setCustomConfigPersistent, setRequestPersistent, setEnforceContextDataPersistent, handleShare, + } = useIndex(); const [open, setOpen] = useState(true); const { enforcer } = useRunTest(); const { shareInfo } = useShareInfo(); const { copy } = useCopy(); - const { setupEnforceContextData, setupHandleEnforceContextChange } = - useSetupEnforceContext({ - onChange: setEnforceContextDataPersistent, - data: enforceContextData, - }); + const { setupEnforceContextData, setupHandleEnforceContextChange } = useSetupEnforceContext({ + onChange: setEnforceContextDataPersistent, + data: enforceContextData, + }); useEffect(() => { if (modelKind) { @@ -94,27 +67,11 @@ export const EditorScreen = () => { }, }); } - }, [ - modelKind, - modelText, - policy, - customConfig, - request, - enforceContextData, - enforcer, - setEcho, - setRequestResult, - ]); + }, [modelKind, modelText, policy, customConfig, request, enforceContextData, enforcer, setEcho, setRequestResult]); return (
-
+
-
- {open &&
Custom config
} -
+
{open &&
Custom config
}
{open && (
@@ -159,12 +111,7 @@ export const EditorScreen = () => { bracketMatching: true, indentOnInput: true, }} - extensions={[ - basicSetup, - StreamLanguage.define(go), - indentUnit.of(' '), - EditorView.lineWrapping, - ]} + extensions={[basicSetup, StreamLanguage.define(go), indentUnit.of(' '), EditorView.lineWrapping]} className={'function'} value={customConfig} /> @@ -178,20 +125,8 @@ export const EditorScreen = () => {
-
-
- Model -
+
+
Model
{ value={setupEnforceContextData.get(r)} placeholder={r} onChange={(event) => { - return setupHandleEnforceContextChange( - r, - event.target.value, - ); + return setupHandleEnforceContextChange(r, event.target.value); }} /> { value={setupEnforceContextData.get(p)} placeholder={p} onChange={(event) => { - return setupHandleEnforceContextChange( - p, - event.target.value, - ); + return setupHandleEnforceContextChange(p, event.target.value); }} /> { value={setupEnforceContextData.get(e)} placeholder={e} onChange={(event) => { - return setupHandleEnforceContextChange( - e, - event.target.value, - ); + return setupHandleEnforceContextChange(e, event.target.value); }} /> { value={setupEnforceContextData.get(m)} placeholder={m} onChange={(event) => { - return setupHandleEnforceContextChange( - m, - event.target.value, - ); + return setupHandleEnforceContextChange(m, event.target.value); }} />
@@ -351,12 +252,7 @@ export const EditorScreen = () => { onChange={(value) => { setRequestPersistent(value); }} - extensions={[ - basicSetup, - CasbinPolicySupport(), - indentUnit.of(' '), - EditorView.lineWrapping, - ]} + extensions={[basicSetup, CasbinPolicySupport(), indentUnit.of(' '), EditorView.lineWrapping]} basicSetup={{ lineNumbers: true, highlightActiveLine: true, @@ -371,14 +267,7 @@ export const EditorScreen = () => {
-
- Enforcement Result -
+
Enforcement Result
{ return; }} theme={monokai} - extensions={[ - basicSetup, - javascriptLanguage, - indentUnit.of(' '), - EditorView.lineWrapping, - ]} + extensions={[basicSetup, javascriptLanguage, indentUnit.of(' '), EditorView.lineWrapping]} basicSetup={{ lineNumbers: true, highlightActiveLine: true,