front end test

This commit is contained in:
5t4l1n
2025-07-25 13:33:18 +05:30
parent 868336188a
commit 35efa955ad
37 changed files with 6947 additions and 4 deletions
+3 -3
View File
@@ -1,6 +1,6 @@
{
"contract_address": "0x68b6014a12702891757fE994d70dE411FF74B94e",
"transaction_hash": "0x26fd0a4dda1212096c20a842d8aed7f5ee2c22258cc606ae97dcdbd55e01a675",
"contract_address": "0xC2FE2F49B3a1384aEdFAae127F054FAf216eF684",
"transaction_hash": "0xfe5a433dae316bd2d60b7190c21866a1fde30777f08d9d37e403ed642433fa28",
"deployer": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
"network": "local",
"abi": [
@@ -685,6 +685,6 @@
}
],
"gas_used": 3387337,
"block_number": 22993928,
"block_number": 22994809,
"status": 1
}
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+69
View File
@@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13 -1
View File
@@ -1 +1,13 @@
<h1>Hi</h1>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+5583
View File
File diff suppressed because it is too large Load Diff
+49
View File
@@ -0,0 +1,49 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@headlessui/react": "^2.2.6",
"@heroicons/react": "^2.2.0",
"@metamask/detect-provider": "^2.0.0",
"@tailwindcss/forms": "^0.5.10",
"@tanstack/react-query": "^5.83.0",
"autoprefixer": "^10.4.21",
"axios": "^1.11.0",
"chart.js": "^4.5.0",
"ethers": "^6.15.0",
"framer-motion": "^12.23.9",
"postcss": "^8.5.6",
"react": "^19.1.0",
"react-chartjs-2": "^5.3.0",
"react-dom": "^19.1.0",
"react-hook-form": "^7.61.1",
"react-hot-toast": "^2.5.2",
"react-router-dom": "^7.7.1",
"recharts": "^3.1.0",
"tailwindcss": "^4.1.11",
"web3": "^4.16.0"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/node": "^24.1.0",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0",
"eslint": "^9.30.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.35.1",
"vite": "^7.0.4",
"vite-tsconfig-paths": "^5.1.4"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+42
View File
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+30
View File
@@ -0,0 +1,30 @@
import React from 'react'
import { Routes, Route, Link } from 'react-router-dom'
import { HomePage } from './pages/HomePage'
import { TestingPage } from './pages/TestingPage'
import { DashboardPage } from './pages/DashboardPage'
import { CertificatesPage } from './pages/CertificatesPage'
function App() {
return (
<>
<nav style={{
background: '#f4f7fb', padding: '1rem', marginBottom: '2rem',
display: 'flex', gap: '1.5rem', borderBottom: '1px solid #eef'
}}>
<Link to="/">Home</Link>
<Link to="/test">Testing</Link>
<Link to="/dashboard">Dashboard</Link>
<Link to="/certificates">Certificates</Link>
</nav>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/test" element={<TestingPage />} />
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/certificates" element={<CertificatesPage />} />
</Routes>
</>
)
}
export default App
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,70 @@
import React, { useState } from 'react'
import detectEthereumProvider from '@metamask/detect-provider'
import { ethers } from 'ethers'
import { useAuth } from '../../contexts/AuthContext'
import { authService } from '../../services/auth'
import toast from 'react-hot-toast'
export const MetaMaskConnect: React.FC = () => {
const [isConnecting, setIsConnecting] = useState(false)
const { login } = useAuth()
const connectWallet = async () => {
setIsConnecting(true)
try {
const provider = await detectEthereumProvider()
if (!provider) {
throw new Error('MetaMask not installed. Please install MetaMask to continue.')
}
const ethereum = provider as any
const accounts = await ethereum.request({
method: 'eth_requestAccounts',
})
if (accounts.length === 0) {
throw new Error('No accounts found. Please connect your MetaMask wallet.')
}
const address = accounts[0]
// Get nonce from backend
const { nonce, message } = await authService.getNonce(address)
// Sign message with MetaMask
const web3Provider = new ethers.providers.Web3Provider(ethereum)
const signer = web3Provider.getSigner()
const signature = await signer.signMessage(message)
// Verify signature and login
await login(address, signature, message)
toast.success('Successfully connected to MetaMask!')
} catch (error: any) {
console.error('MetaMask connection failed:', error)
toast.error(error.message || 'Failed to connect to MetaMask')
} finally {
setIsConnecting(false)
}
}
return (
<button
onClick={connectWallet}
disabled={isConnecting}
className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
>
{isConnecting ? (
<div className="flex items-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Connecting...
</div>
) : (
'Connect MetaMask'
)}
</button>
)
}
@@ -0,0 +1,40 @@
import React, { useState } from 'react'
import { useAuth } from '../../contexts/AuthContext'
export const MetaMaskConnect: React.FC = () => {
const [isConnecting, setIsConnecting] = useState(false)
const { login } = useAuth()
const connectWallet = async () => {
setIsConnecting(true)
try {
if (!window.ethereum) {
alert('MetaMask not installed!')
return
}
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
})
if (accounts.length > 0) {
// Simplified login for now
await login(accounts[0], '', '')
}
} catch (error) {
console.error('Connection failed:', error)
} finally {
setIsConnecting(false)
}
}
return (
<button
onClick={connectWallet}
disabled={isConnecting}
className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 disabled:opacity-50"
>
{isConnecting ? 'Connecting...' : 'Connect MetaMask'}
</button>
)
}
+17
View File
@@ -0,0 +1,17 @@
import React, { ReactNode } from 'react'
import { Navigation } from './Navigation'
interface LayoutProps {
children: ReactNode
}
export const Layout: React.FC<LayoutProps> = ({ children }) => {
return (
<div className="min-h-screen bg-gray-50">
<Navigation />
<main className="container mx-auto px-4 py-8">
{children}
</main>
</div>
)
}
@@ -0,0 +1,70 @@
import React, { useState } from 'react'
import detectEthereumProvider from '@metamask/detect-provider'
import { ethers } from 'ethers'
import { useAuth } from '../../contexts/AuthContext'
import { authService } from '../../services/auth'
import toast from 'react-hot-toast'
export const MetaMaskConnect: React.FC = () => {
const [isConnecting, setIsConnecting] = useState(false)
const { login } = useAuth()
const connectWallet = async () => {
setIsConnecting(true)
try {
const provider = await detectEthereumProvider()
if (!provider) {
throw new Error('MetaMask not installed. Please install MetaMask to continue.')
}
const ethereum = provider as any
const accounts = await ethereum.request({
method: 'eth_requestAccounts',
})
if (accounts.length === 0) {
throw new Error('No accounts found. Please connect your MetaMask wallet.')
}
const address = accounts[0]
// Get nonce from backend
const { nonce, message } = await authService.getNonce(address)
// Sign message with MetaMask
const web3Provider = new ethers.providers.Web3Provider(ethereum)
const signer = web3Provider.getSigner()
const signature = await signer.signMessage(message)
// Verify signature and login
await login(address, signature, message)
toast.success('Successfully connected to MetaMask!')
} catch (error: any) {
console.error('MetaMask connection failed:', error)
toast.error(error.message || 'Failed to connect to MetaMask')
} finally {
setIsConnecting(false)
}
}
return (
<button
onClick={connectWallet}
disabled={isConnecting}
className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
>
{isConnecting ? (
<div className="flex items-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Connecting...
</div>
) : (
'Connect MetaMask'
)}
</button>
)
}
@@ -0,0 +1,62 @@
import React from 'react'
import { Link, useLocation } from 'react-router-dom'
import { useAuth } from '../../contexts/AuthContext'
import { MetaMaskConnect } from '../auth/MetaMaskConnect'
export const Navigation: React.FC = () => {
const { user, logout } = useAuth()
const location = useLocation()
const navItems = [
{ path: '/', label: 'Home' },
{ path: '/test', label: 'Take Test' },
{ path: '/dashboard', label: 'Dashboard' },
{ path: '/certificates', label: 'Certificates' },
]
return (
<nav className="bg-white shadow-md">
<div className="container mx-auto px-4">
<div className="flex justify-between items-center h-16">
<Link to="/" className="text-2xl font-bold text-primary-600">
OpenLearnX
</Link>
<div className="flex items-center space-x-6">
{user && (
<>
{navItems.map((item) => (
<Link
key={item.path}
to={item.path}
className={`px-3 py-2 rounded-md text-sm font-medium ${
location.pathname === item.path
? 'bg-primary-100 text-primary-700'
: 'text-gray-600 hover:text-primary-600'
}`}
>
{item.label}
</Link>
))}
<div className="flex items-center space-x-4">
<span className="text-sm text-gray-600">
{user.walletAddress.slice(0, 6)}...{user.walletAddress.slice(-4)}
</span>
<button
onClick={logout}
className="text-sm text-red-600 hover:text-red-700"
>
Logout
</button>
</div>
</>
)}
{!user && <MetaMaskConnect />}
</div>
</div>
</div>
</nav>
)
}
@@ -0,0 +1,47 @@
import React from 'react'
interface CompetencyData {
subject: string
score: number
tests: number
}
interface CompetencyRadarProps {
data: CompetencyData[]
}
export const CompetencyRadar: React.FC<CompetencyRadarProps> = ({ data }) => {
return (
<div className="card">
<h3 className="text-lg font-semibold mb-4">Competency Overview</h3>
{/* Simple visualization without chart library */}
<div className="space-y-4">
{data.map((item) => (
<div key={item.subject} className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-sm font-medium text-gray-700">{item.subject}</span>
<span className="text-sm text-gray-600">{item.score.toFixed(1)}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-primary-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${item.score}%` }}
/>
</div>
<div className="text-xs text-gray-500">
{item.tests} test{item.tests !== 1 ? 's' : ''} completed
</div>
</div>
))}
</div>
{data.length === 0 && (
<div className="text-center py-8 text-gray-500">
<p>No competency data available yet.</p>
<p className="text-sm mt-2">Take some tests to see your progress!</p>
</div>
)}
</div>
)
}
@@ -0,0 +1,188 @@
import React, { useState, useEffect } from 'react'
import { testingService } from '../../services/api'
import { QuestionCard } from './QuestionCard'
import { InstantFeedback } from './InstantFeedback'
import { ProgressTracker } from './ProgressTracker'
import toast from 'react-hot-toast'
interface Question {
id: string
question: string
options: string[]
difficulty: number
subject: string
}
interface FeedbackData {
correct: boolean
confidence_score: number
explanation: string
correct_answer: string
current_score: number
total_answered: number
}
export const AdaptiveTest: React.FC = () => {
const [sessionId, setSessionId] = useState<string>('')
const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
const [feedback, setFeedback] = useState<FeedbackData | null>(null)
const [questionNumber, setQuestionNumber] = useState(1)
const [totalQuestions] = useState(10)
const [isLoading, setIsLoading] = useState(false)
const [testCompleted, setTestCompleted] = useState(false)
const [selectedSubject, setSelectedSubject] = useState('Mathematics')
const subjects = ['Mathematics', 'Geography', 'Literature', 'Science']
const startTest = async () => {
setIsLoading(true)
setTestCompleted(false)
setQuestionNumber(1)
setFeedback(null)
try {
const data = await testingService.startTest(selectedSubject)
setSessionId(data.session_id)
setCurrentQuestion(data.question)
toast.success('Test started! Good luck!')
} catch (error) {
console.error('Failed to start test:', error)
toast.error('Failed to start test. Please try again.')
} finally {
setIsLoading(false)
}
}
const submitAnswer = async (answerIndex: number) => {
if (!currentQuestion || !sessionId) return
setIsLoading(true)
try {
const data = await testingService.submitAnswer(sessionId, currentQuestion.id, answerIndex)
setFeedback(data.feedback)
// Show feedback, then proceed
setTimeout(() => {
if (data.test_completed) {
setTestCompleted(true)
toast.success('Test completed! Check your results.')
} else if (data.next_question) {
setCurrentQuestion(data.next_question)
setQuestionNumber(prev => prev + 1)
setFeedback(null)
}
}, 3000)
} catch (error) {
console.error('Failed to submit answer:', error)
toast.error('Failed to submit answer. Please try again.')
} finally {
setIsLoading(false)
}
}
if (!sessionId && !isLoading) {
return (
<div className="max-w-2xl mx-auto">
<div className="card text-center">
<h2 className="text-2xl font-bold text-gray-900 mb-6">
OpenLearnX Adaptive Test
</h2>
<p className="text-gray-600 mb-6">
Experience personalized learning with our adaptive testing system that adjusts to your performance in real-time.
</p>
<div className="mb-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Select Subject
</label>
<select
value={selectedSubject}
onChange={(e) => setSelectedSubject(e.target.value)}
className="block w-full max-w-xs mx-auto px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500"
>
{subjects.map((subject) => (
<option key={subject} value={subject}>
{subject}
</option>
))}
</select>
</div>
<button
onClick={startTest}
disabled={isLoading}
className="btn-primary disabled:opacity-50"
>
{isLoading ? 'Starting Test...' : 'Start Adaptive Test'}
</button>
</div>
</div>
)
}
if (testCompleted) {
return (
<div className="max-w-2xl mx-auto">
<div className="card text-center">
<div className="text-6xl mb-4">🎉</div>
<h2 className="text-3xl font-bold text-green-600 mb-4">Test Completed!</h2>
<p className="text-gray-600 mb-6">
Congratulations! You've completed the adaptive test. Your performance has been analyzed and saved.
</p>
<div className="space-y-4">
<button
onClick={() => window.location.href = '/dashboard'}
className="btn-primary mr-4"
>
View Detailed Results
</button>
<button
onClick={() => setSessionId('')}
className="btn-secondary"
>
Take Another Test
</button>
</div>
</div>
</div>
)
}
return (
<div className="max-w-6xl mx-auto">
<ProgressTracker
current={questionNumber}
total={totalQuestions}
score={feedback?.current_score || 0}
subject={selectedSubject}
/>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mt-8">
<div>
{currentQuestion && (
<QuestionCard
question={currentQuestion}
onAnswer={submitAnswer}
isLoading={isLoading}
questionNumber={questionNumber}
/>
)}
</div>
<div>
{feedback ? (
<InstantFeedback feedback={feedback} />
) : (
<div className="card">
<div className="text-center text-gray-500">
<div className="text-4xl mb-4">🤔</div>
<p>Select your answer to receive instant feedback with detailed explanations!</p>
</div>
</div>
)}
</div>
</div>
</div>
)
}
@@ -0,0 +1,109 @@
import React from 'react'
import { CheckCircleIcon, XCircleIcon, LightBulbIcon } from '@heroicons/react/24/solid'
interface FeedbackProps {
feedback: {
correct: boolean
confidence_score: number
explanation: string
correct_answer: string
current_score: number
total_answered: number
}
}
export const InstantFeedback: React.FC<FeedbackProps> = ({ feedback }) => {
const getConfidenceColor = (score: number) => {
if (score > 0.7) return 'bg-green-500'
if (score > 0.4) return 'bg-yellow-500'
return 'bg-red-500'
}
const getConfidenceLabel = (score: number) => {
if (score > 0.8) return 'Very High'
if (score > 0.6) return 'High'
if (score > 0.4) return 'Medium'
if (score > 0.2) return 'Low'
return 'Very Low'
}
return (
<div className="card">
<div className="flex items-center mb-6">
{feedback.correct ? (
<CheckCircleIcon className="h-8 w-8 text-green-500 mr-3" />
) : (
<XCircleIcon className="h-8 w-8 text-red-500 mr-3" />
)}
<div>
<h3 className={`text-xl font-semibold ${feedback.correct ? 'text-green-700' : 'text-red-700'}`}>
{feedback.correct ? 'Correct!' : 'Incorrect'}
</h3>
<p className="text-sm text-gray-600">
Instant feedback powered by AI
</p>
</div>
</div>
<div className="space-y-6">
{/* Confidence Score */}
<div>
<div className="flex justify-between items-center mb-2">
<p className="text-sm font-medium text-gray-700">AI Confidence Score</p>
<span className="text-sm text-gray-500">
{getConfidenceLabel(feedback.confidence_score)}
</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-3">
<div
className={`h-3 rounded-full transition-all duration-500 ${getConfidenceColor(feedback.confidence_score)}`}
style={{ width: `${feedback.confidence_score * 100}%` }}
/>
</div>
<p className="text-sm text-gray-500 mt-1">
{Math.round(feedback.confidence_score * 100)}% confidence
</p>
</div>
{/* Explanation */}
<div>
<div className="flex items-center mb-2">
<LightBulbIcon className="h-5 w-5 text-yellow-500 mr-2" />
<p className="text-sm font-medium text-gray-700">Explanation</p>
</div>
<div className="bg-blue-50 border-l-4 border-blue-400 p-4 rounded">
<p className="text-gray-800">{feedback.explanation}</p>
</div>
</div>
{/* Correct Answer (if incorrect) */}
{!feedback.correct && (
<div>
<p className="text-sm font-medium text-gray-700 mb-2">Correct Answer</p>
<div className="bg-green-50 border-l-4 border-green-400 p-3 rounded">
<p className="text-green-800 font-medium">{feedback.correct_answer}</p>
</div>
</div>
)}
{/* Current Performance */}
<div className="pt-4 border-t border-gray-200">
<div className="grid grid-cols-2 gap-4">
<div className="text-center">
<p className="text-2xl font-bold text-primary-600">
{feedback.current_score.toFixed(1)}%
</p>
<p className="text-sm text-gray-600">Current Score</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold text-gray-700">
{feedback.total_answered}
</p>
<p className="text-sm text-gray-600">Questions Answered</p>
</div>
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,57 @@
import React from 'react'
interface ProgressTrackerProps {
current: number
total: number
score: number
subject: string
}
export const ProgressTracker: React.FC<ProgressTrackerProps> = ({
current,
total,
score,
subject
}) => {
const progressPercentage = (current / total) * 100
return (
<div className="card">
<div className="flex justify-between items-center mb-4">
<div>
<h2 className="text-xl font-semibold text-gray-900">
{subject} - Adaptive Assessment
</h2>
<p className="text-sm text-gray-600">
Question {current} of {total}
</p>
</div>
<div className="text-right">
<p className="text-2xl font-bold text-primary-600">
{score.toFixed(1)}%
</p>
<p className="text-sm text-gray-600">Current Score</p>
</div>
</div>
<div className="mb-2">
<div className="flex justify-between text-sm text-gray-600 mb-1">
<span>Progress</span>
<span>{Math.round(progressPercentage)}% Complete</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-primary-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${progressPercentage}%` }}
/>
</div>
</div>
<div className="flex justify-between items-center text-xs text-gray-500">
<span>🎯 Adaptive Difficulty</span>
<span> Instant Feedback</span>
<span>🏆 Blockchain Certified</span>
</div>
</div>
)
}
@@ -0,0 +1,105 @@
import React, { useState } from 'react'
interface Question {
id: string
question: string
options: string[]
difficulty: number
subject: string
}
interface QuestionCardProps {
question: Question
onAnswer: (answerIndex: number) => void
isLoading: boolean
questionNumber: number
}
export const QuestionCard: React.FC<QuestionCardProps> = ({
question,
onAnswer,
isLoading,
questionNumber
}) => {
const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null)
const handleSubmit = () => {
if (selectedAnswer !== null) {
onAnswer(selectedAnswer)
setSelectedAnswer(null)
}
}
const getDifficultyColor = (difficulty: number) => {
if (difficulty <= 2) return 'text-green-600 bg-green-100'
if (difficulty <= 3) return 'text-yellow-600 bg-yellow-100'
return 'text-red-600 bg-red-100'
}
const getDifficultyLabel = (difficulty: number) => {
if (difficulty <= 2) return 'Easy'
if (difficulty <= 3) return 'Medium'
return 'Hard'
}
return (
<div className="card">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold text-gray-900">
Question {questionNumber}
</h3>
<div className="flex items-center space-x-2">
<span className="text-sm text-gray-500">{question.subject}</span>
<span className={`text-xs px-2 py-1 rounded-full ${getDifficultyColor(question.difficulty)}`}>
{getDifficultyLabel(question.difficulty)}
</span>
</div>
</div>
<div className="mb-6">
<p className="text-lg text-gray-800 leading-relaxed">
{question.question}
</p>
</div>
<div className="space-y-3 mb-6">
{question.options.map((option, index) => (
<label
key={index}
className={`flex items-center p-4 border rounded-lg cursor-pointer transition-colors hover:bg-gray-50 ${
selectedAnswer === index
? 'border-primary-500 bg-primary-50'
: 'border-gray-200'
}`}
>
<input
type="radio"
name="answer"
value={index}
checked={selectedAnswer === index}
onChange={() => setSelectedAnswer(index)}
className="mr-3 text-primary-600 focus:ring-primary-500"
disabled={isLoading}
/>
<span className="text-gray-800">{option}</span>
</label>
))}
</div>
<button
onClick={handleSubmit}
disabled={selectedAnswer === null || isLoading}
className="w-full btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? (
<div className="flex items-center justify-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Processing Answer...
</div>
) : (
'Submit Answer'
)}
</button>
</div>
)
}
+57
View File
@@ -0,0 +1,57 @@
import React, { createContext, useContext, useState, ReactNode } from 'react'
interface User {
id: string
walletAddress: string
totalTests: number
certificates: number
}
interface AuthContextType {
user: User | null
token: string | null
login: (address: string, signature: string, message: string) => Promise<void>
logout: () => void
isLoading: boolean
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export const useAuth = () => {
const context = useContext(AuthContext)
if (!context) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}
interface AuthProviderProps {
children: ReactNode
}
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [user, setUser] = useState<User | null>(null)
const [token, setToken] = useState<string | null>(null)
const [isLoading] = useState(false)
const login = async (address: string, signature: string, message: string) => {
setUser({
id: '1',
walletAddress: address,
totalTests: 0,
certificates: 0
})
setToken('mock-token')
}
const logout = () => {
setUser(null)
setToken(null)
}
return (
<AuthContext.Provider value={{ user, token, login, logout, isLoading }}>
{children}
</AuthContext.Provider>
)
}
+12
View File
@@ -0,0 +1,12 @@
body {
margin: 0;
background: #f8fafc;
color: #22223b;
font-family: system-ui, sans-serif;
}
a {
color: #2563eb;
text-decoration: none;
font-weight: 500;
}
a:hover { text-decoration: underline; }
+13
View File
@@ -0,0 +1,13 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
)
+8
View File
@@ -0,0 +1,8 @@
import React from 'react'
export const CertificatesPage = () => (
<div style={{padding:'2rem'}}>
<h2 style={{fontSize:'2rem', color:'#a21caf'}}>NFT Certificates</h2>
<p>Display users blockchain-minted certificates here.</p>
<p>(Connect to backend/certificate endpoints and show NFT details.)</p>
</div>
)
+8
View File
@@ -0,0 +1,8 @@
import React from 'react'
export const DashboardPage = () => (
<div style={{padding:'2rem'}}>
<h2 style={{fontSize:'2rem', color:'#f59e42'}}>Competency Dashboard</h2>
<p>This will visualize student progress, certificates, and analytics from the backend.</p>
<p>(Integrate charts, subject breakdowns, NFT summary, etc.)</p>
</div>
)
+15
View File
@@ -0,0 +1,15 @@
import React from 'react'
export const HomePage = () => (
<div style={{padding:"2rem",background:"#f9fafb"}}>
<h1 style={{fontSize:'2.5rem', color:'#2563eb'}}>OpenLearnX 🧑🎓</h1>
<p>Welcome! This is your decentralized adaptive learning platform.</p>
<ul style={{margin:'1.5rem 0', fontSize:'1.1rem'}}>
<li> MetaMask/Wallet authentication</li>
<li> Adaptive testing engine (individualized difficulty)</li>
<li> Instant feedback with explanations</li>
<li> NFT blockchain certificates</li>
<li> Competency dashboards</li>
</ul>
<p>(Try switching pages using the top navigation.)</p>
</div>
)
+8
View File
@@ -0,0 +1,8 @@
import React from 'react'
export const TestingPage = () => (
<div style={{padding:'2rem'}}>
<h2 style={{fontSize:'2rem', color:'#059669'}}>Adaptive Testing Demo</h2>
<p>Here, users will take adaptive tests with instant feedback, powered by your OpenLearnX backend.</p>
<p>(Connect to backend API and implement adaptive engine here.)</p>
</div>
)
+17
View File
@@ -0,0 +1,17 @@
export const dashboardService = {
async getStudentDashboard(userId: string) {
return {
user_info: { id: userId, wallet_address: '0x...', member_since: new Date().toISOString(), last_login: new Date().toISOString() },
overview: { total_tests: 0, completed_tests: 0, average_score: 0, certificates_earned: 0, this_week_tests: 0, this_month_tests: 0 },
subject_breakdown: {},
recent_activity: [],
certificates: []
}
}
}
export const certificateService = {
async getUserCertificates(userId: string) {
return { certificates: [] }
}
}
+28
View File
@@ -0,0 +1,28 @@
import axios from 'axios'
const API_BASE_URL = 'http://127.0.0.1:5000/api'
export const authService = {
async getNonce(walletAddress: string) {
const response = await axios.post(`${API_BASE_URL}/auth/nonce`, {
wallet_address: walletAddress
})
return response.data
},
async verifySignature(walletAddress: string, signature: string, message: string) {
const response = await axios.post(`${API_BASE_URL}/auth/verify`, {
wallet_address: walletAddress,
signature,
message
})
return response.data
},
async getProfile(token: string) {
const response = await axios.get(`${API_BASE_URL}/auth/profile`, {
headers: { Authorization: `Bearer ${token}` }
})
return response.data
}
}
+5
View File
@@ -0,0 +1,5 @@
/// <reference types="vite/client" />
interface Window {
ethereum?: any
}
+20
View File
@@ -0,0 +1,20 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
primary: {
50: '#eff6ff',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
}
}
},
},
plugins: [],
}
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})
+82
View File
@@ -102,3 +102,85 @@ Your OpenLearnX Platform URLs
Network Access: http://192.168.35.250:5000
```
## Step 2 Completed:)
# Step 3 Frontend
based on your backend setup and requirements for a comprehensive adaptive learning platform, here's how to build the frontend in your existing frontend directory.
##
```
cd frontend
# Create React + TypeScript + Vite project
npm create vite@latest . -- --template react-ts
# Install dependencies
npm install
# Install additional packages for OpenLearnX features
npm install web3 ethers @metamask/detect-provider
npm install react-router-dom react-query
npm install @headlessui/react @heroicons/react
npm install chart.js react-chartjs-2 recharts
npm install axios react-hook-form
npm install framer-motion react-hot-toast
npm install tailwindcss @tailwindcss/forms
```
## Project Structure
```
frontend/
├── src/
│ ├── components/
│ │ ├── auth/
│ │ │ ├── MetaMaskConnect.tsx
│ │ │ └── WalletAuth.tsx
│ │ ├── testing/
│ │ │ ├── AdaptiveTest.tsx
│ │ │ ├── QuestionCard.tsx
│ │ │ ├── InstantFeedback.tsx
│ │ │ └── ProgressTracker.tsx
│ │ ├── assessment/
│ │ │ ├── PeerReview.tsx
│ │ │ ├── BiasDetection.tsx
│ │ │ └── Portfolio.tsx
│ │ ├── dashboard/
│ │ │ ├── StudentDashboard.tsx
│ │ │ ├── InstructorDashboard.tsx
│ │ │ ├── CompetencyRadar.tsx
│ │ │ └── ProgressChart.tsx
│ │ ├── certificates/
│ │ │ ├── CertificateGallery.tsx
│ │ │ ├── NFTViewer.tsx
│ │ │ └── BlockchainVerify.tsx
│ │ └── common/
│ │ ├── Layout.tsx
│ │ ├── Navigation.tsx
│ │ └── LoadingSpinner.tsx
│ ├── hooks/
│ │ ├── useMetaMask.ts
│ │ ├── useAdaptiveTesting.ts
│ │ ├── useInstantFeedback.ts
│ │ └── useBlockchain.ts
│ ├── services/
│ │ ├── api.ts
│ │ ├── web3.ts
│ │ └── auth.ts
│ ├── types/
│ │ ├── auth.ts
│ │ ├── testing.ts
│ │ └── dashboard.ts
│ ├── utils/
│ │ ├── adaptiveAlgorithm.ts
│ │ ├── biasDetection.ts
│ │ └── competencyMapping.ts
│ └── pages/
│ ├── HomePage.tsx
│ ├── TestingPage.tsx
│ ├── DashboardPage.tsx
│ └── CertificatesPage.tsx
```