Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: remove "syntax validate" button, add toast message to run button #170

Merged
merged 8 commits into from
Nov 29, 2024
8 changes: 4 additions & 4 deletions app/components/editor/hooks/useIndex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default function useIndex() {
const hash = window.location.hash.slice(1);
if (hash && hash !== loadState.current.loadedHash) {
loadState.current.loadedHash = hash;
setEcho(<div>Loading Shared Content...</div>);
setEcho(<div className="text-orange-500">Loading Shared Content...</div>);
fetch(`https://dpaste.com/${hash}.txt`)
.then((resp) => {
return resp.ok ? resp.text() : Promise.reject(`HTTP error: ${resp.status}`);
Expand All @@ -54,10 +54,10 @@ export default function useIndex() {
loadState.current.content = parsed;
const newModelKind = parsed?.modelKind && parsed.modelKind in example ? (parsed.modelKind as ModelKind) : 'basic';
setModelKind(newModelKind);
setEcho(<div>Shared Content Loaded.</div>);
setEcho(<div className="text-green-500">Shared Content Loaded.</div>);
})
.catch((error) => {
return setEcho(<div>Failed to load: {error}</div>);
return setEcho(<div className="text-red-500">Failed to load: {error}</div>);
});
}
}, []);
Expand All @@ -79,7 +79,7 @@ export default function useIndex() {
} else {
const currentPath = window.location.origin + window.location.pathname;
setShare(v as string);
setEcho(<div>{`Shared at ${currentPath}#${v}`}</div>);
setEcho(<div className="text-green-500">{`Shared at ${currentPath}#${v}`}</div>);
}
}

Expand Down
4 changes: 2 additions & 2 deletions app/components/editor/hooks/useRunTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,11 @@ async function enforcer(props: RunTestProps) {

setError(null);

props.onResponse(<div>{'Done in ' + (stopTime - startTime).toFixed(2) + 'ms'}</div>);
props.onResponse(<div className="text-green-500">{'Done in ' + (stopTime - startTime).toFixed(2) + 'ms'}</div>);
props.onResponse(result);
} catch (e) {
const errorMessage = (e as any).message;
props.onResponse(<div>{errorMessage}</div>);
props.onResponse(<div className="text-red-500">{errorMessage}</div>);
props.onResponse([]);
setError(errorMessage);
}
Expand Down
6 changes: 3 additions & 3 deletions app/components/editor/hooks/useShareInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function useShareInfo() {
function shareInfo(props: ShareProps) {
if (sharing) return;
setSharing(true);
props.onResponse(<div>Sharing...</div>);
props.onResponse(<div className="text-orange-500">Sharing...</div>);

// Create an object that contains only non-null values
const shareContent: ShareFormat = {
Expand All @@ -58,7 +58,7 @@ export default function useShareInfo() {
// Check if there are any non-null values to share
if (Object.keys(shareContent).length === 0) {
setSharing(false);
props.onResponse(<div>No content to share</div>);
props.onResponse(<div className="text-red-500">No content to share</div>);
return;
}

Expand All @@ -70,7 +70,7 @@ export default function useShareInfo() {
})
.catch((error) => {
setSharing(false);
props.onResponse(<div>Error sharing content: {error.message}</div>);
props.onResponse(<div className="text-red-500">Error sharing content: {error.message}</div>);
});
}

Expand Down
49 changes: 22 additions & 27 deletions app/components/editor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { go } from '@codemirror/legacy-modes/mode/go';
import { EditorView } from '@codemirror/view';
import { CasbinConfSupport } from '@/app/components/editor/casbin-mode/casbin-conf';
import { CasbinPolicySupport } from '@/app/components/editor/casbin-mode/casbin-csv';
import { Config } from 'casbin';
import { javascriptLanguage } from '@codemirror/lang-javascript';
import useRunTest from '@/app/components/editor/hooks/useRunTest';
import useShareInfo from '@/app/components/editor/hooks/useShareInfo';
Expand All @@ -25,6 +24,7 @@ import { useLang } from '@/app/context/LangContext';
import LanguageMenu from '@/app/components/LanguageMenu';
import { linter, lintGutter } from '@codemirror/lint';
import { casbinLinter } from '@/app/utils/casbinLinter';
import { toast, Toaster } from 'react-hot-toast';

export const EditorScreen = () => {
const {
Expand Down Expand Up @@ -54,6 +54,7 @@ export const EditorScreen = () => {
return message;
};
const { t, lang, theme, toggleTheme } = useLang();
const [isContentLoaded, setIsContentLoaded] = useState(false);

useEffect(() => {
const fetchCasbinVersion = async () => {
Expand All @@ -65,7 +66,8 @@ export const EditorScreen = () => {
}, []);

useEffect(() => {
if (modelKind) {
if (modelKind && modelText) {
setIsContentLoaded(true);
enforcer({
modelKind,
model: modelText,
Expand Down Expand Up @@ -94,6 +96,7 @@ export const EditorScreen = () => {

return (
<div className="flex flex-col sm:flex-row h-full">
<Toaster position="top-center" />
<div
className={clsx('sm:relative', 'pl-0 sm:pl-2 pr-0 sm:pr-2 border-r border-[#dddddd]', 'transition-all duration-300', {
'hidden sm:block': !showCustomConfig,
Expand Down Expand Up @@ -388,27 +391,6 @@ export const EditorScreen = () => {
</div>
<div className={clsx('pt-2 px-1 flex flex-col sm:flex-row items-start sm:items-center')}>
<div className="flex flex-row flex-wrap gap-2 mb-2 sm:mb-0 w-full sm:w-auto">
<button
className={clsx(
'rounded',
'px-2 py-1',
'border border-[#453d7d]',
'bg-[#efefef]',
'text-[#453d7a]',
'hover:bg-[#453d7d] hover:text-white',
'transition-colors duration-500',
)}
onClick={() => {
try {
Config.newConfigFromText(modelText);
setEcho(<div>Passed</div>);
} catch (e) {
setEcho(<div>{(e as any).message}</div>);
}
}}
>
{t('SYNTAX VALIDATE')}
</button>
<button
className={clsx(
'rounded',
Expand All @@ -427,18 +409,30 @@ export const EditorScreen = () => {
customConfig,
request,
enforceContextData,
onResponse: (v) => {
onResponse: (v: JSX.Element | any[]) => {
if (isValidElement(v)) {
setEcho(v);
const props = (v as any).props;
if (props.className?.includes('text-red-500')) {
const errorMessage = props.children;
toast.error(errorMessage);
setRequestResult(errorMessage);
}
} else if (Array.isArray(v)) {
const formattedResults = v.map((res) => {
if (typeof res === 'object') {
const reasonString = Array.isArray(res.reason) && res.reason.length > 0 ? ` Reason: ${JSON.stringify(res.reason)}` : '';
const reasonString = Array.isArray(res.reason) && res.reason.length > 0
? ` Reason: ${JSON.stringify(res.reason)}`
: '';
return `${res.okEx}${reasonString}`;
}
return res;
});
setRequestResult(formattedResults.join('\n'));
const result = formattedResults.join('\n');
setRequestResult(result);
if (result && !result.includes('error')) {
toast.success('Test completed successfully');
}
}
},
});
Expand Down Expand Up @@ -488,7 +482,8 @@ export const EditorScreen = () => {
return copy(
() => {
setShare('');
setEcho(<div>{t('Copied')}</div>);
setEcho(<div className="text-green-500">{t('Copied')}</div>);
toast.success(t('Link copied to clipboard'));
},
`${window.location.origin + window.location.pathname}#${share}`,
);
Expand Down
2 changes: 1 addition & 1 deletion app/utils/contentExtractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const extractPageContent = (boxType: string, t: (key: string) => string,
const modelMatch = mainContent.match(new RegExp(`${t('Model')}\\s+([\\s\\S]*?)\\s+${t('Policy')}`));
const policyMatch = mainContent.match(new RegExp(`${t('Policy')}\\s+([\\s\\S]*?)\\s+${t('Request')}`));
const requestMatch = mainContent.match(new RegExp(`${t('Request')}\\s+([\\s\\S]*?)\\s+${t('Enforcement Result')}`));
const enforcementResultMatch = mainContent.match(new RegExp(`${t('Enforcement Result')}\\s+([\\s\\S]*?)\\s+${t('SYNTAX VALIDATE')}`));
const enforcementResultMatch = mainContent.match(new RegExp(`${t('Enforcement Result')}\\s+([\\s\\S]*?)\\s+${t('RUN THE TEST')}`));

const customConfig = customConfigMatch ? cleanContent(customConfigMatch[1]) : 'No custom config found';
const model = modelMatch
Expand Down
1 change: 0 additions & 1 deletion messages/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "طلب",
"Enforcement Result": "نتيجة التنفيذ",
"Why this result": "لماذا هذه النتيجة",
"SYNTAX VALIDATE": "التحقق من بناء الجملة",
"RUN THE TEST": "تشغيل الاختبار",
"SHARE": "مشاركة",
"Copied": "تم النسخ",
Expand Down
1 change: 0 additions & 1 deletion messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Anfrage",
"Enforcement Result": "Durchsetzungsergebnis",
"Why this result": "Warum dieses Ergebnis?",
"SYNTAX VALIDATE": "Syntax validieren",
"RUN THE TEST": "Test ausführen",
"SHARE": "Teilen",
"Copied": "Kopiert",
Expand Down
1 change: 0 additions & 1 deletion messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Request",
"Enforcement Result": "Enforcement Result",
"Why this result": "Why this result",
"SYNTAX VALIDATE": "SYNTAX VALIDATE",
"RUN THE TEST": "RUN THE TEST",
"SHARE": "SHARE",
"Copied": "Copied",
Expand Down
1 change: 0 additions & 1 deletion messages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Solicitud",
"Enforcement Result": "Resultado de ejecución",
"Why this result": "Por qué este resultado",
"SYNTAX VALIDATE": "VALIDAR SINTAXIS",
"RUN THE TEST": "EJECUTAR PRUEBA",
"SHARE": "COMPARTIR",
"Copied": "Copiado",
Expand Down
1 change: 0 additions & 1 deletion messages/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Requête",
"Enforcement Result": "Résultat d'application",
"Why this result": "Pourquoi ce résultat ?",
"SYNTAX VALIDATE": "Valider la syntaxe",
"RUN THE TEST": "Exécuter le test",
"SHARE": "Partager",
"Copied": "Copié",
Expand Down
1 change: 0 additions & 1 deletion messages/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Permintaan",
"Enforcement Result": "Hasil penegakan",
"Why this result": "Mengapa hasil ini",
"SYNTAX VALIDATE": "VALIDASI SINTAKS",
"RUN THE TEST": "JALANKAN UJI",
"SHARE": "BAGIKAN",
"Copied": "Tersalin",
Expand Down
1 change: 0 additions & 1 deletion messages/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Richiesta",
"Enforcement Result": "Risultato dell'applicazione",
"Why this result": "Perché questo risultato",
"SYNTAX VALIDATE": "VALIDARE LA SINTASSI",
"RUN THE TEST": "ESEGUI IL TEST",
"SHARE": "CONDIVIDI",
"Copied": "Copiato",
Expand Down
1 change: 0 additions & 1 deletion messages/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "リクエスト",
"Enforcement Result": "実行結果",
"Why this result": "なぜこの結果?",
"SYNTAX VALIDATE": "構文検証",
"RUN THE TEST": "テスト実行",
"SHARE": "共有",
"Copied": "コピー完了",
Expand Down
1 change: 0 additions & 1 deletion messages/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "요청",
"Enforcement Result": "집행 결과",
"Why this result": "이 결과의 이유",
"SYNTAX VALIDATE": "구문 유효성 검사",
"RUN THE TEST": "테스트 실행",
"SHARE": "공유",
"Copied": "복사됨",
Expand Down
1 change: 0 additions & 1 deletion messages/ms.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Permintaan",
"Enforcement Result": "Keputusan penguatkuasaan",
"Why this result": "Mengapa keputusan ini",
"SYNTAX VALIDATE": "SAH KAN SINTAKS",
"RUN THE TEST": "JALANKAN UJIAN",
"SHARE": "KONGSI",
"Copied": "Disalin",
Expand Down
1 change: 0 additions & 1 deletion messages/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Solicitação",
"Enforcement Result": "Resultado da aplicação",
"Why this result": "Por que esse resultado",
"SYNTAX VALIDATE": "VALIDAR SINTAXE",
"RUN THE TEST": "EXECUTAR TESTE",
"SHARE": "COMPARTILHAR",
"Copied": "Copiado",
Expand Down
1 change: 0 additions & 1 deletion messages/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Запрос",
"Enforcement Result": "Результат исполнения",
"Why this result": "Почему этот результат",
"SYNTAX VALIDATE": "ПРОВЕРКА СИНТАКСИСА",
"RUN THE TEST": "ЗАПУСТИТЬ ТЕСТ",
"SHARE": "ПОДЕЛИТЬСЯ",
"Copied": "Скопировано",
Expand Down
1 change: 0 additions & 1 deletion messages/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "İstek",
"Enforcement Result": "Uygulama Sonucu",
"Why this result": "Neden bu sonuç",
"SYNTAX VALIDATE": "SÖZDİZİMİ DOĞRULAMA",
"RUN THE TEST": "TESTİ ÇALIŞTIR",
"SHARE": "PAYLAŞ",
"Copied": "Kopyalandı",
Expand Down
1 change: 0 additions & 1 deletion messages/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "Yêu cầu",
"Enforcement Result": "Kết quả thi hành",
"Why this result": "Tại sao kết quả này",
"SYNTAX VALIDATE": "KIỂM TRA CÚ PHÁP",
"RUN THE TEST": "CHẠY THỬ",
"SHARE": "CHIA SẺ",
"Copied": "Đã sao chép",
Expand Down
1 change: 0 additions & 1 deletion messages/zh-Hant.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "請求",
"Enforcement Result": "執行結果",
"Why this result": "為何此結果?",
"SYNTAX VALIDATE": "驗證語法",
"RUN THE TEST": "運行",
"SHARE": "分享",
"Copied": "已複製",
Expand Down
1 change: 0 additions & 1 deletion messages/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"Request": "请求",
"Enforcement Result": "执行结果",
"Why this result": "为何此结果?",
"SYNTAX VALIDATE": "验证语法",
"RUN THE TEST": "运行",
"SHARE": "分享",
"Copied": "已复制",
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@
"codemirror": "^6.0.1",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18"
"react-dom": "^18",
"react-hot-toast": "^2.4.1"
},
"devDependencies": {
"@types/node": "^20",
Expand Down
18 changes: 15 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1357,9 +1357,9 @@ camelcase-css@^2.0.1:
integrity sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==

caniuse-lite@^1.0.30001579, caniuse-lite@^1.0.30001587, caniuse-lite@^1.0.30001599:
version "1.0.30001621"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001621.tgz#4adcb443c8b9c8303e04498318f987616b8fea2e"
integrity sha512-+NLXZiviFFKX0fk8Piwv3PfLPGtRqJeq2TiNoUff/qB5KJgwecJTvCXDpmlyP/eCI/GUEmp/h/y5j0yckiiZrA==
version "1.0.30001684"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001684.tgz"
integrity sha512-G1LRwLIQjBQoyq0ZJGqGIJUXzJ8irpbjHLpVRXDvBEScFJ9b17sgK6vlx0GAJFE21okD7zXl08rRRUfq6HdoEQ==

casbin@^5.36.0:
version "5.36.0"
Expand Down Expand Up @@ -2477,6 +2477,11 @@ globby@^11.1.0:
merge2 "^1.4.1"
slash "^3.0.0"

goober@^2.1.10:
version "2.1.16"
resolved "https://registry.yarnpkg.com/goober/-/goober-2.1.16.tgz#7d548eb9b83ff0988d102be71f271ca8f9c82a95"
integrity sha512-erjk19y1U33+XAMe1VTvIONHYoSqE4iS7BYUZfHaqeohLmnC0FdxEh7rQU+6MZ4OajItzjZFSRtVANrQwNq6/g==

gopd@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.0.1.tgz#29ff76de69dac7489b7c0918a5788e56477c332c"
Expand Down Expand Up @@ -3584,6 +3589,13 @@ react-dom@^18:
loose-envify "^1.1.0"
scheduler "^0.23.2"

react-hot-toast@^2.4.1:
version "2.4.1"
resolved "https://registry.yarnpkg.com/react-hot-toast/-/react-hot-toast-2.4.1.tgz#df04295eda8a7b12c4f968e54a61c8d36f4c0994"
integrity sha512-j8z+cQbWIM5LY37pR6uZR6D4LfseplqnuAO4co4u8917hBUvXlEqyP1ZzqVLcqoyUesZZv/ImreoCeHVDpE5pQ==
dependencies:
goober "^2.1.10"

react-is@^16.13.1:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
Expand Down