Compare commits

...

25 Commits

Author SHA1 Message Date
da676718d1 Merge pull request 'feature/pwa_init' (#2) from feature/pwa_init into develop
Reviewed-on: #2
2026-04-26 11:27:10 +00:00
88b9f5c387 build and format 2026-04-22 08:59:26 +03:30
aace4da04a Merge branch 'develop' 2026-04-22 08:58:01 +03:30
e05a2061c4 add pwa config 2026-04-22 08:56:11 +03:30
7b224c6158 Merge pull request 'feature/components' (#5) from feature/components into develop
Reviewed-on: Ruya/frontend#5
2026-04-21 11:58:52 +00:00
f5f0c63f67 Merge pull request 'feature/components' (#1) from feature/components into develop
Reviewed-on: #1
2026-04-20 12:44:34 +00:00
c14a8a6b5a updated color pallette 2026-04-20 16:12:37 +03:30
cf2093bf34 fixed fa direction for multi language feature 2026-04-20 16:02:15 +03:30
051a3a7d39 updated button interactions 2026-04-20 15:37:36 +03:30
896c812390 created a placeholder PrimaryButton 2026-04-18 10:54:27 +03:30
b312df8151 implemented primary button component 2026-04-18 10:42:55 +03:30
b59a58f8f9 deleted logs 2026-04-15 12:58:15 +03:30
f915213c16 fixed multi language 2026-04-15 12:55:25 +03:30
817bad53ec Merge branch 'develop' of https://git.witel.ir/witel-flix/frontend into develop 2026-04-15 12:49:03 +03:30
415d794147 [wip] implementing multi language 2026-04-15 12:40:43 +03:30
de9457cb80 Merge pull request 'feature/prettier' (#4) from feature/prettier into develop
Reviewed-on: witel-flix/frontend#4
2026-04-15 08:20:44 +00:00
fee71ef99f add pwa config 2026-04-15 11:50:15 +03:30
d163d2c23f add prettier 2026-04-15 11:28:33 +03:30
e37f76ca5a Merge pull request 'implemented theme management' (#3) from feature/theme_management into develop
Reviewed-on: witel-flix/frontend#3
2026-04-15 07:48:12 +00:00
e587a7f6cc implemented theme management 2026-04-15 11:15:15 +03:30
9fb168e888 Merge pull request 'feature/install_packages' (#2) from feature/install_packages into develop
Reviewed-on: witel-flix/frontend#2
2026-04-13 11:26:09 +00:00
e53eda355f added general theme colors to global css 2026-04-13 14:49:40 +03:30
6e6575bf02 installed packages 2026-04-13 13:47:45 +03:30
aaecdbfccd updated configs and global css 2026-04-13 13:28:24 +03:30
0cae4c1902 updated ignore files 2026-04-13 13:23:31 +03:30
45 changed files with 1112 additions and 116 deletions

View File

@@ -1 +1,2 @@
node_modules
node_modules
.next

View File

@@ -0,0 +1,3 @@
NEXT_PUBLIC_VAPID_PUBLIC_KEY=BBVuTTKBNkLp2WCh0mXH-Biy8A50XlAvCcHU5tEJFfuUIDEdKg4gw_evU08KLAGJzgC8iurciHX8Ac_VclRDrJE
VAPID_PRIVATE_KEY=7RHcigeLtd48aZReOYVGrQ-KCin1tWMtIwDSqNuM7F8
VAPID_SUBJECT_EMAIL="mailto:witel@info.com"

1
.gitignore vendored
View File

@@ -1,6 +1,7 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.idea
/package-lock.json
/.pnp

14
.prettierrc Normal file
View File

@@ -0,0 +1,14 @@
{
"plugins": ["prettier-plugin-tailwindcss"],
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"arrowParens": "always",
"endOfLine": "crlf"
}

View File

@@ -0,0 +1 @@
Hello from docker ReadMe

View File

@@ -1,16 +1,16 @@
services:
witelflix-front:
image: witelflix:${VERSION}
container_name: witelflix
# build: #just if we have internet uncomment
# context: .
# dockerfile: Dockerfile
ports:
- "3000:3000"
env_file:
- .env
restart: unless-stopped
# volumes:
# - .:/app # کل پروژه mount شده به /app در کانتینر
# - /app/node_modules # node_modules داخل کانتینر بماند تا با host override نشود
# - /app/.next # next داخل کانتینر بماند تا با host override نشود
services:
witelflix-front:
image: witelflix:${VERSION}
container_name: witelflix
# build: #just if we have internet uncomment
# context: .
# dockerfile: Dockerfile
ports:
- "3000:3000"
env_file:
- .env
restart: unless-stopped
# volumes:
# - .:/app # کل پروژه mount شده به /app در کانتینر
# - /app/node_modules # node_modules داخل کانتینر بماند تا با host override نشود
# - /app/.next # next داخل کانتینر بماند تا با host override نشود

5
messages/ar.json Normal file
View File

@@ -0,0 +1,5 @@
{
"Home": {
"title": "مرحبا"
}
}

5
messages/en.json Normal file
View File

@@ -0,0 +1,5 @@
{
"Home": {
"title": "hello"
}
}

5
messages/fa.json Normal file
View File

@@ -0,0 +1,5 @@
{
"Home": {
"title": "سلام"
}
}

5
messages/ku.json Normal file
View File

@@ -0,0 +1,5 @@
{
"Home": {
"title": "مرحبا"
}
}

2
next-env.d.ts vendored
View File

@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

15
next.config.ts Normal file
View File

@@ -0,0 +1,15 @@
import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin";
const withNextIntl = createNextIntlPlugin();
const nextConfig: NextConfig = {
// output : "standalone",
images: {
remotePatterns: [],
},
};
const configWithIntl = withNextIntl(nextConfig);
export default configWithIntl;

View File

@@ -1,23 +1,50 @@
{
"name": "witelflix",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "16.1.6",
"react": "19.2.4",
"react-dom": "19.2.4"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.18",
"@types/node": "25.0.10",
"@types/react": "19.2.10",
"@types/react-dom": "19.2.3",
"postcss": "8.5.6",
"tailwindcss": "4.1.18",
"typescript": "5.9.3"
}
}
{
"name": "ruya",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"format": "npx prettier . --write"
},
"dependencies": {
"@types/js-cookie": "^3.0.6",
"@types/web-push": "^3.6.4",
"axios": "^1.15.0",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"date-fns-jalali": "4.1.0-0",
"embla-carousel": "^8.6.0",
"embla-carousel-autoplay": "^8.6.0",
"embla-carousel-react": "^8.6.0",
"framer-motion": "^12.38.0",
"js-cookie": "^3.0.5",
"lucide-react": "^1.8.0",
"next": "16.1.6",
"next-intl": "^4.9.1",
"next-pwa": "^5.6.0",
"next-sitemap": "^4.2.3",
"next-themes": "^0.4.6",
"nextjs-toploader": "^3.9.17",
"prettier": "^3.8.2",
"prettier-plugin-tailwindcss": "^0.7.2",
"radix-ui": "^1.4.3",
"react": "19.2.4",
"react-dom": "19.2.4",
"react-hook-form": "^7.72.1",
"react-hot-toast": "^2.6.0",
"tailwind-merge": "^3.5.0",
"tailwind-scrollbar": "^4.0.2",
"web-push": "^3.6.7",
"zustand": "^5.0.12"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.18",
"@types/node": "25.0.10",
"@types/react": "19.2.10",
"@types/react-dom": "19.2.3",
"postcss": "8.5.6",
"tailwindcss": "4.1.18",
"typescript": "5.9.3"
}
}

View File

@@ -1,6 +1,5 @@
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};

BIN
public/logo/144px.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

BIN
public/logo/152px.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

BIN
public/logo/192px.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

BIN
public/logo/384px.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
public/logo/512px.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@@ -0,0 +1,38 @@
{
"id": "/",
"name": "Ru'ya",
"short_name": "Ru'ya",
"description": "Ru'ya",
"start_url": "/",
"display": "standalone",
"orientation": "portrait",
"theme_color": "#283618",
"background_color": "#ffffff",
"icons": [
{
"src": "logo/144px.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "logo/152px.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "logo/192px.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "logo/384px.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "logo/512px.png",
"sizes": "512x512",
"type": "image/png"
}
]
}

10
public/offline.html Normal file
View File

@@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<title>Offline</title>
</head>
<body>
<h1>You are offline</h1>
<p>Please check your connection.</p>
</body>
</html>

77
public/sw.js Normal file
View File

@@ -0,0 +1,77 @@
const CACHE_NAME = "141-cache-v2";
const STATIC_ASSETS = ["/", "/manifest.webmanifest", "/logo/192px.png", "/logo/512px.png"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
await Promise.allSettled(
STATIC_ASSETS.map(async (url) => {
try {
const response = await fetch(url);
if (response.ok) {
await cache.put(url, response);
}
} catch (e) {
console.warn("❌ Failed to cache:", url);
}
})
);
})
);
self.skipWaiting();
});
const sendDeliveryReportAction = () => {
console.log("Web push delivered.");
};
self.addEventListener("push", function (event) {
if (event.data) {
try {
// Try to parse as JSON first
let data;
try {
data = event.data.json();
} catch (jsonError) {
// If JSON parsing fails, treat it as plain text
const text = event.data.text();
data = {
title: "Notification",
body: text,
icon: "/icon.png",
};
}
const options = {
body: data.body || "Default notification body",
icon: data.icon || "/logo/192px.png",
badge: "/badge.png",
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: "2",
url: data.url || "/",
},
};
event.waitUntil(
self.registration.showNotification(data.title, options).then(() => {
sendDeliveryReportAction();
})
);
} catch (error) {
console.error("Error processing push notification:", error);
}
}
});
self.addEventListener("notificationclick", function (event) {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});

View File

@@ -0,0 +1,80 @@
import { getDirection } from "@/i18n/direction";
import { routing } from "@/i18n/routing";
import { ClientAppProvider } from "@/providers/ClientAppProvider";
import "@/styles/globals.css";
import type { Metadata } from "next";
import { hasLocale, NextIntlClientProvider } from "next-intl";
import { getMessages } from "next-intl/server";
import { notFound } from "next/navigation";
export const metadata: Metadata = {
title: {
template: "%s | Ru'ya",
default: "Ru'ya",
},
description: "Ru'ya",
appleWebApp: {
capable: true, // 🔴 REQUIRED for iOS standalone mode
statusBarStyle: "black-translucent",
title: "Ru'ya",
},
applicationName: "Ru'ya",
authors: {
name: "شرکت دانش بنیان ویرا ارتباطات یکتا تلفن (وایتل)",
url: "https://witel.ir",
},
manifest: "/manifest.webmanifest",
icons: {
icon: "/logo/192px.png",
apple: "/logo/512px.png",
},
};
export const viewport = {
width: "device-width",
initialScale: 1,
maximumScale: 1,
};
export default async function RootLayout({
children,
params,
}: Readonly<{
children: React.ReactNode;
params: Promise<{ locale: string }>;
}>) {
const { locale } = await params;
if (!hasLocale(routing.locales, locale)) {
notFound();
}
const messages = await getMessages();
const dir = getDirection(locale);
return (
<html dir={dir} lang={locale} suppressHydrationWarning>
<head>
{/* Prevent theme flicker before hydration */}
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
const stored = localStorage.getItem('theme');
const theme = stored || 'dark';
document.documentElement.setAttribute('data-theme', theme);
} catch (e) {}
})();
`,
}}
/>
</head>
<body className="bg-background">
<NextIntlClientProvider locale={locale} messages={messages}>
<ClientAppProvider>{children}</ClientAppProvider>
</NextIntlClientProvider>
</body>
</html>
);
}

13
src/app/[locale]/page.tsx Normal file
View File

@@ -0,0 +1,13 @@
import ComponentsConteiner from "@/components/ComponentsConteiner";
import { useTranslations } from "next-intl";
export default function Home() {
const t = useTranslations("Home");
return (
<main>
<h1>{t("title")}</h1>
<p>This project was generated completely offline.</p>
<ComponentsConteiner />
</main>
);
}

View File

@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
let notifications = [
{
id: 1,
title: "خوش آمدید",
body: "این یک نوتیفیکیشن تستی است",
type: "info",
created_at: new Date().toISOString(),
},
{
id: 2,
title: "پرداخت موفق",
body: "پرداخت شما با موفقیت انجام شد",
type: "success",
created_at: new Date().toISOString(),
},
];
export async function GET() {
return NextResponse.json(notifications);
}

View File

@@ -0,0 +1,41 @@
import { NextRequest } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(req: NextRequest) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
let counter = 3;
const interval = setInterval(() => {
const data = {
id: counter,
title: `نوتیفیکیشن جدید ${counter}`,
body: "این پیام از SSE اومده",
type: ["info", "success", "warning", "error"][counter % 4],
created_at: new Date().toISOString(),
};
const payload = `data: ${JSON.stringify(data)}\n\n`;
controller.enqueue(encoder.encode(payload));
counter++;
}, 5000);
req.signal.addEventListener("abort", () => {
clearInterval(interval);
controller.close();
});
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}

View File

@@ -0,0 +1,175 @@
import { NextRequest, NextResponse } from "next/server";
import webpush from "web-push";
// Initialize VAPID keys
webpush.setVapidDetails(
process.env.VAPID_SUBJECT_EMAIL!,
process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!,
process.env.VAPID_PRIVATE_KEY!
);
// Define the subscription type that matches what web-push expects
interface WebPushSubscription {
endpoint: string;
keys: {
p256dh: string;
auth: string;
};
}
// Store subscriptions in memory with user IDs
// In production, replace this with Redis or a database
const userSubscriptions: Map<string, WebPushSubscription> = new Map();
// Save subscription for a specific user
async function saveUserSubscription(userId: string, subscription: WebPushSubscription) {
userSubscriptions.set(userId, subscription);
// In production: save to Redis/Database
// await redis.set(`push:${userId}`, JSON.stringify(subscription));
}
// Get subscription for a specific user
async function getUserSubscription(userId: string): Promise<WebPushSubscription | null> {
return userSubscriptions.get(userId) || null;
// In production: get from Redis/Database
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// Handle different actions
const { action, userId, subscription, title, message, icon, url } = body;
// Action 1: Register/update subscription for a user
if (action === "register") {
if (!userId || !subscription) {
return NextResponse.json({ error: "userId and subscription are required" }, { status: 400 });
}
// Validate subscription has required fields
if (!subscription.endpoint || !subscription.keys || !subscription.keys.p256dh || !subscription.keys.auth) {
return NextResponse.json(
{ error: "Invalid subscription format - missing endpoint or keys" },
{ status: 400 }
);
}
const webPushSubscription: WebPushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth,
},
};
await saveUserSubscription(userId, webPushSubscription);
return NextResponse.json({
success: true,
message: `Subscription registered for user ${userId}`,
});
}
// Action 2: Send notification to a specific user
if (action === "send") {
if (!userId) {
return NextResponse.json({ error: "userId is required" }, { status: 400 });
}
const userSubscription = await getUserSubscription(userId);
if (!userSubscription) {
return NextResponse.json({ error: `No subscription found for user ${userId}` }, { status: 404 });
}
const payload = JSON.stringify({
title: title || "Notification",
body: message || "You have a new notification",
icon: icon || "/logo/192px.png",
badge: "/badge.png",
vibrate: [100, 50, 100],
data: {
url: url || "/",
dateOfArrival: Date.now(),
},
});
// Send notification using web-push
await webpush.sendNotification(userSubscription, payload);
return NextResponse.json({
success: true,
message: `Notification sent to user ${userId}`,
});
}
// Action 3: Send to multiple users
if (action === "send-multiple") {
const { userIds, title, message, icon, url } = body;
if (!userIds || !Array.isArray(userIds)) {
return NextResponse.json({ error: "userIds array is required" }, { status: 400 });
}
const results = [];
for (const uid of userIds) {
const userSubscription = await getUserSubscription(uid);
if (userSubscription) {
try {
const payload = JSON.stringify({
title: title || "Notification",
body: message || "You have a new notification",
icon: icon || "/logo/192px.png",
badge: "/badge.png",
data: { url: url || "/" },
});
await webpush.sendNotification(userSubscription, payload);
results.push({ userId: uid, status: "success" });
} catch (error) {
results.push({
userId: uid,
status: "failed",
error: error instanceof Error ? error.message : String(error),
});
}
} else {
results.push({ userId: uid, status: "no_subscription" });
}
}
return NextResponse.json({
success: true,
results,
});
}
return NextResponse.json({ error: "Invalid action. Use: register, send, or send-multiple" }, { status: 400 });
} catch (error) {
console.error("Error in push API:", error);
return NextResponse.json(
{ error: "Internal server error", details: error instanceof Error ? error.message : String(error) },
{ status: 500 }
);
}
}
// GET endpoint to check if a user is subscribed
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const userId = searchParams.get("userId");
if (!userId) {
return NextResponse.json({ error: "userId required" }, { status: 400 });
}
const subscription = await getUserSubscription(userId);
return NextResponse.json({
userId,
isSubscribed: !!subscription,
});
}

View File

@@ -1 +0,0 @@
@import "tailwindcss";

View File

@@ -1,19 +0,0 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Offline App",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}

39
src/app/not-found.tsx Normal file
View File

@@ -0,0 +1,39 @@
import Link from "next/link";
export default function NotFound() {
return (
<div className="bg-pwa-primary text-text flex min-h-screen items-center justify-center">
<div className="bg-pwa-primary mx-4 w-full max-w-md rounded-xl p-8 text-center">
{/* آیکون خطا */}
{/*<div className="mb-4 flex justify-center">*/}
{/* <svg*/}
{/* xmlns="http://www.w3.org/2000/svg"*/}
{/* className="h-16 w-16 text-core-red"*/}
{/* fill="none"*/}
{/* viewBox="0 0 24 24"*/}
{/* stroke="currentColor"*/}
{/* >*/}
{/* <path*/}
{/* strokeLinecap="round"*/}
{/* strokeLinejoin="round"*/}
{/* strokeWidth={2}*/}
{/* d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"*/}
{/* />*/}
{/* </svg>*/}
{/*</div>*/}
{/* متن خطا */}
<h2 className="text-text mb-2 text-2xl font-bold">صفحه مورد نظر یافت نشد</h2>
<p className="text-text mb-6 leading-relaxed">متاسفانه صفحهای مورد نظر وجود ندارد.</p>
{/* دکمه بازگشت با استفاده از کامپوننت Link */}
<Link
href="/"
className="bg-neo-aqua hover:bg-neo-aqua/70 inline-block rounded-lg px-6 py-3 font-medium text-white shadow-md transition-colors duration-200 hover:shadow-lg"
>
بازگشت به صفحه اصلی
</Link>
</div>
</div>
);
}

View File

@@ -1,9 +0,0 @@
export default function Home() {
return (
<main style={{ padding: 40 }}>
<h1>Offline Next.js Template 🚀</h1>
<p>This project was generated completely offline.</p>
</main>
);
}

View File

@@ -0,0 +1,27 @@
"use client";
import { useState } from "react";
import PrimaryButton from "./buttons/PrimaryButton";
import ThemeToggle from "./UI/ThemeToggle";
import { Home } from "lucide-react";
export default function ComponentsConteiner() {
const [isLoading, setIsloading] = useState(false);
function dummyLoading() {
setIsloading(true);
setTimeout(() => {
setIsloading(false);
}, 1500);
}
return (
<div className="flex flex-col items-start gap-2 p-4">
<ThemeToggle />
<div className="w-36">
<PrimaryButton onClick={() => dummyLoading()} loading={isLoading}>
<Home size={20} />
<p>test icon</p>
</PrimaryButton>
</div>
</div>
);
}

View File

@@ -0,0 +1,139 @@
"use client";
import { useEffect } from "react";
function urlBase64ToUint8Array(base64String: string) {
// Add padding if needed
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function getUserId(): string {
let userId = localStorage.getItem("push_user_id");
if (!userId) {
userId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
localStorage.setItem("push_user_id", userId);
}
return userId;
}
function arrayBufferToBase64(buffer: ArrayBuffer | null): string {
if (!buffer) return "";
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
export default function AutoPushManager() {
useEffect(() => {
const initPush = async () => {
if (!("serviceWorker" in navigator && "PushManager" in window)) {
console.log("Push not supported");
return;
}
try {
// Register service worker
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
updateViaCache: "none",
});
await navigator.serviceWorker.ready;
console.log("Service worker ready");
// Check existing subscription
let subscription = await registration.pushManager.getSubscription();
if (subscription) {
console.log("Already subscribed");
// Still register with backend
const subscriptionObj = {
endpoint: subscription.endpoint,
keys: {
p256dh: arrayBufferToBase64(subscription.getKey("p256dh")),
auth: arrayBufferToBase64(subscription.getKey("auth")),
},
};
await fetch("/api/push-notifications", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "register",
userId: getUserId(),
subscription: subscriptionObj,
}),
});
console.log("Push notifications already ready!");
return;
}
// Check permission status
console.log("Current permission:", Notification.permission);
if (Notification.permission === "denied") {
console.log("Notifications are blocked. Please enable them in browser settings.");
return;
}
// Request permission (this shows the browser prompt)
console.log("Requesting permission...");
const permission = await Notification.requestPermission();
console.log("Permission result:", permission);
if (permission === "granted") {
console.log("Creating subscription...");
// This might still take a moment, but should complete
subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!),
});
console.log("Subscription created:", subscription);
const subscriptionObj = {
endpoint: subscription.endpoint,
keys: {
p256dh: arrayBufferToBase64(subscription.getKey("p256dh")),
auth: arrayBufferToBase64(subscription.getKey("auth")),
},
};
await fetch("/api/push-notifications", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "register",
userId: getUserId(),
subscription: subscriptionObj,
}),
});
console.log("Push notifications ready! User ID:", getUserId());
} else {
console.log("Notification permission not granted:", permission);
}
} catch (error) {
console.error("Push error:", error);
}
};
// Add a small delay to ensure everything is loaded
setTimeout(initPush, 1000);
}, []);
return null;
}

View File

@@ -0,0 +1,26 @@
"use client";
import { motion } from "framer-motion";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
export default function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
className="flex cursor-pointer items-center py-2"
>
<motion.div
key={theme}
initial={{ rotate: -90, opacity: 0 }}
animate={{ rotate: 0, opacity: 1 }}
exit={{ rotate: 90, opacity: 0 }}
transition={{ duration: 0.5, ease: "easeInOut" }}
>
{theme === "dark" ? <Moon className="text-text size-6" /> : <Sun className="text-text size-6" />}
</motion.div>
</button>
);
}

View File

@@ -0,0 +1,69 @@
"use client";
import { cn } from "@/lib/utils";
import { AnimatePresence, motion } from "framer-motion";
import { LoaderPinwheel } from "lucide-react";
type PrimaryButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
loading?: boolean;
children: React.ReactNode;
};
export default function PrimaryButton({ children, loading, className, onClick }: PrimaryButtonProps) {
return (
<button
onClick={onClick}
className={cn(
"bg-primary grid w-full place-items-center overflow-hidden rounded-xl px-4 py-2 text-white hover:scale-102 active:scale-98",
className
)}
>
<AnimatePresence mode="wait">
{loading ? (
<motion.div
key={"loading"}
initial={{
opacity: 0,
x: -80,
}}
animate={{
opacity: 1,
x: 0,
}}
exit={{
opacity: 0,
x: -80,
}}
transition={{
duration: 0.2,
}}
>
<LoaderPinwheel className="animate-spin" />
</motion.div>
) : (
<motion.div
key="content"
initial={{
opacity: 0,
x: 80,
}}
animate={{
opacity: 1,
x: 0,
}}
exit={{
opacity: 0,
x: 80,
}}
transition={{
duration: 0.2,
}}
className="flex items-center justify-center gap-2"
>
{children}
</motion.div>
)}
</AnimatePresence>
</button>
);
}

12
src/i18n/direction.ts Normal file
View File

@@ -0,0 +1,12 @@
export type Direction = "ltr" | "rtl";
export const localeDirectionMap: Record<string, Direction> = {
en: "ltr",
ar: "rtl",
ku: "rtl",
fa: "rtl",
};
export function getDirection(locale: string): Direction {
return localeDirectionMap[locale] ?? "ltr";
}

4
src/i18n/navigation.ts Normal file
View File

@@ -0,0 +1,4 @@
import { createNavigation } from "next-intl/navigation";
import { routing } from "./routing";
export const { Link, redirect, usePathname, useRouter, getPathname } = createNavigation(routing);

13
src/i18n/request.ts Normal file
View File

@@ -0,0 +1,13 @@
import { getRequestConfig } from "next-intl/server";
import { hasLocale } from "next-intl";
import { routing } from "./routing";
export default getRequestConfig(async ({ requestLocale }) => {
const requested = await requestLocale;
const locale = hasLocale(routing.locales, requested) ? requested : routing.defaultLocale;
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default,
};
});

7
src/i18n/routing.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineRouting } from "next-intl/routing";
export const routing = defineRouting({
locales: ["en", "ar", "ku", "fa"],
defaultLocale: "en",
localePrefix: "never",
});

9
src/i18n/useDirection.ts Normal file
View File

@@ -0,0 +1,9 @@
"use client";
import { useLocale } from "next-intl";
import { Direction, getDirection } from "./direction";
export function useDirection(): Direction {
const locale = useLocale();
return getDirection(locale);
}

6
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

View File

@@ -0,0 +1,60 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { ThemeProvider } from "next-themes";
import { useEffect, useState } from "react";
export function ClientAppProvider({ children }: { children: React.ReactNode }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
if ("serviceWorker" in navigator) {
const registerSW = async () => {
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
updateViaCache: "none",
});
console.log("Service Worker registered successfully:", registration);
} catch (error) {
console.error("Service Worker registration failed:", error);
}
};
// Register on page load and after navigation
registerSW();
window.addEventListener("load", registerSW);
}
}, []);
// wait for hydration
useEffect(() => {
setMounted(true);
}, []);
return (
<ThemeProvider attribute="data-theme" defaultTheme="dark" enableSystem={false}>
<AnimatePresence mode="wait">
{!mounted ? (
<motion.div
key="splash"
className="bg-map-bg flex h-dvh w-dvw items-center justify-center"
initial={{ opacity: 1 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
) : (
<motion.div
key="app"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3, ease: "easeOut" }}
className="bg-map-bg"
>
{children}
</motion.div>
)}
</AnimatePresence>
</ThemeProvider>
);
}

8
src/proxy.ts Normal file
View File

@@ -0,0 +1,8 @@
import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
export default createMiddleware(routing);
export const config = {
matcher: "/((?!api|trpc|_next|_vercel|.*\\..*).*)",
};

81
src/styles/globals.css Normal file
View File

@@ -0,0 +1,81 @@
@import "tailwindcss";
*,
*::before,
*::after,
*::-webkit-scrollbar {
box-sizing: border-box;
}
* {
-ms-overflow-style: none;
scrollbar-width: none;
transition:
background-color 0.3s ease,
color 0.3s ease,
border-color 0.3s ease;
}
*::-webkit-scrollbar {
display: none;
}
body {
margin: 0;
}
button {
cursor: pointer;
}
@theme {
/* Core */
--color-background: #f4f6f8;
--color-text: #1e242e;
/* Brand */
--color-primary: #2a7fff;
--color-secondary: #64748b;
--color-accent: #ff6b3d;
/* Feedback */
--color-warning: #f5c04f;
--color-information: #3abff8;
--color-error: #ef5350;
--color-success: #4ade80;
/* Surfaces */
--color-surface: #ffffff;
--color-surface-alt: #e9eef2;
--color-border: #d4d9df;
--color-muted-text: #6c7480;
/* Overlays */
--color-overlay-light: rgba(0, 0, 0, 0.05);
--color-overlay-medium: rgba(0, 0, 0, 0.15);
--color-overlay-strong: rgba(0, 0, 0, 0.35);
/* Gradients */
--gradient-primary: linear-gradient(135deg, #2a7fff, #1a5fd1);
--gradient-accent: linear-gradient(135deg, #ff6b3d, #ff784d);
}
[data-theme="dark"] {
--color-background: #1a1f27;
--color-text: #e5e9f0;
--color-secondary: #94a3b8;
--color-accent: #ff8a5c;
--color-surface: #232833;
--color-surface-alt: #2c323e;
--color-border: #3a404c;
--color-muted-text: #a6aebc;
--color-overlay-light: rgba(255, 255, 255, 0.05);
--color-overlay-medium: rgba(255, 255, 255, 0.12);
--color-overlay-strong: rgba(255, 255, 255, 0.25);
--gradient-primary: linear-gradient(135deg, #63a6ff, #3d7dce);
--gradient-accent: linear-gradient(135deg, #ff8a5c, #ff9c75);
}

View File

@@ -1,40 +1,28 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"strict": true,
"noEmit": true,
"module": "esnext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"paths": {
"@/*": ["./src/*"],
"&/*": ["./public/*"]
},
"exclude": [
"node_modules"
]
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"],
"&/*": ["./public/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
"exclude": ["node_modules"]
}