Feat: Login localization, design, märchenzauber feature complete webapp

This commit is contained in:
Till-JS 2025-11-25 02:19:40 +01:00
parent 9c584a2580
commit 84f9343d25
47 changed files with 3254 additions and 175 deletions

View file

@ -0,0 +1,10 @@
# Database connection URL
# Format: postgresql://user:password@host:port/database
DATABASE_URL=postgresql://postgres:password@localhost:5432/manadeck
# Alternative name (used as fallback)
MANADECK_DATABASE_URL=postgresql://postgres:password@localhost:5432/manadeck
# Supabase credentials (only needed for migration)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your-service-role-key

23
packages/manadeck-database/.gitignore vendored Normal file
View file

@ -0,0 +1,23 @@
# Environment variables
.env
.env.local
.env.*.local
# Dependencies
node_modules/
# Build output
dist/
# Drizzle migrations (optional - can be tracked)
# drizzle/
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db

View file

@ -0,0 +1,39 @@
services:
postgres:
image: postgres:16-alpine
container_name: manadeck-postgres
restart: unless-stopped
environment:
POSTGRES_USER: manadeck
POSTGRES_PASSWORD: manadeck_dev_password
POSTGRES_DB: manadeck
ports:
- "5433:5432"
volumes:
- manadeck_postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U manadeck -d manadeck"]
interval: 10s
timeout: 5s
retries: 5
# Optional: pgAdmin for database management UI
pgadmin:
image: dpage/pgadmin4:latest
container_name: manadeck-pgadmin
restart: unless-stopped
environment:
PGADMIN_DEFAULT_EMAIL: admin@manadeck.local
PGADMIN_DEFAULT_PASSWORD: admin
PGADMIN_CONFIG_SERVER_MODE: 'False'
ports:
- "5050:80"
volumes:
- manadeck_pgadmin_data:/var/lib/pgadmin
depends_on:
postgres:
condition: service_healthy
volumes:
manadeck_postgres_data:
manadeck_pgadmin_data:

View file

@ -0,0 +1,12 @@
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/schema/index.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
verbose: true,
strict: true,
});

View file

@ -0,0 +1,39 @@
{
"name": "@manacore/manadeck-database",
"version": "1.0.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./schema": "./src/schema/index.ts",
"./client": "./src/client.ts"
},
"scripts": {
"docker:up": "docker compose up -d",
"docker:down": "docker compose down",
"docker:logs": "docker compose logs -f postgres",
"db:generate": "dotenv -- drizzle-kit generate",
"db:migrate": "dotenv -- drizzle-kit migrate",
"db:push": "dotenv -- drizzle-kit push --force",
"db:studio": "dotenv -- drizzle-kit studio",
"db:seed": "dotenv -- tsx src/seed.ts",
"db:migrate-from-supabase": "dotenv -- tsx src/migrate-from-supabase.ts",
"db:reset": "docker compose down -v && docker compose up -d && sleep 3 && pnpm db:push",
"db:test": "dotenv -- tsx src/test-connection.ts",
"type-check": "tsc --noEmit"
},
"dependencies": {
"drizzle-orm": "^0.36.0",
"postgres": "^3.4.5"
},
"devDependencies": {
"@supabase/supabase-js": "^2.81.1",
"dotenv-cli": "^7.4.0",
"drizzle-kit": "^0.28.0",
"tsx": "^4.19.0",
"typescript": "^5.7.3",
"@types/node": "^22.10.0"
}
}

View file

@ -0,0 +1,73 @@
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
// Singleton instance for the database client
let dbInstance: ReturnType<typeof drizzle<typeof schema>> | null = null;
let pgClient: ReturnType<typeof postgres> | null = null;
/**
* Get the database URL from environment variables
*/
function getDatabaseUrl(): string {
const url = process.env.DATABASE_URL || process.env.MANADECK_DATABASE_URL;
if (!url) {
throw new Error(
'Database URL not found. Set DATABASE_URL or MANADECK_DATABASE_URL environment variable.'
);
}
return url;
}
/**
* Create a new database client
* Uses connection pooling with sensible defaults for serverless environments
*/
export function createClient(connectionString?: string) {
const url = connectionString || getDatabaseUrl();
const client = postgres(url, {
max: 10, // Maximum connections in the pool
idle_timeout: 20, // Close idle connections after 20 seconds
connect_timeout: 10, // Connection timeout in seconds
prepare: false, // Disable prepared statements for serverless
});
return drizzle(client, { schema });
}
/**
* Get the singleton database instance
* Creates a new instance if one doesn't exist
*/
export function getDb() {
if (!dbInstance) {
const url = getDatabaseUrl();
pgClient = postgres(url, {
max: 10,
idle_timeout: 20,
connect_timeout: 10,
prepare: false,
});
dbInstance = drizzle(pgClient, { schema });
}
return dbInstance;
}
/**
* Close the database connection
* Should be called when shutting down the application
*/
export async function closeDb() {
if (pgClient) {
await pgClient.end();
pgClient = null;
dbInstance = null;
}
}
// Export the database type for typing purposes
export type Database = ReturnType<typeof createClient>;
// Re-export commonly used Drizzle utilities
export { eq, ne, gt, gte, lt, lte, and, or, not, inArray, notInArray, isNull, isNotNull, like, ilike, sql, asc, desc, count, sum, avg, min, max } from 'drizzle-orm';

View file

@ -0,0 +1,34 @@
// Main entry point for @manacore/manadeck-database
// Export database client utilities
export { createClient, getDb, closeDb, type Database } from './client';
// Export Drizzle utilities
export {
eq,
ne,
gt,
gte,
lt,
lte,
and,
or,
not,
inArray,
notInArray,
isNull,
isNotNull,
like,
ilike,
sql,
asc,
desc,
count,
sum,
avg,
min,
max,
} from './client';
// Export all schemas and types
export * from './schema';

View file

@ -0,0 +1,237 @@
/**
* Migration script to move data from Supabase to the new PostgreSQL database
*
* Prerequisites:
* 1. Set SUPABASE_URL and SUPABASE_SERVICE_KEY environment variables
* 2. Set DATABASE_URL for the new PostgreSQL database
* 3. Run migrations on the new database first: pnpm db:migrate
*
* Usage:
* SUPABASE_URL=... SUPABASE_SERVICE_KEY=... DATABASE_URL=... tsx src/migrate-from-supabase.ts
*/
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
import { getDb, closeDb } from './client';
import {
decks,
cards,
studySessions,
cardProgress,
deckTemplates,
aiGenerations,
userStats,
dailyProgress,
} from './schema';
// Initialize Supabase client
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY;
if (!supabaseUrl || !supabaseServiceKey) {
console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_KEY environment variables');
process.exit(1);
}
const supabase = createSupabaseClient(supabaseUrl, supabaseServiceKey);
const db = getDb();
interface MigrationStats {
table: string;
migrated: number;
errors: number;
}
const stats: MigrationStats[] = [];
async function migrateTable<T>(
tableName: string,
supabaseTableName: string,
drizzleTable: any,
transformer: (row: any) => T
) {
console.log(`\nMigrating ${tableName}...`);
let migrated = 0;
let errors = 0;
try {
// Fetch all data from Supabase
const { data, error } = await supabase.from(supabaseTableName).select('*');
if (error) {
console.error(`Error fetching ${tableName}:`, error);
stats.push({ table: tableName, migrated: 0, errors: 1 });
return;
}
if (!data || data.length === 0) {
console.log(`No data found in ${tableName}`);
stats.push({ table: tableName, migrated: 0, errors: 0 });
return;
}
console.log(`Found ${data.length} rows in ${tableName}`);
// Process in batches of 100
const batchSize = 100;
for (let i = 0; i < data.length; i += batchSize) {
const batch = data.slice(i, i + batchSize);
const transformed = batch.map(transformer);
try {
await db.insert(drizzleTable).values(transformed).onConflictDoNothing();
migrated += batch.length;
process.stdout.write(`\r Migrated ${migrated}/${data.length} rows`);
} catch (err) {
console.error(`\n Error inserting batch:`, err);
errors += batch.length;
}
}
console.log(`\n Completed: ${migrated} migrated, ${errors} errors`);
} catch (err) {
console.error(`Error migrating ${tableName}:`, err);
errors++;
}
stats.push({ table: tableName, migrated, errors });
}
async function main() {
console.log('=== ManaDeck Data Migration ===');
console.log('From: Supabase');
console.log('To: PostgreSQL (Drizzle)');
console.log('==============================\n');
try {
// 1. Migrate decks
await migrateTable('decks', 'decks', decks, (row) => ({
id: row.id,
userId: row.user_id,
title: row.title,
description: row.description,
coverImageUrl: row.cover_image_url,
isPublic: row.is_public ?? false,
isFeatured: row.is_featured ?? false,
featuredAt: row.featured_at ? new Date(row.featured_at) : null,
settings: row.settings ?? {},
tags: row.tags ?? [],
metadata: row.metadata ?? {},
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 2. Migrate cards
await migrateTable('cards', 'cards', cards, (row) => ({
id: row.id,
deckId: row.deck_id,
position: row.position ?? 0,
title: row.title,
content: row.content,
cardType: row.card_type,
aiModel: row.ai_model,
aiPrompt: row.ai_prompt,
version: row.version ?? 1,
isFavorite: row.is_favorite ?? false,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 3. Migrate study sessions
await migrateTable('study_sessions', 'study_sessions', studySessions, (row) => ({
id: row.id,
deckId: row.deck_id,
userId: row.user_id,
mode: row.mode,
totalCards: row.total_cards ?? 0,
completedCards: row.completed_cards ?? 0,
correctCards: row.correct_cards ?? 0,
startedAt: new Date(row.started_at),
completedAt: row.completed_at ? new Date(row.completed_at) : null,
timeSpentSeconds: row.time_spent_seconds ?? 0,
}));
// 4. Migrate card progress
await migrateTable('card_progress', 'card_progress', cardProgress, (row) => ({
id: row.id,
userId: row.user_id,
cardId: row.card_id,
easeFactor: row.ease_factor?.toString() ?? '2.5',
interval: row.interval ?? 0,
repetitions: row.repetitions ?? 0,
lastReviewed: row.last_reviewed ? new Date(row.last_reviewed) : null,
nextReview: row.next_review ? new Date(row.next_review) : null,
status: row.status ?? 'new',
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 5. Migrate deck templates
await migrateTable('deck_templates', 'deck_templates', deckTemplates, (row) => ({
id: row.id,
title: row.title,
description: row.description,
category: row.category,
templateData: row.template_data ?? { cards: [] },
isActive: row.is_active ?? true,
isPublic: row.is_public ?? true,
popularity: row.popularity ?? 0,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// 6. Migrate AI generations
await migrateTable('ai_generations', 'ai_generations', aiGenerations, (row) => ({
id: row.id,
userId: row.user_id,
deckId: row.deck_id,
functionName: row.function_name,
prompt: row.prompt,
model: row.model,
status: row.status ?? 'pending',
metadata: row.metadata ?? {},
completedAt: row.completed_at ? new Date(row.completed_at) : null,
createdAt: new Date(row.created_at),
}));
// 7. Migrate user stats
await migrateTable('user_stats', 'user_stats', userStats, (row) => ({
userId: row.user_id,
totalWins: row.total_wins ?? 0,
totalSessions: row.total_sessions ?? 0,
totalCardsStudied: row.total_cards_studied ?? 0,
totalTimeSeconds: row.total_time_seconds ?? 0,
averageAccuracy: row.average_accuracy?.toString() ?? '0',
streakDays: row.streak_days ?? 0,
longestStreak: row.longest_streak ?? 0,
lastStudyDate: row.last_study_date,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
}));
// Print summary
console.log('\n\n=== Migration Summary ===');
console.log('-------------------------');
let totalMigrated = 0;
let totalErrors = 0;
for (const stat of stats) {
console.log(`${stat.table}: ${stat.migrated} migrated, ${stat.errors} errors`);
totalMigrated += stat.migrated;
totalErrors += stat.errors;
}
console.log('-------------------------');
console.log(`Total: ${totalMigrated} rows migrated, ${totalErrors} errors`);
if (totalErrors === 0) {
console.log('\n✅ Migration completed successfully!');
} else {
console.log('\n⚠ Migration completed with some errors. Please review.');
}
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
} finally {
await closeDb();
}
}
main();

View file

@ -0,0 +1,23 @@
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import { createClient } from './client';
import path from 'path';
async function runMigrations() {
console.log('Running migrations...');
const db = createClient();
try {
await migrate(db, {
migrationsFolder: path.join(__dirname, '../drizzle'),
});
console.log('Migrations completed successfully!');
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
}
process.exit(0);
}
runMigrations();

View file

@ -0,0 +1,63 @@
import {
pgTable,
uuid,
varchar,
text,
timestamp,
jsonb,
index,
pgEnum,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { decks } from './decks';
// AI generation status enum
export const aiGenerationStatusEnum = pgEnum('ai_generation_status', [
'pending',
'processing',
'completed',
'failed',
]);
// AI generation metadata structure
export interface AIGenerationMetadata {
inputTokens?: number;
outputTokens?: number;
totalTokens?: number;
duration?: number;
error?: string;
cardCount?: number;
[key: string]: unknown;
}
export const aiGenerations = pgTable(
'ai_generations',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
deckId: uuid('deck_id').references(() => decks.id, { onDelete: 'set null' }),
functionName: varchar('function_name', { length: 100 }).notNull(),
prompt: text('prompt').notNull(),
model: varchar('model', { length: 100 }),
status: aiGenerationStatusEnum('status').default('pending').notNull(),
metadata: jsonb('metadata').default({}).$type<AIGenerationMetadata>(),
completedAt: timestamp('completed_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_ai_generations_user_id').on(table.userId),
index('idx_ai_generations_deck_id').on(table.deckId),
index('idx_ai_generations_status').on(table.status),
index('idx_ai_generations_created_at').on(table.createdAt),
]
);
export const aiGenerationsRelations = relations(aiGenerations, ({ one }) => ({
deck: one(decks, {
fields: [aiGenerations.deckId],
references: [decks.id],
}),
}));
export type AIGeneration = typeof aiGenerations.$inferSelect;
export type NewAIGeneration = typeof aiGenerations.$inferInsert;

View file

@ -0,0 +1,57 @@
import {
pgTable,
uuid,
integer,
timestamp,
index,
pgEnum,
decimal,
unique,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { cards } from './cards';
// Progress status enum (SM-2 algorithm states)
export const progressStatusEnum = pgEnum('progress_status', [
'new',
'learning',
'review',
'relearning',
]);
export const cardProgress = pgTable(
'card_progress',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
cardId: uuid('card_id')
.notNull()
.references(() => cards.id, { onDelete: 'cascade' }),
// SM-2 algorithm fields
easeFactor: decimal('ease_factor', { precision: 4, scale: 2 }).default('2.5').notNull(),
interval: integer('interval').default(0).notNull(), // Days until next review
repetitions: integer('repetitions').default(0).notNull(),
lastReviewed: timestamp('last_reviewed', { withTimezone: true }),
nextReview: timestamp('next_review', { withTimezone: true }),
status: progressStatusEnum('status').default('new').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_card_progress_user_id').on(table.userId),
index('idx_card_progress_card_id').on(table.cardId),
index('idx_card_progress_next_review').on(table.nextReview),
index('idx_card_progress_status').on(table.status),
unique('unique_user_card').on(table.userId, table.cardId),
]
);
export const cardProgressRelations = relations(cardProgress, ({ one }) => ({
card: one(cards, {
fields: [cardProgress.cardId],
references: [cards.id],
}),
}));
export type CardProgress = typeof cardProgress.$inferSelect;
export type NewCardProgress = typeof cardProgress.$inferInsert;

View file

@ -0,0 +1,82 @@
import {
pgTable,
uuid,
varchar,
text,
integer,
boolean,
timestamp,
jsonb,
index,
pgEnum,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { decks } from './decks';
import { cardProgress } from './cardProgress';
// Card type enum
export const cardTypeEnum = pgEnum('card_type', ['text', 'flashcard', 'quiz', 'mixed']);
// Card content types
export interface TextContent {
text: string;
formatting?: {
bold?: boolean;
italic?: boolean;
underline?: boolean;
};
}
export interface FlashcardContent {
front: string;
back: string;
hint?: string;
}
export interface QuizContent {
question: string;
options: string[];
correctAnswer: number;
explanation?: string;
}
export interface MixedContent {
sections: Array<TextContent | FlashcardContent | QuizContent>;
}
export type CardContent = TextContent | FlashcardContent | QuizContent | MixedContent;
export const cards = pgTable(
'cards',
{
id: uuid('id').primaryKey().defaultRandom(),
deckId: uuid('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
position: integer('position').notNull().default(0),
title: varchar('title', { length: 255 }),
content: jsonb('content').notNull().$type<CardContent>(),
cardType: cardTypeEnum('card_type').notNull(),
aiModel: varchar('ai_model', { length: 100 }),
aiPrompt: text('ai_prompt'),
version: integer('version').default(1).notNull(),
isFavorite: boolean('is_favorite').default(false).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_cards_deck_id').on(table.deckId),
index('idx_cards_position').on(table.deckId, table.position),
]
);
export const cardsRelations = relations(cards, ({ one, many }) => ({
deck: one(decks, {
fields: [cards.deckId],
references: [decks.id],
}),
progress: many(cardProgress),
}));
export type Card = typeof cards.$inferSelect;
export type NewCard = typeof cards.$inferInsert;

View file

@ -0,0 +1,35 @@
import {
pgTable,
uuid,
date,
integer,
decimal,
text,
timestamp,
index,
unique,
} from 'drizzle-orm/pg-core';
export const dailyProgress = pgTable(
'daily_progress',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
date: date('date').notNull(),
cardsStudied: integer('cards_studied').default(0).notNull(),
timeSpentMinutes: integer('time_spent_minutes').default(0).notNull(),
accuracyPercentage: decimal('accuracy_percentage', { precision: 5, scale: 2 }).default('0').notNull(),
decksStudied: text('decks_studied').array().default([]),
sessionsCompleted: integer('sessions_completed').default(0).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_daily_progress_user_id').on(table.userId),
index('idx_daily_progress_date').on(table.date),
unique('unique_user_date').on(table.userId, table.date),
]
);
export type DailyProgress = typeof dailyProgress.$inferSelect;
export type NewDailyProgress = typeof dailyProgress.$inferInsert;

View file

@ -0,0 +1,46 @@
import {
pgTable,
uuid,
varchar,
text,
boolean,
integer,
timestamp,
jsonb,
index,
} from 'drizzle-orm/pg-core';
// Template data structure
export interface DeckTemplateData {
cards: Array<{
title?: string;
content: Record<string, unknown>;
cardType: 'text' | 'flashcard' | 'quiz' | 'mixed';
}>;
settings?: Record<string, unknown>;
tags?: string[];
}
export const deckTemplates = pgTable(
'deck_templates',
{
id: uuid('id').primaryKey().defaultRandom(),
title: varchar('title', { length: 255 }).notNull(),
description: text('description'),
category: varchar('category', { length: 100 }),
templateData: jsonb('template_data').notNull().$type<DeckTemplateData>(),
isActive: boolean('is_active').default(true).notNull(),
isPublic: boolean('is_public').default(true).notNull(),
popularity: integer('popularity').default(0).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_deck_templates_category').on(table.category),
index('idx_deck_templates_is_active').on(table.isActive),
index('idx_deck_templates_popularity').on(table.popularity),
]
);
export type DeckTemplate = typeof deckTemplates.$inferSelect;
export type NewDeckTemplate = typeof deckTemplates.$inferInsert;

View file

@ -0,0 +1,48 @@
import {
pgTable,
uuid,
varchar,
text,
boolean,
timestamp,
jsonb,
index,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { cards } from './cards';
import { studySessions } from './studySessions';
import { aiGenerations } from './aiGenerations';
export const decks = pgTable(
'decks',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
title: varchar('title', { length: 255 }).notNull(),
description: text('description'),
coverImageUrl: text('cover_image_url'),
isPublic: boolean('is_public').default(false).notNull(),
isFeatured: boolean('is_featured').default(false).notNull(),
featuredAt: timestamp('featured_at', { withTimezone: true }),
settings: jsonb('settings').default({}).$type<Record<string, unknown>>(),
tags: text('tags').array().default([]),
metadata: jsonb('metadata').default({}).$type<Record<string, unknown>>(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_decks_user_id').on(table.userId),
index('idx_decks_is_public').on(table.isPublic),
index('idx_decks_is_featured').on(table.isFeatured),
index('idx_decks_updated_at').on(table.updatedAt),
]
);
export const decksRelations = relations(decks, ({ many }) => ({
cards: many(cards),
studySessions: many(studySessions),
aiGenerations: many(aiGenerations),
}));
export type Deck = typeof decks.$inferSelect;
export type NewDeck = typeof decks.$inferInsert;

View file

@ -0,0 +1,16 @@
// Export all schemas
export * from './decks';
export * from './cards';
export * from './studySessions';
export * from './cardProgress';
export * from './deckTemplates';
export * from './aiGenerations';
export * from './userStats';
export * from './dailyProgress';
// Re-export relations for use with Drizzle query builder
export { decksRelations } from './decks';
export { cardsRelations } from './cards';
export { studySessionsRelations } from './studySessions';
export { cardProgressRelations } from './cardProgress';
export { aiGenerationsRelations } from './aiGenerations';

View file

@ -0,0 +1,47 @@
import {
pgTable,
uuid,
varchar,
integer,
timestamp,
index,
pgEnum,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { decks } from './decks';
// Study mode enum
export const studyModeEnum = pgEnum('study_mode', ['all', 'new', 'review', 'favorites', 'random']);
export const studySessions = pgTable(
'study_sessions',
{
id: uuid('id').primaryKey().defaultRandom(),
deckId: uuid('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
userId: uuid('user_id').notNull(),
mode: studyModeEnum('mode').notNull(),
totalCards: integer('total_cards').notNull().default(0),
completedCards: integer('completed_cards').notNull().default(0),
correctCards: integer('correct_cards').notNull().default(0),
startedAt: timestamp('started_at', { withTimezone: true }).defaultNow().notNull(),
completedAt: timestamp('completed_at', { withTimezone: true }),
timeSpentSeconds: integer('time_spent_seconds').default(0).notNull(),
},
(table) => [
index('idx_study_sessions_user_id').on(table.userId),
index('idx_study_sessions_deck_id').on(table.deckId),
index('idx_study_sessions_started_at').on(table.startedAt),
]
);
export const studySessionsRelations = relations(studySessions, ({ one }) => ({
deck: one(decks, {
fields: [studySessions.deckId],
references: [decks.id],
}),
}));
export type StudySession = typeof studySessions.$inferSelect;
export type NewStudySession = typeof studySessions.$inferInsert;

View file

@ -0,0 +1,33 @@
import {
pgTable,
uuid,
integer,
decimal,
date,
timestamp,
index,
} from 'drizzle-orm/pg-core';
export const userStats = pgTable(
'user_stats',
{
userId: uuid('user_id').primaryKey(),
totalWins: integer('total_wins').default(0).notNull(),
totalSessions: integer('total_sessions').default(0).notNull(),
totalCardsStudied: integer('total_cards_studied').default(0).notNull(),
totalTimeSeconds: integer('total_time_seconds').default(0).notNull(),
averageAccuracy: decimal('average_accuracy', { precision: 5, scale: 2 }).default('0').notNull(),
streakDays: integer('streak_days').default(0).notNull(),
longestStreak: integer('longest_streak').default(0).notNull(),
lastStudyDate: date('last_study_date'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('idx_user_stats_total_wins').on(table.totalWins),
index('idx_user_stats_streak_days').on(table.streakDays),
]
);
export type UserStats = typeof userStats.$inferSelect;
export type NewUserStats = typeof userStats.$inferInsert;

View file

@ -0,0 +1,105 @@
import { getDb, closeDb } from './client';
import { deckTemplates } from './schema';
/**
* Seed the database with initial data
*/
async function seed() {
console.log('Seeding database...');
const db = getDb();
try {
// Seed deck templates
const templates = [
{
title: 'Language Basics',
description: 'Learn basic vocabulary and phrases for a new language',
category: 'languages',
templateData: {
cards: [
{
cardType: 'flashcard' as const,
content: { front: 'Hello', back: 'Hallo', hint: 'Greeting' },
},
{
cardType: 'flashcard' as const,
content: { front: 'Goodbye', back: 'Auf Wiedersehen' },
},
],
settings: { language: 'de' },
tags: ['language', 'basics', 'german'],
},
isActive: true,
isPublic: true,
popularity: 100,
},
{
title: 'Math Fundamentals',
description: 'Essential math concepts and formulas',
category: 'education',
templateData: {
cards: [
{
cardType: 'quiz' as const,
content: {
question: 'What is 2 + 2?',
options: ['3', '4', '5', '6'],
correctAnswer: 1,
explanation: '2 + 2 equals 4',
},
},
],
settings: { difficulty: 'beginner' },
tags: ['math', 'basics'],
},
isActive: true,
isPublic: true,
popularity: 80,
},
{
title: 'Programming Concepts',
description: 'Core programming concepts and terminology',
category: 'technology',
templateData: {
cards: [
{
cardType: 'flashcard' as const,
content: {
front: 'Variable',
back: 'A named storage location in memory that holds a value',
},
},
{
cardType: 'flashcard' as const,
content: {
front: 'Function',
back: 'A reusable block of code that performs a specific task',
},
},
],
settings: {},
tags: ['programming', 'coding', 'basics'],
},
isActive: true,
isPublic: true,
popularity: 90,
},
];
console.log('Inserting deck templates...');
await db.insert(deckTemplates).values(templates).onConflictDoNothing();
console.log('Seeding completed successfully!');
} catch (error) {
console.error('Seeding failed:', error);
throw error;
} finally {
await closeDb();
}
}
seed().catch((error) => {
console.error('Seed script failed:', error);
process.exit(1);
});

View file

@ -0,0 +1,44 @@
/**
* Test database connection
* Usage: pnpm db:test
*/
import { getDb, closeDb, sql } from './client';
async function testConnection() {
console.log('Testing database connection...\n');
try {
const db = getDb();
// Test basic connection
const result = await db.execute(sql`SELECT NOW() as current_time, version() as pg_version`);
console.log('✅ Connection successful!');
console.log(` Time: ${result[0].current_time}`);
console.log(` PostgreSQL: ${result[0].pg_version}\n`);
// List tables
const tables = await db.execute(sql`
SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename
`);
if (tables.length > 0) {
console.log('📋 Tables in database:');
tables.forEach((t: any) => console.log(` - ${t.tablename}`));
} else {
console.log('📋 No tables found. Run "pnpm db:push" to create schema.');
}
console.log('\n✅ All tests passed!');
} catch (error) {
console.error('❌ Connection failed:', error);
process.exit(1);
} finally {
await closeDb();
}
}
testConnection();

View file

@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

View file

@ -37,5 +37,10 @@ export type {
IconName
} from './types';
// Page Translation Types
export type { LoginTranslations } from './pages/LoginPage.svelte';
export type { RegisterTranslations } from './pages/RegisterPage.svelte';
export type { ForgotPasswordTranslations } from './pages/ForgotPasswordPage.svelte';
// Icon paths
export { iconPaths } from './icons/iconPaths';

View file

@ -5,6 +5,38 @@
type PageMode = 'form' | 'success';
/** Translation strings for the forgot password page */
export interface ForgotPasswordTranslations {
titleForm: string;
titleSuccess: string;
description: string;
emailPlaceholder: string;
sendResetLinkButton: string;
sending: string;
backToLogin: string;
resendEmail: string;
// Success message (uses template with email)
successMessage: string;
// Error messages
emailRequired: string;
sendFailed: string;
}
/** Default English translations */
const defaultTranslations: ForgotPasswordTranslations = {
titleForm: 'Reset Password',
titleSuccess: 'Email Sent',
description: "Enter your email address and we'll send you a link to reset your password.",
emailPlaceholder: 'Email',
sendResetLinkButton: 'Send Reset Link',
sending: 'Sending...',
backToLogin: 'Back to Login',
resendEmail: 'Resend Email',
successMessage: "We've sent a password reset link to {email}. Please check your inbox.",
emailRequired: 'Email is required',
sendFailed: 'Failed to send reset email'
};
interface Props {
/** App name */
appName: string;
@ -24,6 +56,8 @@
darkBackground?: string;
/** App slider snippet */
appSlider?: Snippet;
/** Translations for i18n support */
translations?: Partial<ForgotPasswordTranslations>;
}
let {
@ -35,9 +69,18 @@
loginPath = '/login',
lightBackground = '#f5f5f5',
darkBackground = '#121212',
appSlider
appSlider,
translations = {}
}: Props = $props();
// Merge provided translations with defaults
const t = $derived({ ...defaultTranslations, ...translations });
// Helper to interpolate success message with email
function getSuccessMessage(email: string): string {
return t.successMessage.replace('{email}', email);
}
let loading = $state(false);
let error = $state<string | null>(null);
let email = $state('');
@ -68,7 +111,7 @@
error = null;
if (!email) {
error = 'Email is required';
error = t.emailRequired;
loading = false;
return;
}
@ -82,7 +125,7 @@
email = '';
mode = 'success';
} else {
error = result.error || 'Failed to send reset email';
error = result.error || t.sendFailed;
}
}
</script>
@ -121,7 +164,7 @@
class="mb-6 text-center text-xl font-semibold"
style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};"
>
{mode === 'form' ? 'Reset Password' : 'Email Sent'}
{mode === 'form' ? t.titleForm : t.titleSuccess}
</h2>
<!-- Error Messages -->
@ -144,14 +187,14 @@
class="mb-4 text-sm"
style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};"
>
Enter your email address and we'll send you a link to reset your password.
{t.description}
</p>
<div class="mb-4">
<input
type="email"
bind:value={email}
placeholder="Email"
placeholder={t.emailPlaceholder}
required
class="h-14 w-full rounded-xl border px-4 text-lg transition-colors focus:outline-none focus:ring-2"
style="background-color: {isDark ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'}; --tw-ring-color: {primaryColor};"
@ -165,7 +208,7 @@
style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};"
>
<Icon name="key" size={20} />
{loading ? 'Sending...' : 'Send Reset Link'}
{loading ? t.sending : t.sendResetLinkButton}
</button>
</form>
@ -177,7 +220,7 @@
style="color: {isDark ? '#ffffff' : '#000000'};"
>
<Icon name="arrow-left" size={20} />
Back to Login
{t.backToLogin}
</button>
</div>
@ -196,8 +239,7 @@
class="text-sm text-center px-2"
style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};"
>
We've sent a password reset link to <strong>{resetEmail}</strong>. Please check your
inbox.
{@html getSuccessMessage(resetEmail).replace(resetEmail, `<strong>${resetEmail}</strong>`)}
</p>
</div>
@ -208,7 +250,7 @@
style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};"
>
<Icon name="sign-in" size={20} />
Back to Login
{t.backToLogin}
</button>
<button
@ -219,7 +261,7 @@
class="flex h-10 items-center justify-center gap-2 rounded-xl font-medium transition-all hover:opacity-80 border"
style="background-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'};"
>
Resend Email
{t.resendEmail}
</button>
</div>
</div>

View file

@ -5,6 +5,60 @@
import GoogleSignInButton from '../components/GoogleSignInButton.svelte';
import AppleSignInButton from '../components/AppleSignInButton.svelte';
/** Translation strings for the login page */
export interface LoginTranslations {
title: string;
subtitle: string;
emailPlaceholder: string;
passwordPlaceholder: string;
rememberMe: string;
forgotPassword: string;
signInButton: string;
signingIn: string;
success: string;
orDivider: string;
noAccount: string;
createAccount: string;
skipToForm: string;
showPassword: string;
hidePassword: string;
// Error messages
emailRequired: string;
emailInvalid: string;
passwordRequired: string;
signInFailed: string;
googleSignInFailed: string;
// Success messages
signInSuccess: string;
googleSignInSuccess: string;
}
/** Default English translations */
const defaultTranslations: LoginTranslations = {
title: 'Sign In',
subtitle: 'Sign in with your Mana account',
emailPlaceholder: 'Email',
passwordPlaceholder: 'Password',
rememberMe: 'Remember me',
forgotPassword: 'Forgot password?',
signInButton: 'Sign In',
signingIn: 'Signing in...',
success: 'Success!',
orDivider: 'or',
noAccount: "Don't have an account?",
createAccount: 'Create one',
skipToForm: 'Skip to login form',
showPassword: 'Show password',
hidePassword: 'Hide password',
emailRequired: 'Email is required',
emailInvalid: 'Please enter a valid email address',
passwordRequired: 'Password is required',
signInFailed: 'Sign in failed',
googleSignInFailed: 'Google sign in failed',
signInSuccess: 'Successfully signed in. Redirecting...',
googleSignInSuccess: 'Successfully signed in with Google. Redirecting...'
};
interface Props {
/** App name */
appName: string;
@ -38,6 +92,8 @@
appSlider?: Snippet;
/** Header snippet for controls like theme toggle and language selector */
headerControls?: Snippet;
/** Translations for i18n support */
translations?: Partial<LoginTranslations>;
}
let {
@ -56,9 +112,13 @@
lightBackground = '#f5f5f5',
darkBackground = '#121212',
appSlider,
headerControls
headerControls,
translations = {}
}: Props = $props();
// Merge provided translations with defaults
const t = $derived({ ...defaultTranslations, ...translations });
let loading = $state(false);
let error = $state<string | null>(null);
let errorField = $state<'email' | 'password' | 'general' | null>(null);
@ -135,19 +195,19 @@
clearError();
if (!email) {
setError('Email is required', 'email');
setError(t.emailRequired, 'email');
loading = false;
return;
}
if (!isValidEmail(email)) {
setError('Please enter a valid email address', 'email');
setError(t.emailInvalid, 'email');
loading = false;
return;
}
if (!password) {
setError('Password is required', 'password');
setError(t.passwordRequired, 'password');
loading = false;
return;
}
@ -159,12 +219,12 @@
if (result.success) {
// Show success feedback before redirect
showSuccess = true;
successAnnouncement = 'Successfully signed in. Redirecting...';
successAnnouncement = t.signInSuccess;
setTimeout(() => {
goto(successRedirect);
}, 600);
} else {
setError(result.error || 'Sign in failed', 'general');
setError(result.error || t.signInFailed, 'general');
}
}
@ -179,12 +239,12 @@
if (result.success) {
showSuccess = true;
successAnnouncement = 'Successfully signed in with Google. Redirecting...';
successAnnouncement = t.googleSignInSuccess;
setTimeout(() => {
goto(successRedirect);
}, 600);
} else {
setError(result.error || 'Google sign in failed', 'general');
setError(result.error || t.googleSignInFailed, 'general');
}
}
@ -285,7 +345,7 @@
onclick={skipToForm}
type="button"
>
Skip to login form
{t.skipToForm}
</button>
<!-- Screen reader announcements -->
@ -340,13 +400,13 @@
class="text-center text-xl font-semibold"
style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};"
>
Sign In
{t.title}
</h2>
<p
class="mt-2 text-sm text-center"
style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};"
>
Sign in with your Mana account
{t.subtitle}
</p>
</div>
@ -375,13 +435,13 @@
>
<!-- Email Field -->
<div class="mb-3">
<label for="email" class="sr-only">Email address</label>
<label for="email" class="sr-only">{t.emailPlaceholder}</label>
<input
id="email"
type="email"
bind:this={emailInput}
bind:value={email}
placeholder="Email"
placeholder={t.emailPlaceholder}
required
autocomplete="email"
aria-invalid={errorField === 'email'}
@ -393,13 +453,13 @@
<!-- Password Field -->
<div class="mb-3 relative">
<label for="password" class="sr-only">Password</label>
<label for="password" class="sr-only">{t.passwordPlaceholder}</label>
<input
id="password"
type={showPassword ? 'text' : 'password'}
bind:this={passwordInput}
bind:value={password}
placeholder="Password"
placeholder={t.passwordPlaceholder}
required
autocomplete="current-password"
aria-invalid={errorField === 'password'}
@ -411,9 +471,9 @@
type="button"
onclick={() => (showPassword = !showPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors touch-target flex items-center justify-center"
aria-label={showPassword ? 'Hide password' : 'Show password'}
aria-label={showPassword ? t.hidePassword : t.showPassword}
aria-pressed={showPassword}
title={showPassword ? 'Hide password' : 'Show password'}
title={showPassword ? t.hidePassword : t.showPassword}
>
<Icon
name={showPassword ? 'eye-off' : 'eye'}
@ -436,7 +496,7 @@
class="text-sm"
style="color: {isDark ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)'};"
>
Remember me
{t.rememberMe}
</span>
</label>
@ -446,7 +506,7 @@
class="text-sm font-medium transition-opacity hover:opacity-70 touch-target flex items-center justify-center px-2"
style="color: {primaryColor};"
>
Forgot password?
{t.forgotPassword}
</button>
</div>
@ -470,13 +530,13 @@
<circle cx="12" cy="12" r="10" stroke-opacity="0.25" />
<path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round" />
</svg>
<span>Signing in...</span>
<span>{t.signingIn}</span>
{:else if showSuccess}
<Icon name="check" size={20} />
<span>Success!</span>
<span>{t.success}</span>
{:else}
<Icon name="sign-in" size={20} />
<span>Sign In</span>
<span>{t.signInButton}</span>
{/if}
</button>
</form>
@ -485,7 +545,7 @@
{#if enableGoogle || enableApple}
<div class="my-4 flex items-center gap-3" role="separator" aria-orientation="horizontal">
<div class="flex-1 border-t" style="border-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};"></div>
<span class="text-xs" style="color: {isDark ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)'};">or</span>
<span class="text-xs" style="color: {isDark ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)'};">{t.orDivider}</span>
<div class="flex-1 border-t" style="border-color: {isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};"></div>
</div>
@ -505,14 +565,14 @@
class="text-sm"
style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};"
>
Don't have an account?
{t.noAccount}
<button
type="button"
onclick={() => goto(registerPath)}
class="font-medium transition-opacity hover:opacity-70 touch-target inline-flex items-center justify-center px-1"
style="color: {primaryColor};"
>
Create one
{t.createAccount}
</button>
</p>
</div>

View file

@ -5,6 +5,52 @@
import type { Snippet } from 'svelte';
/** Translation strings for the register page */
export interface RegisterTranslations {
title: string;
emailPlaceholder: string;
passwordPlaceholder: string;
confirmPasswordPlaceholder: string;
passwordRequirements: string;
createAccountButton: string;
creatingAccount: string;
backToLogin: string;
showPassword: string;
hidePassword: string;
// Error messages
emailRequired: string;
passwordRequired: string;
confirmPasswordRequired: string;
passwordsDoNotMatch: string;
passwordTooShort: string;
passwordStrengthError: string;
registrationFailed: string;
// Success messages
accountCreated: string;
}
/** Default English translations */
const defaultTranslations: RegisterTranslations = {
title: 'Create Account',
emailPlaceholder: 'Email',
passwordPlaceholder: 'Password',
confirmPasswordPlaceholder: 'Confirm Password',
passwordRequirements: 'Password must be at least 8 characters with lowercase, uppercase, number, and special character.',
createAccountButton: 'Create Account',
creatingAccount: 'Creating Account...',
backToLogin: 'Back to Login',
showPassword: 'Show password',
hidePassword: 'Hide password',
emailRequired: 'Email is required',
passwordRequired: 'Password is required',
confirmPasswordRequired: 'Please confirm your password',
passwordsDoNotMatch: 'Passwords do not match',
passwordTooShort: 'Password must be at least 8 characters',
passwordStrengthError: 'Password must include lowercase, uppercase, number, and special character',
registrationFailed: 'Registration failed',
accountCreated: 'Account created! Please check your email to verify your account.'
};
interface Props {
/** App name */
appName: string;
@ -26,6 +72,8 @@
darkBackground?: string;
/** App slider snippet */
appSlider?: Snippet;
/** Translations for i18n support */
translations?: Partial<RegisterTranslations>;
}
let {
@ -38,9 +86,13 @@
loginPath = '/login',
lightBackground = '#f5f5f5',
darkBackground = '#121212',
appSlider
appSlider,
translations = {}
}: Props = $props();
// Merge provided translations with defaults
const t = $derived({ ...defaultTranslations, ...translations });
let loading = $state(false);
let error = $state<string | null>(null);
let success = $state(false);
@ -98,31 +150,31 @@
// Validation
if (!email) {
error = 'Email is required';
error = t.emailRequired;
loading = false;
return;
}
if (!password) {
error = 'Password is required';
error = t.passwordRequired;
loading = false;
return;
}
if (!confirmPassword) {
error = 'Please confirm your password';
error = t.confirmPasswordRequired;
loading = false;
return;
}
if (password !== confirmPassword) {
error = 'Passwords do not match';
error = t.passwordsDoNotMatch;
loading = false;
return;
}
if (password.length < 8) {
error = 'Password must be at least 8 characters';
error = t.passwordTooShort;
loading = false;
return;
}
@ -134,7 +186,7 @@
const hasSymbol = /[^a-zA-Z0-9]/.test(password);
if (!hasLowercase || !hasUppercase || !hasDigit || !hasSymbol) {
error = 'Password must include lowercase, uppercase, number, and special character';
error = t.passwordStrengthError;
loading = false;
return;
}
@ -153,7 +205,7 @@
goto(successRedirect);
}
} else {
error = result.error || 'Registration failed';
error = result.error || t.registrationFailed;
}
}
</script>
@ -192,7 +244,7 @@
class="mb-6 text-center text-xl font-semibold"
style="color: {isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'};"
>
Create Account
{t.title}
</h2>
<!-- Error Messages -->
@ -206,7 +258,7 @@
{#if success && needsVerification}
<div class="mb-4 rounded-xl bg-green-500/20 border border-green-500/30 p-3">
<p class="text-sm text-green-500">
Account created! Please check your email to verify your account.
{t.accountCreated}
</p>
</div>
{/if}
@ -223,7 +275,7 @@
<input
type="email"
bind:value={email}
placeholder="Email"
placeholder={t.emailPlaceholder}
required
class="h-14 w-full rounded-xl border px-4 text-lg transition-colors focus:outline-none focus:ring-2"
style="background-color: {isDark ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.8)'}; border-color: {isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)'}; color: {isDark ? '#ffffff' : '#000000'}; --tw-ring-color: {primaryColor};"
@ -234,7 +286,7 @@
<input
type={showPassword ? 'text' : 'password'}
bind:value={password}
placeholder="Password"
placeholder={t.passwordPlaceholder}
required
minlength={8}
class="h-14 w-full rounded-xl border px-4 pr-12 text-lg transition-colors focus:outline-none focus:ring-2"
@ -244,6 +296,7 @@
type="button"
onclick={() => (showPassword = !showPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors"
aria-label={showPassword ? t.hidePassword : t.showPassword}
>
<Icon
name={showPassword ? 'eye-off' : 'eye'}
@ -257,7 +310,7 @@
<input
type={showConfirmPassword ? 'text' : 'password'}
bind:value={confirmPassword}
placeholder="Confirm Password"
placeholder={t.confirmPasswordPlaceholder}
required
minlength={8}
class="h-14 w-full rounded-xl border px-4 pr-12 text-lg transition-colors focus:outline-none focus:ring-2"
@ -267,6 +320,7 @@
type="button"
onclick={() => (showConfirmPassword = !showConfirmPassword)}
class="absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 transition-colors"
aria-label={showConfirmPassword ? t.hidePassword : t.showPassword}
>
<Icon
name={showConfirmPassword ? 'eye-off' : 'eye'}
@ -281,8 +335,7 @@
class="mb-4 mt-2 text-xs"
style="color: {isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'};"
>
Password must be at least 8 characters with lowercase, uppercase, number, and special
character.
{t.passwordRequirements}
</p>
<button
@ -292,7 +345,7 @@
style="background-color: {primaryColor}60; border-color: {primaryColor}; color: {isDark ? '#ffffff' : '#000000'};"
>
<Icon name="user-plus" size={20} />
{loading ? 'Creating Account...' : 'Create Account'}
{loading ? t.creatingAccount : t.createAccountButton}
</button>
</form>
@ -304,7 +357,7 @@
style="color: {isDark ? '#ffffff' : '#000000'};"
>
<Icon name="arrow-left" size={20} />
Back to Login
{t.backToLogin}
</button>
</div>
</div>

View file

@ -45,5 +45,21 @@ export {
mergeWithCommon,
} from './translations/common';
// Auth translations
export {
en as authTranslationsEn,
de as authTranslationsDe,
it as authTranslationsIt,
fr as authTranslationsFr,
es as authTranslationsEs,
type AuthTranslations,
type AuthLocale,
authTranslations,
getAuthTranslations,
getLoginTranslations,
getRegisterTranslations,
getForgotPasswordTranslations,
} from './translations/auth';
// Components
export { LanguageSelector } from './components';

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Anmelden",
"subtitle": "Melde dich mit deinem Mana-Konto an",
"emailPlaceholder": "E-Mail",
"passwordPlaceholder": "Passwort",
"rememberMe": "Angemeldet bleiben",
"forgotPassword": "Passwort vergessen?",
"signInButton": "Anmelden",
"signingIn": "Anmeldung...",
"success": "Erfolgreich!",
"orDivider": "oder",
"noAccount": "Noch kein Konto?",
"createAccount": "Jetzt erstellen",
"skipToForm": "Zum Anmeldeformular springen",
"showPassword": "Passwort anzeigen",
"hidePassword": "Passwort verbergen",
"emailRequired": "E-Mail ist erforderlich",
"emailInvalid": "Bitte gib eine gültige E-Mail-Adresse ein",
"passwordRequired": "Passwort ist erforderlich",
"signInFailed": "Anmeldung fehlgeschlagen",
"googleSignInFailed": "Google-Anmeldung fehlgeschlagen",
"signInSuccess": "Erfolgreich angemeldet. Weiterleitung...",
"googleSignInSuccess": "Erfolgreich mit Google angemeldet. Weiterleitung..."
},
"register": {
"title": "Konto erstellen",
"emailPlaceholder": "E-Mail",
"passwordPlaceholder": "Passwort",
"confirmPasswordPlaceholder": "Passwort bestätigen",
"passwordRequirements": "Das Passwort muss mindestens 8 Zeichen mit Kleinbuchstaben, Großbuchstaben, Zahl und Sonderzeichen enthalten.",
"createAccountButton": "Konto erstellen",
"creatingAccount": "Konto wird erstellt...",
"backToLogin": "Zurück zur Anmeldung",
"showPassword": "Passwort anzeigen",
"hidePassword": "Passwort verbergen",
"emailRequired": "E-Mail ist erforderlich",
"passwordRequired": "Passwort ist erforderlich",
"confirmPasswordRequired": "Bitte bestätige dein Passwort",
"passwordsDoNotMatch": "Passwörter stimmen nicht überein",
"passwordTooShort": "Passwort muss mindestens 8 Zeichen lang sein",
"passwordStrengthError": "Passwort muss Kleinbuchstaben, Großbuchstaben, Zahl und Sonderzeichen enthalten",
"registrationFailed": "Registrierung fehlgeschlagen",
"accountCreated": "Konto erstellt! Bitte überprüfe deine E-Mails, um dein Konto zu bestätigen."
},
"forgotPassword": {
"titleForm": "Passwort zurücksetzen",
"titleSuccess": "E-Mail gesendet",
"description": "Gib deine E-Mail-Adresse ein und wir senden dir einen Link zum Zurücksetzen deines Passworts.",
"emailPlaceholder": "E-Mail",
"sendResetLinkButton": "Link senden",
"sending": "Wird gesendet...",
"backToLogin": "Zurück zur Anmeldung",
"resendEmail": "E-Mail erneut senden",
"successMessage": "Wir haben einen Link zum Zurücksetzen des Passworts an {email} gesendet. Bitte überprüfe deinen Posteingang.",
"emailRequired": "E-Mail ist erforderlich",
"sendFailed": "E-Mail konnte nicht gesendet werden"
}
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Sign In",
"subtitle": "Sign in with your Mana account",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"rememberMe": "Remember me",
"forgotPassword": "Forgot password?",
"signInButton": "Sign In",
"signingIn": "Signing in...",
"success": "Success!",
"orDivider": "or",
"noAccount": "Don't have an account?",
"createAccount": "Create one",
"skipToForm": "Skip to login form",
"showPassword": "Show password",
"hidePassword": "Hide password",
"emailRequired": "Email is required",
"emailInvalid": "Please enter a valid email address",
"passwordRequired": "Password is required",
"signInFailed": "Sign in failed",
"googleSignInFailed": "Google sign in failed",
"signInSuccess": "Successfully signed in. Redirecting...",
"googleSignInSuccess": "Successfully signed in with Google. Redirecting..."
},
"register": {
"title": "Create Account",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"confirmPasswordPlaceholder": "Confirm Password",
"passwordRequirements": "Password must be at least 8 characters with lowercase, uppercase, number, and special character.",
"createAccountButton": "Create Account",
"creatingAccount": "Creating Account...",
"backToLogin": "Back to Login",
"showPassword": "Show password",
"hidePassword": "Hide password",
"emailRequired": "Email is required",
"passwordRequired": "Password is required",
"confirmPasswordRequired": "Please confirm your password",
"passwordsDoNotMatch": "Passwords do not match",
"passwordTooShort": "Password must be at least 8 characters",
"passwordStrengthError": "Password must include lowercase, uppercase, number, and special character",
"registrationFailed": "Registration failed",
"accountCreated": "Account created! Please check your email to verify your account."
},
"forgotPassword": {
"titleForm": "Reset Password",
"titleSuccess": "Email Sent",
"description": "Enter your email address and we'll send you a link to reset your password.",
"emailPlaceholder": "Email",
"sendResetLinkButton": "Send Reset Link",
"sending": "Sending...",
"backToLogin": "Back to Login",
"resendEmail": "Resend Email",
"successMessage": "We've sent a password reset link to {email}. Please check your inbox.",
"emailRequired": "Email is required",
"sendFailed": "Failed to send reset email"
}
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Iniciar Sesión",
"subtitle": "Inicia sesión con tu cuenta Mana",
"emailPlaceholder": "Correo electrónico",
"passwordPlaceholder": "Contraseña",
"rememberMe": "Recordarme",
"forgotPassword": "¿Olvidaste tu contraseña?",
"signInButton": "Iniciar Sesión",
"signingIn": "Iniciando sesión...",
"success": "¡Éxito!",
"orDivider": "o",
"noAccount": "¿No tienes cuenta?",
"createAccount": "Crear una",
"skipToForm": "Ir al formulario de inicio de sesión",
"showPassword": "Mostrar contraseña",
"hidePassword": "Ocultar contraseña",
"emailRequired": "El correo electrónico es obligatorio",
"emailInvalid": "Por favor ingresa un correo electrónico válido",
"passwordRequired": "La contraseña es obligatoria",
"signInFailed": "Error al iniciar sesión",
"googleSignInFailed": "Error al iniciar sesión con Google",
"signInSuccess": "Sesión iniciada correctamente. Redirigiendo...",
"googleSignInSuccess": "Sesión iniciada con Google correctamente. Redirigiendo..."
},
"register": {
"title": "Crear Cuenta",
"emailPlaceholder": "Correo electrónico",
"passwordPlaceholder": "Contraseña",
"confirmPasswordPlaceholder": "Confirmar Contraseña",
"passwordRequirements": "La contraseña debe tener al menos 8 caracteres con minúsculas, mayúsculas, números y caracteres especiales.",
"createAccountButton": "Crear Cuenta",
"creatingAccount": "Creando cuenta...",
"backToLogin": "Volver al inicio de sesión",
"showPassword": "Mostrar contraseña",
"hidePassword": "Ocultar contraseña",
"emailRequired": "El correo electrónico es obligatorio",
"passwordRequired": "La contraseña es obligatoria",
"confirmPasswordRequired": "Por favor confirma tu contraseña",
"passwordsDoNotMatch": "Las contraseñas no coinciden",
"passwordTooShort": "La contraseña debe tener al menos 8 caracteres",
"passwordStrengthError": "La contraseña debe incluir minúsculas, mayúsculas, números y caracteres especiales",
"registrationFailed": "Error en el registro",
"accountCreated": "¡Cuenta creada! Por favor revisa tu correo para verificar tu cuenta."
},
"forgotPassword": {
"titleForm": "Restablecer Contraseña",
"titleSuccess": "Correo Enviado",
"description": "Ingresa tu correo electrónico y te enviaremos un enlace para restablecer tu contraseña.",
"emailPlaceholder": "Correo electrónico",
"sendResetLinkButton": "Enviar Enlace",
"sending": "Enviando...",
"backToLogin": "Volver al inicio de sesión",
"resendEmail": "Reenviar correo",
"successMessage": "Hemos enviado un enlace de restablecimiento a {email}. Por favor revisa tu bandeja de entrada.",
"emailRequired": "El correo electrónico es obligatorio",
"sendFailed": "No se pudo enviar el correo"
}
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Connexion",
"subtitle": "Connectez-vous avec votre compte Mana",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Mot de passe",
"rememberMe": "Se souvenir de moi",
"forgotPassword": "Mot de passe oublié ?",
"signInButton": "Se connecter",
"signingIn": "Connexion...",
"success": "Succès !",
"orDivider": "ou",
"noAccount": "Pas encore de compte ?",
"createAccount": "Créer un compte",
"skipToForm": "Aller au formulaire de connexion",
"showPassword": "Afficher le mot de passe",
"hidePassword": "Masquer le mot de passe",
"emailRequired": "L'email est requis",
"emailInvalid": "Veuillez entrer une adresse email valide",
"passwordRequired": "Le mot de passe est requis",
"signInFailed": "Échec de la connexion",
"googleSignInFailed": "Échec de la connexion Google",
"signInSuccess": "Connexion réussie. Redirection...",
"googleSignInSuccess": "Connexion Google réussie. Redirection..."
},
"register": {
"title": "Créer un compte",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Mot de passe",
"confirmPasswordPlaceholder": "Confirmer le mot de passe",
"passwordRequirements": "Le mot de passe doit contenir au moins 8 caractères avec des minuscules, majuscules, chiffres et caractères spéciaux.",
"createAccountButton": "Créer un compte",
"creatingAccount": "Création du compte...",
"backToLogin": "Retour à la connexion",
"showPassword": "Afficher le mot de passe",
"hidePassword": "Masquer le mot de passe",
"emailRequired": "L'email est requis",
"passwordRequired": "Le mot de passe est requis",
"confirmPasswordRequired": "Veuillez confirmer votre mot de passe",
"passwordsDoNotMatch": "Les mots de passe ne correspondent pas",
"passwordTooShort": "Le mot de passe doit contenir au moins 8 caractères",
"passwordStrengthError": "Le mot de passe doit contenir des minuscules, majuscules, chiffres et caractères spéciaux",
"registrationFailed": "Échec de l'inscription",
"accountCreated": "Compte créé ! Veuillez vérifier votre email pour activer votre compte."
},
"forgotPassword": {
"titleForm": "Réinitialiser le mot de passe",
"titleSuccess": "Email envoyé",
"description": "Entrez votre adresse email et nous vous enverrons un lien pour réinitialiser votre mot de passe.",
"emailPlaceholder": "Email",
"sendResetLinkButton": "Envoyer le lien",
"sending": "Envoi en cours...",
"backToLogin": "Retour à la connexion",
"resendEmail": "Renvoyer l'email",
"successMessage": "Nous avons envoyé un lien de réinitialisation à {email}. Veuillez vérifier votre boîte de réception.",
"emailRequired": "L'email est requis",
"sendFailed": "Impossible d'envoyer l'email"
}
}

View file

@ -0,0 +1,123 @@
/**
* Auth translations exports
*/
import en from './en.json';
import de from './de.json';
import it from './it.json';
import fr from './fr.json';
import es from './es.json';
export { en, de, it, fr, es };
/**
* Auth translations type structure
*/
export interface AuthTranslations {
login: {
title: string;
subtitle: string;
emailPlaceholder: string;
passwordPlaceholder: string;
rememberMe: string;
forgotPassword: string;
signInButton: string;
signingIn: string;
success: string;
orDivider: string;
noAccount: string;
createAccount: string;
skipToForm: string;
showPassword: string;
hidePassword: string;
emailRequired: string;
emailInvalid: string;
passwordRequired: string;
signInFailed: string;
googleSignInFailed: string;
signInSuccess: string;
googleSignInSuccess: string;
};
register: {
title: string;
emailPlaceholder: string;
passwordPlaceholder: string;
confirmPasswordPlaceholder: string;
passwordRequirements: string;
createAccountButton: string;
creatingAccount: string;
backToLogin: string;
showPassword: string;
hidePassword: string;
emailRequired: string;
passwordRequired: string;
confirmPasswordRequired: string;
passwordsDoNotMatch: string;
passwordTooShort: string;
passwordStrengthError: string;
registrationFailed: string;
accountCreated: string;
};
forgotPassword: {
titleForm: string;
titleSuccess: string;
description: string;
emailPlaceholder: string;
sendResetLinkButton: string;
sending: string;
backToLogin: string;
resendEmail: string;
successMessage: string;
emailRequired: string;
sendFailed: string;
};
}
/**
* Supported auth locales
*/
export type AuthLocale = 'en' | 'de' | 'it' | 'fr' | 'es';
/**
* All auth translations by locale
*/
export const authTranslations: Record<AuthLocale, AuthTranslations> = {
en,
de,
it,
fr,
es
};
/**
* Get auth translations by locale
*/
export function getAuthTranslations(locale: string): AuthTranslations {
const supportedLocale = locale as AuthLocale;
if (supportedLocale in authTranslations) {
return authTranslations[supportedLocale];
}
// Default to English
return authTranslations.en;
}
/**
* Get login translations for a specific locale
*/
export function getLoginTranslations(locale: string): AuthTranslations['login'] {
return getAuthTranslations(locale).login;
}
/**
* Get register translations for a specific locale
*/
export function getRegisterTranslations(locale: string): AuthTranslations['register'] {
return getAuthTranslations(locale).register;
}
/**
* Get forgot password translations for a specific locale
*/
export function getForgotPasswordTranslations(locale: string): AuthTranslations['forgotPassword'] {
return getAuthTranslations(locale).forgotPassword;
}

View file

@ -0,0 +1,59 @@
{
"login": {
"title": "Accedi",
"subtitle": "Accedi con il tuo account Mana",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"rememberMe": "Ricordami",
"forgotPassword": "Password dimenticata?",
"signInButton": "Accedi",
"signingIn": "Accesso in corso...",
"success": "Successo!",
"orDivider": "oppure",
"noAccount": "Non hai un account?",
"createAccount": "Creane uno",
"skipToForm": "Vai al modulo di accesso",
"showPassword": "Mostra password",
"hidePassword": "Nascondi password",
"emailRequired": "L'email è obbligatoria",
"emailInvalid": "Inserisci un indirizzo email valido",
"passwordRequired": "La password è obbligatoria",
"signInFailed": "Accesso fallito",
"googleSignInFailed": "Accesso con Google fallito",
"signInSuccess": "Accesso effettuato. Reindirizzamento...",
"googleSignInSuccess": "Accesso con Google effettuato. Reindirizzamento..."
},
"register": {
"title": "Crea Account",
"emailPlaceholder": "Email",
"passwordPlaceholder": "Password",
"confirmPasswordPlaceholder": "Conferma Password",
"passwordRequirements": "La password deve contenere almeno 8 caratteri con minuscole, maiuscole, numeri e caratteri speciali.",
"createAccountButton": "Crea Account",
"creatingAccount": "Creazione account...",
"backToLogin": "Torna al login",
"showPassword": "Mostra password",
"hidePassword": "Nascondi password",
"emailRequired": "L'email è obbligatoria",
"passwordRequired": "La password è obbligatoria",
"confirmPasswordRequired": "Conferma la tua password",
"passwordsDoNotMatch": "Le password non corrispondono",
"passwordTooShort": "La password deve contenere almeno 8 caratteri",
"passwordStrengthError": "La password deve contenere minuscole, maiuscole, numeri e caratteri speciali",
"registrationFailed": "Registrazione fallita",
"accountCreated": "Account creato! Controlla la tua email per verificare il tuo account."
},
"forgotPassword": {
"titleForm": "Reimposta Password",
"titleSuccess": "Email Inviata",
"description": "Inserisci il tuo indirizzo email e ti invieremo un link per reimpostare la password.",
"emailPlaceholder": "Email",
"sendResetLinkButton": "Invia Link",
"sending": "Invio in corso...",
"backToLogin": "Torna al login",
"resendEmail": "Invia di nuovo",
"successMessage": "Abbiamo inviato un link per reimpostare la password a {email}. Controlla la tua casella di posta.",
"emailRequired": "L'email è obbligatoria",
"sendFailed": "Impossibile inviare l'email"
}
}