Remove unused components and models for improved maintainability
- Deleted redundant components (`AddActionButton`, `AlertBox`, `AlertStack`, `BackButton`, `CancelButton`, and `CollapsableArea`) and related files. - Removed unused models (`Book`, `BookSerie`, `BookTables`, `Character`, and `Chapter`) to reduce codebase clutter. - Updated project structure and references to reflect these removals.
This commit is contained in:
313
app/globals.css
313
app/globals.css
@@ -1,30 +1,178 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/*
|
||||
* === ERitors Scribe Design Tokens ===
|
||||
*
|
||||
* Theme values are defined in :root and overridable via [data-theme].
|
||||
* The @theme block references these variables so Tailwind utilities
|
||||
* (bg-primary, text-muted, etc.) automatically follow the active theme.
|
||||
*
|
||||
* COLORS:
|
||||
* Brand ........... primary, primary-dark, primary-light
|
||||
* Surfaces ........ background, dark-background, darkest-background, secondary, tertiary
|
||||
* Semantic surfaces surface-primary, surface-secondary, surface-elevated
|
||||
* Text ............ text-primary, text-secondary, muted, text-dimmed
|
||||
* Semantic ........ success, error, warning, info
|
||||
* Editor .......... editor-text, editor-bold, editor-heading, editor-page-sepia
|
||||
* Scrollbar ....... scrollbar-track, scrollbar-thumb, scrollbar-thumb-hover
|
||||
* Utility ......... glass-bg, surface-gradient-dark, surface-gradient-light
|
||||
* Accents ......... accent-blue, accent-green, accent-orange, accent-purple, accent-red
|
||||
* Interactive ..... interactive, interactive-hover
|
||||
*
|
||||
* SHADOWS: shadow-feature-hover, shadow-focus-ring
|
||||
* FONTS: font-family-lora, font-family-lora-italic, font-family-adlam
|
||||
*/
|
||||
|
||||
:root, :root[data-theme="dark"] {
|
||||
/* Brand */
|
||||
--theme-primary: #51AE84;
|
||||
--theme-primary-dark: #3A8B69;
|
||||
--theme-primary-light: #74C9A0;
|
||||
|
||||
/* Surfaces */
|
||||
--theme-secondary: #393B40;
|
||||
--theme-tertiary: #26272B;
|
||||
--theme-background: #1E1E22;
|
||||
--theme-dark-background: #1B1C1F;
|
||||
--theme-darkest-background: #191A1C;
|
||||
--theme-surface-gradient-dark: #313337;
|
||||
--theme-surface-gradient-light: #45474D;
|
||||
--theme-glass-bg: rgba(43, 45, 48, 0.7);
|
||||
|
||||
/* Text */
|
||||
--theme-text-primary: #F0F0F4;
|
||||
--theme-text-secondary: #BCBEC4;
|
||||
--theme-muted: #B0B0B0;
|
||||
--theme-text-dimmed: #6F737A;
|
||||
|
||||
/* Semantic */
|
||||
--theme-success: #28A745;
|
||||
--theme-error: #DC3545;
|
||||
--theme-warning: #FFC107;
|
||||
--theme-info: #17A2B8;
|
||||
|
||||
/* Gray scale */
|
||||
--theme-gray: #808388;
|
||||
--theme-gray-light: #A0A3A8;
|
||||
--theme-gray-dark: #45474D;
|
||||
|
||||
/* Scrollbar */
|
||||
--theme-scrollbar-track: #1E1F22;
|
||||
--theme-scrollbar-thumb: #51AE84;
|
||||
--theme-scrollbar-thumb-hover: #3A8B69;
|
||||
|
||||
/* Editor content */
|
||||
--theme-editor-text: #E0E0E4;
|
||||
--theme-editor-bold: #F0F0F4;
|
||||
--theme-editor-heading: #34acd0;
|
||||
--theme-editor-page-sepia: #f4f1e8;
|
||||
|
||||
/* Accents */
|
||||
--theme-accent-blue: #5C9CE6;
|
||||
--theme-accent-green: #5FB87B;
|
||||
--theme-accent-orange: #D4923A;
|
||||
--theme-accent-purple: #B07CD8;
|
||||
--theme-accent-red: #E06C75;
|
||||
|
||||
/* Shadows */
|
||||
--theme-shadow-feature-hover: 0 10px 25px -5px rgba(81, 174, 132, 0.2);
|
||||
--theme-shadow-focus-ring: 0 0 0 4px rgba(81, 174, 132, 0.1);
|
||||
}
|
||||
|
||||
/* Light theme — à remplir quand le design sera prêt */
|
||||
:root[data-theme="light"] {
|
||||
--theme-background: #F5F5F5;
|
||||
--theme-secondary: #E0E0E0;
|
||||
--theme-tertiary: #EBEBEB;
|
||||
--theme-dark-background: #D5D5D5;
|
||||
--theme-darkest-background: #C0C0C0;
|
||||
--theme-surface-gradient-dark: #D0D0D0;
|
||||
--theme-surface-gradient-light: #E8E8E8;
|
||||
--theme-glass-bg: rgba(240, 240, 240, 0.7);
|
||||
--theme-text-primary: #1A1A1A;
|
||||
--theme-text-secondary: #555555;
|
||||
--theme-muted: #888888;
|
||||
--theme-text-dimmed: #999999;
|
||||
--theme-scrollbar-track: #E0E0E0;
|
||||
--theme-scrollbar-thumb: #51AE84;
|
||||
--theme-scrollbar-thumb-hover: #3A8B69;
|
||||
--theme-editor-text: #333333;
|
||||
--theme-editor-bold: #1A1A1A;
|
||||
--theme-editor-heading: #2196B8;
|
||||
--theme-editor-page-sepia: #f4f1e8;
|
||||
--theme-gray: #999999;
|
||||
--theme-gray-light: #BBBBBB;
|
||||
--theme-gray-dark: #666666;
|
||||
--theme-accent-blue: #3A7BD5;
|
||||
--theme-accent-green: #2E8B57;
|
||||
--theme-accent-orange: #C47F17;
|
||||
--theme-accent-purple: #8B5CC4;
|
||||
--theme-accent-red: #C94F5A;
|
||||
}
|
||||
|
||||
@theme {
|
||||
/* Colors */
|
||||
--color-primary: #51AE84;
|
||||
--color-primary-dark: #3A8B69;
|
||||
--color-primary-light: #74C9A0;
|
||||
--color-secondary: #3E3E3E;
|
||||
--color-tertiary: #2C2C2C;
|
||||
--color-background: #2B2D30;
|
||||
--color-dark-background: #2C2C2C;
|
||||
--color-darkest-background: #1A1A1A;
|
||||
--color-text-primary: #FFFFFF;
|
||||
--color-text-secondary: #B0B0B0;
|
||||
--color-muted: #B0B0B0;
|
||||
--color-success: #28A745;
|
||||
--color-error: #DC3545;
|
||||
--color-warning: #FFC107;
|
||||
--color-info: #17A2B8;
|
||||
/* Brand */
|
||||
--color-primary: var(--theme-primary);
|
||||
--color-primary-dark: var(--theme-primary-dark);
|
||||
--color-primary-light: var(--theme-primary-light);
|
||||
|
||||
--color-gray: #808080;
|
||||
--color-gray-light: #A0A0A0;
|
||||
--color-gray-dark: #404040;
|
||||
/* Surfaces */
|
||||
--color-secondary: var(--theme-secondary);
|
||||
--color-tertiary: var(--theme-tertiary);
|
||||
--color-background: var(--theme-background);
|
||||
--color-dark-background: var(--theme-dark-background);
|
||||
--color-darkest-background: var(--theme-darkest-background);
|
||||
--color-surface-gradient-dark: var(--theme-surface-gradient-dark);
|
||||
--color-surface-gradient-light: var(--theme-surface-gradient-light);
|
||||
--color-glass-bg: var(--theme-glass-bg);
|
||||
|
||||
/* Aliases pour compatibilité */
|
||||
--color-textPrimary: #FFFFFF;
|
||||
--color-textSecondary: #B0B0B0;
|
||||
/* Semantic surfaces */
|
||||
--color-surface-primary: var(--theme-background);
|
||||
--color-surface-secondary: var(--theme-secondary);
|
||||
--color-surface-elevated: var(--theme-darkest-background);
|
||||
|
||||
/* Text */
|
||||
--color-text-primary: var(--theme-text-primary);
|
||||
--color-text-secondary: var(--theme-text-secondary);
|
||||
--color-muted: var(--theme-muted);
|
||||
--color-text-dimmed: var(--theme-text-dimmed);
|
||||
|
||||
/* Semantic */
|
||||
--color-success: var(--theme-success);
|
||||
--color-error: var(--theme-error);
|
||||
--color-warning: var(--theme-warning);
|
||||
--color-info: var(--theme-info);
|
||||
|
||||
/* Gray scale */
|
||||
--color-gray: var(--theme-gray);
|
||||
--color-gray-light: var(--theme-gray-light);
|
||||
--color-gray-dark: var(--theme-gray-dark);
|
||||
|
||||
/* Scrollbar */
|
||||
--color-scrollbar-track: var(--theme-scrollbar-track);
|
||||
--color-scrollbar-thumb: var(--theme-scrollbar-thumb);
|
||||
--color-scrollbar-thumb-hover: var(--theme-scrollbar-thumb-hover);
|
||||
|
||||
/* Editor content */
|
||||
--color-editor-text: var(--theme-editor-text);
|
||||
--color-editor-bold: var(--theme-editor-bold);
|
||||
--color-editor-heading: var(--theme-editor-heading);
|
||||
--color-editor-page-sepia: var(--theme-editor-page-sepia);
|
||||
|
||||
/* Accents */
|
||||
--color-accent-blue: var(--theme-accent-blue);
|
||||
--color-accent-green: var(--theme-accent-green);
|
||||
--color-accent-orange: var(--theme-accent-orange);
|
||||
--color-accent-purple: var(--theme-accent-purple);
|
||||
--color-accent-red: var(--theme-accent-red);
|
||||
|
||||
/* Interactive */
|
||||
--color-interactive: var(--theme-primary);
|
||||
--color-interactive-hover: var(--theme-primary-dark);
|
||||
|
||||
/* Shadows */
|
||||
--shadow-feature-hover: var(--theme-shadow-feature-hover);
|
||||
--shadow-focus-ring: var(--theme-shadow-focus-ring);
|
||||
|
||||
/* Font Family */
|
||||
--font-family-lora: 'Lora', Georgia, serif;
|
||||
@@ -53,15 +201,8 @@
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
:root {
|
||||
--foreground-rgb: 0, 0, 0;
|
||||
--background-start-rgb: 214, 219, 220;
|
||||
--background-end-rgb: 255, 255, 255;
|
||||
}
|
||||
|
||||
body {
|
||||
--tw-bg-opacity: 1;
|
||||
background-color: rgb(17 24 39 / var(--tw-bg-opacity))
|
||||
background-color: var(--color-background);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
@@ -70,23 +211,23 @@ body {
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: #2d2d2d;
|
||||
background: var(--color-scrollbar-track);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #51AE84;
|
||||
background: var(--color-scrollbar-thumb);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #3a8b69;
|
||||
background: var(--color-scrollbar-thumb-hover);
|
||||
}
|
||||
|
||||
/* Scrollbar Styles for Firefox */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #51AE84 #2d2d2d;
|
||||
scrollbar-color: var(--color-scrollbar-thumb) var(--color-scrollbar-track);
|
||||
}
|
||||
|
||||
.fade-in {
|
||||
@@ -200,8 +341,15 @@ body {
|
||||
}
|
||||
|
||||
/* Styles pour l'éditeur principal avec classes dynamiques */
|
||||
.editor-content .tiptap > p:first-child,
|
||||
.editor-content .tiptap > h1:first-child,
|
||||
.editor-content .tiptap > h2:first-child,
|
||||
.editor-content .tiptap > h3:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.editor-content .tiptap p {
|
||||
color: #dedede;
|
||||
color: var(--color-editor-text);
|
||||
margin-top: 0.7em;
|
||||
margin-bottom: 0.7em;
|
||||
}
|
||||
@@ -212,11 +360,11 @@ body {
|
||||
|
||||
.editor-content .tiptap p strong {
|
||||
font-weight: 900;
|
||||
color: #f9f9f9;
|
||||
color: var(--color-editor-bold);
|
||||
}
|
||||
|
||||
.editor-content .tiptap h1, .editor-content .tiptap h2, .editor-content .tiptap h3 {
|
||||
color: #34acd0;
|
||||
color: var(--color-editor-heading);
|
||||
margin-top: 1em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
@@ -251,6 +399,7 @@ body {
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
|
||||
.composer-panel-h {
|
||||
height: calc(100vh - 8rem);
|
||||
}
|
||||
@@ -286,13 +435,13 @@ body {
|
||||
position: relative;
|
||||
transition: all 0.3s ease;
|
||||
overflow: hidden;
|
||||
background-color: #3E3E3E;
|
||||
background-color: var(--color-secondary);
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
|
||||
.feature-card:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 10px 25px -5px rgba(81, 174, 132, 0.2);
|
||||
box-shadow: var(--shadow-feature-hover);
|
||||
}
|
||||
|
||||
.feature-card-bg {
|
||||
@@ -310,7 +459,7 @@ body {
|
||||
width: 4rem;
|
||||
height: 4rem;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #313131, #4A4A4A);
|
||||
background: linear-gradient(135deg, var(--color-surface-gradient-dark), var(--color-surface-gradient-light));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -331,7 +480,7 @@ body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.feature-title-container {
|
||||
@@ -356,7 +505,7 @@ body {
|
||||
.feature-shine-line {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background-color: #4A4A4A;
|
||||
background-color: var(--color-surface-gradient-light);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -421,7 +570,7 @@ body {
|
||||
width: 4rem;
|
||||
height: 4rem;
|
||||
border-radius: 50%;
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
background-color: var(--color-glass-bg);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -446,7 +595,7 @@ body {
|
||||
}
|
||||
|
||||
.last-updated {
|
||||
color: #777777;
|
||||
color: var(--color-text-dimmed);
|
||||
font-size: 0.75rem;
|
||||
text-align: center;
|
||||
margin-top: 1rem;
|
||||
@@ -484,19 +633,42 @@ body {
|
||||
margin-bottom: 0.7em;
|
||||
}
|
||||
|
||||
/* Form input base */
|
||||
.input-base {
|
||||
@apply w-full text-text-primary bg-dark-background px-4 py-2.5 rounded-xl
|
||||
border border-secondary
|
||||
focus:border-primary focus:ring-4 focus:ring-primary/20
|
||||
placeholder:text-muted
|
||||
outline-none transition-all duration-200;
|
||||
}
|
||||
|
||||
.input-base:disabled {
|
||||
@apply opacity-50 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.input-base[readonly] {
|
||||
@apply cursor-default;
|
||||
}
|
||||
|
||||
.scrollbar-hide {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.scrollbar-hide::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Smooth transitions for all interactive elements */
|
||||
button, a, input, textarea, select {
|
||||
transition: all 0.2s ease-in-out;
|
||||
}
|
||||
|
||||
/* Enhanced focus states */
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
textarea:focus-visible,
|
||||
select:focus-visible {
|
||||
outline: 2px solid #51AE84;
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
box-shadow: 0 0 0 4px rgba(81, 174, 132, 0.1);
|
||||
box-shadow: var(--shadow-focus-ring);
|
||||
}
|
||||
|
||||
/* Smooth hover scale for interactive elements */
|
||||
@@ -509,7 +681,7 @@ select:focus-visible {
|
||||
.literary-ornament::before,
|
||||
.literary-ornament::after {
|
||||
content: "❖";
|
||||
color: #51AE84;
|
||||
color: var(--color-primary);
|
||||
opacity: 0.3;
|
||||
font-size: 0.8em;
|
||||
margin: 0 0.5em;
|
||||
@@ -531,9 +703,9 @@ select:focus-visible {
|
||||
|
||||
/* Glass morphism effect */
|
||||
.glass-effect {
|
||||
background: rgba(62, 62, 62, 0.7);
|
||||
background: var(--color-glass-bg);
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid var(--color-surface-gradient-light);
|
||||
}
|
||||
|
||||
/* Fade in pour le texte qui stream */
|
||||
@@ -549,3 +721,38 @@ select:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Alert animations */
|
||||
@keyframes shrink {
|
||||
from {
|
||||
width: 100%;
|
||||
}
|
||||
to {
|
||||
width: 0%;
|
||||
}
|
||||
}
|
||||
|
||||
.alert-progress-shrink {
|
||||
animation: shrink 5s linear forwards;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.alert-slide-in {
|
||||
animation: slideInFromRight 0.3s ease-out forwards;
|
||||
}
|
||||
|
||||
/* Pulse dots for loading indicators */
|
||||
.pulse-dot-1 {
|
||||
animation-delay: 0ms;
|
||||
animation-duration: 1.5s;
|
||||
}
|
||||
|
||||
.pulse-dot-2 {
|
||||
animation-delay: 300ms;
|
||||
animation-duration: 1.5s;
|
||||
}
|
||||
|
||||
.pulse-dot-3 {
|
||||
animation-delay: 600ms;
|
||||
animation-duration: 1.5s;
|
||||
}
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
import type {Metadata} from "next";
|
||||
import "./globals.css";
|
||||
import {ReactNode} from "react";
|
||||
import ScribeShell from "@/components/layout/ScribeShell";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "ERitors Scribe",
|
||||
description: "Les meilleurs livres sont ceux qui ont le meilleur plan.",
|
||||
icons: {
|
||||
icon: "/eritors-favicon-white.png"
|
||||
},
|
||||
robots: {
|
||||
index: false,
|
||||
follow: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default function RootLayout(
|
||||
{
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: ReactNode;
|
||||
}>) {
|
||||
}>) {
|
||||
return (
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<title>ERitors Scribe</title>
|
||||
<meta name="description" content="Les meilleurs livres sont ceux qui ont le meilleur plan." />
|
||||
<link rel="icon" href="/eritors-favicon-white.png" />
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
<ScribeShell>{children}</ScribeShell>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -1,29 +1,19 @@
|
||||
'use client'
|
||||
|
||||
import frMessages from '@/lib/locales/fr.json';
|
||||
import enMessages from '@/lib/locales/en.json';
|
||||
import {useEffect, useState} from "react";
|
||||
import {LangContext} from "@/context/LangContext";
|
||||
import {NextIntlClientProvider} from "next-intl";
|
||||
import StaticAlert from "@/components/StaticAlert";
|
||||
import {SessionProps} from "@/lib/models/Session";
|
||||
import System from "@/lib/models/System";
|
||||
import StaticAlert from "@/components/ui/StaticAlert";
|
||||
import {SessionProps} from "@/lib/types/session";
|
||||
import {getCookie} from "@/lib/utils/cookies";
|
||||
import {SessionContext} from "@/context/SessionContext";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {changeLanguage} from "@/lib/i18n";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
|
||||
const messagesMap = {
|
||||
fr: frMessages,
|
||||
en: enMessages
|
||||
};
|
||||
|
||||
export default function LoginWrapper({children}: { children: React.ReactNode }) {
|
||||
const [locale, setLocale] = useState<'fr' | 'en'>('fr');
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
const [successMessage, setSuccessMessage] = useState('');
|
||||
const [infoMessage, setInfoMessage] = useState('');
|
||||
const [warningMessage, setWarningMessage] = useState('');
|
||||
const messages = messagesMap[locale];
|
||||
|
||||
const [session, setSession] = useState<SessionProps>({
|
||||
isConnected: false,
|
||||
@@ -35,6 +25,10 @@ export default function LoginWrapper({children}: { children: React.ReactNode })
|
||||
checkAuthentification().then()
|
||||
}, []);
|
||||
|
||||
useEffect((): void => {
|
||||
changeLanguage(locale);
|
||||
}, [locale]);
|
||||
|
||||
useEffect((): void => {
|
||||
if (session.isConnected) {
|
||||
tauri.loginSuccess();
|
||||
@@ -42,36 +36,36 @@ export default function LoginWrapper({children}: { children: React.ReactNode })
|
||||
}, [session]);
|
||||
|
||||
async function checkAuthentification(): Promise<void> {
|
||||
const language: "fr" | "en" | null = System.getCookie('lang') as "fr" | "en" | null;
|
||||
const language: "fr" | "en" | null = getCookie('lang') as "fr" | "en" | null;
|
||||
if (language) {
|
||||
setLocale(language);
|
||||
}
|
||||
|
||||
// Pas besoin de vérifier le token ici dans Electron
|
||||
// Le main process gère quelle fenêtre ouvrir
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={{session: session, setSession: setSession}}>
|
||||
<LangContext.Provider value={{lang: locale, setLang: setLocale}}>
|
||||
<NextIntlClientProvider locale={locale} messages={messages}>
|
||||
<AlertContext.Provider value={{errorMessage: setErrorMessage, successMessage: setSuccessMessage, infoMessage: setInfoMessage, warningMessage: setWarningMessage}}>
|
||||
{children}
|
||||
<div className="fixed top-4 right-4 z-[9999] flex flex-col gap-3">
|
||||
{
|
||||
successMessage && <StaticAlert type={'success'} message={successMessage} onClose={() => {
|
||||
setSuccessMessage('')
|
||||
}}/>
|
||||
}
|
||||
{
|
||||
errorMessage && <StaticAlert type={'error'} message={errorMessage} onClose={() => {
|
||||
setErrorMessage('')
|
||||
}}/>
|
||||
}
|
||||
</div>
|
||||
</AlertContext.Provider>
|
||||
</NextIntlClientProvider>
|
||||
<AlertContext.Provider value={{
|
||||
errorMessage: setErrorMessage,
|
||||
successMessage: setSuccessMessage,
|
||||
infoMessage: setInfoMessage,
|
||||
warningMessage: setWarningMessage
|
||||
}}>
|
||||
{children}
|
||||
<div className="fixed top-4 right-4 z-[9999] flex flex-col gap-3">
|
||||
{
|
||||
successMessage && <StaticAlert type={'success'} message={successMessage} onClose={() => {
|
||||
setSuccessMessage('')
|
||||
}}/>
|
||||
}
|
||||
{
|
||||
errorMessage && <StaticAlert type={'error'} message={errorMessage} onClose={() => {
|
||||
setErrorMessage('')
|
||||
}}/>
|
||||
}
|
||||
</div>
|
||||
</AlertContext.Provider>
|
||||
</LangContext.Provider>
|
||||
</SessionContext.Provider>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,117 +1,106 @@
|
||||
import {useContext, useState} from "react";
|
||||
import System from "@/lib/models/System";
|
||||
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
|
||||
import {faEnvelope, faLock} from "@fortawesome/free-solid-svg-icons";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
|
||||
export default function LoginForm() {
|
||||
const {errorMessage} = useContext(AlertContext);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent): Promise<void> {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
errorMessage('');
|
||||
|
||||
if (email.length === 0) {
|
||||
errorMessage(t('loginForm.error.emailRequired'));
|
||||
return;
|
||||
}
|
||||
if (password.length === 0) {
|
||||
errorMessage(t('loginForm.error.passwordRequired'));
|
||||
return;
|
||||
}
|
||||
if (email.length < 3) {
|
||||
errorMessage(t('loginForm.error.emailLength'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (System.verifyInput(email) || System.verifyInput(password)) {
|
||||
errorMessage(t('loginForm.error.emailInvalidChars'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: string = await System.postToServer<string>('login', {
|
||||
email: email,
|
||||
password: password,
|
||||
}, lang)
|
||||
if (!response) {
|
||||
errorMessage(t('loginForm.error.connection'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
await tauri.setToken(response);
|
||||
await tauri.loginSuccess();
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('loginForm.error.server'));
|
||||
} else {
|
||||
errorMessage(t('loginForm.error.unknown'));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="mb-5">
|
||||
<label htmlFor="email" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('loginForm.fields.email.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faEnvelope}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
placeholder={t('loginForm.fields.email.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-5">
|
||||
<div className="flex justify-between items-center mb-1">
|
||||
<label htmlFor="password" className="block text-sm font-medium text-muted">
|
||||
{t('loginForm.fields.password.label')}
|
||||
</label>
|
||||
<a href="/login/reset-password" className="text-xs text-primary hover:underline">
|
||||
{t('loginForm.fields.password.forgot')}
|
||||
</a>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faLock}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
placeholder={t('loginForm.fields.password.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className={`w-full py-4 mb-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all ${isLoading ? 'opacity-75 cursor-not-allowed' : ''}`}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? t('loginForm.loading') : t('loginForm.submit')}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
import {useContext, useState} from "react";
|
||||
import {Mail, Lock} from "lucide-react";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
import {verifyInput} from "@/lib/utils/validation";
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
import Button from "@/components/ui/Button";
|
||||
import InputField from "@/components/form/InputField";
|
||||
import TextInput from "@/components/form/TextInput";
|
||||
|
||||
export default function LoginForm() {
|
||||
const {errorMessage} = useContext(AlertContext);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent): Promise<void> {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
errorMessage('');
|
||||
|
||||
if (email.length === 0) {
|
||||
errorMessage(t('loginForm.error.emailRequired'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
if (password.length === 0) {
|
||||
errorMessage(t('loginForm.error.passwordRequired'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
if (email.length < 3) {
|
||||
errorMessage(t('loginForm.error.emailLength'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (verifyInput(email) || verifyInput(password)) {
|
||||
errorMessage(t('loginForm.error.emailInvalidChars'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: string = await apiPostPublic<string>('login', {
|
||||
email: email,
|
||||
password: password,
|
||||
}, lang)
|
||||
if (!response) {
|
||||
errorMessage(t('loginForm.error.connection'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
await tauri.setToken(response);
|
||||
await tauri.loginSuccess();
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('loginForm.error.server'));
|
||||
} else {
|
||||
errorMessage(t('loginForm.error.unknown'));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<InputField icon={Mail} fieldName={t('loginForm.fields.email.label')} input={
|
||||
<TextInput
|
||||
value={email}
|
||||
setValue={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('loginForm.fields.email.placeholder')}
|
||||
size="lg"
|
||||
/>
|
||||
}/>
|
||||
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('loginForm.fields.password.label')}
|
||||
</h3>
|
||||
<a href="/login/reset-password" className="text-xs text-primary hover:underline">
|
||||
{t('loginForm.fields.password.forgot')}
|
||||
</a>
|
||||
</div>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={t('loginForm.fields.password.placeholder')}
|
||||
className="input-base px-5 py-3 text-base rounded-xl"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button variant="primary" fullWidth size="lg" type="submit" isLoading={isLoading}>
|
||||
{t('loginForm.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,124 +1,140 @@
|
||||
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
|
||||
import {faApple, faFacebookF, faGoogle} from "@fortawesome/free-brands-svg-icons";
|
||||
import React, {useContext, useEffect} from "react";
|
||||
import System from "@/lib/models/System";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {configs} from "@/lib/configs";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
|
||||
export default function SocialForm() {
|
||||
const {errorMessage} = useContext(AlertContext);
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
useEffect((): void => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const provider: string | null = params.get('provider');
|
||||
if (!provider) return;
|
||||
|
||||
const code: string | null = params.get('code');
|
||||
if (!code) return;
|
||||
|
||||
if (provider === 'google') {
|
||||
handleGoogleLogin(code).then();
|
||||
return;
|
||||
}
|
||||
if (provider === 'facebook') {
|
||||
const state: string | null = params.get('state');
|
||||
if (!state) return;
|
||||
handleFacebookLogin(code, state).then();
|
||||
return;
|
||||
}
|
||||
if (provider === 'apple') {
|
||||
const state: string | null = params.get('state');
|
||||
if (!state) return;
|
||||
handleAppleLogin(code, state).then();
|
||||
return;
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function handleLoginSuccess(token: string): Promise<void> {
|
||||
await tauri.setToken(token);
|
||||
await tauri.loginSuccess();
|
||||
}
|
||||
|
||||
async function handleFacebookLogin(code: string, state: string): Promise<void> {
|
||||
if (code && state) {
|
||||
const response: string = await System.postToServer<string>(`auth/facebook`, {
|
||||
code: code,
|
||||
state: state,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
return;
|
||||
}
|
||||
await handleLoginSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGoogleLogin(code: string): Promise<void> {
|
||||
if (code) {
|
||||
const response: string = await System.postToServer<string>(`auth/google`, {
|
||||
code: code,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
return;
|
||||
}
|
||||
await handleLoginSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAppleLogin(code: string, state: string): Promise<void> {
|
||||
if (code && state) {
|
||||
const response: string = await System.postToServer<string>(`auth/apple`, {
|
||||
code: code,
|
||||
state: state,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
return;
|
||||
}
|
||||
await handleLoginSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleOAuthClick(provider: 'google' | 'facebook' | 'apple'): Promise<void> {
|
||||
try {
|
||||
const oauthUrl = `${configs.baseUrl}auth/${provider}/desktop`;
|
||||
await tauri.openExternal(oauthUrl);
|
||||
} catch {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex justify-center gap-3">
|
||||
<button
|
||||
onClick={() => handleOAuthClick('facebook')}
|
||||
className="flex items-center justify-center w-14 h-14 bg-[#1877F2] hover:bg-opacity-90 text-textPrimary rounded-xl transition-colors cursor-pointer"
|
||||
aria-label="Login with Facebook"
|
||||
>
|
||||
<FontAwesomeIcon icon={faFacebookF} className="w-6 h-6 text-textPrimary"/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleOAuthClick('google')}
|
||||
className="flex items-center justify-center w-14 h-14 bg-white hover:bg-opacity-90 text-[#4285F4] rounded-xl transition-colors cursor-pointer"
|
||||
aria-label="Login with Google"
|
||||
>
|
||||
<FontAwesomeIcon icon={faGoogle} className="w-6 h-6 text-[#4285F4]"/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleOAuthClick('apple')}
|
||||
className="flex items-center justify-center w-14 h-14 bg-black hover:bg-opacity-90 text-white rounded-xl transition-colors cursor-pointer"
|
||||
aria-label="Login with Apple"
|
||||
>
|
||||
<FontAwesomeIcon icon={faApple} className="w-6 h-6 text-white"/>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import React, {useContext, useEffect} from "react";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {configs} from "@/lib/configs";
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
|
||||
const FacebookIcon = () => (
|
||||
<svg className="w-6 h-6" viewBox="0 0 320 512" fill="currentColor">
|
||||
<path d="M80 299.3V512H196V299.3h86.5l18-97.8H196V166.9c0-51.7 20.3-71.5 72.7-71.5c16.3 0 29.4.4 37 1.2V7.9C291.4 4 256.4 0 236.2 0C129.3 0 80 50.5 80 159.4v42.1H14v97.8H80z"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<svg className="w-6 h-6" viewBox="0 0 488 512" fill="currentColor">
|
||||
<path d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const AppleIcon = () => (
|
||||
<svg className="w-6 h-6" viewBox="0 0 384 512" fill="currentColor">
|
||||
<path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default function SocialForm() {
|
||||
const {errorMessage} = useContext(AlertContext);
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
useEffect((): void => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const provider: string | null = params.get('provider');
|
||||
if (!provider) return;
|
||||
|
||||
const code: string | null = params.get('code');
|
||||
if (!code) return;
|
||||
|
||||
if (provider === 'google') {
|
||||
handleGoogleLogin(code).then();
|
||||
return;
|
||||
}
|
||||
if (provider === 'facebook') {
|
||||
const state: string | null = params.get('state');
|
||||
if (!state) return;
|
||||
handleFacebookLogin(code, state).then();
|
||||
return;
|
||||
}
|
||||
if (provider === 'apple') {
|
||||
const state: string | null = params.get('state');
|
||||
if (!state) return;
|
||||
handleAppleLogin(code, state).then();
|
||||
return;
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function handleLoginSuccess(token: string): Promise<void> {
|
||||
await tauri.setToken(token);
|
||||
await tauri.loginSuccess();
|
||||
}
|
||||
|
||||
async function handleFacebookLogin(code: string, state: string): Promise<void> {
|
||||
if (code && state) {
|
||||
const response: string = await apiPostPublic<string>(`auth/facebook`, {
|
||||
code: code,
|
||||
state: state,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
return;
|
||||
}
|
||||
await handleLoginSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGoogleLogin(code: string): Promise<void> {
|
||||
if (code) {
|
||||
const response: string = await apiPostPublic<string>(`auth/google`, {
|
||||
code: code,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
return;
|
||||
}
|
||||
await handleLoginSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAppleLogin(code: string, state: string): Promise<void> {
|
||||
if (code && state) {
|
||||
const response: string = await apiPostPublic<string>(`auth/apple`, {
|
||||
code: code,
|
||||
state: state,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
return;
|
||||
}
|
||||
await handleLoginSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleOAuthClick(provider: 'google' | 'facebook' | 'apple'): Promise<void> {
|
||||
try {
|
||||
const oauthUrl = `${configs.baseUrl}auth/${provider}/desktop`;
|
||||
await tauri.openExternal(oauthUrl);
|
||||
} catch {
|
||||
errorMessage(t('socialForm.error.connection'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex justify-center gap-3">
|
||||
<button
|
||||
onClick={() => handleOAuthClick('facebook')}
|
||||
className="flex items-center justify-center w-14 h-14 bg-[#1877F2] hover:bg-opacity-90 text-text-primary rounded-xl transition-colors cursor-pointer"
|
||||
aria-label="Login with Facebook"
|
||||
>
|
||||
<FacebookIcon/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleOAuthClick('google')}
|
||||
className="flex items-center justify-center w-14 h-14 bg-white hover:bg-opacity-90 text-[#4285F4] rounded-xl transition-colors cursor-pointer"
|
||||
aria-label="Login with Google"
|
||||
>
|
||||
<GoogleIcon/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleOAuthClick('apple')}
|
||||
className="flex items-center justify-center w-14 h-14 bg-black hover:bg-opacity-90 text-white rounded-xl transition-colors cursor-pointer"
|
||||
aria-label="Login with Apple"
|
||||
>
|
||||
<AppleIcon/>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,172 +1,214 @@
|
||||
'use client'
|
||||
import {useContext, useEffect, useState} from 'react';
|
||||
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
|
||||
import {faEnvelope, faWifi, faCloudArrowUp} from "@fortawesome/free-solid-svg-icons";
|
||||
import LoginForm from "@/app/login/login/LoginForm";
|
||||
import SocialForm from "@/app/login/login/SocialForm";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {LangContext} from "@/context/LangContext";
|
||||
import System from "@/lib/models/System";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
|
||||
export default function LoginPage() {
|
||||
const t = useTranslations();
|
||||
const {lang, setLang} = useContext(LangContext);
|
||||
const [showOfflineWarning, setShowOfflineWarning] = useState(false);
|
||||
const [isOnline, setIsOnline] = useState(true);
|
||||
const [resetDone, setResetDone] = useState(false);
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
const handleDevReset = async () => {
|
||||
try {
|
||||
await tauri.devResetAll();
|
||||
setResetDone(true);
|
||||
} catch (error) {
|
||||
console.error('[DevReset]', error);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleLanguage = () => {
|
||||
const newLang = lang === 'fr' ? 'en' : 'fr';
|
||||
setLang(newLang);
|
||||
System.setCookie('lang', newLang, 365);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
async function checkFirstConnectionAndNetwork() {
|
||||
try {
|
||||
const token = await tauri.getToken();
|
||||
const hasToken = !!token;
|
||||
const online = navigator.onLine;
|
||||
setIsOnline(online);
|
||||
|
||||
if (!hasToken && !online) {
|
||||
setShowOfflineWarning(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking first connection:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkFirstConnectionAndNetwork();
|
||||
|
||||
const handleOnline = () => {
|
||||
setIsOnline(true);
|
||||
setShowOfflineWarning(false);
|
||||
};
|
||||
const handleOffline = async () => {
|
||||
setIsOnline(false);
|
||||
try {
|
||||
const token = await tauri.getToken();
|
||||
if (!token) {
|
||||
setShowOfflineWarning(true);
|
||||
}
|
||||
} catch {
|
||||
setShowOfflineWarning(true);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('online', handleOnline);
|
||||
window.addEventListener('offline', handleOffline);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('online', handleOnline);
|
||||
window.removeEventListener('offline', handleOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-background text-textPrimary p-4">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<div className="w-[90%] max-w-[320px] relative">
|
||||
<img
|
||||
src="/logo.png"
|
||||
alt="ERitors"
|
||||
className="object-contain"
|
||||
style={{width: 320, height: 107}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Offline warning notification */}
|
||||
{showOfflineWarning && (
|
||||
<div className="mb-6 bg-gradient-to-r from-orange-500/20 to-amber-500/20 border border-orange-500/40 rounded-xl p-4 shadow-lg shadow-orange-500/10">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-shrink-0 mt-0.5">
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faWifi} className="w-5 h-5 text-orange-400" />
|
||||
<div className="absolute inset-0 w-6 h-0.5 bg-orange-400 rotate-45 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-orange-200 mb-1 flex items-center gap-2">
|
||||
<FontAwesomeIcon icon={faCloudArrowUp} className="w-4 h-4" />
|
||||
{t('loginPage.offlineWarning.title')}
|
||||
</h3>
|
||||
<p className="text-sm text-orange-300/90 leading-relaxed">
|
||||
{t('loginPage.offlineWarning.message')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="bg-tertiary rounded-2xl overflow-hidden shadow-xl shadow-primary/10 w-full relative">
|
||||
<button
|
||||
onClick={toggleLanguage}
|
||||
className="absolute right-4 top-4 z-10 flex items-center gap-2 px-3 py-2 bg-secondary border border-gray-dark rounded-lg hover:bg-tertiary transition-colors"
|
||||
aria-label="Toggle language"
|
||||
>
|
||||
<span
|
||||
className={`text-sm font-medium ${lang === 'fr' ? 'text-primary' : 'text-muted'}`}>FR</span>
|
||||
<span className="text-muted">/</span>
|
||||
<span
|
||||
className={`text-sm font-medium ${lang === 'en' ? 'text-primary' : 'text-muted'}`}>EN</span>
|
||||
</button>
|
||||
<div
|
||||
className="absolute top-0 left-0 right-0 h-2 bg-gradient-to-r from-primary to-info pointer-events-none"></div>
|
||||
<div
|
||||
className="absolute -top-10 -left-10 w-40 h-40 bg-gradient-to-br from-primary/20 to-transparent rounded-full blur-xl pointer-events-none"></div>
|
||||
<div
|
||||
className="absolute -bottom-10 -right-10 w-40 h-40 bg-gradient-to-br from-info/20 to-transparent rounded-full blur-xl pointer-events-none"></div>
|
||||
|
||||
<div className="p-6 sm:p-8">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM Display']">{t('loginPage.title')}</h1>
|
||||
<p className="text-muted">{t('loginPage.welcome')}</p>
|
||||
</div>
|
||||
<LoginForm/>
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-dark"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center">
|
||||
<span className="px-3 bg-tertiary text-muted text-sm">{t('loginPage.orSocial')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-center gap-3 mb-6">
|
||||
<a
|
||||
href="/login/register"
|
||||
className="flex items-center justify-center w-14 h-14 bg-gradient-to-r from-primary to-info hover:shadow-lg hover:shadow-primary/20 text-textPrimary rounded-xl transition-all"
|
||||
aria-label="Register with email"
|
||||
>
|
||||
<FontAwesomeIcon icon={faEnvelope} className="w-6 h-6 text-textPrimary"/>
|
||||
</a>
|
||||
<SocialForm/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isDev && (
|
||||
resetDone
|
||||
? <span className="mt-6 text-xs text-green-400">Reset OK</span>
|
||||
: <button onClick={handleDevReset} className="mt-6 px-4 py-2 text-xs text-red-400 border border-red-400/30 rounded-lg hover:bg-red-400/10 transition-colors">
|
||||
DEV: Reset All Data
|
||||
</button>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
'use client'
|
||||
import {useContext, useEffect, useState} from 'react';
|
||||
import {Mail, Lock, Wifi, CloudUpload, Globe} from "lucide-react";
|
||||
import SocialForm from "@/app/login/login/SocialForm";
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import {setCookie} from "@/lib/utils/cookies";
|
||||
import {verifyInput} from "@/lib/utils/validation";
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
import Button from "@/components/ui/Button";
|
||||
import InputField from "@/components/form/InputField";
|
||||
import TextInput from "@/components/form/TextInput";
|
||||
import ToggleGroup from "@/components/ui/ToggleGroup";
|
||||
|
||||
export default function LoginPage() {
|
||||
const t = useTranslations();
|
||||
const {errorMessage} = useContext(AlertContext);
|
||||
const {lang, setLang} = useContext<LangContextProps>(LangContext);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [showOfflineWarning, setShowOfflineWarning] = useState(false);
|
||||
const [resetDone, setResetDone] = useState(false);
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
useEffect(() => {
|
||||
async function checkFirstConnectionAndNetwork() {
|
||||
try {
|
||||
const token = await tauri.getToken();
|
||||
const online = navigator.onLine;
|
||||
if (!token && !online) {
|
||||
setShowOfflineWarning(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking first connection:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkFirstConnectionAndNetwork();
|
||||
|
||||
const handleOnline = () => setShowOfflineWarning(false);
|
||||
const handleOffline = async () => {
|
||||
try {
|
||||
const token = await tauri.getToken();
|
||||
if (!token) setShowOfflineWarning(true);
|
||||
} catch {
|
||||
setShowOfflineWarning(true);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('online', handleOnline);
|
||||
window.addEventListener('offline', handleOffline);
|
||||
return () => {
|
||||
window.removeEventListener('online', handleOnline);
|
||||
window.removeEventListener('offline', handleOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent): Promise<void> {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
errorMessage('');
|
||||
|
||||
if (email.length === 0) {
|
||||
errorMessage(t('loginForm.error.emailRequired'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
if (password.length === 0) {
|
||||
errorMessage(t('loginForm.error.passwordRequired'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
if (email.length < 3) {
|
||||
errorMessage(t('loginForm.error.emailLength'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
if (verifyInput(email) || verifyInput(password)) {
|
||||
errorMessage(t('loginForm.error.emailInvalidChars'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response: string = await apiPostPublic<string>('login', {
|
||||
email: email,
|
||||
password: password,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('loginForm.error.connection'));
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
await tauri.setToken(response);
|
||||
await tauri.loginSuccess();
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('loginForm.error.server'));
|
||||
} else {
|
||||
errorMessage(t('loginForm.error.unknown'));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-tertiary text-text-primary p-4 font-['Lora']">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<img src="/logo.png" alt="ERitors" className="object-contain" style={{width: 320, height: 107}}/>
|
||||
</div>
|
||||
|
||||
{showOfflineWarning && (
|
||||
<div className="mb-6 bg-warning/10 border border-warning/30 rounded-xl p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Wifi className="w-5 h-5 text-warning mt-0.5" strokeWidth={1.75}/>
|
||||
<div>
|
||||
<h3 className="font-semibold text-warning mb-1 flex items-center gap-2">
|
||||
<CloudUpload className="w-4 h-4" strokeWidth={1.75}/>
|
||||
{t('loginPage.offlineWarning.title')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted leading-relaxed">
|
||||
{t('loginPage.offlineWarning.message')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center mb-6">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM_Display']">{t('loginPage.title')}</h1>
|
||||
<p className="text-muted">{t('loginPage.welcome')}</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="bg-darkest-background rounded-xl p-5 space-y-5">
|
||||
<div className="flex justify-end">
|
||||
<ToggleGroup
|
||||
options={[{value: 'fr', label: 'FR'}, {value: 'en', label: 'EN'}]}
|
||||
value={lang}
|
||||
onChange={(value: string) => {
|
||||
setLang(value as 'fr' | 'en');
|
||||
setCookie('lang', value, 365);
|
||||
}}
|
||||
icon={Globe}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<InputField icon={Mail} fieldName={t('loginForm.fields.email.label')} input={
|
||||
<TextInput value={email} setValue={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('loginForm.fields.email.placeholder')} size="lg"/>
|
||||
}/>
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('loginForm.fields.password.label')}
|
||||
</h3>
|
||||
<a href="/login/reset-password" className="text-xs text-primary hover:underline">
|
||||
{t('loginForm.fields.password.forgot')}
|
||||
</a>
|
||||
</div>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={t('loginForm.fields.password.placeholder')}
|
||||
className="input-base px-5 py-3 text-base rounded-xl"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<Button variant="primary" fullWidth size="lg" type="submit" isLoading={isLoading}>
|
||||
{t('loginForm.submit')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-secondary"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center">
|
||||
<span className="px-3 bg-tertiary text-muted text-sm">{t('loginPage.orSocial')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center gap-3 mb-6">
|
||||
<a href="/login/register"
|
||||
className="flex items-center justify-center w-14 h-14 bg-primary-dark hover:bg-primary text-text-primary rounded-xl transition-colors duration-200">
|
||||
<Mail className="w-6 h-6" strokeWidth={1.75}/>
|
||||
</a>
|
||||
<SocialForm/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isDev && (
|
||||
resetDone
|
||||
? <span className="mt-6 text-xs text-success">Reset OK</span>
|
||||
: <button onClick={async () => { await tauri.devResetAll(); setResetDone(true); }}
|
||||
className="mt-6 px-4 py-2 text-xs text-error border border-error/30 rounded-lg hover:bg-error/10 transition-colors">
|
||||
DEV: Reset All Data
|
||||
</button>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,79 +1,67 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import OfflinePinVerify from '@/components/offline/OfflinePinVerify';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faWifi, faArrowLeft } from '@fortawesome/free-solid-svg-icons';
|
||||
import * as tauri from '@/lib/tauri';
|
||||
|
||||
export default function OfflineLoginPage() {
|
||||
const t = useTranslations();
|
||||
|
||||
async function handlePinSuccess(userId: string): Promise<void> {
|
||||
try {
|
||||
const encryptionKey = await tauri.getUserEncryptionKey(userId);
|
||||
if (encryptionKey) {
|
||||
await tauri.dbInitialize(userId, encryptionKey);
|
||||
await tauri.loginSuccess();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[OfflineLogin] Error initializing database:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function handleBackToOnline(): void {
|
||||
tauri.logout();
|
||||
}
|
||||
|
||||
useEffect((): void => {
|
||||
async function checkOfflineCapability() {
|
||||
const offlineStatus = await tauri.offlineModeGet();
|
||||
if (!offlineStatus.hasPin) {
|
||||
window.location.href = '/login/login';
|
||||
}
|
||||
}
|
||||
|
||||
checkOfflineCapability().then();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-background text-textPrimary">
|
||||
<div className="w-full max-w-md px-4">
|
||||
{/* Offline indicator */}
|
||||
<div className="mb-6 flex items-center justify-center">
|
||||
<div className="px-4 py-2 bg-warning/10 border border-warning/30 rounded-full flex items-center gap-2">
|
||||
<FontAwesomeIcon icon={faWifi} className="w-4 h-4 text-warning" />
|
||||
<span className="text-sm text-warning font-medium">{t('offline.mode.title')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Logo */}
|
||||
<div className="flex justify-center mb-8">
|
||||
<img
|
||||
src="/logo.png"
|
||||
alt="ERitors"
|
||||
className="object-contain w-full max-w-[240px] h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* PIN Verify Component */}
|
||||
<OfflinePinVerify
|
||||
onSuccess={handlePinSuccess}
|
||||
onCancel={handleBackToOnline}
|
||||
/>
|
||||
|
||||
{/* Back to online link */}
|
||||
<div className="mt-6 text-center">
|
||||
<button
|
||||
onClick={handleBackToOnline}
|
||||
className="text-sm text-muted hover:text-textPrimary transition-colors inline-flex items-center gap-2"
|
||||
>
|
||||
<FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3" />
|
||||
{t('offline.mode.backToOnline')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
'use client';
|
||||
|
||||
import {useEffect} from 'react';
|
||||
import OfflinePinVerify from '@/components/offline/OfflinePinVerify';
|
||||
import {useTranslations} from '@/lib/i18n';
|
||||
import {Wifi, ArrowLeft} from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import * as tauri from '@/lib/tauri';
|
||||
|
||||
export default function OfflineLoginPage() {
|
||||
const t = useTranslations();
|
||||
|
||||
async function handlePinSuccess(userId: string): Promise<void> {
|
||||
try {
|
||||
const encryptionKey = await tauri.getUserEncryptionKey(userId);
|
||||
if (encryptionKey) {
|
||||
await tauri.dbInitialize(userId, encryptionKey);
|
||||
await tauri.loginSuccess();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[OfflineLogin] Error initializing database:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function handleBackToOnline(): void {
|
||||
tauri.logout();
|
||||
}
|
||||
|
||||
useEffect((): void => {
|
||||
async function checkOfflineCapability() {
|
||||
const offlineStatus = await tauri.offlineModeGet();
|
||||
if (!offlineStatus.hasPin) {
|
||||
window.location.href = '/login/login';
|
||||
}
|
||||
}
|
||||
|
||||
checkOfflineCapability().then();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-tertiary text-text-primary p-4 font-['Lora']">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<img src="/logo.png" alt="ERitors" className="object-contain" style={{width: 320, height: 107}}/>
|
||||
</div>
|
||||
|
||||
<div className="text-center mb-6">
|
||||
<div className="inline-flex items-center gap-2 px-3 py-1.5 bg-warning/10 border border-warning/30 rounded-full mb-3">
|
||||
<Wifi className="w-4 h-4 text-warning" strokeWidth={1.75}/>
|
||||
<span className="text-sm text-warning font-medium">{t('offline.mode.title')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-darkest-background rounded-xl p-5 mb-4">
|
||||
<OfflinePinVerify
|
||||
onSuccess={handlePinSuccess}
|
||||
onCancel={handleBackToOnline}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button variant="ghost" fullWidth icon={ArrowLeft} onClick={handleBackToOnline}>
|
||||
{t('offline.mode.backToOnline')}
|
||||
</Button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,205 +1,147 @@
|
||||
import React, {Dispatch, SetStateAction, useContext, useState} from "react";
|
||||
import System from "@/lib/models/System";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
|
||||
import {faEnvelope, faLock, faSignature, faUser} from '@fortawesome/free-solid-svg-icons';
|
||||
import {useTranslations} from "next-intl";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
|
||||
export default function StepOne(
|
||||
{
|
||||
username,
|
||||
email,
|
||||
setUsername,
|
||||
setEmail,
|
||||
handleNextStep
|
||||
}: {
|
||||
username: string;
|
||||
email: string;
|
||||
setUsername: Dispatch<SetStateAction<string>>,
|
||||
setEmail: Dispatch<SetStateAction<string>>,
|
||||
handleNextStep: Function;
|
||||
}) {
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
const [firstName, setFirstName] = useState<string>('');
|
||||
const [lastName, setLastName] = useState<string>('');
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [repeatPassword, setRepeatPassword] = useState<string>('');
|
||||
const [userId, setUserId] = useState<string>('')
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleStep(): Promise<void> {
|
||||
|
||||
if (!firstName || !lastName || !username || !password || !repeatPassword || !email) {
|
||||
errorMessage(t('registerStepOne.error.requiredFields'));
|
||||
return;
|
||||
}
|
||||
if (firstName.length < 2 || firstName.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.firstNameLength'));
|
||||
return;
|
||||
}
|
||||
if (lastName.length < 2 || lastName.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.lastNameLength'));
|
||||
return;
|
||||
}
|
||||
if (username.length < 3 || username.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.usernameLength'));
|
||||
return;
|
||||
}
|
||||
if (System.verifyInput(firstName) || System.verifyInput(lastName) || System.verifyInput(username) || System.verifyInput(password) || System.verifyInput(repeatPassword) || System.verifyInput(email)) {
|
||||
errorMessage(t('registerStepOne.error.invalidInput'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (password != repeatPassword) {
|
||||
errorMessage(t('registerStepOne.error.passwordMismatch'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: string = await System.postToServer<string>(`register/pre`, {
|
||||
firstName,
|
||||
lastName,
|
||||
username,
|
||||
email,
|
||||
password,
|
||||
retypePass: repeatPassword
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('registerStepOne.error.preRegister'));
|
||||
return;
|
||||
}
|
||||
setUserId(response);
|
||||
successMessage(t('registerStepOne.success.preRegister'));
|
||||
handleNextStep();
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t('registerStepOne.error.unknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="space-y-4">
|
||||
<div className="mb-4">
|
||||
<label htmlFor="firstName" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepOne.fields.firstName.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faSignature}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="text"
|
||||
id="firstName"
|
||||
placeholder={t('registerStepOne.fields.firstName.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<label htmlFor="lastName" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepOne.fields.lastName.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faSignature}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="text"
|
||||
id="lastName"
|
||||
placeholder={t('registerStepOne.fields.lastName.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<label htmlFor="username" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepOne.fields.username.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faUser}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
placeholder={t('registerStepOne.fields.username.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted mt-1">{t('registerStepOne.fields.username.note')}</p>
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<label htmlFor="email" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepOne.fields.email.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faEnvelope}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
placeholder={t('registerStepOne.fields.email.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<label htmlFor="password" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepOne.fields.password.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faLock}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
placeholder={t('registerStepOne.fields.password.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<label htmlFor="repeatPassword" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepOne.fields.repeatPassword.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faLock}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="password"
|
||||
id="repeatPassword"
|
||||
placeholder={t('registerStepOne.fields.repeatPassword.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={repeatPassword}
|
||||
onChange={(e) => setRepeatPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStep()}
|
||||
className="w-full py-4 mt-6 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
|
||||
>
|
||||
{t('registerStepOne.next')}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
import React, {Dispatch, SetStateAction, useContext, useState} from "react";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {Mail, Lock, PenLine, User} from 'lucide-react';
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import {verifyInput} from "@/lib/utils/validation";
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
import Button from "@/components/ui/Button";
|
||||
import InputField from "@/components/form/InputField";
|
||||
import TextInput from "@/components/form/TextInput";
|
||||
|
||||
export default function StepOne(
|
||||
{
|
||||
username,
|
||||
email,
|
||||
setUsername,
|
||||
setEmail,
|
||||
handleNextStep
|
||||
}: {
|
||||
username: string;
|
||||
email: string;
|
||||
setUsername: Dispatch<SetStateAction<string>>,
|
||||
setEmail: Dispatch<SetStateAction<string>>,
|
||||
handleNextStep: Function;
|
||||
}) {
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
const [firstName, setFirstName] = useState<string>('');
|
||||
const [lastName, setLastName] = useState<string>('');
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [repeatPassword, setRepeatPassword] = useState<string>('');
|
||||
const [userId, setUserId] = useState<string>('')
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleStep(): Promise<void> {
|
||||
|
||||
if (!firstName || !lastName || !username || !password || !repeatPassword || !email) {
|
||||
errorMessage(t('registerStepOne.error.requiredFields'));
|
||||
return;
|
||||
}
|
||||
if (firstName.length < 2 || firstName.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.firstNameLength'));
|
||||
return;
|
||||
}
|
||||
if (lastName.length < 2 || lastName.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.lastNameLength'));
|
||||
return;
|
||||
}
|
||||
if (username.length < 3 || username.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.usernameLength'));
|
||||
return;
|
||||
}
|
||||
if (verifyInput(firstName) || verifyInput(lastName) || verifyInput(username) || verifyInput(password) || verifyInput(repeatPassword) || verifyInput(email)) {
|
||||
errorMessage(t('registerStepOne.error.invalidInput'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (password != repeatPassword) {
|
||||
errorMessage(t('registerStepOne.error.passwordMismatch'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: string = await apiPostPublic<string>(`register/pre`, {
|
||||
firstName,
|
||||
lastName,
|
||||
username,
|
||||
email,
|
||||
password,
|
||||
retypePass: repeatPassword
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('registerStepOne.error.preRegister'));
|
||||
return;
|
||||
}
|
||||
setUserId(response);
|
||||
successMessage(t('registerStepOne.success.preRegister'));
|
||||
handleNextStep();
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t('registerStepOne.error.unknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="space-y-4">
|
||||
<InputField icon={PenLine} fieldName={t('registerStepOne.fields.firstName.label')} input={
|
||||
<TextInput value={firstName} setValue={(e) => setFirstName(e.target.value)}
|
||||
placeholder={t('registerStepOne.fields.firstName.placeholder')}/>
|
||||
}/>
|
||||
|
||||
<InputField icon={PenLine} fieldName={t('registerStepOne.fields.lastName.label')} input={
|
||||
<TextInput value={lastName} setValue={(e) => setLastName(e.target.value)}
|
||||
placeholder={t('registerStepOne.fields.lastName.placeholder')}/>
|
||||
}/>
|
||||
|
||||
<div>
|
||||
<InputField icon={User} fieldName={t('registerStepOne.fields.username.label')} input={
|
||||
<TextInput value={username} setValue={(e) => setUsername(e.target.value)}
|
||||
placeholder={t('registerStepOne.fields.username.placeholder')}/>
|
||||
}/>
|
||||
<p className="text-xs text-muted mt-1">{t('registerStepOne.fields.username.note')}</p>
|
||||
</div>
|
||||
|
||||
<InputField icon={Mail} fieldName={t('registerStepOne.fields.email.label')} input={
|
||||
<TextInput value={email} setValue={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('registerStepOne.fields.email.placeholder')}/>
|
||||
}/>
|
||||
|
||||
<div>
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('registerStepOne.fields.password.label')}
|
||||
</h3>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={t('registerStepOne.fields.password.placeholder')}
|
||||
className="input-base"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('registerStepOne.fields.repeatPassword.label')}
|
||||
</h3>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={t('registerStepOne.fields.repeatPassword.placeholder')}
|
||||
className="input-base"
|
||||
value={repeatPassword}
|
||||
onChange={(e) => setRepeatPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button variant="primary" fullWidth size="lg" onClick={() => handleStep()}>
|
||||
{t('registerStepOne.next')}
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,114 +1,91 @@
|
||||
import React, {useContext, useState} from "react";
|
||||
import Link from "next/link";
|
||||
import System from "@/lib/models/System";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
|
||||
import {faKey} from '@fortawesome/free-solid-svg-icons';
|
||||
import {useTranslations} from "next-intl";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
|
||||
export default function StepTree(
|
||||
{
|
||||
email,
|
||||
prevStep
|
||||
}: {
|
||||
email: string;
|
||||
prevStep: Function;
|
||||
}) {
|
||||
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
|
||||
const [isConfirmed, setIsConfirmed] = useState<boolean>(false);
|
||||
const [verifyCode, setVerifyCode] = useState<string>('');
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleVerifyCode(): Promise<void> {
|
||||
if (verifyCode === '') {
|
||||
errorMessage(t('registerStepTwo.error.codeIncorrect'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: boolean = await System.postToServer<boolean>('register/verify-code', {
|
||||
verifyCode,
|
||||
email,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('registerStepTwo.error.codeIncorrect'));
|
||||
return;
|
||||
}
|
||||
setIsConfirmed(true);
|
||||
successMessage(t('registerStepTwo.success.verified'));
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t('registerStepTwo.error.unknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
!isConfirmed ? (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center mb-6">
|
||||
<p className="text-muted">{t('registerStepTwo.instructions.sent')}</p>
|
||||
<p className="text-muted text-sm mt-2">{t('registerStepTwo.instructions.checkInbox')}</p>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<label htmlFor="verifyCode" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('registerStepTwo.fields.code.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faKey}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="text"
|
||||
id="verifyCode"
|
||||
placeholder={t('registerStepTwo.fields.code.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={verifyCode}
|
||||
onChange={(e) => setVerifyCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-3 mt-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleVerifyCode()}
|
||||
className="w-full py-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
|
||||
>
|
||||
{t('registerStepTwo.verify')}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => prevStep()}
|
||||
className="w-full py-4 bg-secondary text-textPrimary font-semibold rounded-xl hover:bg-gray-dark transition-colors"
|
||||
>
|
||||
{t('registerStepTwo.back')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
<div className="p-4 bg-success/20 border border-success rounded-xl">
|
||||
<p className="text-center text-text">{t('registerStepTwo.confirmed')}</p>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<Link href="/login" className="block w-full">
|
||||
<button
|
||||
type="button"
|
||||
className="w-full py-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
|
||||
>
|
||||
{t('registerStepTwo.start')}
|
||||
</button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)
|
||||
}
|
||||
import React, {useContext, useState} from "react";
|
||||
import {Link} from "@/lib/navigation";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {KeyRound} from 'lucide-react';
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
import Button from "@/components/ui/Button";
|
||||
import InputField from "@/components/form/InputField";
|
||||
import TextInput from "@/components/form/TextInput";
|
||||
|
||||
export default function StepTree(
|
||||
{
|
||||
email,
|
||||
prevStep
|
||||
}: {
|
||||
email: string;
|
||||
prevStep: Function;
|
||||
}) {
|
||||
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
|
||||
const [isConfirmed, setIsConfirmed] = useState<boolean>(false);
|
||||
const [verifyCode, setVerifyCode] = useState<string>('');
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleVerifyCode(): Promise<void> {
|
||||
if (verifyCode === '') {
|
||||
errorMessage(t('registerStepTwo.error.codeIncorrect'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: boolean = await apiPostPublic<boolean>('register/verify-code', {
|
||||
verifyCode,
|
||||
email,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('registerStepTwo.error.codeIncorrect'));
|
||||
return;
|
||||
}
|
||||
setIsConfirmed(true);
|
||||
successMessage(t('registerStepTwo.success.verified'));
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t('registerStepTwo.error.unknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
!isConfirmed ? (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center mb-6">
|
||||
<p className="text-muted">{t('registerStepTwo.instructions.sent')}</p>
|
||||
<p className="text-muted text-sm mt-2">{t('registerStepTwo.instructions.checkInbox')}</p>
|
||||
</div>
|
||||
|
||||
<InputField icon={KeyRound} fieldName={t('registerStepTwo.fields.code.label')} input={
|
||||
<TextInput value={verifyCode} setValue={(e) => setVerifyCode(e.target.value)}
|
||||
placeholder={t('registerStepTwo.fields.code.placeholder')}/>
|
||||
}/>
|
||||
|
||||
<div className="flex flex-col space-y-3 mt-6">
|
||||
<Button variant="primary" fullWidth size="lg" onClick={() => handleVerifyCode()}>
|
||||
{t('registerStepTwo.verify')}
|
||||
</Button>
|
||||
|
||||
<Button variant="secondary" fullWidth size="lg" onClick={() => prevStep()}>
|
||||
{t('registerStepTwo.back')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
<div className="p-4 bg-success/20 border border-success rounded-xl">
|
||||
<p className="text-center text-text-primary">{t('registerStepTwo.confirmed')}</p>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<Link href="/login" className="block w-full">
|
||||
<Button variant="primary" fullWidth size="lg">
|
||||
{t('registerStepTwo.start')}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,95 +1,202 @@
|
||||
'use client'
|
||||
import {useState} from 'react';
|
||||
import StepOne from "./StepOne";
|
||||
import StepTree from "@/app/login/register/StepTree";
|
||||
import SocialForm from "@/app/login/login/SocialForm";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
|
||||
import {faArrowLeft} from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
export default function Register() {
|
||||
const t = useTranslations();
|
||||
const [username, setUsername] = useState<string>('');
|
||||
const [email, setEmail] = useState<string>('');
|
||||
const [step, setStep] = useState<number>(1);
|
||||
|
||||
function handleNextStep(): void {
|
||||
setStep(step + 1);
|
||||
}
|
||||
|
||||
function handlePrevStep(): void {
|
||||
setStep(step - 1);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-background text-textPrimary p-4">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<div className="w-[90%] max-w-[320px]">
|
||||
<img
|
||||
src="/logo.png"
|
||||
alt="ERitors"
|
||||
className="w-full h-auto object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-tertiary rounded-2xl overflow-hidden shadow-xl shadow-primary/10 w-full relative">
|
||||
<div className="absolute top-0 left-0 right-0 h-2 bg-gradient-to-r from-primary to-info"></div>
|
||||
<div
|
||||
className="absolute -top-10 -left-10 w-40 h-40 bg-gradient-to-br from-primary/20 to-transparent rounded-full blur-xl"></div>
|
||||
<div
|
||||
className="absolute -bottom-10 -right-10 w-40 h-40 bg-gradient-to-br from-info/20 to-transparent rounded-full blur-xl"></div>
|
||||
|
||||
<div className="p-6 sm:p-8">
|
||||
<div className="text-center mb-6">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM Display']">{t('registerPage.title')}</h1>
|
||||
<p className="text-muted">{t('registerPage.subtitle')}</p>
|
||||
</div>
|
||||
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center">
|
||||
<div
|
||||
className={`flex-grow h-2 rounded-full ${step >= 1 ? 'bg-gradient-to-r from-primary to-info' : 'bg-secondary'}`}></div>
|
||||
<div className="w-4"></div>
|
||||
<div
|
||||
className={`flex-grow h-2 rounded-full ${step >= 2 ? 'bg-gradient-to-r from-primary to-info' : 'bg-secondary'}`}></div>
|
||||
</div>
|
||||
<div className="flex justify-between items-center mt-2 text-xs text-muted">
|
||||
<span>{t('registerPage.progress.infos')}</span>
|
||||
<span>{t('registerPage.progress.verif')}</span>
|
||||
</div>
|
||||
</div>
|
||||
{
|
||||
step === 1 && <SocialForm/>
|
||||
}
|
||||
{
|
||||
step === 1 && (
|
||||
<>
|
||||
<StepOne username={username}
|
||||
email={email}
|
||||
setUsername={setUsername}
|
||||
setEmail={setEmail}
|
||||
handleNextStep={handleNextStep}
|
||||
/>
|
||||
<a
|
||||
href="/login/login"
|
||||
className="w-full py-4 mt-3 bg-secondary text-textPrimary font-semibold rounded-xl hover:bg-gray-dark transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<FontAwesomeIcon icon={faArrowLeft} className="w-4 h-4" />
|
||||
{t('registerPage.backToLogin')}
|
||||
</a>
|
||||
</>
|
||||
)
|
||||
}
|
||||
{
|
||||
step === 2 && (
|
||||
<StepTree email={email} prevStep={handlePrevStep}/>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
'use client'
|
||||
import {useContext, useState} from 'react';
|
||||
import {Mail, Lock, User, KeyRound, ArrowLeft} from 'lucide-react';
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import {verifyInput} from "@/lib/utils/validation";
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
import {Link} from "@/lib/navigation";
|
||||
import Button from "@/components/ui/Button";
|
||||
import InputField from "@/components/form/InputField";
|
||||
import TextInput from "@/components/form/TextInput";
|
||||
|
||||
export default function Register() {
|
||||
const t = useTranslations();
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
const {lang} = useContext<LangContextProps>(LangContext);
|
||||
|
||||
const [step, setStep] = useState<number>(1);
|
||||
const [username, setUsername] = useState<string>('');
|
||||
const [email, setEmail] = useState<string>('');
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [repeatPassword, setRepeatPassword] = useState<string>('');
|
||||
const [verifyCode, setVerifyCode] = useState<string>('');
|
||||
const [isConfirmed, setIsConfirmed] = useState<boolean>(false);
|
||||
|
||||
async function handleStepOne(): Promise<void> {
|
||||
if (!username || !password || !repeatPassword || !email) {
|
||||
errorMessage(t('registerStepOne.error.requiredFields'));
|
||||
return;
|
||||
}
|
||||
if (username.length < 3 || username.length > 50) {
|
||||
errorMessage(t('registerStepOne.error.usernameLength'));
|
||||
return;
|
||||
}
|
||||
if (verifyInput(username) || verifyInput(password) || verifyInput(repeatPassword) || verifyInput(email)) {
|
||||
errorMessage(t('registerStepOne.error.invalidInput'));
|
||||
return;
|
||||
}
|
||||
if (password !== repeatPassword) {
|
||||
errorMessage(t('registerStepOne.error.passwordMismatch'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: string = await apiPostPublic<string>('register/pre', {
|
||||
username, email, password, retypePass: repeatPassword
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('registerStepOne.error.preRegister'));
|
||||
return;
|
||||
}
|
||||
successMessage(t('registerStepOne.success.preRegister'));
|
||||
setStep(2);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t('registerStepOne.error.unknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleVerifyCode(): Promise<void> {
|
||||
if (verifyCode === '') {
|
||||
errorMessage(t('registerStepTwo.error.codeIncorrect'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: boolean = await apiPostPublic<boolean>('register/verify-code', {
|
||||
verifyCode, email,
|
||||
}, lang);
|
||||
if (!response) {
|
||||
errorMessage(t('registerStepTwo.error.codeIncorrect'));
|
||||
return;
|
||||
}
|
||||
setIsConfirmed(true);
|
||||
successMessage(t('registerStepTwo.success.verified'));
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t('registerStepTwo.error.unknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-tertiary text-text-primary p-4 font-['Lora']">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<img src="/logo.png" alt="ERitors" className="object-contain" style={{width: 320, height: 107}}/>
|
||||
</div>
|
||||
|
||||
<div className="text-center mb-6">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM_Display'] tracking-wide">{t('registerPage.title')}</h1>
|
||||
<p className="text-muted text-sm">{t('registerPage.subtitle')}</p>
|
||||
</div>
|
||||
|
||||
{step === 1 && !isConfirmed && (
|
||||
<>
|
||||
<div className="overflow-hidden rounded-xl mb-4">
|
||||
<div className="flex items-center">
|
||||
<div className={`flex-grow h-2 ${step >= 1 ? 'bg-primary' : 'bg-secondary'}`}></div>
|
||||
<div className="w-1 bg-tertiary"></div>
|
||||
<div className={`flex-grow h-2 ${step >= 2 ? 'bg-primary' : 'bg-secondary'}`}></div>
|
||||
</div>
|
||||
<div className="bg-darkest-background p-5 space-y-4">
|
||||
<div>
|
||||
<InputField icon={User} fieldName={t('registerStepOne.fields.username.label')} input={
|
||||
<TextInput value={username} setValue={(e) => setUsername(e.target.value)}
|
||||
placeholder={t('registerStepOne.fields.username.placeholder')}/>
|
||||
}/>
|
||||
<p className="text-xs text-muted mt-1">{t('registerStepOne.fields.username.note')}</p>
|
||||
</div>
|
||||
<InputField icon={Mail} fieldName={t('registerStepOne.fields.email.label')} input={
|
||||
<TextInput value={email} setValue={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('registerStepOne.fields.email.placeholder')}/>
|
||||
}/>
|
||||
<div>
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('registerStepOne.fields.password.label')}
|
||||
</h3>
|
||||
<input type="password" placeholder={t('registerStepOne.fields.password.placeholder')}
|
||||
className="input-base" value={password}
|
||||
onChange={(e) => setPassword(e.target.value)} required/>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('registerStepOne.fields.repeatPassword.label')}
|
||||
</h3>
|
||||
<input type="password" placeholder={t('registerStepOne.fields.repeatPassword.placeholder')}
|
||||
className="input-base" value={repeatPassword}
|
||||
onChange={(e) => setRepeatPassword(e.target.value)} required/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button variant="primary" fullWidth size="lg" onClick={handleStepOne}>
|
||||
{t('registerStepOne.next')}
|
||||
</Button>
|
||||
<a href="/login/login" className="block w-full">
|
||||
<Button variant="secondary" fullWidth icon={ArrowLeft}>
|
||||
{t('registerPage.backToLogin')}
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 2 && !isConfirmed && (
|
||||
<>
|
||||
<div className="overflow-hidden rounded-xl mb-4">
|
||||
<div className="flex items-center">
|
||||
<div className="flex-grow h-2 bg-primary"></div>
|
||||
<div className="w-1 bg-tertiary"></div>
|
||||
<div className="flex-grow h-2 bg-primary"></div>
|
||||
</div>
|
||||
<div className="bg-darkest-background p-5 space-y-4">
|
||||
<div className="text-center">
|
||||
<p className="text-muted">{t('registerStepTwo.instructions.sent')}</p>
|
||||
<p className="text-muted text-sm mt-2">{t('registerStepTwo.instructions.checkInbox')}</p>
|
||||
</div>
|
||||
<InputField icon={KeyRound} fieldName={t('registerStepTwo.fields.code.label')} input={
|
||||
<TextInput value={verifyCode} setValue={(e) => setVerifyCode(e.target.value)}
|
||||
placeholder={t('registerStepTwo.fields.code.placeholder')}/>
|
||||
}/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button variant="primary" fullWidth size="lg" onClick={handleVerifyCode}>
|
||||
{t('registerStepTwo.verify')}
|
||||
</Button>
|
||||
<Button variant="secondary" fullWidth onClick={() => setStep(1)}>
|
||||
{t('registerStepTwo.back')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isConfirmed && (
|
||||
<>
|
||||
<div className="bg-darkest-background rounded-xl p-5 mb-4">
|
||||
<div className="p-4 bg-success/20 border border-success rounded-xl">
|
||||
<p className="text-center text-text-primary">{t('registerStepTwo.confirmed')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Link href="/login" className="block w-full">
|
||||
<Button variant="primary" fullWidth size="lg">
|
||||
{t('registerStepTwo.start')}
|
||||
</Button>
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,277 +1,190 @@
|
||||
'use client'
|
||||
import {useContext, useState} from "react";
|
||||
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
|
||||
import {faEnvelope, faKey, faLock, faArrowLeft} from '@fortawesome/free-solid-svg-icons';
|
||||
import System from "@/lib/models/System";
|
||||
import {QueryDataResponse} from "@/shared/interface";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
|
||||
export default function ForgetPasswordPage() {
|
||||
const [step, setStep] = useState(1);
|
||||
const [email, setEmail] = useState('');
|
||||
const [verificationCode, setVerificationCode] = useState('');
|
||||
const [isConfirmed, setIsConfirmed] = useState(false);
|
||||
const [newPassword, setNewPassword] = useState<string>('');
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
function handleNextStep(): void {
|
||||
setStep(step + 1);
|
||||
}
|
||||
|
||||
function handlePrevStep(): void {
|
||||
setStep(step - 1);
|
||||
}
|
||||
|
||||
async function handleConfirm() {
|
||||
try {
|
||||
const response: QueryDataResponse<null> = await System.postToServer<QueryDataResponse<null>>('user/verify-code', {
|
||||
verifyCode: verificationCode,
|
||||
email,
|
||||
}, lang);
|
||||
if (response.valid) {
|
||||
successMessage(response.message ?? '');
|
||||
setIsConfirmed(true);
|
||||
} else {
|
||||
errorMessage(response.message ?? '');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('resetPassword.error.codeServer'));
|
||||
} else {
|
||||
errorMessage(t('resetPassword.error.codeUnknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEmailCheck(): Promise<void> {
|
||||
if (email == null || email == "") {
|
||||
errorMessage(t('resetPassword.error.emailInvalid'));
|
||||
return;
|
||||
}
|
||||
|
||||
const emailRegEx = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
if (!emailRegEx.test(email)) {
|
||||
errorMessage(t('resetPassword.error.emailFormat'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response: QueryDataResponse<null> = await System.postToServer<QueryDataResponse<null>>('user/email-check', {
|
||||
email: email
|
||||
}, lang);
|
||||
if (response.valid) {
|
||||
successMessage(response.message ?? '');
|
||||
handleNextStep();
|
||||
} else {
|
||||
errorMessage(response.message ?? '');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('resetPassword.error.emailServer'));
|
||||
} else {
|
||||
errorMessage(t('resetPassword.error.emailUnknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNewPassword(): Promise<void> {
|
||||
try {
|
||||
const response: QueryDataResponse<null> = await System.postToServer('password/reset', {
|
||||
email: email,
|
||||
newPassword: newPassword,
|
||||
code: verificationCode
|
||||
}, lang);
|
||||
if (response.valid) {
|
||||
successMessage(response.message ?? '');
|
||||
handleNextStep();
|
||||
} else {
|
||||
errorMessage(response.message ?? '');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('resetPassword.error.passwordServer'));
|
||||
} else {
|
||||
errorMessage(t('resetPassword.error.passwordUnknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-background text-textPrimary p-4">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<div className="w-[90%] max-w-[320px]">
|
||||
<img
|
||||
src="/logo.png"
|
||||
alt="ERitors"
|
||||
className="w-full h-auto object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-tertiary rounded-2xl overflow-hidden shadow-xl shadow-primary/10 w-full relative">
|
||||
<div className="absolute top-0 left-0 right-0 h-2 bg-gradient-to-r from-primary to-info"></div>
|
||||
<div
|
||||
className="absolute -top-10 -left-10 w-40 h-40 bg-gradient-to-br from-primary/20 to-transparent rounded-full blur-xl"></div>
|
||||
<div
|
||||
className="absolute -bottom-10 -right-10 w-40 h-40 bg-gradient-to-br from-info/20 to-transparent rounded-full blur-xl"></div>
|
||||
|
||||
<div className="p-6 sm:p-8">
|
||||
<div className="text-center mb-6">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM Display']">{t('resetPassword.title')}</h1>
|
||||
<p className="text-muted">{t('resetPassword.subtitle')}</p>
|
||||
</div>
|
||||
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center">
|
||||
<div
|
||||
className={`flex-grow h-2 rounded-full ${step >= 1 ? 'bg-gradient-to-r from-primary to-info' : 'bg-secondary'}`}></div>
|
||||
<div className="w-4"></div>
|
||||
<div
|
||||
className={`flex-grow h-2 rounded-full ${step >= 2 ? 'bg-gradient-to-r from-primary to-info' : 'bg-secondary'}`}></div>
|
||||
<div className="w-4"></div>
|
||||
<div
|
||||
className={`flex-grow h-2 rounded-full ${step >= 3 ? 'bg-gradient-to-r from-primary to-info' : 'bg-secondary'}`}></div>
|
||||
</div>
|
||||
<div className="flex justify-between mt-2 text-xs text-muted">
|
||||
<span>{t('resetPassword.progress.email')}</span>
|
||||
<span>{t('resetPassword.progress.verification')}</span>
|
||||
<span>{t('resetPassword.progress.final')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{step === 1 && (
|
||||
<form className="space-y-4">
|
||||
<div className="mb-5">
|
||||
<label htmlFor="email" className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('resetPassword.fields.email.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faEnvelope}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
placeholder={t('resetPassword.fields.email.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEmailCheck}
|
||||
className="w-full py-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
|
||||
>
|
||||
{t('resetPassword.verify')}
|
||||
</button>
|
||||
|
||||
<a
|
||||
href="/login/login"
|
||||
className="w-full py-4 bg-secondary text-textPrimary font-semibold rounded-xl hover:bg-gray-dark transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<FontAwesomeIcon icon={faArrowLeft} className="w-4 h-4" />
|
||||
{t('resetPassword.backToLogin')}
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<form className="space-y-4">
|
||||
<div className="mb-5">
|
||||
<label htmlFor="verificationCode"
|
||||
className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('resetPassword.fields.code.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faKey}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="text"
|
||||
id="verificationCode"
|
||||
placeholder={t('resetPassword.fields.code.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={verificationCode}
|
||||
onChange={(e) => setVerificationCode(e.target.value)}
|
||||
disabled={isConfirmed}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isConfirmed && (
|
||||
<div className="mb-5">
|
||||
<label htmlFor="newPassword"
|
||||
className="block text-sm font-medium mb-1 text-muted">
|
||||
{t('resetPassword.fields.newPassword.label')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<FontAwesomeIcon icon={faLock}
|
||||
className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
|
||||
<input
|
||||
type="password"
|
||||
id="newPassword"
|
||||
placeholder={t('resetPassword.fields.newPassword.placeholder')}
|
||||
className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col space-y-3 mt-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={isConfirmed ? handleNewPassword : handleConfirm}
|
||||
className="w-full py-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
|
||||
>
|
||||
{isConfirmed ? t('resetPassword.changePassword') : t('resetPassword.confirm')}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePrevStep}
|
||||
className="w-full py-4 bg-secondary text-textPrimary font-semibold rounded-xl hover:bg-gray-dark transition-colors"
|
||||
>
|
||||
{t('resetPassword.back')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<div className="space-y-6">
|
||||
<div className="p-4 bg-success/20 border border-success rounded-xl">
|
||||
<p className="text-center text-text">
|
||||
{t('resetPassword.success')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<a href="/login/login" className="block w-full">
|
||||
<button
|
||||
type="button"
|
||||
className="w-full py-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
|
||||
>
|
||||
{t('resetPassword.goToLogin')}
|
||||
</button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
'use client'
|
||||
import {useContext, useState} from "react";
|
||||
import {Mail, KeyRound, Lock, ArrowLeft} from 'lucide-react';
|
||||
import {QueryDataResponse} from "@/shared/interface";
|
||||
import {AlertContext} from "@/context/AlertContext";
|
||||
import {useTranslations} from "@/lib/i18n";
|
||||
import {LangContext, LangContextProps} from "@/context/LangContext";
|
||||
import {apiPostPublic} from "@/lib/api/client";
|
||||
import Button from "@/components/ui/Button";
|
||||
import InputField from "@/components/form/InputField";
|
||||
import TextInput from "@/components/form/TextInput";
|
||||
|
||||
export default function ForgetPasswordPage() {
|
||||
const [step, setStep] = useState(1);
|
||||
const [email, setEmail] = useState('');
|
||||
const [verificationCode, setVerificationCode] = useState('');
|
||||
const [isConfirmed, setIsConfirmed] = useState(false);
|
||||
const [newPassword, setNewPassword] = useState<string>('');
|
||||
const {errorMessage, successMessage} = useContext(AlertContext);
|
||||
const t = useTranslations();
|
||||
const {lang} = useContext<LangContextProps>(LangContext)
|
||||
|
||||
async function handleEmailCheck(): Promise<void> {
|
||||
if (!email) {
|
||||
errorMessage(t('resetPassword.error.emailInvalid'));
|
||||
return;
|
||||
}
|
||||
const emailRegEx = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegEx.test(email)) {
|
||||
errorMessage(t('resetPassword.error.emailFormat'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response: QueryDataResponse<null> = await apiPostPublic<QueryDataResponse<null>>('user/email-check', {email}, lang);
|
||||
if (response.valid) {
|
||||
successMessage(response.message ?? '');
|
||||
setStep(2);
|
||||
} else {
|
||||
errorMessage(response.message ?? '');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('resetPassword.error.emailServer'));
|
||||
} else {
|
||||
errorMessage(t('resetPassword.error.emailUnknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirm(): Promise<void> {
|
||||
try {
|
||||
const response: QueryDataResponse<null> = await apiPostPublic<QueryDataResponse<null>>('user/verify-code', {
|
||||
verifyCode: verificationCode, email,
|
||||
}, lang);
|
||||
if (response.valid) {
|
||||
successMessage(response.message ?? '');
|
||||
setIsConfirmed(true);
|
||||
} else {
|
||||
errorMessage(response.message ?? '');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('resetPassword.error.codeServer'));
|
||||
} else {
|
||||
errorMessage(t('resetPassword.error.codeUnknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNewPassword(): Promise<void> {
|
||||
try {
|
||||
const response: QueryDataResponse<null> = await apiPostPublic<QueryDataResponse<null>>('password/reset', {
|
||||
email, newPassword, code: verificationCode
|
||||
}, lang);
|
||||
if (response.valid) {
|
||||
successMessage(response.message ?? '');
|
||||
setStep(3);
|
||||
} else {
|
||||
errorMessage(response.message ?? '');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(t('resetPassword.error.passwordServer'));
|
||||
} else {
|
||||
errorMessage(t('resetPassword.error.passwordUnknown'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-tertiary text-text-primary p-4 font-['Lora']">
|
||||
<div className="w-full max-w-md px-4 py-10">
|
||||
<div className="flex justify-center mb-8">
|
||||
<img src="/logo.png" alt="ERitors" className="object-contain" style={{width: 320, height: 107}}/>
|
||||
</div>
|
||||
|
||||
<div className="text-center mb-6">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM_Display'] tracking-wide">{t('resetPassword.title')}</h1>
|
||||
<p className="text-muted text-sm">{t('resetPassword.subtitle')}</p>
|
||||
</div>
|
||||
|
||||
{step < 3 && (
|
||||
<>
|
||||
<div className="overflow-hidden rounded-xl mb-4">
|
||||
<div className="flex items-center">
|
||||
<div className={`flex-grow h-2 ${step >= 1 ? 'bg-primary' : 'bg-secondary'}`}></div>
|
||||
<div className="w-1 bg-tertiary"></div>
|
||||
<div className={`flex-grow h-2 ${step >= 2 ? 'bg-primary' : 'bg-secondary'}`}></div>
|
||||
<div className="w-1 bg-tertiary"></div>
|
||||
<div className={`flex-grow h-2 ${step >= 3 ? 'bg-primary' : 'bg-secondary'}`}></div>
|
||||
</div>
|
||||
<div className="bg-darkest-background p-5 space-y-4">
|
||||
{step === 1 && (
|
||||
<InputField icon={Mail} fieldName={t('resetPassword.fields.email.label')} input={
|
||||
<TextInput value={email} setValue={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('resetPassword.fields.email.placeholder')}/>
|
||||
}/>
|
||||
)}
|
||||
{step === 2 && (
|
||||
<>
|
||||
<InputField icon={KeyRound} fieldName={t('resetPassword.fields.code.label')} input={
|
||||
<TextInput value={verificationCode}
|
||||
setValue={(e) => setVerificationCode(e.target.value)}
|
||||
placeholder={t('resetPassword.fields.code.placeholder')}
|
||||
disabled={isConfirmed}/>
|
||||
}/>
|
||||
{isConfirmed && (
|
||||
<div>
|
||||
<h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
|
||||
<Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
|
||||
{t('resetPassword.fields.newPassword.label')}
|
||||
</h3>
|
||||
<input type="password"
|
||||
placeholder={t('resetPassword.fields.newPassword.placeholder')}
|
||||
className="input-base" value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)} required/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{step === 1 && (
|
||||
<>
|
||||
<Button variant="primary" fullWidth size="lg" onClick={handleEmailCheck}>
|
||||
{t('resetPassword.verify')}
|
||||
</Button>
|
||||
<a href="/login/login" className="block w-full">
|
||||
<Button variant="secondary" fullWidth icon={ArrowLeft}>
|
||||
{t('resetPassword.backToLogin')}
|
||||
</Button>
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
{step === 2 && (
|
||||
<>
|
||||
<Button variant="primary" fullWidth size="lg"
|
||||
onClick={isConfirmed ? handleNewPassword : handleConfirm}>
|
||||
{isConfirmed ? t('resetPassword.changePassword') : t('resetPassword.confirm')}
|
||||
</Button>
|
||||
<Button variant="secondary" fullWidth onClick={() => setStep(1)}>
|
||||
{t('resetPassword.back')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<>
|
||||
<div className="bg-darkest-background rounded-xl p-5 mb-4">
|
||||
<div className="p-4 bg-success/20 border border-success rounded-xl">
|
||||
<p className="text-center text-text-primary">{t('resetPassword.success')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="/login/login" className="block w-full">
|
||||
<Button variant="primary" fullWidth size="lg">
|
||||
{t('resetPassword.goToLogin')}
|
||||
</Button>
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
797
app/page.tsx
797
app/page.tsx
@@ -1,797 +1,6 @@
|
||||
'use client';
|
||||
import {useCallback, useContext, useEffect, useRef, useState} from 'react';
|
||||
import {BookContext} from "@/context/BookContext";
|
||||
import {ChapterProps} from "@/lib/models/Chapter";
|
||||
import {ChapterContext} from '@/context/ChapterContext';
|
||||
import {EditorContext} from '@/context/EditorContext'
|
||||
import {Editor, useEditor} from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Underline from "@tiptap/extension-underline";
|
||||
import TextAlign from "@tiptap/extension-text-align";
|
||||
import {AlertContext, AlertProvider} from "@/context/AlertContext";
|
||||
import System from "@/lib/models/System";
|
||||
import {SessionContext} from '@/context/SessionContext';
|
||||
import {SessionProps} from "@/lib/models/Session";
|
||||
import User, {UserProps} from "@/lib/models/User";
|
||||
import {BookProps} from "@/lib/models/Book";
|
||||
import ScribeTopBar from "@/components/ScribeTopBar";
|
||||
import ScribeControllerBar from "@/components/ScribeControllerBar";
|
||||
import ScribeLeftBar from "@/components/leftbar/ScribeLeftBar";
|
||||
import ScribeEditor from "@/components/editor/ScribeEditor";
|
||||
import ComposerRightBar from "@/components/rightbar/ComposerRightBar";
|
||||
import ScribeFooterBar from "@/components/ScribeFooterBar";
|
||||
import GuideTour, {GuideStep} from "@/components/GuideTour";
|
||||
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
|
||||
import {faBookMedical, faFeather} from "@fortawesome/free-solid-svg-icons";
|
||||
import TermsOfUse from "@/components/TermsOfUse";
|
||||
import frMessages from '@/lib/locales/fr.json';
|
||||
import enMessages from '@/lib/locales/en.json';
|
||||
import {NextIntlClientProvider, useTranslations} from "next-intl";
|
||||
import {LangContext} from "@/context/LangContext";
|
||||
import {AIUsageContext} from "@/context/AIUsageContext";
|
||||
import OfflineProvider from "@/context/OfflineProvider";
|
||||
import OfflineContext, {OfflineMode} from "@/context/OfflineContext";
|
||||
import OfflinePinSetup from "@/components/offline/OfflinePinSetup";
|
||||
import OfflinePinVerify from "@/components/offline/OfflinePinVerify";
|
||||
import {SyncedBook, BookSyncCompare, compareBookSyncs} from "@/lib/models/SyncedBook";
|
||||
import {SyncedSeries, SeriesSyncCompare, compareSeriesSyncs} from "@/lib/models/SyncedSeries";
|
||||
import {BooksSyncContext} from "@/context/BooksSyncContext";
|
||||
import {SeriesSyncContext} from "@/context/SeriesSyncContext";
|
||||
import useSyncBooks from "@/hooks/useSyncBooks";
|
||||
import useSyncSeries from "@/hooks/useSyncSeries";
|
||||
import {LocalSyncQueueContext, LocalSyncOperation} from "@/context/SyncQueueContext";
|
||||
import * as tauri from '@/lib/tauri';
|
||||
import BookList from '@/components/book/BookList';
|
||||
|
||||
interface RemovedItemRecord {
|
||||
removal_id: string;
|
||||
table_name: string;
|
||||
entity_id: string;
|
||||
book_id: string | null;
|
||||
user_id: string;
|
||||
deleted_at: number;
|
||||
}
|
||||
|
||||
interface SyncedBooksResponse {
|
||||
books: SyncedBook[];
|
||||
tombstones: RemovedItemRecord[];
|
||||
}
|
||||
|
||||
interface SyncedSeriesResponse {
|
||||
series: SyncedSeries[];
|
||||
tombstones: RemovedItemRecord[];
|
||||
}
|
||||
|
||||
const messagesMap = {
|
||||
fr: frMessages,
|
||||
en: enMessages
|
||||
};
|
||||
|
||||
function AutoSyncOnReconnect() {
|
||||
const {offlineMode} = useContext(OfflineContext);
|
||||
const {session} = useContext(SessionContext);
|
||||
const {syncAllToServer: syncAllBooksToServer, syncAllFromServer: syncAllBooksFromServer, refreshBooks, booksToSyncToServer, booksToSyncFromServer} = useSyncBooks();
|
||||
const {syncAllToServer: syncAllSeriesToServer, syncAllFromServer: syncAllSeriesFromServer, refreshSeries, seriesToSyncToServer, seriesToSyncFromServer} = useSyncSeries();
|
||||
const isSyncingRef = useRef<boolean>(false);
|
||||
const hasRefreshedRef = useRef<boolean>(false);
|
||||
|
||||
const saveLastOnlineTimestamp = useCallback((): void => {
|
||||
const timestamp: number = Math.floor(Date.now() / 1000);
|
||||
localStorage.setItem('lastOnlineTimestamp', timestamp.toString());
|
||||
}, []);
|
||||
|
||||
// Refresh sync data when online + authenticated + DB ready
|
||||
useEffect((): void => {
|
||||
if (!offlineMode.isOffline && session.isConnected && offlineMode.isDatabaseInitialized) {
|
||||
hasRefreshedRef.current = true;
|
||||
Promise.all([refreshBooks(), refreshSeries()]);
|
||||
}
|
||||
}, [offlineMode.isOffline, session.isConnected, offlineMode.isDatabaseInitialized]);
|
||||
|
||||
// Auto-sync when diffs become available (reactive, no flags)
|
||||
useEffect((): void => {
|
||||
if (offlineMode.isOffline || !session.isConnected || isSyncingRef.current || !hasRefreshedRef.current) return;
|
||||
|
||||
const syncPromises: Promise<void>[] = [];
|
||||
|
||||
if (booksToSyncToServer.length > 0) syncPromises.push(syncAllBooksToServer());
|
||||
if (booksToSyncFromServer.length > 0) syncPromises.push(syncAllBooksFromServer());
|
||||
if (seriesToSyncToServer.length > 0) syncPromises.push(syncAllSeriesToServer());
|
||||
if (seriesToSyncFromServer.length > 0) syncPromises.push(syncAllSeriesFromServer());
|
||||
|
||||
if (syncPromises.length > 0) {
|
||||
isSyncingRef.current = true;
|
||||
Promise.all(syncPromises).then((): void => {
|
||||
saveLastOnlineTimestamp();
|
||||
isSyncingRef.current = false;
|
||||
}).catch((): void => {
|
||||
isSyncingRef.current = false;
|
||||
});
|
||||
}
|
||||
}, [booksToSyncToServer, booksToSyncFromServer, seriesToSyncToServer, seriesToSyncFromServer]);
|
||||
|
||||
// Update lastOnlineTimestamp every 5 minutes while online
|
||||
useEffect((): (() => void) | void => {
|
||||
if (!offlineMode.isOffline && session.isConnected) {
|
||||
const intervalId: NodeJS.Timeout = setInterval((): void => {
|
||||
saveLastOnlineTimestamp();
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
return (): void => clearInterval(intervalId);
|
||||
}
|
||||
}, [offlineMode.isOffline, session.isConnected, saveLastOnlineTimestamp]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ScribeContent() {
|
||||
const t = useTranslations();
|
||||
const {lang: locale} = useContext(LangContext);
|
||||
const {errorMessage} = useContext(AlertContext);
|
||||
const {initializeDatabase, setOfflineMode, isCurrentlyOffline, offlineMode} = useContext(OfflineContext);
|
||||
const editor: Editor | null = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Underline,
|
||||
TextAlign.configure({
|
||||
types: ['heading', 'paragraph'],
|
||||
}),
|
||||
],
|
||||
injectCSS: false,
|
||||
immediatelyRender: false,
|
||||
shouldRerenderOnTransaction: true,
|
||||
});
|
||||
|
||||
const [session, setSession] = useState<SessionProps>({user: null, accessToken: '', isConnected: false});
|
||||
const [currentChapter, setCurrentChapter] = useState<ChapterProps | undefined>(undefined);
|
||||
const [currentBook, setCurrentBook] = useState<BookProps | null>(null);
|
||||
|
||||
const [serverSyncedBooks, setServerSyncedBooks] = useState<SyncedBook[]>([]);
|
||||
const [localSyncedBooks, setLocalSyncedBooks] = useState<SyncedBook[]>([]);
|
||||
const [bookSyncDiffsFromServer, setBookSyncDiffsFromServer] = useState<BookSyncCompare[]>([]);
|
||||
const [bookSyncDiffsToServer, setBookSyncDiffsToServer] = useState<BookSyncCompare[]>([]);
|
||||
const [serverOnlyBooks, setServerOnlyBooks] = useState<SyncedBook[]>([]);
|
||||
const [localOnlyBooks, setLocalOnlyBooks] = useState<SyncedBook[]>([]);
|
||||
|
||||
const [serverSyncedSeries, setServerSyncedSeries] = useState<SyncedSeries[]>([]);
|
||||
const [localSyncedSeries, setLocalSyncedSeries] = useState<SyncedSeries[]>([]);
|
||||
const [seriesSyncDiffsFromServer, setSeriesSyncDiffsFromServer] = useState<SeriesSyncCompare[]>([]);
|
||||
const [seriesSyncDiffsToServer, setSeriesSyncDiffsToServer] = useState<SeriesSyncCompare[]>([]);
|
||||
const [serverOnlySeries, setServerOnlySeries] = useState<SyncedSeries[]>([]);
|
||||
const [localOnlySeries, setLocalOnlySeries] = useState<SyncedSeries[]>([]);
|
||||
|
||||
const [currentCredits, setCurrentCredits] = useState<number>(160);
|
||||
const [amountSpent, setAmountSpent] = useState<number>(session.user?.aiUsage || 0);
|
||||
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
|
||||
const [isTermsAccepted, setIsTermsAccepted] = useState<boolean>(false);
|
||||
const [homeStepsGuide, setHomeStepsGuide] = useState<boolean>(false);
|
||||
const [showPinSetup, setShowPinSetup] = useState<boolean>(false);
|
||||
const [showPinVerify, setShowPinVerify] = useState<boolean>(false);
|
||||
|
||||
const [localSyncQueue, setLocalSyncQueue] = useState<LocalSyncOperation[]>([]);
|
||||
const [isQueueProcessing, setIsQueueProcessing] = useState<boolean>(false);
|
||||
|
||||
|
||||
function addToLocalSyncQueue(channel: string, data: Record<string, unknown>): void {
|
||||
const operation: LocalSyncOperation = {
|
||||
id: `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
|
||||
channel,
|
||||
data,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
setLocalSyncQueue((prev: LocalSyncOperation[]): LocalSyncOperation[] => [...prev, operation]);
|
||||
}
|
||||
|
||||
useEffect((): void => {
|
||||
if (localSyncQueue.length === 0 || isQueueProcessing) {
|
||||
return;
|
||||
}
|
||||
|
||||
async function processQueue(): Promise<void> {
|
||||
setIsQueueProcessing(true);
|
||||
|
||||
const queueCopy: LocalSyncOperation[] = [...localSyncQueue];
|
||||
|
||||
for (const operation of queueCopy) {
|
||||
try {
|
||||
await tauri.invoke(operation.channel, operation.data);
|
||||
setLocalSyncQueue((prev: LocalSyncOperation[]): LocalSyncOperation[] =>
|
||||
prev.filter((op: LocalSyncOperation): boolean => op.id !== operation.id)
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`[LocalSyncQueue] Failed to process operation ${operation.channel}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
setIsQueueProcessing(false);
|
||||
}
|
||||
|
||||
processQueue().then();
|
||||
}, [localSyncQueue, isQueueProcessing]);
|
||||
|
||||
const homeSteps: GuideStep[] = [
|
||||
{
|
||||
id: 0,
|
||||
x: 50,
|
||||
y: 50,
|
||||
title: t("homePage.guide.welcome", {name: session.user?.name || ''}),
|
||||
content: (
|
||||
<div>
|
||||
<p>{t("homePage.guide.step0.description1")}</p>
|
||||
<br/>
|
||||
<p>{t("homePage.guide.step0.description2")}</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 1, position: 'right',
|
||||
targetSelector: `[data-guide="left-panel-container"]`,
|
||||
title: t("homePage.guide.step1.title"),
|
||||
content: (
|
||||
<div>
|
||||
<p className={'flex items-center space-x-2'}>
|
||||
<strong>
|
||||
<FontAwesomeIcon icon={faBookMedical} className={'w-5 h-5'}/> :
|
||||
</strong>
|
||||
{t("homePage.guide.step1.addBook")}
|
||||
</p>
|
||||
<br/>
|
||||
<p><strong><FontAwesomeIcon icon={faFeather}
|
||||
className={'w-5 h-5'}/> :</strong> {t("homePage.guide.step1.generateStory")}
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: t("homePage.guide.step2.title"), position: 'bottom',
|
||||
targetSelector: `[data-guide="search-bar"]`,
|
||||
content: (
|
||||
<div>
|
||||
<p>{t("homePage.guide.step2.description")}</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: t("homePage.guide.step3.title"),
|
||||
targetSelector: `[data-guide="user-dropdown"]`,
|
||||
position: 'auto',
|
||||
content: (
|
||||
<div>
|
||||
<p>{t("homePage.guide.step3.description")}</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: t("homePage.guide.step4.title"),
|
||||
content: (
|
||||
<div>
|
||||
<p>{t("homePage.guide.step4.description1")}</p>
|
||||
<br/>
|
||||
<p>{t("homePage.guide.step4.description2")}</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
useEffect((): void => {
|
||||
checkAuthentification().then();
|
||||
|
||||
let unlisten: (() => void) | undefined;
|
||||
import('@tauri-apps/api/event').then(function ({listen}) {
|
||||
listen('auth-success', function () {
|
||||
checkAuthentification().then();
|
||||
}).then(function (fn) {
|
||||
unlisten = fn;
|
||||
});
|
||||
});
|
||||
|
||||
return (): void => {
|
||||
if (unlisten) unlisten();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect((): void => {
|
||||
if (session.isConnected) {
|
||||
setIsTermsAccepted(session.user?.termsAccepted ?? false);
|
||||
setHomeStepsGuide(User.guideTourDone(session.user?.guideTour ?? [], 'home-basic'));
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
useEffect((): void => {
|
||||
if (session.isConnected) {
|
||||
if (currentBook) {
|
||||
getLastChapter().then();
|
||||
} else {
|
||||
refreshBooks().then();
|
||||
}
|
||||
}
|
||||
}, [currentBook]);
|
||||
|
||||
useEffect((): void => {
|
||||
const diffsFromServer: BookSyncCompare[] = [];
|
||||
const diffsToServer: BookSyncCompare[] = [];
|
||||
|
||||
serverSyncedBooks.forEach((serverBook: SyncedBook): void => {
|
||||
const localBook: SyncedBook | undefined = localSyncedBooks.find((book: SyncedBook): boolean => book.id === serverBook.id);
|
||||
if (!localBook) {
|
||||
return;
|
||||
}
|
||||
|
||||
const diff: BookSyncCompare | null = compareBookSyncs(serverBook, localBook);
|
||||
if (diff) {
|
||||
diffsFromServer.push(diff);
|
||||
}
|
||||
});
|
||||
|
||||
localSyncedBooks.forEach((localBook: SyncedBook): void => {
|
||||
const serverBook: SyncedBook | undefined = serverSyncedBooks.find((book: SyncedBook): boolean => book.id === localBook.id);
|
||||
if (!serverBook) {
|
||||
return;
|
||||
}
|
||||
|
||||
const diff: BookSyncCompare | null = compareBookSyncs(localBook, serverBook);
|
||||
if (diff) {
|
||||
diffsToServer.push(diff);
|
||||
}
|
||||
});
|
||||
|
||||
setBookSyncDiffsFromServer(diffsFromServer);
|
||||
setBookSyncDiffsToServer(diffsToServer);
|
||||
setServerOnlyBooks(serverSyncedBooks.filter((serverBook: SyncedBook):boolean => !localSyncedBooks.find((localBook: SyncedBook):boolean => localBook.id === serverBook.id)))
|
||||
setLocalOnlyBooks(localSyncedBooks.filter((localBook: SyncedBook):boolean => !serverSyncedBooks.find((serverBook: SyncedBook):boolean => serverBook.id === localBook.id)))
|
||||
}, [localSyncedBooks, serverSyncedBooks]);
|
||||
|
||||
useEffect((): void => {
|
||||
const diffsFromServer: SeriesSyncCompare[] = [];
|
||||
const diffsToServer: SeriesSyncCompare[] = [];
|
||||
|
||||
serverSyncedSeries.forEach((serverSeries: SyncedSeries): void => {
|
||||
const localSeries: SyncedSeries | undefined = localSyncedSeries.find((series: SyncedSeries): boolean => series.id === serverSeries.id);
|
||||
if (!localSeries) {
|
||||
return;
|
||||
}
|
||||
|
||||
const diff: SeriesSyncCompare | null = compareSeriesSyncs(serverSeries, localSeries);
|
||||
if (diff) {
|
||||
diffsFromServer.push(diff);
|
||||
}
|
||||
});
|
||||
|
||||
localSyncedSeries.forEach((localSeries: SyncedSeries): void => {
|
||||
const serverSeries: SyncedSeries | undefined = serverSyncedSeries.find((series: SyncedSeries): boolean => series.id === localSeries.id);
|
||||
if (!serverSeries) {
|
||||
return;
|
||||
}
|
||||
|
||||
const diff: SeriesSyncCompare | null = compareSeriesSyncs(localSeries, serverSeries);
|
||||
if (diff) {
|
||||
diffsToServer.push(diff);
|
||||
}
|
||||
});
|
||||
|
||||
setSeriesSyncDiffsFromServer(diffsFromServer);
|
||||
setSeriesSyncDiffsToServer(diffsToServer);
|
||||
setServerOnlySeries(serverSyncedSeries.filter((serverSeries: SyncedSeries): boolean => !localSyncedSeries.find((localSeries: SyncedSeries): boolean => localSeries.id === serverSeries.id)));
|
||||
setLocalOnlySeries(localSyncedSeries.filter((localSeries: SyncedSeries): boolean => !serverSyncedSeries.find((serverSeries: SyncedSeries): boolean => serverSeries.id === localSeries.id)));
|
||||
}, [localSyncedSeries, serverSyncedSeries]);
|
||||
|
||||
async function refreshBooks(): Promise<void> {
|
||||
try {
|
||||
let localBooksResponse: SyncedBook[] = [];
|
||||
let serverBooksResponse: SyncedBook[] = [];
|
||||
|
||||
if (!isCurrentlyOffline()) {
|
||||
if (offlineMode.isDatabaseInitialized) {
|
||||
localBooksResponse = await tauri.getSyncedBooks() as SyncedBook[];
|
||||
const lastOnlineStr: string | null = localStorage.getItem('lastOnlineTimestamp');
|
||||
const lastOnlineTimestamp: number = lastOnlineStr ? parseInt(lastOnlineStr, 10) : 0;
|
||||
const localTombstones: RemovedItemRecord[] = await tauri.getTombstonesSince(lastOnlineTimestamp) as RemovedItemRecord[];
|
||||
const serverResponse: SyncedBooksResponse = await System.authPostToServer<SyncedBooksResponse>('books/synced', { lastOnlineTimestamp, tombstones: localTombstones }, session.accessToken, locale);
|
||||
serverBooksResponse = serverResponse.books;
|
||||
await tauri.applyBookTombstones(serverResponse.tombstones);
|
||||
} else {
|
||||
const serverResponse: SyncedBooksResponse = await System.authPostToServer<SyncedBooksResponse>('books/synced', { lastOnlineTimestamp: 0, tombstones: [] }, session.accessToken, locale);
|
||||
serverBooksResponse = serverResponse.books;
|
||||
}
|
||||
} else {
|
||||
if (offlineMode.isDatabaseInitialized) {
|
||||
localBooksResponse = await tauri.getSyncedBooks() as SyncedBook[];
|
||||
}
|
||||
}
|
||||
|
||||
setServerSyncedBooks(serverBooksResponse);
|
||||
setLocalSyncedBooks(localBooksResponse);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.fetchBooksError"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshSeries(): Promise<void> {
|
||||
try {
|
||||
let localSeriesResponse: SyncedSeries[] = [];
|
||||
let serverSeriesResponse: SyncedSeries[] = [];
|
||||
|
||||
if (!isCurrentlyOffline()) {
|
||||
if (offlineMode.isDatabaseInitialized) {
|
||||
localSeriesResponse = await tauri.getSyncedSeries() as SyncedSeries[];
|
||||
const lastOnlineStr: string | null = localStorage.getItem('lastOnlineTimestamp');
|
||||
const lastOnlineTimestamp: number = lastOnlineStr ? parseInt(lastOnlineStr, 10) : 0;
|
||||
const localTombstones: RemovedItemRecord[] = await tauri.getTombstonesSince(lastOnlineTimestamp) as RemovedItemRecord[];
|
||||
const serverResponse: SyncedSeriesResponse = await System.authPostToServer<SyncedSeriesResponse>('series/synced', { lastOnlineTimestamp, tombstones: localTombstones }, session.accessToken, locale);
|
||||
serverSeriesResponse = serverResponse.series;
|
||||
await tauri.applySeriesTombstones(serverResponse.tombstones);
|
||||
} else {
|
||||
const serverResponse: SyncedSeriesResponse = await System.authPostToServer<SyncedSeriesResponse>('series/synced', { lastOnlineTimestamp: 0, tombstones: [] }, session.accessToken, locale);
|
||||
serverSeriesResponse = serverResponse.series;
|
||||
}
|
||||
} else {
|
||||
if (offlineMode.isDatabaseInitialized) {
|
||||
localSeriesResponse = await tauri.getSyncedSeries() as SyncedSeries[];
|
||||
}
|
||||
}
|
||||
|
||||
setServerSyncedSeries(serverSeriesResponse);
|
||||
setLocalSyncedSeries(localSeriesResponse);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.fetchSeriesError"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function handlePinVerifySuccess(userId: string): Promise<void> {
|
||||
try {
|
||||
const storedToken: string | null = await tauri.getToken();
|
||||
const encryptionKey: string | null = await tauri.getUserEncryptionKey(userId);
|
||||
|
||||
if (encryptionKey) {
|
||||
await tauri.dbInitialize(userId, encryptionKey);
|
||||
setOfflineMode(prev => ({...prev, isDatabaseInitialized: true}));
|
||||
|
||||
const localUser: UserProps = await tauri.getUserInfo();
|
||||
if (localUser && localUser.id) {
|
||||
setSession({
|
||||
isConnected: true,
|
||||
user: localUser,
|
||||
accessToken: storedToken || '',
|
||||
});
|
||||
setShowPinVerify(false);
|
||||
setCurrentCredits(localUser.creditsBalance || 0);
|
||||
setAmountSpent(localUser.aiUsage || 0);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.localDataError"));
|
||||
}
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.encryptionKeyError"));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[OfflinePin] Error initializing offline mode:', error);
|
||||
errorMessage(t("homePage.errors.offlineModeError"));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleHomeTour(): Promise<void> {
|
||||
try {
|
||||
if (!isCurrentlyOffline()) {
|
||||
const response: boolean = await System.authPostToServer<boolean>('logs/tour', {
|
||||
plateforme: 'desktop',
|
||||
tour: 'home-basic'
|
||||
},
|
||||
session.accessToken,
|
||||
locale
|
||||
);
|
||||
if (response) {
|
||||
setSession(User.setNewGuideTour(session, 'home-basic'));
|
||||
setHomeStepsGuide(false);
|
||||
}
|
||||
} else {
|
||||
const completedGuides = JSON.parse(localStorage.getItem('completedGuides') || '[]');
|
||||
if (!completedGuides.includes('home-basic')) {
|
||||
completedGuides.push('home-basic');
|
||||
localStorage.setItem('completedGuides', JSON.stringify(completedGuides));
|
||||
}
|
||||
setSession(User.setNewGuideTour(session, 'home-basic'));
|
||||
setHomeStepsGuide(false);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.termsError"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function checkAuthentification(): Promise<void> {
|
||||
let token: string | null = null;
|
||||
|
||||
try {
|
||||
token = await tauri.getToken();
|
||||
} catch (e) {
|
||||
console.error('Error getting token:', e);
|
||||
}
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const user: UserProps = await System.authGetQueryToServer<UserProps>('user/infos', token, locale);
|
||||
if (!user) {
|
||||
errorMessage(t("homePage.errors.userNotFound"));
|
||||
await tauri.removeToken();
|
||||
tauri.logout();
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.id) {
|
||||
try {
|
||||
const initResult = await tauri.initUser(user.id);
|
||||
if (!initResult.success) {
|
||||
errorMessage(initResult.error || t("homePage.errors.offlineInitError"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const offlineStatus = await tauri.offlineModeGet();
|
||||
if (!offlineStatus.hasPin) {
|
||||
setTimeout(():void => {
|
||||
setShowPinSetup(true);
|
||||
}, 2000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Page] Error checking offline mode:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Page] Error initializing user:', error);
|
||||
}
|
||||
}
|
||||
if (user.id) {
|
||||
try {
|
||||
const dbInitialized: boolean = await initializeDatabase(user.id);
|
||||
if (dbInitialized) {
|
||||
try {
|
||||
await tauri.syncUser({
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
email: user.email
|
||||
});
|
||||
} catch (syncError) {
|
||||
console.error('[Page] syncUser failed:', syncError);
|
||||
errorMessage(t("homePage.errors.syncError"));
|
||||
}
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.dbInitError"));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Page] DB init or sync failed:', error);
|
||||
errorMessage(t("homePage.errors.syncError"));
|
||||
}
|
||||
}
|
||||
setSession({
|
||||
isConnected: true,
|
||||
user: user,
|
||||
accessToken: token,
|
||||
});
|
||||
setCurrentCredits(user.creditsBalance)
|
||||
setAmountSpent(user.aiUsage)
|
||||
} catch (e: unknown) {
|
||||
try {
|
||||
const offlineStatus = await tauri.offlineModeGet();
|
||||
|
||||
if (offlineStatus.hasPin && offlineStatus.lastUserId) {
|
||||
setOfflineMode((prev:OfflineMode):OfflineMode => ({...prev, isOffline: true, isManuallyOffline: true, isNetworkOnline: false}));
|
||||
setShowPinVerify(true);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
} else {
|
||||
await tauri.removeToken();
|
||||
tauri.logout();
|
||||
}
|
||||
} catch (offlineError) {
|
||||
errorMessage(t("homePage.errors.offlineError"));
|
||||
}
|
||||
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.authenticationError"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const offlineStatus = await tauri.offlineModeGet();
|
||||
|
||||
if (offlineStatus.hasPin && offlineStatus.lastUserId) {
|
||||
setOfflineMode(prev => ({...prev, isOffline: true, isManuallyOffline: true, isNetworkOnline: false}));
|
||||
setShowPinVerify(true);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage(t("homePage.errors.authenticationError"));
|
||||
}
|
||||
tauri.logout();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTermsAcceptance(): Promise<void> {
|
||||
try {
|
||||
const response: boolean = await System.authPostToServer<boolean>(`user/terms/accept`, {
|
||||
version: '2025-07-1'
|
||||
}, session.accessToken, locale);
|
||||
if (response) {
|
||||
setIsTermsAccepted(true);
|
||||
setHomeStepsGuide(true);
|
||||
const newSession: SessionProps = {
|
||||
...session,
|
||||
user: {
|
||||
...session?.user as UserProps,
|
||||
termsAccepted: true
|
||||
}
|
||||
}
|
||||
setSession(newSession);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.termsAcceptError"));
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.termsAcceptError"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function getLastChapter(): Promise<void> {
|
||||
if (session?.accessToken) {
|
||||
try {
|
||||
let response: ChapterProps | null
|
||||
if (isCurrentlyOffline()){
|
||||
if (!offlineMode.isDatabaseInitialized) {
|
||||
setCurrentChapter(undefined);
|
||||
return;
|
||||
}
|
||||
response = await tauri.getLastChapter(currentBook?.bookId ?? '')
|
||||
} else {
|
||||
if (currentBook?.localBook) {
|
||||
if (!offlineMode.isDatabaseInitialized) {
|
||||
setCurrentChapter(undefined);
|
||||
return;
|
||||
}
|
||||
response = await tauri.getLastChapter(currentBook?.bookId ?? '')
|
||||
} else {
|
||||
response = await System.authGetQueryToServer<ChapterProps | null>(`chapter/last-chapter`, session.accessToken, locale, {bookid: currentBook?.bookId});
|
||||
}
|
||||
}
|
||||
if (response) {
|
||||
setCurrentChapter(response)
|
||||
} else {
|
||||
setCurrentChapter(undefined);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("homePage.errors.lastChapterError"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div
|
||||
className="bg-background text-text-primary h-screen flex flex-col items-center justify-center font-['Lora']">
|
||||
<div className="flex flex-col items-center space-y-6">
|
||||
<div className="animate-pulse">
|
||||
<img src="/eritors-favicon-white.png" alt="ERitors Logo" style={{width: 400, height: 400}} />
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<div className="w-2 h-2 bg-primary rounded-full animate-bounce"></div>
|
||||
<div className="w-2 h-2 bg-primary rounded-full animate-bounce delay-100"></div>
|
||||
<div className="w-2 h-2 bg-primary rounded-full animate-bounce delay-200"></div>
|
||||
</div>
|
||||
<p className="text-text-secondary text-sm">
|
||||
{t("homePage.loading")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={{session: session, setSession: setSession}}>
|
||||
<LocalSyncQueueContext.Provider value={{
|
||||
queue: localSyncQueue,
|
||||
setQueue: setLocalSyncQueue,
|
||||
addToQueue: addToLocalSyncQueue,
|
||||
isProcessing: isQueueProcessing,
|
||||
}}>
|
||||
<BooksSyncContext.Provider value={{serverSyncedBooks, localSyncedBooks, booksToSyncFromServer:bookSyncDiffsFromServer, booksToSyncToServer:bookSyncDiffsToServer, setServerSyncedBooks, setLocalSyncedBooks, setServerOnlyBooks, setLocalOnlyBooks, setBooksToSyncFromServer:setBookSyncDiffsFromServer, setBooksToSyncToServer:setBookSyncDiffsToServer, serverOnlyBooks, localOnlyBooks}}>
|
||||
<SeriesSyncContext.Provider value={{serverSyncedSeries, localSyncedSeries, seriesToSyncFromServer:seriesSyncDiffsFromServer, seriesToSyncToServer:seriesSyncDiffsToServer, setServerSyncedSeries, setLocalSyncedSeries, setServerOnlySeries, setLocalOnlySeries, setSeriesToSyncFromServer:setSeriesSyncDiffsFromServer, setSeriesToSyncToServer:setSeriesSyncDiffsToServer, serverOnlySeries, localOnlySeries}}>
|
||||
<AutoSyncOnReconnect/>
|
||||
<BookContext.Provider value={{book: currentBook, setBook: setCurrentBook}}>
|
||||
<ChapterContext.Provider value={{chapter: currentChapter, setChapter: setCurrentChapter}}>
|
||||
<AIUsageContext.Provider value={{totalCredits: currentCredits, setTotalCredits: setCurrentCredits, totalPrice: amountSpent, setTotalPrice: setAmountSpent}}>
|
||||
<div className="bg-background text-text-primary h-screen flex flex-col font-['Lora']">
|
||||
<ScribeTopBar/>
|
||||
<EditorContext.Provider value={{editor: editor}}>
|
||||
<ScribeControllerBar/>
|
||||
<div className="flex-1 flex overflow-hidden">
|
||||
<ScribeLeftBar/>
|
||||
<ScribeEditor/>
|
||||
<ComposerRightBar/>
|
||||
</div>
|
||||
<ScribeFooterBar/>
|
||||
</EditorContext.Provider>
|
||||
</div>
|
||||
{
|
||||
homeStepsGuide && !isCurrentlyOffline() &&
|
||||
<GuideTour stepId={0} steps={homeSteps} onComplete={handleHomeTour}
|
||||
onClose={(): void => setHomeStepsGuide(false)}/>
|
||||
}
|
||||
{
|
||||
!isTermsAccepted && !isCurrentlyOffline() && <TermsOfUse onAccept={handleTermsAcceptance}/>
|
||||
}
|
||||
{
|
||||
showPinSetup && (
|
||||
<OfflinePinSetup
|
||||
showOnFirstLogin={true}
|
||||
onClose={():void => setShowPinSetup(false)}
|
||||
onSuccess={():void => {
|
||||
setShowPinSetup(false);
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
{
|
||||
showPinVerify && (
|
||||
<OfflinePinVerify
|
||||
onSuccess={handlePinVerifySuccess}
|
||||
onCancel={():void => {}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</AIUsageContext.Provider>
|
||||
</ChapterContext.Provider>
|
||||
</BookContext.Provider>
|
||||
</SeriesSyncContext.Provider>
|
||||
</BooksSyncContext.Provider>
|
||||
</LocalSyncQueueContext.Provider>
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Scribe() {
|
||||
const [locale, setLocale] = useState<'fr' | 'en'>('fr');
|
||||
|
||||
useEffect((): void => {
|
||||
const lang: "fr" | "en" | null = System.getCookie('lang') as "fr" | "en" | null;
|
||||
if (lang) {
|
||||
setLocale(lang);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const messages = messagesMap[locale];
|
||||
|
||||
return (
|
||||
<LangContext.Provider value={{lang: locale, setLang: setLocale}}>
|
||||
<NextIntlClientProvider locale={locale} messages={messages} timeZone="America/Montreal">
|
||||
<OfflineProvider>
|
||||
<AlertProvider>
|
||||
<ScribeContent/>
|
||||
</AlertProvider>
|
||||
</OfflineProvider>
|
||||
</NextIntlClientProvider>
|
||||
</LangContext.Provider>
|
||||
);
|
||||
export default function HomePage() {
|
||||
return <BookList/>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user