13 Commits
Author SHA1 Message Date
ahp 924cb52a38 release v0.4.0: bump image tags and chart appVersion
build-and-push / build (push) Successful in 4m15s
2026-10-20 17:53:19 +03:30
ahp 3c5a32394d chore(infra): update dev compose, add playwright e2e suite & assets 2026-10-20 17:51:23 +03:30
ahp f6ce2bd340 refactor(video-player): LTR timeline, unified buffer/progress layers, controls layout, remove ambient
- timeline: unified dir="ltr" container; buffer and progress as stacked absolute fills in correct z-order
- playhead: physical left property instead of insetInlineStart (fixes RTL mirroring)
- control bar: dir="ltr" explicit groups — left: play/rewind/volume/speed, right: theater/fullscreen
- rewind: replace flipped SkipBack with Rewind icon; seek indicator at physical right-8
- ambient effect: removed entirely (canvas, rAF loop, state, constants, toggle)
- settings menu: removed (speed accessible via pill; ambient gone)
- restart button: removed
2026-10-20 17:51:23 +03:30
ahp 96b10c9148 fix(ui): design-system consistency — typography, borders, admin IA, search removal
- typography: font-semibold/font-medium → font-bold throughout (card, dialog, empty-state, notification-bell, quiz-experience, questions-panel, profile-manage)
- borders: border → border-2 for content containers (leaderboard error, notifications page, quiz pass screen, quiz option tiles, learning-panel error)
- admin IA: remove Card-in-SectionPanel nesting from announce-panel, challenges-panel, physical-orders-panel; SectionPanel gains optional actions slot
- announce-panel: flat composer + live preview; history as flat list; cancel-edit button
- lockout: raw textarea → Textarea design-system component
- global-search: delete component and all references (feature removed)
- progress.tsx: dir="ltr" for correct RTL fill direction; remove rtl:me-auto
2026-10-20 17:51:23 +03:30
ahp 7716c1677c feat(frontend): draft/publish, certificate approval UI, contributors, leaderboard tiers
- admin-studio: chapter/lesson publish toggle with Draft/Published badges; per-chapter accordion
- cap/page: remove auto-issue effect; student requests, admin approves
- learning-panel: admin issue-certificate action per student
- site-settings: contributors editor with avatar upload (ContributorAvatarPicker, TagInput)
- community-panel: render contributors section below social links
- leaderboard-panel: TierBadge, totalParticipants, tier on entries and self
- page.tsx: fix "شروع مسیر" routing to /register instead of /login
- navbar: correct icons (Settings, Palette) in user dropdown
- types: Contributor, LeaderboardTier, Certificate status field, updated LeaderboardData/Entry
- layout: PWA icon metadata (192, 512, apple-touch-icon)
2026-10-20 17:51:23 +03:30
ahp 161610049c feat(backend): leaderboard tiers, N+1 fix, contributors, certificate approval, physical disable
- leaderboard: batch-fetch users (GetUsersByIDs), deterministic tie-break by user_id
- leaderboard: tier system (champion/gold/silver/bronze) based on rank percentile
- store: HasCompletedCurriculum requires cert.Status == "issued"; pending does not satisfy
- certificate: issueCertificateIfEligible creates pending row; admin approves via handleAdminIssueCertificate
- certificate: handleRequestPhysicalCertificate returns 410 Gone (feature disabled)
- settings: contributors CRUD (loadContributors, validateContributors, handleAdminContributorAvatarUpload)
- community: expose contributors in /api/community response
- rate_limit: separate DevMode bypass from redis-nil check in allowWSHandshake
- router: remove /api/search route; fix missing tab indent on /api/meta line
- migration 0032: contributors app_setting with seed entry
2026-10-20 17:51:22 +03:30
ahp 617d8ff680 release v0.3.9: bump frontend image tags
build-and-push / build (push) Successful in 30s
2026-10-19 19:45:14 +03:30
ahp 88c86ac810 release v0.3.9: bump image tags
build-and-push / build (push) Successful in 18s
2026-10-19 19:24:57 +03:30
ahp f59ff54256 feat: chapter labels, staff draft visibility, and chat FAB mobile fix
build-and-push / build (push) Successful in 3m27s
- Rename chapter labels from "هفتهٔ N" to "فصل N" in skill-tree
  - Show dashed "پیش‌نویس" badge on unpublished chapters/lessons for staff
  - Add isPublished to TreeLesson type (backend already exposes it)
  - Fix chat FAB and notification banner overlapping bottom nav on mobile
2026-10-19 18:41:16 +03:30
ahp 12ecbf991e release v0.3.8: chart metadata + image tags
build-and-push / build (push) Successful in 28s
- Chart 0.2.3 -> 0.2.4, appVersion 0.2.1 -> 0.3.7 (metadata labels only;
  pod templates use selectorLabels, no statefulset churn)
- values-apollo image tags 0.3.7 -> 0.3.8 (backend+frontend roll once)
2026-10-19 00:49:16 +03:30
ahp 951610cda2 chart: add backend ServiceMonitor (token-auth /metrics, off by default)
- /metrics is bearer-protected via METRICS_TOKEN; the endpoint carries
  authorization.credentials (pargar-app/metrics-token) so Prometheus
  scrapes it the same way the live probe does.
- disabled by default: plain 'helm template' renders byte-identical;
  values-apollo enables it (enabled: true, interval 30s already present).
- kube-prometheus (ns infra) selects ServiceMonitors in all namespaces;
  its operator holds cluster-wide secret read to resolve the credential.
2026-10-19 00:47:54 +03:30
ahp 943897044a fix(chart): fail loudly instead of generating random secrets on lookup miss
build-and-push / build (push) Successful in 28s
randAlphaNum fallbacks silently minted new db/redis/rustfs passwords on
every cluster-less render (always the case under Argo CD's helm
template), overwriting live credentials. Fresh installs now get a clear
error demanding explicit values; helm upgrades are unaffected (lookup
preserves existing secrets).
2026-10-18 23:20:22 +03:30
ahp 53c8c8e94c fix(deploy): imagePullSecrets items must be objects ({name: ...}), not bare strings
build-and-push / build (push) Successful in 30s
Bare string items rendered an invalid Deployment spec (LocalObjectReference
is a struct) which made Argo CD's strategic-merge patch fail with
'cannot restore struct from: string' on both Deployments.
2026-10-18 22:59:04 +03:30
73 changed files with 1998 additions and 781 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 842 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1024" height="1024" viewBox="0 0 1024 1024">
<title>Compass master</title>
<image width="1024" height="1024" href="png/1024x1024.png" xlink:href="png/1024x1024.png"/>
</svg>

After

Width:  |  Height:  |  Size: 267 B

+50
View File
@@ -0,0 +1,50 @@
package api_test
import (
"context"
"net/http"
"testing"
)
// TestPendingCertDoesNotShortCircuitCurriculumCheck ensures that a pending
// certificate does not satisfy HasCompletedCurriculum. Only an issued
// (non-revoked) certificate should bypass the lesson-completion check.
func TestPendingCertDoesNotShortCircuitCurriculumCheck(t *testing.T) {
e := setup(t)
token, uid := register(t, e, "CertPending", "cert-pending@test.dev")
admin := login(t, e, bootstrapAdminEmail)
// Forcibly create a pending certificate in the DB (simulating a student
// who triggered issueCertificateIfEligible via quiz submit).
_, err := e.pool.Exec(context.Background(),
`INSERT INTO certificates (user_id, full_name, status)
VALUES ($1, 'CertPending', 'pending')
ON CONFLICT DO NOTHING`, uid)
if err != nil {
t.Fatalf("insert pending cert: %v", err)
}
// The student has NOT passed any lessons — eligible must be false.
code, body := e.do(t, "GET", "/api/me/certificate", token, nil)
if code != http.StatusOK {
t.Fatalf("get cert: %d %v", code, body)
}
if body["eligible"] != false {
t.Fatalf("pending cert must not make student eligible; got eligible=%v", body["eligible"])
}
// Admin issues the certificate manually.
code, _ = e.do(t, "POST", "/api/admin/users/"+itoa(uid)+"/certificate/issue", admin, nil)
if code != http.StatusOK {
t.Fatalf("admin issue: %d", code)
}
// Physical order endpoint must return 410 Gone.
code, _ = e.do(t, "POST", "/api/me/certificate/physical", token, map[string]any{
"recipientName": "Test", "phone": "09123456789", "address": "addr",
"city": "tehran", "postalCode": "1234567890",
})
if code != http.StatusGone {
t.Fatalf("physical endpoint must be disabled (410), got %d", code)
}
}
+3 -1
View File
@@ -5,7 +5,9 @@ import (
)
func (s *Server) handleCommunity(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
writeJSON(w, http.StatusOK, map[string]any{
"socials": s.loadSocials(r.Context()),
"socials": s.loadSocials(ctx),
"contributors": s.loadContributors(ctx),
})
}
+8 -2
View File
@@ -95,10 +95,16 @@ func (s *Server) handleWeeklyLeaderboard(w http.ResponseWriter, r *http.Request)
return scoredList[i].userID < scoredList[j].userID
})
ids := make([]int64, len(scoredList))
for i, sc := range scoredList {
ids[i] = sc.userID
}
usersMap, _ := s.store.GetUsersByIDs(context.Background(), ids)
entries := make([]lbEntry, 0, len(scoredList))
for i, sc := range scoredList {
usr, err := s.store.GetUserByID(context.Background(), sc.userID)
if err != nil {
usr, ok := usersMap[sc.userID]
if !ok {
continue
}
s.signUserMedia(usr)
-63
View File
@@ -504,69 +504,6 @@ func (s *Server) handleMeActivity(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"days": days, "weekDays": week, "monthDays": month})
}
func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) {
q := strings.TrimSpace(r.URL.Query().Get("q"))
if utf8.RuneCountInString(q) < 2 {
writeJSON(w, http.StatusOK, map[string]any{"results": []any{}})
return
}
me := currentUser(r)
like := "%" + q + "%"
var results []map[string]any
rows, err := s.store.Pool().Query(r.Context(), `
SELECT id, title FROM lessons WHERE title ILIKE $1 ORDER BY id LIMIT 8`, like)
if err == nil {
for rows.Next() {
var id int64
var title string
if rows.Scan(&id, &title) == nil {
results = append(results, map[string]any{"kind": "lesson", "title": title, "href": "/player/" + strconv.FormatInt(id, 10)})
}
}
rows.Close()
}
rows, err = s.store.Pool().Query(r.Context(), `
SELECT id, title FROM events WHERE title ILIKE $1 ORDER BY starts_at DESC LIMIT 8`, like)
if err == nil {
for rows.Next() {
var id int64
var title string
if rows.Scan(&id, &title) == nil {
results = append(results, map[string]any{"kind": "event", "title": title, "href": "/unwrap"})
}
}
rows.Close()
}
if me.Role.IsStaff() {
people, _, _ := s.store.ListUsers(r.Context(), q, "", 8, 0)
for _, p := range people {
results = append(results, map[string]any{"kind": "person", "title": p.Name, "href": "/profile/" + strconv.FormatInt(p.ID, 10)})
}
} else {
people, _, _ := s.store.ListActiveByRoles(r.Context(), []string{"mentor", "admin"}, 40, 0)
n := 0
for _, p := range people {
if n >= 8 || !strings.Contains(strings.ToLower(p.Name), strings.ToLower(q)) {
continue
}
results = append(results, map[string]any{"kind": "person", "title": p.Name, "href": "/profile/" + strconv.FormatInt(p.ID, 10)})
n++
}
}
pages := []struct{ title, href string }{
{"درخت مهارت", "/cap"}, {"اعلان‌ها", "/notifications"}, {"لیگ", "/leaderboard"},
{"تنظیمات", "/settings"}, {"پروفایل", "/profile"},
}
for _, p := range pages {
if strings.Contains(p.title, q) {
results = append(results, map[string]any{"kind": "page", "title": p.title, "href": p.href})
}
}
if results == nil {
results = []map[string]any{}
}
writeJSON(w, http.StatusOK, map[string]any{"results": results})
}
func (s *Server) handleMeta(w http.ResponseWriter, r *http.Request) {
env := "production"
+4 -1
View File
@@ -282,8 +282,11 @@ func (s *Server) perUserRateLimit(limit int64, scope string, next http.HandlerFu
// allowWSHandshake enforces a per-IP budget on WebSocket upgrades.
// Returns false when the caller should receive 429 (already written by caller).
func (s *Server) allowWSHandshake(r *http.Request) bool {
if s.cfg.DevMode {
return true
}
if s.redis == nil {
return s.cfg.DevMode
return false
}
ip := clientAddress(r)
if ip == "" {
+1 -1
View File
@@ -106,6 +106,7 @@ func newRouter(s *Server) http.Handler {
mux.HandleFunc("POST /api/admin/users/{id}/certificate/revoke", staff(s.handleAdminRevokeCertificate))
mux.HandleFunc("GET /api/admin/settings", admin(s.handleAdminGetSettings))
mux.HandleFunc("PUT /api/admin/settings", admin(s.handleAdminPutSettings))
mux.HandleFunc("POST /api/admin/contributor-avatar", admin(s.handleAdminContributorAvatarUpload))
mux.HandleFunc("GET /api/admin/chat-export", admin(s.handleAdminChatExport))
mux.HandleFunc("GET /api/admin/chat-export/stats", admin(s.handleAdminChatExportStats))
mux.HandleFunc("POST /api/admin/chat-export/restore", admin(s.handleAdminChatExportRestore))
@@ -181,7 +182,6 @@ func newRouter(s *Server) http.Handler {
mux.HandleFunc("GET /api/me/achievements", s.requireAuth(s.handleMeAchievements))
mux.HandleFunc("GET /api/me/activity", s.requireAuth(s.handleMeActivity))
mux.HandleFunc("GET /api/me/export", s.requireAuth(s.handleMeExport))
mux.HandleFunc("GET /api/search", s.requireAuth(s.handleSearch))
mux.HandleFunc("GET /api/meta", s.handleMeta)
mux.HandleFunc("POST /api/bot/send", s.handleBotSend)
mux.HandleFunc("GET /api/bot/updates", s.handleBotUpdates)
+137
View File
@@ -3,9 +3,11 @@ package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"pargar/backend/internal/observability"
@@ -93,12 +95,138 @@ func validateSocialLinks(v string) string {
return ""
}
func (s *Server) loadContributors(ctx context.Context) []map[string]any {
raw, err := s.store.GetSetting(ctx, "contributors")
if err != nil || strings.TrimSpace(raw) == "" {
return []map[string]any{}
}
var list []map[string]any
if err := json.Unmarshal([]byte(raw), &list); err != nil {
return []map[string]any{}
}
out := make([]map[string]any, 0, len(list))
for _, item := range list {
name, _ := item["name"].(string)
if strings.TrimSpace(name) == "" {
continue
}
role, _ := item["role"].(string)
bio, _ := item["bio"].(string)
url, _ := item["url"].(string)
avatar, _ := item["avatar"].(string)
contributions, _ := item["contributions"].([]any)
cats := make([]string, 0, len(contributions))
for _, c := range contributions {
if s, ok := c.(string); ok && s != "" {
cats = append(cats, s)
}
}
out = append(out, map[string]any{
"name": strings.TrimSpace(name),
"role": strings.TrimSpace(role),
"bio": strings.TrimSpace(bio),
"url": strings.TrimSpace(url),
"avatar": strings.TrimSpace(avatar),
"contributions": cats,
})
}
return out
}
func validateContributors(v string) string {
if v == "" || v == "[]" {
return ""
}
var tmp []map[string]any
if err := json.Unmarshal([]byte(v), &tmp); err != nil {
return "فرمت مشارکت‌کنندگان نامعتبر است"
}
if len(tmp) > 50 {
return "حداکثر ۵۰ مشارکت‌کننده مجاز است"
}
for _, item := range tmp {
name, _ := item["name"].(string)
if strings.TrimSpace(name) == "" {
return "نام مشارکت‌کننده الزامی است"
}
if utf8.RuneCountInString(strings.TrimSpace(name)) > 100 {
return "نام مشارکت‌کننده خیلی طولانی است"
}
if role, _ := item["role"].(string); utf8.RuneCountInString(strings.TrimSpace(role)) > 100 {
return "نقش مشارکت‌کننده خیلی طولانی است"
}
if bio, _ := item["bio"].(string); utf8.RuneCountInString(strings.TrimSpace(bio)) > 300 {
return "بیوگرافی خیلی طولانی است"
}
if url, _ := item["url"].(string); url != "" {
u := strings.TrimSpace(url)
if !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
return "لینک پروفایل باید با http شروع شود"
}
if utf8.RuneCountInString(u) > 500 {
return "لینک پروفایل خیلی طولانی است"
}
}
if contributions, ok := item["contributions"].([]any); ok {
if len(contributions) > 20 {
return "حداکثر ۲۰ دسته مشارکت برای هر نفر مجاز است"
}
for _, c := range contributions {
s, ok := c.(string)
if !ok {
return "دسته مشارکت باید رشته باشد"
}
s = strings.TrimSpace(s)
if s == "" {
return "دسته مشارکت نمی‌تواند خالی باشد"
}
if utf8.RuneCountInString(s) > 50 {
return "دسته مشارکت خیلی طولانی است"
}
}
}
}
return ""
}
func (s *Server) handleAdminContributorAvatarUpload(w http.ResponseWriter, r *http.Request) {
const maxSize = 6 << 20
r.Body = http.MaxBytesReader(w, r.Body, maxSize+1<<20)
if err := r.ParseMultipartForm(maxSize + 1<<20); err != nil {
writeErr(w, http.StatusRequestEntityTooLarge, "حجم فایل بیش از حد مجاز است")
return
}
file, h, err := r.FormFile("file")
if err != nil {
writeErr(w, http.StatusBadRequest, "فایل ارسال نشده است")
return
}
defer file.Close()
if h.Size > maxSize {
writeErr(w, http.StatusRequestEntityTooLarge, "حجم فایل باید کمتر از ۶ مگابایت باشد")
return
}
accepted, err := acceptAvatarImage(h, file)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
key := fmt.Sprintf("contributor-avatars/%d%s", time.Now().UnixNano(), accepted.Ext)
rawURL, err := s.storage.Save(key, file, h.Size)
if err != nil {
writeErr(w, http.StatusInternalServerError, "ذخیرهٔ فایل ممکن نشد")
return
}
writeJSON(w, http.StatusCreated, map[string]any{"url": s.signExistingMediaURL(rawURL)})
}
func (s *Server) handleAdminGetSettings(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
keys := []string{
"physical_cert_enabled", "physical_cert_price_irr", "physical_cert_window_days",
"sponsors",
"social_links",
"contributors",
"hearts_max",
"hearts_regen_minutes",
"hearts_lock_on_empty",
@@ -163,6 +291,7 @@ func (s *Server) handleAdminPutSettings(w http.ResponseWriter, r *http.Request)
"registration_enabled": true,
"registration_require_whitelist": true,
"social_links": true,
"contributors": true,
"hearts_max": true,
"hearts_regen_minutes": true,
"hearts_lock_on_empty": true,
@@ -226,6 +355,14 @@ func (s *Server) handleAdminPutSettings(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusBadRequest, msg)
return
}
case "contributors":
if v == "" {
v = "[]"
}
if msg := validateContributors(v); msg != "" {
writeErr(w, http.StatusBadRequest, msg)
return
}
case "hearts_max":
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > store.MaxHearts {
@@ -0,0 +1,6 @@
-- Add contributors setting key. Seed one verified entry (sole git author).
-- Admins can update via the site settings panel.
INSERT INTO app_settings (key, value) VALUES (
'contributors',
'[{"name":"Amir Husayn Panahifar","role":"بنیان‌گذار و توسعه‌دهنده","bio":"","url":"","avatar":"","contributions":["code"]}]'
) ON CONFLICT (key) DO NOTHING;
+23 -1
View File
@@ -148,6 +148,27 @@ func (s *Store) GetUserByID(ctx context.Context, id int64) (*models.User, error)
return u, err
}
// GetUsersByIDs fetches multiple users in a single query. Missing IDs are silently skipped.
func (s *Store) GetUsersByIDs(ctx context.Context, ids []int64) (map[int64]*models.User, error) {
if len(ids) == 0 {
return map[int64]*models.User{}, nil
}
rows, err := s.pool.Query(ctx, `SELECT `+userCols+` FROM users WHERE id = ANY($1)`, ids)
if err != nil {
return nil, err
}
defer rows.Close()
out := make(map[int64]*models.User, len(ids))
for rows.Next() {
u, err := scanUser(rows)
if err != nil {
continue
}
out[u.ID] = u
}
return out, rows.Err()
}
func (s *Store) UpdateUserStats(ctx context.Context, userID int64, xp int, streak int, streakLongest int, lastActivity *time.Time) error {
_, err := s.pool.Exec(ctx, `
UPDATE users SET xp=$1, streak_current=$2, streak_longest=$3, last_activity_date=$4
@@ -634,7 +655,8 @@ func (s *Store) CountPassedActiveLessons(ctx context.Context, userID int64) (int
func (s *Store) HasCompletedCurriculum(ctx context.Context, userID int64) (bool, error) {
// An issued (non-revoked) certificate is permanent proof of completion regardless
// of subsequent curriculum changes (e.g. new lessons added after the student finished).
if cert, err := s.GetCertificateByUser(ctx, userID); err == nil && cert.RevokedAt == nil {
// Pending certs do NOT count — they haven't been approved yet.
if cert, err := s.GetCertificateByUser(ctx, userID); err == nil && cert.RevokedAt == nil && cert.Status == "issued" {
return true, nil
}
active, err := s.CountActiveLessons(ctx)
+3
View File
@@ -33,6 +33,7 @@ services:
environment:
DEV_MODE: ${DEV_MODE:-false}
SEED_CURRICULUM: ${SEED_CURRICULUM:-false}
CAPTCHA_EXPOSE_ANSWER: ${CAPTCHA_EXPOSE_ANSWER:-false}
deploy:
resources:
limits:
@@ -66,6 +67,8 @@ services:
# Allow slow, large uploads (admin video ≤ 200MB); default is 60s.
- --entrypoints.web.transport.respondingTimeouts.readTimeout=3600
- --entrypoints.websecure.transport.respondingTimeouts.readTimeout=3600
# Disable HTTP/2 so WebSocket upgrades work from Chromium (RFC 8441 not enabled).
- --entrypoints.websecure.http2.maxConcurrentStreams=0
# Dev: Traefik default certificate (browser warning expected on localhost).
- --api.dashboard=true
- --api.insecure=true
+2 -2
View File
@@ -2,8 +2,8 @@ apiVersion: v2
name: pargar
description: Pargar gated LMS - Go API, Next.js frontend, Postgres, Redis, S3-compatible storage
type: application
version: 0.2.3
appVersion: "0.2.1"
version: 0.2.4
appVersion: "0.4.0"
keywords:
- lms
- pargar
@@ -8,7 +8,10 @@
{{- else if and .Values.postgres.auth.password (not (hasPrefix "change-me" .Values.postgres.auth.password)) (ne .Values.postgres.auth.password "") }}
{{- $pgPass = .Values.postgres.auth.password }}
{{- else }}
{{- $pgPass = randAlphaNum 32 }}
{{- /* Fail loudly instead of silently minting a random password: under
Argo CD (helm template) `lookup` is always empty, and a random
value would diverge from the live service on every render. */}}
{{- fail "postgres.auth.password must be set: no existing pargar-postgres secret was found and .Values.postgres.auth.password is empty or a change-me placeholder" }}
{{- end }}
apiVersion: v1
kind: Secret
@@ -30,7 +33,7 @@ stringData:
{{- else if and .Values.redis.auth.password (not (hasPrefix "change-me" .Values.redis.auth.password)) (ne .Values.redis.auth.password "") }}
{{- $rdPass = .Values.redis.auth.password }}
{{- else }}
{{- $rdPass = randAlphaNum 32 }}
{{- fail "redis.auth.password must be set: no existing pargar-redis secret was found and .Values.redis.auth.password is empty or a change-me placeholder" }}
{{- end }}
apiVersion: v1
kind: Secret
@@ -56,7 +59,7 @@ stringData:
{{- else if and .Values.rustfs.auth.secretKey (not (hasPrefix "change-me" .Values.rustfs.auth.secretKey)) (ne .Values.rustfs.auth.secretKey "") }}
{{- $secret = .Values.rustfs.auth.secretKey }}
{{- else }}
{{- $secret = randAlphaNum 40 }}
{{- fail "rustfs.auth.secretKey must be set: no existing pargar-rustfs secret was found and .Values.rustfs.auth.secretKey is empty or a change-me placeholder" }}
{{- end }}
apiVersion: v1
kind: Secret
@@ -0,0 +1,29 @@
{{- if .Values.backend.metrics.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: {{ include "pargar.fullname" . }}-backend
labels:
{{- include "pargar.labels" . | nindent 4 }}
app.kubernetes.io/component: backend
spec:
selector:
matchLabels:
{{- include "pargar.selectorLabels" . | nindent 6 }}
app.kubernetes.io/component: backend
namespaceSelector:
matchNames:
- {{ .Release.Namespace }}
endpoints:
- port: http
path: /metrics
interval: {{ .Values.backend.metrics.serviceMonitor.interval | default "30s" }}
scheme: http
# /metrics answers 401 without it; Prometheus sends it as
# Authorization: Bearer <token>.
authorization:
type: Bearer
credentials:
name: {{ include "pargar.appSecretName" . }}
key: metrics-token
{{- end }}
+3 -3
View File
@@ -11,7 +11,7 @@ backend:
image:
pullPolicy: IfNotPresent
repository: pargar-backend
tag: 0.3.7
tag: 0.4.0
metrics:
serviceMonitor:
enabled: true
@@ -41,7 +41,7 @@ frontend:
image:
pullPolicy: IfNotPresent
repository: pargar-frontend
tag: 0.3.7
tag: 0.4.0
podDisruptionBudget:
enabled: false
replicaCount: 2
@@ -61,7 +61,7 @@ global:
# Gitea packages are private: kubelet pulls need secret `gitea-pull`
# (docker-registry secret for src.panahifar.ir, created in ns pargar).
imagePullSecrets:
- gitea-pull
- name: gitea-pull
ingress:
enabled: true
tls:
+7
View File
@@ -25,6 +25,13 @@ backend:
pullPolicy: IfNotPresent
service:
port: 8080
metrics:
# Prometheus Operator ServiceMonitor. /metrics is bearer-protected by
# METRICS_TOKEN, so the endpoint carries authorization credentials
# (pargar-app secret) instead of scraping anonymously.
serviceMonitor:
enabled: false
interval: 30s
resources:
requests:
cpu: 50m
+1
View File
@@ -0,0 +1 @@
{"available":true,"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEsInJvbGUiOiJhZG1pbiIsInN1YiI6IjEiLCJleHAiOjE3OTI0OTc0MjcsImlhdCI6MTc5MjQ5NjUyN30.0RuGRaPhMeQ36aHrn_x2iAgJPpyH7pfXGr_cOOOeG1c","refreshToken":"e4059f725d0648ae77b0147835296228c5bba0d0bcda638ebb9a65adeed6c5f72e56d0da268de11d34393e9d4ea96acb","user":{"id":1,"email":"admin@example.com","username":"admin","name":"Admin","role":"admin","xp":0,"hearts":5,"heartsUpdatedAt":"2026-10-18T06:49:58.329935Z","streakCurrent":0,"streakLongest":0,"isLocked":false,"isActive":true,"avatarVariant":"beam","avatarPalette":"","phone":"","hasSecurityAnswer":false,"createdAt":"2026-10-18T06:49:58.329935Z","usernameChangesRemaining":3,"isFrozen":false,"isClosed":false}}
+79
View File
@@ -0,0 +1,79 @@
import { test, expect } from "@playwright/test";
import { ADMIN_EMAIL, ADMIN_PASSWORD, BASE, requireAuth, injectAuth, apiLogin } from "./helpers";
test.describe("Auth — public endpoints", () => {
test("login page renders", async ({ page }) => {
await page.goto("/login");
await expect(page).toHaveTitle(/.+/);
const hasForm = await page.locator("form, input[type=password]").count();
expect(hasForm).toBeGreaterThan(0);
});
test("protected routes reject unauthenticated requests", async ({ page }) => {
const routes = ["/api/tree", "/api/leaderboard/weekly", "/api/notifications"];
for (const route of routes) {
const res = await page.request.get(`${BASE}${route}`);
expect(res.status(), `${route} should be 401`).toBe(401);
}
});
test("invalid credentials: bad captcha → 400, bad password → 401", async ({ page }) => {
// Bad captcha answer returns 400
const r1 = await page.request.post(`${BASE}/api/auth/login`, {
data: { username: "x", password: "x", challengeId: "fake", captchaAnswer: "wrong" },
});
expect([400, 429]).toContain(r1.status());
// Correct captcha, wrong password → 401
const auth = requireAuth();
const captchaRes = await page.request.get(`${BASE}/api/auth/captcha`);
const { challengeId, answer } = await captchaRes.json();
const r2 = await page.request.post(`${BASE}/api/auth/login`, {
data: { username: ADMIN_EMAIL, password: "definitely-wrong", challengeId, captchaAnswer: answer },
});
expect(r2.status()).toBe(401);
});
});
test.describe("Auth — requires working CAPTCHA", () => {
test("admin login via API succeeds and /me returns admin role", async ({ page }) => {
const auth = requireAuth();
const res = await page.request.get(`${BASE}/api/auth/me`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
expect(res.status()).toBe(200);
const body = await res.json();
expect(body.user.role).toBe("admin");
});
test("logout invalidates refresh token", async ({ page }) => {
requireAuth();
// Issue a fresh session for this test only (don't use the shared token)
const captchaRes = await page.request.get(`${BASE}/api/auth/captcha`);
const { challengeId, answer } = await captchaRes.json();
if (!answer) { test.skip(true, "CAPTCHA not solvable"); return; }
const loginRes = await page.request.post(`${BASE}/api/auth/login`, {
data: { username: ADMIN_EMAIL, password: ADMIN_PASSWORD, challengeId, captchaAnswer: answer },
});
const { accessToken, refreshToken } = await loginRes.json();
const logout = await page.request.post(`${BASE}/api/auth/logout`, {
data: { refreshToken },
headers: { Authorization: `Bearer ${accessToken}` },
});
expect(logout.status()).toBe(200);
const refresh = await page.request.post(`${BASE}/api/auth/refresh`, {
data: { refreshToken },
});
expect(refresh.status()).toBe(401);
});
test("cap page loads and stays off /login", async ({ page }) => {
await injectAuth(page);
await page.goto("/cap");
await page.waitForLoadState("networkidle", { timeout: 15_000 });
expect(page.url()).not.toContain("/login");
});
});
+65
View File
@@ -0,0 +1,65 @@
import { test, expect } from "@playwright/test";
import { BASE, requireAuth, injectAuth } from "./helpers";
test.describe("Chat", () => {
test("conversations endpoint returns list", async ({ page }) => {
const auth = requireAuth();
const res = await page.request.get(`${BASE}/api/chats/conversations`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
expect(res.status()).toBe(200);
const data = await res.json();
expect(data).toHaveProperty("conversations");
expect(Array.isArray(data.conversations)).toBe(true);
});
test("student→student chat is rejected (IDOR guard)", async ({ page }) => {
const auth = requireAuth();
const adminId = auth.user!.id;
// Create a student
const u1 = await page.request.post(`${BASE}/api/admin/users`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
data: {
name: "ChatTest", email: "chat-idor@e2e.test", username: "chat_idor_e2e",
password: "TestPass123!", role: "student",
securityQuestion: "Q", securityAnswer: "A",
},
});
// 201 = created, 409 = already exists from prior run — both are fine
if (u1.status() !== 201 && u1.status() !== 409) {
test.skip(true, `Unexpected status creating test user: ${u1.status()}`);
return;
}
const studentId = u1.status() === 201
? (await u1.json()).user.id
: null;
if (!studentId) { test.skip(true, "Could not get student ID"); return; }
// Log in as the student
const captchaRes = await page.request.get(`${BASE}/api/auth/captcha`);
const { challengeId, answer } = await captchaRes.json();
if (!answer) { test.skip(true, "CAPTCHA not solvable"); return; }
const loginRes = await page.request.post(`${BASE}/api/auth/login`, {
data: { username: "chat_idor_e2e", password: "TestPass123!", challengeId, captchaAnswer: answer },
});
const studentSession = await loginRes.json();
if (!studentSession.accessToken) { test.skip(true, "Student login failed"); return; }
// Student tries to read another student's conversations — must fail
const forbidden = await page.request.get(`${BASE}/api/chats/${studentId}/messages`, {
headers: { Authorization: `Bearer ${studentSession.accessToken}` },
});
expect([403, 404]).toContain(forbidden.status());
});
test("chat page renders without redirect to /login", async ({ page }) => {
await injectAuth(page);
await page.goto("/unwrap?tab=chats");
await page.waitForLoadState("networkidle", { timeout: 15_000 });
expect(page.url()).not.toContain("/login");
});
});
+59
View File
@@ -0,0 +1,59 @@
import { chromium } from "@playwright/test";
import { ADMIN_EMAIL, ADMIN_PASSWORD, BASE } from "./helpers";
import * as fs from "fs";
import * as path from "path";
const AUTH_FILE = path.join(__dirname, ".auth-state.json");
export default async function globalSetup() {
// If answer is not exposed in captcha, skip auth — tests requiring auth will skip themselves.
const browser = await chromium.launch({
executablePath: `${process.env.HOME}/.cache/ms-playwright/chromium_headless_shell-1234/chrome-headless-shell-linux64/chrome-headless-shell`,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
const context = await browser.newContext({ ignoreHTTPSErrors: true });
const page = await context.newPage();
try {
const captchaRes = await page.request.get(`${BASE}/api/auth/captcha`);
const captchaData = await captchaRes.json();
if (!captchaData.answer) {
console.warn("\n⚠ CAPTCHA_EXPOSE_ANSWER not set — restart the API container to enable auth tests.\n Run: ./scripts/compose-dev.sh restart api\n");
fs.writeFileSync(AUTH_FILE, JSON.stringify({ available: false }));
await browser.close();
return;
}
const loginRes = await page.request.post(`${BASE}/api/auth/login`, {
data: {
username: ADMIN_EMAIL,
password: ADMIN_PASSWORD,
challengeId: captchaData.challengeId,
captchaAnswer: captchaData.answer,
rememberMe: true,
},
});
const body = await loginRes.json();
if (!body.accessToken) {
console.warn("\n⚠ Admin login failed in global setup:", JSON.stringify(body));
fs.writeFileSync(AUTH_FILE, JSON.stringify({ available: false }));
await browser.close();
return;
}
fs.writeFileSync(AUTH_FILE, JSON.stringify({
available: true,
accessToken: body.accessToken,
refreshToken: body.refreshToken,
user: body.user,
}));
console.log("\n✓ Auth state cached for test suite\n");
} catch (e) {
fs.writeFileSync(AUTH_FILE, JSON.stringify({ available: false }));
console.warn("\n⚠ Global setup failed:", e);
}
await browser.close();
}
+83
View File
@@ -0,0 +1,83 @@
import { type Page, test } from "@playwright/test";
import * as fs from "fs";
import * as path from "path";
export const ADMIN_EMAIL = "admin";
export const ADMIN_PASSWORD = "wZW64CUbXbv9679dmR1FIbz3";
export const BASE = "https://localhost";
const AUTH_FILE = path.join(__dirname, ".auth-state.json");
interface AuthState {
available: boolean;
accessToken?: string;
refreshToken?: string;
user?: { id: number; role: string; email: string };
}
export function loadAuth(): AuthState {
try {
return JSON.parse(fs.readFileSync(AUTH_FILE, "utf-8")) as AuthState;
} catch {
return { available: false };
}
}
/** Skip this test if auth is not available (CAPTCHA not exposed). */
export function requireAuth(): AuthState {
const auth = loadAuth();
if (!auth.available) {
test.skip(true, "Auth not available — restart API with CAPTCHA_EXPOSE_ANSWER=true");
}
return auth;
}
/** Inject cached auth cookies into the page context. */
export async function injectAuth(page: Page): Promise<AuthState> {
const auth = requireAuth();
// Seed Zustand persist store so the app hydrates with a valid user (skips redirect)
await page.addInitScript(({ user }) => {
try {
localStorage.setItem(
"pargar.auth",
JSON.stringify({ state: { user }, version: 0 }),
);
} catch {}
}, { user: auth.user });
await page.context().addCookies([
{ name: "pargar_access", value: auth.accessToken!, domain: "localhost", path: "/", secure: true, sameSite: "Lax" },
{ name: "pargar_refresh", value: auth.refreshToken!, domain: "localhost", path: "/", secure: true, httpOnly: true, sameSite: "Lax" },
]);
return auth;
}
export async function loginAs(page: Page, identity: string, password: string) {
const captchaRes = await page.request.get(`${BASE}/api/auth/captcha`);
const captchaData = await captchaRes.json();
const answer: string = captchaData.answer ?? "";
const challengeId: string = captchaData.challengeId ?? "";
const loginRes = await page.request.post(`${BASE}/api/auth/login`, {
data: { username: identity, password, challengeId, captchaAnswer: answer, rememberMe: false },
});
const loginBody = await loginRes.json();
if (!loginBody.accessToken) {
throw new Error(`Login failed for ${identity}: ${JSON.stringify(loginBody)}`);
}
await page.context().addCookies([
{ name: "access_token", value: loginBody.accessToken, domain: "localhost", path: "/", secure: true, sameSite: "Lax" },
{ name: "refresh_token", value: loginBody.refreshToken, domain: "localhost", path: "/", secure: true, httpOnly: true, sameSite: "Lax" },
]);
return loginBody;
}
export async function apiLogin(page: Page, identity: string, password: string) {
const captchaRes = await page.request.get(`${BASE}/api/auth/captcha`);
const { challengeId, answer } = await captchaRes.json();
const res = await page.request.post(`${BASE}/api/auth/login`, {
data: { username: identity, password, challengeId, captchaAnswer: answer, rememberMe: false },
});
return res.json();
}
+37
View File
@@ -0,0 +1,37 @@
import { test, expect } from "@playwright/test";
import { BASE, requireAuth, injectAuth } from "./helpers";
test.describe("Leaderboard", () => {
test("weekly leaderboard returns valid shape", async ({ page }) => {
const auth = requireAuth();
const res = await page.request.get(`${BASE}/api/leaderboard/weekly`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
expect(res.status()).toBe(200);
const data = await res.json();
expect(data).toHaveProperty("week");
expect(data).toHaveProperty("entries");
expect(data).toHaveProperty("totalParticipants");
expect(data).toHaveProperty("me");
expect(Array.isArray(data.entries)).toBe(true);
});
test("leaderboard entries have tier field", async ({ page }) => {
const auth = requireAuth();
const res = await page.request.get(`${BASE}/api/leaderboard/weekly`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
const data = await res.json();
for (const entry of data.entries) {
expect(["champion", "gold", "silver", "bronze"]).toContain(entry.tier);
expect(entry.rank).toBeGreaterThanOrEqual(1);
}
});
test("leaderboard page renders without redirect to /login", async ({ page }) => {
await injectAuth(page);
await page.goto("/leaderboard");
await page.waitForLoadState("networkidle", { timeout: 15_000 });
expect(page.url()).not.toContain("/login");
});
});
+49
View File
@@ -0,0 +1,49 @@
import { test, expect } from "@playwright/test";
import { requireAuth, injectAuth } from "./helpers";
const VIEWPORTS = [
{ name: "mobile-sm (375px)", width: 375, height: 812 },
{ name: "mobile-lg (430px)", width: 430, height: 932 },
{ name: "tablet (768px)", width: 768, height: 1024 },
{ name: "desktop (1280px)", width: 1280, height: 800 },
{ name: "desktop-xl (1440px)", width: 1440, height: 900 },
];
const ROUTES = ["/cap", "/leaderboard", "/community", "/settings", "/notifications"];
for (const vp of VIEWPORTS) {
test(`no horizontal overflow — ${vp.name}`, async ({ page }) => {
requireAuth();
await page.setViewportSize({ width: vp.width, height: vp.height });
await injectAuth(page);
for (const route of ROUTES) {
await page.goto(route);
await page.waitForLoadState("networkidle", { timeout: 15_000 });
const overflow = await page.evaluate(() => {
return document.documentElement.scrollWidth > document.documentElement.clientWidth;
});
expect(overflow, `Horizontal overflow at ${route} / ${vp.name}`).toBe(false);
}
});
test(`no interactive elements clipped off-screen — ${vp.name}`, async ({ page }) => {
requireAuth();
await page.setViewportSize({ width: vp.width, height: vp.height });
await injectAuth(page);
await page.goto("/cap");
await page.waitForLoadState("networkidle", { timeout: 15_000 });
const clipped = await page.evaluate((vpWidth) => {
return Array.from(document.querySelectorAll("button, a, input"))
.filter((el) => {
const r = el.getBoundingClientRect();
return r.right < 0 || r.left > vpWidth + 50;
}).length;
}, vp.width);
expect(clipped, `${clipped} elements clipped at ${vp.name}`).toBe(0);
});
}
+75
View File
@@ -0,0 +1,75 @@
import { test, expect } from "@playwright/test";
import { BASE, requireAuth, injectAuth } from "./helpers";
test.describe("Video player & media signing", () => {
test("lesson endpoint returns a signed videoUrl", async ({ page }) => {
const auth = requireAuth();
const treeRes = await page.request.get(`${BASE}/api/tree`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
expect(treeRes.status()).toBe(200);
const tree = await treeRes.json();
const firstLesson = tree.chapters?.[0]?.lessons?.[0];
if (!firstLesson) { test.skip(true, "No lessons in tree"); return; }
const lessonRes = await page.request.get(`${BASE}/api/lessons/${firstLesson.id}`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
expect(lessonRes.status()).toBe(200);
const lesson = await lessonRes.json();
expect(lesson.videoUrl).toBeTruthy();
expect(lesson.videoUrl).toMatch(/^https?:\/\//);
// Must be signed (has query params) or served via /media/ proxy
const url = new URL(lesson.videoUrl);
const isSigned = url.searchParams.size > 0 || lesson.videoUrl.includes("/media/");
expect(isSigned, `videoUrl not signed: ${lesson.videoUrl}`).toBe(true);
});
test("player page renders without JS errors for first lesson", async ({ page }) => {
const auth = requireAuth();
const treeRes = await page.request.get(`${BASE}/api/tree`, {
headers: { Authorization: `Bearer ${auth.accessToken}` },
});
const tree = await treeRes.json();
const firstLesson = tree.chapters?.[0]?.lessons?.[0];
if (!firstLesson) { test.skip(true, "No lessons in tree"); return; }
const jsErrors: string[] = [];
page.on("pageerror", (err) => jsErrors.push(err.message));
await injectAuth(page);
await page.goto(`/player/${firstLesson.id}`);
await page.waitForLoadState("networkidle", { timeout: 20_000 });
// Filter known expected media errors (video load failures in headless are expected)
const realErrors = jsErrors.filter(
(e) => !e.includes("video") && !e.includes("media") && !e.includes("hls") && !e.includes("AbortError")
);
expect(realErrors, `JS errors on player page: ${realErrors.join(", ")}`).toHaveLength(0);
});
test("admin videos panel fires no media requests on grid load", async ({ page }) => {
requireAuth();
const videoRequests: string[] = [];
page.on("request", (req) => {
if (req.resourceType() === "media" || /\.(mp4|m3u8|ts)(\?|$)/.test(req.url())) {
videoRequests.push(req.url());
}
});
await injectAuth(page);
await page.goto("/admin");
await page.waitForLoadState("networkidle", { timeout: 15_000 });
// Click Videos tab if present
const videosTab = page.getByRole("button", { name: /ویدیو/i });
if (await videosTab.count() > 0) {
await videosTab.first().click();
await page.waitForLoadState("networkidle", { timeout: 10_000 });
}
expect(videoRequests, `Unexpected media requests on grid load: ${videoRequests.join(", ")}`).toHaveLength(0);
});
});
+56
View File
@@ -0,0 +1,56 @@
import * as tls from "tls";
import { test, expect } from "@playwright/test";
import { BASE, requireAuth } from "./helpers";
test.describe("WebSocket", () => {
// Test WS via raw TLS to avoid browser HTTP/2 and Node.js http module quirks.
test("WS handshake with valid token succeeds", async () => {
const auth = requireAuth();
const statusCode = await new Promise<number>((resolve) => {
const socket = tls.connect(
{ host: "localhost", port: 443, rejectUnauthorized: false },
() => {
const handshake = [
"GET /api/ws HTTP/1.1",
"Host: localhost",
"Upgrade: websocket",
"Connection: Upgrade",
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==",
"Sec-WebSocket-Version: 13",
`Authorization: Bearer ${auth.accessToken!}`,
"",
"",
].join("\r\n");
socket.write(handshake);
},
);
let buf = "";
socket.on("data", (chunk) => {
buf += chunk.toString();
const firstLine = buf.split("\r\n")[0] ?? "";
const m = firstLine.match(/HTTP\/1\.\d\s+(\d+)/);
if (m) {
socket.destroy();
resolve(parseInt(m[1], 10));
}
});
socket.on("error", () => resolve(0));
setTimeout(() => { socket.destroy(); resolve(0); }, 8000);
});
expect(statusCode, `WS upgrade returned ${statusCode}`).toBe(101);
});
test("WS handshake without token is rejected", async ({ page }) => {
const result = await page.evaluate((wsUrl) => {
return new Promise<{ code: number }>((resolve) => {
const ws = new WebSocket(wsUrl);
ws.onclose = (e) => resolve({ code: e.code });
setTimeout(() => resolve({ code: -1 }), 6000);
});
}, BASE.replace("https", "wss") + "/api/ws");
expect(result.code).not.toBe(1000);
});
});
+46
View File
@@ -42,6 +42,7 @@
"zustand": "^5.0.2"
},
"devDependencies": {
"@playwright/test": "^1.64.1",
"@tailwindcss/postcss": "^4.0.0",
"@types/node": "^22.10.0",
"@types/react": "^19.0.0",
@@ -796,6 +797,22 @@
"node": ">= 10"
}
},
"node_modules/@playwright/test": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
"integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@radix-ui/primitive": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.7.tgz",
@@ -2973,6 +2990,35 @@
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/playwright": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+1
View File
@@ -46,6 +46,7 @@
"zustand": "^5.0.2"
},
"devDependencies": {
"@playwright/test": "^1.64.1",
"@tailwindcss/postcss": "^4.0.0",
"@types/node": "^22.10.0",
"@types/react": "^19.0.0",
+31
View File
@@ -0,0 +1,31 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
timeout: 30_000,
retries: 0,
workers: 1,
globalSetup: "./e2e/global-setup.ts",
reporter: [["list"], ["html", { open: "never", outputFolder: "playwright-report" }]],
use: {
baseURL: "https://localhost",
ignoreHTTPSErrors: true,
screenshot: "only-on-failure",
video: "off",
trace: "retain-on-failure",
locale: "fa-IR",
},
projects: [
{
name: "chromium",
use: {
browserName: "chromium",
viewport: { width: 1280, height: 800 },
launchOptions: {
executablePath: `${process.env.HOME}/.cache/ms-playwright/chromium_headless_shell-1234/chrome-headless-shell-linux64/chrome-headless-shell`,
args: ["--no-sandbox", "--disable-dev-shm-usage", "--disable-http2"],
},
},
},
],
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 149 KiB

After

Width:  |  Height:  |  Size: 253 KiB

-7
View File
@@ -73,13 +73,6 @@ function CapPageInner() {
enabled: !!user && curriculumDone,
});
useEffect(() => {
if (!curriculumDone || !user) return;
void http
.post("/api/me/certificate/issue", {})
.then(() => qc.invalidateQueries({ queryKey: ["me", "certificate"] }))
.catch((e) => toast.error(toUserError(e, "صدور گواهینامه ممکن نشد")));
}, [curriculumDone, user, qc]);
if (isLoading) {
return <CapSkeleton />;
+8
View File
@@ -35,6 +35,14 @@ const vazirmatnLatin = localFont({
export const metadata: Metadata = {
title: "پرگار",
description: "مسیر یادگیری واقعی پرگار",
icons: {
icon: [
{ url: "/favicon.ico" },
{ url: "/icon-192.png", sizes: "192x192", type: "image/png" },
{ url: "/icon-512.png", sizes: "512x512", type: "image/png" },
],
apple: { url: "/apple-touch-icon.png", sizes: "180x180", type: "image/png" },
},
};
export const viewport: Viewport = {
+3 -2
View File
@@ -8,6 +8,7 @@ import { api, http, toUserError } from "@/lib/api";
import { MAX_HEARTS, clampHearts, hasInfiniteHearts } from "@/lib/hearts";
import type { Mentor, User } from "@/lib/types";
import { Card } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/providers";
import { cn } from "@/lib/utils";
@@ -116,14 +117,14 @@ export default function LockoutPage() {
</Card>
<div className="mt-5 w-full space-y-2">
<textarea
<Textarea
value={note}
onChange={(e) => setNote(e.target.value)}
maxLength={500}
rows={3}
dir="rtl"
placeholder="اختیاری: چه آزمونی گیر کردید؟ چه کمکی لازم دارید؟"
className="w-full rounded-xl border-2 border-border bg-background px-3 py-2 text-sm outline-none focus-visible:border-primary/50"
className="min-h-0"
/>
<div className="flex flex-col gap-2 sm:flex-row">
<Button className="flex-1" disabled={busy || requested} onClick={() => void requestUnlock()}>
+1 -1
View File
@@ -48,7 +48,7 @@ export default function NotificationsPage() {
<Skeleton className="h-8 w-44" />
<Skeleton className="h-4 w-72" />
</div>
<div className="rounded-2xl border border-border/70 bg-card p-6 shadow-soft">
<div className="rounded-2xl border-2 border-border/70 bg-card p-6 shadow-soft">
<div className="flex items-center gap-3">
<Skeleton className="h-10 w-10 rounded-xl" />
<div className="flex-1 space-y-1.5">
+3 -2
View File
@@ -93,6 +93,7 @@ export default function Home() {
const goCap = () => router.push("/cap");
const goLogin = () => router.push("/login");
const goRegister = () => router.push("/register");
return (
<div className="mx-auto flex max-w-5xl flex-col items-center">
@@ -134,7 +135,7 @@ export default function Home() {
<Button size="lg" onClick={goLogin} className="gap-2 px-8">
ورود
</Button>
<Button size="lg" variant="outline" onClick={goLogin} className="gap-2 px-8">
<Button size="lg" variant="outline" onClick={goRegister} className="gap-2 px-8">
<Zap className="h-5 w-5" /> شروع مسیر
</Button>
</>
@@ -288,7 +289,7 @@ export default function Home() {
<Link href="/login">ورود</Link>
</Button>
<Button size="lg" variant="outline" asChild className="gap-2 px-8">
<Link href="/login">
<Link href="/register">
<PlayCircle className="h-5 w-5" /> شروع مسیر
</Link>
</Button>
+256 -79
View File
@@ -12,6 +12,7 @@ import {
Copy,
Cpu,
Eye,
EyeOff,
Flag,
GitBranch,
Globe,
@@ -21,6 +22,7 @@ import {
Loader2,
Lock,
MapPin,
MoreHorizontal,
Pencil,
Plus,
Rocket,
@@ -59,6 +61,15 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { PasswordInput } from "@/components/ui/password-input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
@@ -685,7 +696,11 @@ function CurriculumPanel() {
const [lessonModal, setLessonModal] = useState<Lesson | null>(null);
const [chapterModal, setChapterModal] = useState<Chapter | null>(null);
const [dragIdx, setDragIdx] = useState<{ chapter: number; from: number; over?: number } | null>(null);
const [activeChapter, setActiveChapter] = useState<number | null>(null);
const [dragIdx, setDragIdx] = useState<{ chapter: number; from: number } | null>(null);
const toggleChapter = (id: number) =>
setActiveChapter((prev) => (prev === id ? null : id));
const persistChapterOrder = async (list: Chapter[]) => {
for (let i = 0; i < list.length; i++) {
@@ -772,12 +787,14 @@ function CurriculumPanel() {
}
};
const newLesson = (chapterId: number) =>
const newLesson = (chapterId: number) => {
setActiveChapter(chapterId);
setLessonModal({
id: 0, chapterId, title: "", description: "", videoKey: "",
durationSeconds: 45, completionThresholdPct: 85, requiresLessonId: undefined,
x: lessons.filter((l) => l.chapterId === chapterId).length, y: 0, sortOrder: 1, xpReward: 50, isActive: true, isPublished: false,
});
};
const duplicateLesson = async (l: Lesson) => {
try {
@@ -812,6 +829,7 @@ function CurriculumPanel() {
}
try {
await http.del(`/api/admin/chapters/${ch.id}`);
if (activeChapter === ch.id) setActiveChapter(null);
qc.invalidateQueries({ queryKey: ["admin", "lessons"] });
qc.invalidateQueries({ queryKey: ["admin", "stats"] });
toast.success("فصل حذف شد");
@@ -820,70 +838,159 @@ function CurriculumPanel() {
}
};
const publishedChapters = chapters.filter((c) => c.isPublished).length;
const publishedLessons = lessons.filter((l) => l.isPublished).length;
return (
<>
{dialog}
<Card>
<CardHeader className="flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">فصل‌ها و درخت مهارت</CardTitle>
<p className="mt-1 text-xs text-muted-foreground">
{chapters.length} فصل · {lessons.length} درس · ترتیب با کشیدن یا فلش · موقعیت x,y
</p>
{/* Course overview header */}
<div className="mb-4 flex flex-wrap items-start justify-between gap-3 rounded-xl border border-border bg-muted/30 px-4 py-3">
<div className="space-y-1">
<p className="text-sm font-bold">دوره آموزشی</p>
<div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
<span>{chapters.length} فصل</span>
<span>{lessons.length} درس</span>
<span className="text-success">{publishedChapters} فصل منتشر</span>
<span className="text-success">{publishedLessons} درس منتشر</span>
</div>
<Button className="gap-1.5 rounded-2xl" onClick={() => setChapterModal({ id: 0, title: "", description: "", icon: "terminal", sortOrder: chapters.length + 1, isPublished: false })}>
</div>
<Button
size="sm"
className="shrink-0"
onClick={() => setChapterModal({ id: 0, title: "", description: "", icon: "terminal", sortOrder: chapters.length + 1, isPublished: false })}
>
<Plus className="h-4 w-4" /> فصل جدید
</Button>
</CardHeader>
<CardContent className="space-y-4">
</div>
{/* Chapter list */}
{isLoading && <Loader />}
<div className="space-y-2">
{chapters.map((ch, ci) => {
const ls = lessons.filter((l) => l.chapterId === ch.id);
const ChIcon = chapterIconOf(ch.icon);
const isOpen = activeChapter === ch.id;
return (
<div key={ch.id} className={cn("rounded-xl border border-border bg-muted/20", dragIdx !== null && dragIdx?.chapter === ch.id && "border-primary/50")}>
<div className="flex items-center gap-2 p-3 pb-2">
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-primary/10 text-primary">
<div
key={ch.id}
className={cn(
"overflow-hidden rounded-xl border border-border transition-colors",
isOpen && "border-primary/40 shadow-sm",
)}
>
{/* Chapter header row */}
<div className="flex items-center gap-2 px-3 py-2.5">
{/* Expand toggle + identity — takes full remaining width */}
<button
type="button"
aria-expanded={isOpen}
aria-controls={`chapter-${ch.id}-lessons`}
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-md py-0.5 text-start outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => toggleChapter(ch.id)}
>
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-primary/10 text-primary">
<ChIcon className="h-4 w-4" />
</span>
<div className="min-w-0 flex-1">
<h3 className="truncate font-bold">{ch.title}</h3>
{ch.description && <p className="truncate text-xs text-muted-foreground">{ch.description}</p>}
<p className="truncate text-sm font-bold">{ch.title}</p>
{ch.description && (
<p className="truncate text-[11px] text-muted-foreground">{ch.description}</p>
)}
</div>
<Badge variant="outline" className="shrink-0">{ls.length} درس</Badge>
<Badge variant={ch.isPublished ? "success" : "secondary"} className="shrink-0 px-1.5 text-[10px]">
<ChevronDown
className={cn(
"h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200",
isOpen && "rotate-180",
)}
aria-hidden
/>
</button>
{/* Status badges */}
<Badge variant="outline" className="shrink-0 px-2 text-[10px]">
{ls.length} درس
</Badge>
<Badge
variant={ch.isPublished ? "success" : "secondary"}
className="hidden shrink-0 px-1.5 text-[10px] sm:inline-flex"
>
{ch.isPublished ? "منتشر" : "پیش‌نویس"}
</Badge>
<GroupNav
onUp={ci > 0 ? () => moveChapter(ci, -1) : undefined}
onDown={ci < chapters.length - 1 ? () => moveChapter(ci, 1) : undefined}
/>
<Button size="sm" variant="outline" className="h-7 gap-1 text-xs" onClick={() => setChapterModal(ch)}>
<Pencil className="h-3 w-3" /> فصل
</Button>
{/* Chapter actions menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-xs"
onClick={() => publishChapter(ch, !ch.isPublished)}
title={ch.isPublished ? "برگشت به پیش‌نویس" : "انتشار فصل"}
variant="ghost"
className="h-8 w-8 shrink-0 px-0"
aria-label={`اقدامات فصل ${ch.title}`}
>
{ch.isPublished ? "برگشت" : "انتشار"}
<MoreHorizontal className="h-4 w-4" />
</Button>
<Button size="sm" variant="outline" className="h-7 gap-1 text-xs" onClick={() => newLesson(ch.id)}>
<Plus className="h-3.5 w-3.5" /> درس
</Button>
<Button size="sm" variant="ghost" className="h-7 w-7 px-0 text-destructive" onClick={() => delChapter(ch)} title="حذف فصل">
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
{ls.length === 0 ? (
<p className="px-3 pb-3 text-xs text-muted-foreground">هنوز درسی نیست. «+ درس» را بزنید.</p>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuLabel>فصل {ci + 1}</DropdownMenuLabel>
<DropdownMenuItem onClick={() => setChapterModal(ch)}>
<Pencil className="h-3.5 w-3.5" /> ویرایش فصل
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setActiveChapter(ch.id);
newLesson(ch.id);
}}
>
<Plus className="h-3.5 w-3.5" /> درس جدید
</DropdownMenuItem>
<DropdownMenuSeparator />
{ci > 0 && (
<DropdownMenuItem onClick={() => moveChapter(ci, -1)}>
<ChevronUp className="h-3.5 w-3.5" /> جابجا به بالا
</DropdownMenuItem>
)}
{ci < chapters.length - 1 && (
<DropdownMenuItem onClick={() => moveChapter(ci, 1)}>
<ChevronDown className="h-3.5 w-3.5" /> جابجا به پایین
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => publishChapter(ch, !ch.isPublished)}>
{ch.isPublished ? (
<><EyeOff className="h-3.5 w-3.5" /> برگشت به پیش‌نویس</>
) : (
<div className="px-3 pb-3">
<div className="grid gap-1.5 sm:grid-cols-2">
<><Globe className="h-3.5 w-3.5" /> انتشار فصل</>
)}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={() => delChapter(ch)}
>
<Trash2 className="h-3.5 w-3.5" /> حذف فصل
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Lessons panel (progressive disclosure) */}
{isOpen && (
<div
id={`chapter-${ch.id}-lessons`}
className="border-t border-border/70"
>
{ls.length === 0 ? (
<div className="px-4 py-5 text-center text-sm text-muted-foreground">
هنوز درسی نیست — از دکمه زیر درس اضافه کنید.
</div>
) : (
<div className="divide-y divide-border/60">
{ls.map((l, li) => {
const cols = ls.filter((o) => o.x === l.x && o.y === l.y && o.id !== l.id);
const collision = ls.some(
(o) => o.x === l.x && o.y === l.y && o.id !== l.id,
);
return (
<div
key={l.id}
@@ -892,80 +999,150 @@ function CurriculumPanel() {
onDragOver={(e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setDragIdx((d) => (d ? { ...d, over: li, chapter: ch.id } : d));
}}
onDrop={() => {
if (dragIdx && dragIdx.chapter === ch.id && dragIdx.from !== li) {
const idx = dragIdx.from;
const next = reorderArray(ls, idx, li);
const next = reorderArray(ls, dragIdx.from, li);
persistLessonOrder(next).catch(() => {});
}
setDragIdx(null);
}}
onDragEnd={() => setDragIdx(null)}
className={cn(
"group flex cursor-grab items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors active:cursor-grabbing",
"flex items-center gap-2 px-3 py-2.5 transition-colors hover:bg-muted/40",
dragIdx?.from === li && dragIdx.chapter === ch.id && "opacity-40",
!l.videoKey && "border-dashed"
)}
>
<GripVertical className="h-4 w-4 shrink-0 text-muted-foreground/50" />
<span className="shrink-0 text-xs font-bold tabular-nums text-muted-foreground">L{l.id}</span>
{/* Grip handle */}
<GripVertical className="h-4 w-4 shrink-0 cursor-grab text-muted-foreground/40 active:cursor-grabbing" aria-hidden />
{/* Lesson identity */}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{l.title}</p>
<div className="flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
<Timer className="h-3 w-3" /> {formatDur(l.durationSeconds)}
<Sparkles className="h-3 w-3 text-gold" /> +{formatFaNumber(l.xpReward)}
<MapPin className="h-3 w-3" /> {l.x},{l.y}
<p className="truncate text-sm font-medium leading-tight">
{l.title}
</p>
<div className="mt-0.5 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground">
<span className="inline-flex items-center gap-0.5">
<Timer className="h-3 w-3" />
{formatDur(l.durationSeconds)}
</span>
<span className="inline-flex items-center gap-0.5 text-gold">
<Sparkles className="h-3 w-3" />
+{formatFaNumber(l.xpReward)}
</span>
{l.videoKey ? (
<span className="inline-flex items-center gap-0.5 text-success"><Video className="h-3 w-3" /> ویدیو</span>
<span className="inline-flex items-center gap-0.5 text-success">
<Video className="h-3 w-3" /> ویدیو
</span>
) : (
<span className="text-warning">بدون ویدیو</span>
)}
{cols.length > 0 && <Badge variant="destructive" className="px-1 text-[9px]">تداخل</Badge>}
{collision && (
<Badge variant="destructive" className="px-1 text-[9px]">
تداخل موقعیت
</Badge>
)}
</div>
</div>
<Badge variant={l.isPublished ? "success" : "secondary"} className="shrink-0 px-1.5 text-[10px]">
{/* Publish badge */}
<Badge
variant={l.isPublished ? "success" : "secondary"}
className="hidden shrink-0 px-1.5 text-[10px] sm:inline-flex"
>
{l.isPublished ? "منتشر" : "پیش‌نویس"}
</Badge>
<div className="flex shrink-0 gap-0.5">
<GroupNav onUp={li > 0 ? () => moveLesson(ch.id, li, -1) : undefined} onDown={li < ls.length - 1 ? () => moveLesson(ch.id, li, 1) : undefined} compact />
<Button size="sm" variant="ghost" className="h-7 px-1.5" title="تکثیر" onClick={() => duplicateLesson(l)}>
<Copy className="h-3.5 w-3.5" />
</Button>
<Button size="sm" variant="ghost" className="h-7 px-1.5" onClick={() => setLessonModal(l)} title="ویرایش">
<Pencil className="h-3.5 w-3.5" />
</Button>
{/* Up/down reorder (accessible) */}
<GroupNav
onUp={li > 0 ? () => moveLesson(ch.id, li, -1) : undefined}
onDown={li < ls.length - 1 ? () => moveLesson(ch.id, li, 1) : undefined}
compact
/>
{/* Edit (primary action) */}
<Button
size="sm"
variant="ghost"
className="h-7 px-1.5 text-[10px]"
title={l.isPublished ? "برگشت به پیش‌نویس" : "انتشار درس"}
onClick={() => publishLesson(l, !l.isPublished)}
className="h-8 w-8 shrink-0 px-0"
title="ویرایش درس"
aria-label={`ویرایش ${l.title}`}
onClick={() => setLessonModal(l)}
>
{l.isPublished ? "برگشت" : "انتشار"}
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button size="sm" variant="ghost" className="h-7 w-7 px-0 text-destructive opacity-60 hover:opacity-100" onClick={() => delLesson(l)} title="حذف درس">
<Trash2 className="h-3.5 w-3.5" />
{/* Secondary actions menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 shrink-0 px-0"
aria-label={`اقدامات ${l.title}`}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuLabel className="truncate">L{l.id}</DropdownMenuLabel>
<DropdownMenuItem onClick={() => duplicateLesson(l)}>
<Copy className="h-3.5 w-3.5" /> تکثیر
</DropdownMenuItem>
<DropdownMenuItem onClick={() => publishLesson(l, !l.isPublished)}>
{l.isPublished ? (
<><EyeOff className="h-3.5 w-3.5" /> برگشت به پیش‌نویس</>
) : (
<><Globe className="h-3.5 w-3.5" /> انتشار درس</>
)}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={() => delLesson(l)}
>
<Trash2 className="h-3.5 w-3.5" /> حذف درس
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
})}
</div>
)}
{/* Add lesson footer */}
<div className="border-t border-border/60 px-3 py-2.5">
<Button
size="sm"
variant="outline"
className="gap-1.5"
onClick={() => newLesson(ch.id)}
>
<Plus className="h-3.5 w-3.5" /> درس جدید در این فصل
</Button>
</div>
</div>
)}
</div>
);
})}
</div>
{chapters.length === 0 && !isLoading && (
<div className="rounded-xl border border-dashed border-border p-8 text-center">
<div className="rounded-xl border border-dashed border-border p-10 text-center">
<p className="font-bold">هنوز فصلی نیست</p>
<p className="mt-1 text-sm text-muted-foreground">با «فصل جدید» شروع کنید؛ درس‌های هر فصل روی درخت مهارت هنرجو نمایش داده می‌شود.</p>
<p className="mt-1 text-sm text-muted-foreground">
با «فصل جدید» شروع کنید؛ درس‌های هر فصل روی درخت مهارت هنرجو نمایش داده می‌شود.
</p>
<Button
className="mt-4"
onClick={() => setChapterModal({ id: 0, title: "", description: "", icon: "terminal", sortOrder: 1, isPublished: false })}
>
<Plus className="h-4 w-4" /> فصل جدید
</Button>
</div>
)}
</CardContent>
</Card>
<ChapterDialog chapter={chapterModal} onClose={() => setChapterModal(null)} onSave={saveChapter} />
<LessonDialog
@@ -1437,11 +1614,11 @@ function EventDialog({ event, onClose, onSave }: { event: AdminEvent | null; onC
</div>
<div className="space-y-1.5">
<Label>توضیحات</Label>
<textarea
<Textarea
value={draft.description}
onChange={(e) => set({ description: e.target.value })}
rows={3}
className="w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
className="resize-y"
placeholder="شرح کوتاه رویداد (اختیاری)…"
/>
</div>
@@ -19,9 +19,9 @@ import {
} from "lucide-react";
import { http, toUserError } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Dialog,
DialogContent,
@@ -158,16 +158,10 @@ export function AnnouncePanel() {
return (
<>
<div className="flex flex-col gap-6">
<div data-announce-compose className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-base">نگارش اعلان</CardTitle>
<p className="text-xs text-muted-foreground">
به همه هنرجویان فعال می‌رسد و در مرکز اعلان‌ها دیده می‌شود.
</p>
</CardHeader>
<CardContent className="space-y-5">
{/* Composer + Live Preview */}
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_18rem]">
{/* Form */}
<div className="space-y-5">
<div className="space-y-2">
<Label className="text-sm font-bold">عنوان</Label>
<Input
@@ -184,15 +178,12 @@ export function AnnouncePanel() {
<Label className="text-sm font-bold">پیام</Label>
<span className="text-[11px] tabular-nums text-muted-foreground">{body.length}/۴۰۰۰</span>
</div>
<textarea
<Textarea
value={body}
onChange={(e) => setBody(e.target.value.slice(0, 4000))}
rows={5}
maxLength={4000}
className={cn(
"w-full resize-y rounded-xl border bg-background px-4 py-3 text-sm leading-relaxed focus:outline-none focus:ring-2 focus:ring-primary",
!bodyOk && body.length > 0 ? "border-destructive/50" : "border-input"
)}
className={cn("resize-y", !bodyOk && body.length > 0 ? "border-destructive/50" : "")}
placeholder="یک جملهٔ واضح و کوتاه — لینک یا زمان را حتماً بگویید…"
/>
{body.trim().length > 0 && body.trim().length < 8 && (
@@ -236,9 +227,9 @@ export function AnnouncePanel() {
<div className="space-y-2">
<Label className="flex h-5 items-center gap-1.5 text-sm font-bold">
<Route className="h-3.5 w-3.5" /> با زدن اعلان این صفحه باز می‌شود
<Route className="h-3.5 w-3.5" /> صفحه‌ای که با کلیک باز می‌شود
</Label>
<p className="text-[11px] text-muted-foreground">خالی بگذارید تا اعلان فقط خوانده شود و صفحه‌ای باز نکند.</p>
<p className="text-[11px] text-muted-foreground">خالی بگذارید تا اعلان فقط خوانده شود.</p>
<div className="flex flex-wrap gap-2">
{ROUTES.map((r) => (
<button
@@ -277,68 +268,65 @@ export function AnnouncePanel() {
onClick={() => setConfirmOpen(true)}
>
<Eye className="h-4 w-4" />
پیش‌نمایش و ارسال
{editingId ? "پیش‌نمایش و ذخیره" : "پیش‌نمایش و ارسال"}
</Button>
{editingId && (
<Button
size="lg"
variant="outline"
onClick={() => { setEditingId(null); setTitle(""); setBody(""); setPinned(false); }}
>
انصراف از ویرایش
</Button>
)}
{!valid && (
<p className="text-xs text-muted-foreground">عنوان و پیام را کامل کنید تا ادامه فعال شود.</p>
)}
</div>
</CardContent>
</Card>
</div>
<div className="space-y-4">
<Card className="border bg-muted/20">
<CardHeader className="space-y-1 pb-3">
<CardTitle className="flex h-6 items-center gap-2 text-sm">
{/* Sidebar: live preview + last sent */}
<div className="space-y-4 lg:sticky lg:top-24">
<div className="space-y-1.5">
<p className="flex items-center gap-1.5 text-xs font-bold text-muted-foreground">
<Eye className="h-3.5 w-3.5" /> پیش‌نمایش زنده
</CardTitle>
<p className="text-[11px] text-muted-foreground">هم‌زمان با تایپ به‌روز می‌شود.</p>
</CardHeader>
<CardContent>
</p>
<PreviewCard title={title} body={body} category={category} route={route} />
</CardContent>
</Card>
</div>
{lastSent && (
<Card className="border border-success/40 bg-success/5">
<CardContent className="space-y-1 pt-5 text-sm">
<div className="rounded-xl border border-success/40 bg-success/5 px-4 py-3 text-sm">
<p className="font-bold text-success">آخرین ارسال موفق</p>
<p className="truncate font-extrabold">{lastSent.title}</p>
<p className="mt-0.5 truncate font-extrabold">{lastSent.title}</p>
<p className="text-xs text-muted-foreground">{lastSent.recipients} گیرنده</p>
</CardContent>
</Card>
</div>
)}
</div>
</div>
<Card data-announce-list className="rounded-2xl border border-border">
<CardHeader>
<CardTitle className="text-base">اطلاعیه‌های ثبت‌شده</CardTitle>
</CardHeader>
<CardContent>
{/* History */}
<div className="mt-8 space-y-3 border-t border-border/70 pt-6">
<h3 className="text-sm font-black text-muted-foreground">اطلاعیه‌های ثبت‌شده</h3>
{(listQ.data?.announcements ?? []).length > 0 ? (
<ul className="flex list-none flex-col gap-3 p-0">
<ul className="flex list-none flex-col gap-2.5 p-0">
{(listQ.data?.announcements ?? []).map((a) => {
const cat = CATEGORIES.find((c) => c.id === a.category);
const excerpt = announcementExcerpt(a.body);
return (
<li key={a.id} className="rounded-2xl border border-border bg-background p-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<li key={a.id} className="flex flex-col gap-3 rounded-2xl border border-border bg-background p-4 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 flex-1 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<p className="min-w-0 text-sm font-bold leading-snug">{a.title}</p>
<Badge variant="secondary" className="text-[10px]">
{cat?.label ?? a.category}
</Badge>
{a.pinned ? (
<Badge variant="gold" className="text-[10px]">
سنجاق
</Badge>
) : null}
{a.pinned && (
<Badge variant="gold" className="text-[10px]">سنجاق</Badge>
)}
</div>
{excerpt ? (
{excerpt && (
<p className="line-clamp-2 text-xs leading-relaxed text-muted-foreground">{excerpt}</p>
) : null}
)}
</div>
<div className="flex shrink-0 items-center gap-2">
<Button
@@ -352,6 +340,7 @@ export function AnnouncePanel() {
setCategory(a.category);
setRoute(a.route);
setPinned(a.pinned);
window.scrollTo({ top: 0, behavior: "smooth" });
}}
>
ویرایش
@@ -371,7 +360,6 @@ export function AnnouncePanel() {
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
</li>
);
})}
@@ -381,8 +369,6 @@ export function AnnouncePanel() {
هنوز اطلاعیه‌ای ثبت نشده است.
</p>
) : null}
</CardContent>
</Card>
</div>
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
@@ -5,9 +5,9 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Plus, Trash2, Trophy } from "lucide-react";
import { http, toUserError } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Skeleton } from "@/components/ui/skeleton";
@@ -86,20 +86,7 @@ export function ChallengesPanel() {
minute: "2-digit",
}).format(new Date(iso));
return (
<>
{dialog}
<Card>
<CardHeader className="flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">چالش‌های امتیاز</CardTitle>
<p className="mt-1 text-xs text-muted-foreground">
چالش ماهانه با هدف امتیاز؛ پیشرفت هنرجو با تکمیل آزمون‌ها به‌روز می‌شود.
</p>
</div>
<Button
className="gap-1.5"
onClick={() =>
const newChallenge = () =>
setModal({
id: 0,
title: "",
@@ -109,13 +96,21 @@ export function ChallengesPanel() {
endsAt: "",
isActive: true,
createdAt: "",
})
}
>
});
return (
<>
{dialog}
<div className="space-y-4">
<div className="flex items-center justify-between gap-4">
<p className="text-xs text-muted-foreground">
پیشرفت هنرجو با تکمیل آزمون‌ها به‌روز می‌شود.
</p>
<Button className="shrink-0 gap-1.5" onClick={newChallenge}>
<Plus className="h-4 w-4" /> چالش جدید
</Button>
</CardHeader>
<CardContent>
</div>
{isLoading && (
<div className="space-y-3">
{[0, 1].map((i) => (
@@ -124,8 +119,8 @@ export function ChallengesPanel() {
</div>
)}
{isError && (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm">
<p className="font-medium text-destructive">{toUserError(error)}</p>
<div className="rounded-md border-2 border-destructive/30 bg-destructive/5 p-4 text-sm">
<p className="font-bold text-destructive">{toUserError(error)}</p>
<Button size="sm" variant="outline" className="mt-2" onClick={() => refetch()}>
تلاش دوباره
</Button>
@@ -133,7 +128,7 @@ export function ChallengesPanel() {
)}
<div className="grid gap-3 sm:grid-cols-2">
{(data?.challenges ?? []).map((c) => (
<div key={c.id} className="rounded-md border border-border p-4">
<div key={c.id} className="rounded-xl border border-border p-4">
<div className="flex items-center gap-2">
<Trophy className="h-4 w-4 text-gold" />
<Badge variant={c.isActive ? "success" : "secondary"}>{c.isActive ? "فعال" : "خاموش"}</Badge>
@@ -147,7 +142,7 @@ export function ChallengesPanel() {
</Button>
</div>
</div>
<p className="mt-2 font-medium">{c.title}</p>
<p className="mt-2 font-bold">{c.title}</p>
<p className="line-clamp-2 text-xs text-muted-foreground">{c.description || "—"}</p>
<p className="mt-1.5 text-xs text-muted-foreground">
{fmt(c.startsAt)} تا {fmt(c.endsAt)}
@@ -156,11 +151,12 @@ export function ChallengesPanel() {
))}
</div>
{!isLoading && !isError && (data?.challenges ?? []).length === 0 && (
<p className="py-8 text-center text-sm text-muted-foreground">هنوز چالشی نیست.</p>
<p className="rounded-2xl border border-dashed border-border px-4 py-6 text-center text-sm text-muted-foreground">
هنوز چالشی نیست.
</p>
)}
</CardContent>
</div>
<ChallengeDialog challenge={modal} onClose={() => setModal(null)} onSave={save} />
</Card>
</>
);
}
@@ -199,11 +195,11 @@ function ChallengeDialog({
</div>
<div className="space-y-1.5">
<Label>توضیحات</Label>
<textarea
<Textarea
value={draft.description}
onChange={(e) => set({ description: e.target.value })}
rows={3}
className="w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
className="resize-y"
placeholder="هدف و انگیزهٔ چالش…"
/>
</div>
@@ -148,7 +148,7 @@ export function LearningPanel() {
return (
<div className="space-y-4">
{(overviewQ.isError || studentsQ.isError) && (
<div className="flex flex-wrap items-center gap-3 rounded-2xl border border-destructive/40 bg-destructive/5 px-4 py-3 text-sm">
<div className="flex flex-wrap items-center gap-3 rounded-2xl border-2 border-destructive/40 bg-destructive/5 px-4 py-3 text-sm">
<AlertTriangle className="h-4 w-4 shrink-0 text-destructive" />
<p className="min-w-0 flex-1 font-bold text-destructive">
{toUserError(overviewQ.error ?? studentsQ.error, "بارگذاری داشبورد یادگیری ممکن نشد")}
@@ -6,7 +6,6 @@ import { Loader2 } from "lucide-react";
import { http, toUserError } from "@/lib/api";
import type { CertificatePhysicalOrder, PhysicalCertSettings, PhysicalOrderStatus } from "@/lib/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { toast } from "@/components/providers";
@@ -75,16 +74,16 @@ export function PhysicalOrdersPanel() {
};
return (
<Card>
<CardHeader className="flex flex-row flex-wrap items-center justify-between gap-3 space-y-0">
<CardTitle className="text-base">فهرست سفارش‌ها</CardTitle>
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">پیگیری درخواست و ارسال گواهینامه فیزیکی.</p>
<div className="flex flex-wrap items-center gap-2">
<select
className="h-10 rounded-lg border border-input bg-card px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
>
<option value="">همه</option>
<option value="">همه وضعیت‌ها</option>
<option value="requested">درخواست‌شده</option>
<option value="paid">پرداخت‌شده</option>
<option value="shipped">ارسال‌شده</option>
@@ -97,15 +96,15 @@ export function PhysicalOrdersPanel() {
</span>
)}
</div>
</CardHeader>
<CardContent className="space-y-2">
</div>
<div className="space-y-2">
{isLoading && (
<div className="flex justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
)}
{(data?.orders ?? []).map((o) => (
<div key={o.id} className="space-y-2 rounded-md border border-border px-3 py-3">
<div key={o.id} className="space-y-2 rounded-xl border border-border px-3 py-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<p className="text-sm font-medium">{o.userName ?? `کاربر ${o.userId}`}</p>
@@ -167,7 +166,9 @@ export function PhysicalOrdersPanel() {
</div>
))}
{!isLoading && (data?.orders ?? []).length === 0 && (
<p className="py-8 text-center text-sm text-muted-foreground">سفارشی نیست.</p>
<p className="rounded-2xl border border-dashed border-border px-4 py-6 text-center text-sm text-muted-foreground">
سفارشی نیست.
</p>
)}
<ListPagination
page={page}
@@ -175,7 +176,7 @@ export function PhysicalOrdersPanel() {
total={data?.total ?? 0}
onPageChange={setPage}
/>
</CardContent>
</Card>
</div>
</div>
);
}
@@ -238,7 +238,7 @@ function AccountFact({
{icon}
{label}
</dt>
<dd className={cn("mt-1.5 text-sm font-semibold leading-relaxed [overflow-wrap:anywhere]", ltr && "font-latin")} dir={ltr ? "ltr" : undefined}>
<dd className={cn("mt-1.5 text-sm font-bold leading-relaxed [overflow-wrap:anywhere]", ltr && "font-latin")} dir={ltr ? "ltr" : undefined}>
{value}
</dd>
</div>
@@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
Dialog,
@@ -338,15 +339,15 @@ function QuestionDialog({
<div className="space-y-5">
<div className="space-y-2">
<Label className="text-sm font-bold">متن سوال</Label>
<textarea
<Textarea
value={draft.question}
onChange={(e) => set({ question: e.target.value })}
rows={3}
autoFocus
placeholder="مثلاً نتیجهٔ اجرای git status چیست؟"
className={cn(
"w-full resize-y rounded-xl border bg-background px-4 py-3 text-base font-medium leading-relaxed focus:outline-none focus:ring-2 focus:ring-primary",
questionOk ? "border-input" : "border-destructive/40"
"resize-y",
questionOk ? "" : "border-destructive/40"
)}
/>
{!questionOk && (
@@ -485,7 +486,7 @@ function QuestionDialog({
>
<span
className={cn(
"flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md border px-1.5 text-[11px] font-semibold",
"flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md border px-1.5 text-[11px] font-bold",
isAns
? "border-primary bg-primary text-primary-foreground"
: "border-border text-muted-foreground"
@@ -1,21 +1,139 @@
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { Heart, Loader2, Package, Save, Settings2, Share2, Sparkles } from "lucide-react";
import { http, toUserError } from "@/lib/api";
import { useEffect, useRef, useState } from "react";
import { Camera, Heart, Loader2, Package, Save, Settings2, Share2, Sparkles, Trash2, Users } from "lucide-react";
import { apiForm, http, toUserError } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { TagInput } from "@/components/ui/tag-input";
import { AvatarCropDialog } from "@/components/avatar-crop";
import { toast } from "@/components/providers";
import type { AdminTabId } from "@/components/admin/nav";
import { cn } from "@/lib/utils";
type SettingsMap = Record<string, string>;
type SponsorDraft = { name: string; url: string; blurb: string };
type SocialDraft = { name: string; url: string };
type ContributorDraft = { name: string; role: string; bio: string; url: string; avatar: string; contributions: string[] };
function ContributorAvatarPicker({
value,
name,
onChange,
}: {
value: string;
name: string;
onChange: (url: string) => void;
}) {
const fileRef = useRef<HTMLInputElement>(null);
const [pending, setPending] = useState<File | null>(null);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
const initials = name
.split(" ")
.map((w) => w[0])
.slice(0, 2)
.join("")
.toUpperCase() || "؟";
const onUpload = async (blob: Blob) => {
setUploading(true);
setError(null);
try {
const form = new FormData();
form.append("file", new File([blob], "avatar.png", { type: "image/png" }), "avatar.png");
const { url } = await apiForm<{ url: string }>("/api/admin/contributor-avatar", form);
onChange(url);
setPending(null);
} catch (e) {
setError(toUserError(e, "خطا در آپلود"));
} finally {
setUploading(false);
}
};
return (
<div className="flex items-center gap-3">
<div className="relative shrink-0">
{value ? (
<img
src={value}
alt={name}
className="h-14 w-14 rounded-full border-2 border-border object-cover"
/>
) : (
<span className="flex h-14 w-14 items-center justify-center rounded-full border-2 border-dashed border-border bg-muted text-sm font-bold text-muted-foreground">
{initials}
</span>
)}
{uploading && (
<span className="absolute inset-0 flex items-center justify-center rounded-full bg-background/70">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
</span>
)}
</div>
<div className="flex flex-col gap-1.5">
<div className="flex gap-1.5">
<button
type="button"
disabled={uploading}
onClick={() => fileRef.current?.click()}
className={cn(
"flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-bold text-primary-foreground disabled:opacity-50",
)}
>
<Camera className="h-3 w-3" />
{value ? "تغییر" : "آپلود"}
</button>
{value && (
<button
type="button"
disabled={uploading}
onClick={() => onChange("")}
className="flex items-center gap-1 rounded-md bg-destructive/10 px-2.5 py-1 text-xs font-bold text-destructive disabled:opacity-50"
>
<Trash2 className="h-3 w-3" />
حذف
</button>
)}
</div>
{error && <p className="text-[11px] text-destructive">{error}</p>}
<input
ref={fileRef}
type="file"
accept="image/png,image/jpeg,image/webp"
className="hidden"
onChange={(e) => {
const f = e.target.files?.[0];
if (f) setPending(f);
e.target.value = "";
}}
/>
</div>
<AvatarCropDialog
file={pending}
busy={uploading}
error={error}
onCancel={() => {
if (uploading) return;
setPending(null);
setError(null);
}}
onInvalid={() => {
setPending(null);
setError("خواندن این عکس ممکن نشد. JPEG، PNG یا WebP را انتخاب کنید.");
}}
onCrop={(blob) => onUpload(blob)}
/>
</div>
);
}
function SectionHeading({
icon: Icon,
@@ -46,6 +164,7 @@ export function SiteSettingsPanel({
const [draft, setDraft] = useState<SettingsMap>({});
const [sponsors, setSponsors] = useState<SponsorDraft[]>([]);
const [socials, setSocials] = useState<SocialDraft[]>([]);
const [contributors, setContributors] = useState<ContributorDraft[]>([]);
const [busy, setBusy] = useState(false);
const { data, isLoading } = useQuery({
@@ -76,6 +195,25 @@ export function SiteSettingsPanel({
} catch {
setSocials([]);
}
try {
const parsed = JSON.parse(data.settings.contributors || "[]") as Array<Record<string, unknown>>;
setContributors(
Array.isArray(parsed)
? parsed.map((c) => ({
name: typeof c.name === "string" ? c.name : "",
role: typeof c.role === "string" ? c.role : "",
bio: typeof c.bio === "string" ? c.bio : "",
url: typeof c.url === "string" ? c.url : "",
avatar: typeof c.avatar === "string" ? c.avatar : "",
contributions: Array.isArray(c.contributions)
? (c.contributions as unknown[]).filter((x): x is string => typeof x === "string")
: [],
}))
: [],
);
} catch {
setContributors([]);
}
}, [data]);
const set = (key: string, value: string) => setDraft((d) => ({ ...d, [key]: value }));
@@ -126,11 +264,24 @@ export function SiteSettingsPanel({
blurb: s.blurb.trim(),
})),
),
contributors: JSON.stringify(
contributors
.filter((c) => c.name.trim())
.map((c) => ({
name: c.name.trim(),
role: c.role.trim(),
bio: c.bio.trim(),
url: c.url.trim(),
avatar: c.avatar.trim(),
contributions: c.contributions.map((s) => s.trim()).filter(Boolean),
})),
),
};
await http.put("/api/admin/settings", { settings });
toast.success("تنظیمات ذخیره شد");
qc.invalidateQueries({ queryKey: ["admin", "settings"] });
qc.invalidateQueries({ queryKey: ["community"] });
qc.invalidateQueries({ queryKey: ["contributors"] });
qc.invalidateQueries({ queryKey: ["sponsors"] });
qc.invalidateQueries({ queryKey: ["auth", "register-status"] });
} catch (e) {
@@ -327,6 +478,97 @@ export function SiteSettingsPanel({
))}
</section>
<section className="space-y-3">
<div className="flex items-end justify-between gap-3">
<SectionHeading
icon={Users}
title="مشارکت‌کنندگان"
hint="افرادی که در ساخت پرگار سهیم بوده‌اند. در زبانه جامعه نمایش داده می‌شود."
/>
<Button
type="button"
size="sm"
variant="outline"
className="mb-2 shrink-0"
onClick={() =>
setContributors((list) => [
...list,
{ name: "", role: "", bio: "", url: "", avatar: "", contributions: [] },
])
}
>
افزودن
</Button>
</div>
{contributors.length === 0 && (
<p className="rounded-xl border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground">
هنوز مشارکت‌کننده‌ای ثبت نشده. با «افزودن» شروع کنید.
</p>
)}
{contributors.map((c, i) => (
<div key={i} className="space-y-3 rounded-xl border border-border p-3">
<ContributorAvatarPicker
value={c.avatar}
name={c.name || "مشارکت‌کننده"}
onChange={(url) =>
setContributors((list) => list.map((x, j) => (j === i ? { ...x, avatar: url } : x)))
}
/>
<div className="grid gap-2 sm:grid-cols-2">
<Input
placeholder="نام"
value={c.name}
onChange={(e) =>
setContributors((list) => list.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)))
}
/>
<Input
placeholder="نقش (مثال: بنیان‌گذار)"
value={c.role}
onChange={(e) =>
setContributors((list) => list.map((x, j) => (j === i ? { ...x, role: e.target.value } : x)))
}
/>
</div>
<Textarea
placeholder="بیوگرافی کوتاه (اختیاری)"
value={c.bio}
rows={2}
onChange={(e) =>
setContributors((list) => list.map((x, j) => (j === i ? { ...x, bio: e.target.value } : x)))
}
/>
<Input
placeholder="لینک پروفایل (اختیاری، https://…)"
value={c.url}
dir="ltr"
onChange={(e) =>
setContributors((list) => list.map((x, j) => (j === i ? { ...x, url: e.target.value } : x)))
}
/>
<div className="space-y-1">
<p className="text-[11px] text-muted-foreground">دسته‌های مشارکت — Enter یا کاما برای افزودن</p>
<TagInput
value={c.contributions}
onChange={(tags) =>
setContributors((list) => list.map((x, j) => (j === i ? { ...x, contributions: tags } : x)))
}
placeholder="توسعه، طراحی، محتوا…"
/>
</div>
<Button
type="button"
size="sm"
variant="ghost"
className="text-destructive"
onClick={() => setContributors((list) => list.filter((_, j) => j !== i))}
>
حذف مشارکت‌کننده
</Button>
</div>
))}
</section>
<p className="text-[11px] text-muted-foreground">
رمزها، دیتابیس و JWT همچنان در فایل محیط (.env) می‌مانند — اینجا فقط تنظیمات قابل‌تغییر
روزمره است.
+99 -4
View File
@@ -1,17 +1,50 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { ExternalLink, Share2 } from "lucide-react";
import { ExternalLink, Share2, Tag, Users } from "lucide-react";
import { http, toUserError } from "@/lib/api";
import { Panel } from "@/components/panel";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import type { Contributor } from "@/lib/types";
export type SocialLink = { name: string; url: string };
export type CommunityPayload = {
socials: SocialLink[];
contributors: Contributor[];
};
function ContributorAvatar({ contributor }: { contributor: Contributor }) {
if (contributor.avatar) {
return (
<img
src={contributor.avatar}
alt={contributor.name}
className="h-12 w-12 shrink-0 rounded-full border-2 border-border object-cover"
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
(e.currentTarget.nextElementSibling as HTMLElement | null)?.removeAttribute("hidden");
}}
/>
);
}
const initials = contributor.name
.split(" ")
.map((w) => w[0])
.slice(0, 2)
.join("")
.toUpperCase();
return (
<span
aria-hidden
className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full border-2 border-border bg-primary/10 text-sm font-bold text-primary"
>
{initials}
</span>
);
}
export function CommunityPanel() {
const { data, isLoading, isError, error, refetch } = useQuery({
queryKey: ["community"],
@@ -19,12 +52,17 @@ export function CommunityPanel() {
});
if (isLoading) {
return <div className="h-72 animate-pulse rounded-2xl border-2 border-border bg-muted/40" />;
return (
<div className="mx-auto max-w-2xl space-y-4">
<div className="h-40 animate-pulse rounded-2xl border-2 border-border bg-muted/40" />
<div className="h-64 animate-pulse rounded-2xl border-2 border-border bg-muted/40" />
</div>
);
}
if (isError) {
return (
<div className="mx-auto max-w-xl rounded-2xl border-2 border-destructive/30 bg-destructive/5 p-8 text-center">
<div className="mx-auto max-w-2xl rounded-2xl border-2 border-destructive/30 bg-destructive/5 p-8 text-center">
<p className="font-medium text-destructive">{toUserError(error)}</p>
<Button className="mt-4" variant="outline" onClick={() => refetch()}>
تلاش دوباره
@@ -34,9 +72,11 @@ export function CommunityPanel() {
}
const socials = data?.socials ?? [];
const contributors = data?.contributors ?? [];
return (
<div className="mx-auto max-w-xl">
<div className="mx-auto max-w-2xl space-y-4">
{/* Social links */}
<Panel
title="شبکه‌های پرگار"
description="راه‌های رسمی ارتباط با برنامه. لینک شخصی هر کاربر روی پروفایل خودش است."
@@ -63,6 +103,61 @@ export function CommunityPanel() {
</ul>
)}
</Panel>
{/* Contributors */}
<Panel
title="مشارکت‌کنندگان"
description="افرادی که در ساخت پرگار سهیم بوده‌اند. ممنون از هر کمکی."
icon={<Users className="h-5 w-5" />}
tint="bg-emerald-500/15 text-emerald-600 dark:text-emerald-400"
>
{contributors.length === 0 ? (
<p className="py-8 text-center text-sm text-muted-foreground">اطلاعات مشارکت‌کنندگان هنوز ثبت نشده است.</p>
) : (
<ul className="divide-y divide-border/60">
{contributors.map((c, i) => (
<li key={i} className="flex flex-col gap-3 py-4 first:pt-0 last:pb-0 sm:flex-row sm:items-start">
<ContributorAvatar contributor={c} />
<div className="min-w-0 flex-1 space-y-1.5">
<div className="flex flex-wrap items-center gap-2">
{c.url ? (
<a
href={c.url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 font-bold hover:text-primary hover:underline"
>
{c.name}
<ExternalLink className="h-3 w-3 shrink-0 text-muted-foreground" />
</a>
) : (
<span className="font-bold">{c.name}</span>
)}
{c.role && (
<span className="text-xs text-muted-foreground">{c.role}</span>
)}
</div>
{c.bio && <p className="text-sm leading-relaxed text-muted-foreground">{c.bio}</p>}
{c.contributions.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{c.contributions.map((cat) => (
<Badge
key={cat}
variant="secondary"
className="gap-1 px-2 py-0.5 text-xs"
>
<Tag className="h-3 w-3" />
{cat}
</Badge>
))}
</div>
)}
</div>
</li>
))}
</ul>
)}
</Panel>
</div>
);
}
+1 -1
View File
@@ -27,7 +27,7 @@ export function EmptyState({
</span>
)}
<div className="space-y-1 px-6">
<p className="text-sm font-semibold">{title}</p>
<p className="text-sm font-bold">{title}</p>
{description && <p className="text-xs leading-relaxed text-muted-foreground sm:text-sm">{description}</p>}
</div>
{action && <div className="mt-1">{action}</div>}
-65
View File
@@ -1,65 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Search } from "lucide-react";
import { http } from "@/lib/api";
type Hit = { kind: string; title: string; href: string };
export function GlobalSearch() {
const router = useRouter();
const [q, setQ] = useState("");
const [hits, setHits] = useState<Hit[]>([]);
const [open, setOpen] = useState(false);
useEffect(() => {
const query = q.trim();
if (query.length < 2) {
setHits([]);
return;
}
const t = setTimeout(() => {
void http
.get<{ results: Hit[] }>(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => setHits(res.results ?? []))
.catch(() => setHits([]));
}, 250);
return () => clearTimeout(t);
}, [q]);
return (
<div className="relative min-w-0 w-28 sm:w-56">
<Search className="pointer-events-none absolute start-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<input
value={q}
onChange={(e) => {
setQ(e.target.value);
setOpen(true);
}}
onFocus={() => setOpen(true)}
placeholder="جستجو"
className="h-9 w-full rounded-full border border-border bg-background/70 ps-8 pe-3 text-sm outline-none focus:border-primary"
/>
{open && hits.length > 0 && (
<div className="absolute z-50 mt-1 w-full overflow-hidden rounded-xl border bg-popover shadow-lg">
{hits.map((h) => (
<button
key={h.kind + h.href + h.title}
type="button"
className="block w-full px-3 py-2 text-start text-sm hover:bg-muted"
onClick={() => {
setOpen(false);
setQ("");
router.push(h.href);
}}
>
<span className="text-[10px] text-muted-foreground">{h.kind}</span>
<span className="block truncate font-bold">{h.title}</span>
</button>
))}
</div>
)}
</div>
);
}
@@ -68,7 +68,7 @@ export function LeaderboardPanel() {
if (isError) {
return (
<div className="mx-auto max-w-2xl rounded-xl border border-destructive/30 bg-destructive/5 p-6 text-center">
<div className="mx-auto max-w-2xl rounded-xl border-2 border-destructive/30 bg-destructive/5 p-6 text-center">
<p className="font-medium text-destructive">{toUserError(error)}</p>
<Button className="mt-3" variant="outline" onClick={() => refetch()}>
تلاش دوباره
+4 -2
View File
@@ -3269,7 +3269,7 @@ ws.onmessage = (ev) => {
setOpen(true);
setNotif(null);
}}
className="fixed bottom-24 start-5 end-5 z-[64] flex max-w-full items-center gap-2.5 rounded-2xl border-2 border-white/50 bg-card/85 p-2.5 text-right shadow-offset backdrop-blur-2xl sm:end-auto sm:max-w-[300px]"
className="fixed bottom-[calc(5.5rem+env(safe-area-inset-bottom,0px))] start-5 end-5 z-[64] flex max-w-full items-center gap-2.5 rounded-2xl border-2 border-white/50 bg-card/85 p-2.5 text-right shadow-offset backdrop-blur-2xl sm:bottom-24 sm:end-auto sm:max-w-[300px]"
>
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-accent/15">
<MessageSquare className="h-4 w-4 text-accent" />
@@ -3286,7 +3286,9 @@ ws.onmessage = (ev) => {
</AnimatePresence>
{me && !open && (
<div className="fixed bottom-5 start-5 z-[64]">
// On mobile the bottom nav is 56px; lift FAB above it + safe area + gap.
// md:bottom-5 restores original position when the bottom nav is hidden.
<div className="fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom,0px))] start-5 z-[64] md:bottom-5">
<div className="relative">
{unreadTotal > 0 && (
<span className="pointer-events-none absolute -inset-1 -z-10 animate-ping rounded-2xl bg-accent/40" aria-hidden />
+3 -5
View File
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Flame, Heart, LogOut, Sparkles, User, UserCog } from "lucide-react";
import { Flame, Heart, LogOut, Palette, Settings, Sparkles, User, UserCog } from "lucide-react";
import { NotificationBell } from "@/components/notification-bell";
import { ThemeToggle } from "@/components/theme-toggle";
import { BrandMark } from "@/components/brand-mark";
@@ -28,7 +28,6 @@ import {
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { cn, formatFaNumber } from "@/lib/utils";
import { GlobalSearch } from "@/components/global-search";
import { isVerifiedRole, VerifiedBadge } from "@/components/verified-badge";
const navLinks = [
@@ -65,7 +64,6 @@ export function Navbar() {
<BrandMark />
</Link>
<div className="flex items-center gap-2">
<GlobalSearch />
<ThemeToggle />
{pathname !== "/login" && (
<Button asChild size="sm" className="font-bold">
@@ -188,10 +186,10 @@ export function Navbar() {
<User /> پروفایل من
</DropdownMenuItem>
<DropdownMenuItem onClick={() => router.push("/settings")}>
<User /> تنظیمات
<Settings /> تنظیمات
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setStudioOpen(true)}>
<User /> ویرایش آواتار
<Palette /> ویرایش آواتار
</DropdownMenuItem>
{liveUser.role === "admin" && (
<DropdownMenuItem onClick={() => router.push("/admin")}>
@@ -64,7 +64,7 @@ export function NotificationBell() {
<div dir="rtl" className="text-start">
<div className="flex items-center justify-between gap-3 border-b border-border px-3 py-2.5">
<div className="min-w-0">
<p className="text-sm font-semibold">اعلان‌ها</p>
<p className="text-sm font-bold">اعلان‌ها</p>
<p className="text-[11px] text-muted-foreground">
{unread > 0 ? `${unread} خوانده‌نشده` : "همه خوانده شده"}
</p>
@@ -133,7 +133,7 @@ export function NotificationBell() {
<button
type="button"
onClick={() => router.push("/notifications")}
className="w-full border-t border-border bg-muted/40 py-2.5 text-xs font-semibold text-primary hover:bg-muted"
className="w-full border-t border-border bg-muted/40 py-2.5 text-xs font-bold text-primary hover:bg-muted"
>
مشاهده همه اعلان‌ها
</button>
+5 -5
View File
@@ -119,7 +119,7 @@ export function QuizExperience({ lessonId }: { lessonId: number }) {
return (
<Card className="mx-auto max-w-md p-8 text-center">
<Lock className="mx-auto mb-3 h-10 w-10 text-destructive" />
<h2 className="mb-2 text-lg font-semibold">آزمون در دسترس نیست</h2>
<h2 className="mb-2 text-lg font-bold">آزمون در دسترس نیست</h2>
<p className="mb-4 text-sm text-muted-foreground">{msg}</p>
<Button onClick={() => router.push(`/player/${lessonId}`)}>ابتدا درس را تماشا کنید</Button>
</Card>
@@ -188,7 +188,7 @@ export function QuizExperience({ lessonId }: { lessonId: number }) {
<Badge variant="secondary" className="h-6 w-6 justify-center rounded-md p-0">
{qi + 1}
</Badge>
<p className="font-medium leading-snug">{q.question}</p>
<p className="font-bold leading-snug">{q.question}</p>
</div>
<div className="grid gap-2">
{q.options.map((opt, oi) => {
@@ -198,7 +198,7 @@ export function QuizExperience({ lessonId }: { lessonId: number }) {
key={oi}
onClick={() => select(q.id, oi)}
className={cn(
"flex items-center gap-3 rounded-md border px-4 py-3 text-right text-sm transition-colors",
"flex items-center gap-3 rounded-md border-2 px-4 py-3 text-right text-sm transition-colors",
active
? "border-primary bg-primary/10 ring-1 ring-primary"
: "border-border hover:bg-muted/50"
@@ -206,7 +206,7 @@ export function QuizExperience({ lessonId }: { lessonId: number }) {
>
<span
className={cn(
"flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md border px-1.5 text-[11px] font-semibold",
"flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md border px-1.5 text-[11px] font-bold",
active ? "border-primary bg-primary text-primary-foreground" : "border-border text-muted-foreground"
)}
>
@@ -305,7 +305,7 @@ function HeartsMeterInline({ hearts, infinite }: { hearts: number; infinite?: bo
function PassScreen({ result, onNext, onLeagues }: { result: QuizResult; onNext: () => void; onLeagues: () => void }) {
return (
<div className="mx-auto max-w-md rounded-lg border border-border bg-card p-10 text-center">
<div className="mx-auto max-w-md rounded-2xl border-2 border-border bg-card p-10 text-center">
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-lg bg-primary">
<PartyPopper className="h-9 w-9 text-primary-foreground" />
</div>
+9 -4
View File
@@ -103,21 +103,26 @@ export function SectionPanel({
titleId,
title,
description,
actions,
children,
}: {
id?: string;
titleId: string;
title: string;
description: string;
actions?: ReactNode;
children: ReactNode;
}) {
return (
<section id={id} aria-labelledby={titleId} className="min-w-0 rounded-2xl border-2 border-border bg-card">
<header className="border-b border-border/70 px-5 py-4 sm:px-6">
<h2 id={titleId} className="text-lg font-black">
{title}
</h2>
<p className="mt-1 text-sm text-muted-foreground">{description}</p>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<h2 id={titleId} className="text-lg font-black">{title}</h2>
{description && <p className="mt-1 text-sm text-muted-foreground">{description}</p>}
</div>
{actions && <div className="shrink-0">{actions}</div>}
</div>
</header>
<div className="p-5 sm:p-6">{children}</div>
</section>
+20 -2
View File
@@ -21,6 +21,7 @@ import {
} from "lucide-react";
import { useMemo, useState } from "react";
import type { TreeChapter, TreeData, TreeLesson } from "@/lib/types";
import { useAuth } from "@/lib/auth-store";
import { cn, formatFaNumber } from "@/lib/utils";
const CHAPTER_ICONS: Record<string, typeof Terminal> = {
@@ -38,6 +39,8 @@ const CHAPTER_ICONS: Record<string, typeof Terminal> = {
export function SkillTree({ data, onSelect }: { data: TreeData; onSelect?: (id: number) => void }) {
const router = useRouter();
const role = useAuth((s) => s.user?.role);
const isStaff = role === "admin" || role === "mentor";
const chapters = useMemo(() => [...data.chapters].sort((a, b) => a.sortOrder - b.sortOrder), [data]);
const byId = useMemo(() => {
@@ -97,6 +100,7 @@ export function SkillTree({ data, onSelect }: { data: TreeData; onSelect?: (id:
open={expanded.has(ch.id)}
onToggle={() => toggle(ch.id)}
onSelect={onSelect ?? ((id: number) => router.push(`/player/${id}`))}
isStaff={isStaff}
/>
))}
</div>
@@ -110,12 +114,14 @@ function ChapterRow({
open,
onToggle,
onSelect,
isStaff,
}: {
ch: TreeChapter;
byId: Map<number, TreeLesson>;
open: boolean;
onToggle: () => void;
onSelect: (id: number) => void;
isStaff: boolean;
}) {
const lessons = [...(ch.lessons ?? [])].sort((a, b) => a.y - b.y || a.x - b.x);
const done = lessons.filter((l) => l.progress?.passedQuiz).length;
@@ -147,8 +153,13 @@ function ChapterRow({
<CheckCircle2 className="h-3.5 w-3.5" /> کامل شد
</span>
)}
{isStaff && !ch.isPublished && (
<span className="hidden shrink-0 rounded-full border border-dashed border-warning/50 bg-warning/10 px-2 py-0.5 text-[11px] font-bold text-warning sm:inline-block">
پیش‌نویس
</span>
)}
<span className="hidden shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11px] font-bold text-muted-foreground sm:inline-block">
هفتهٔ {ch.sortOrder}
فصل {ch.sortOrder}
</span>
</div>
<p className="truncate text-xs text-muted-foreground">{ch.description}</p>
@@ -173,7 +184,7 @@ function ChapterRow({
<div className="overflow-hidden">
<div className="grid gap-2.5 border-t-2 border-border/70 p-4 sm:grid-cols-2">
{lessons.map((lesson) => (
<LessonRow key={lesson.id} lesson={lesson} byId={byId} onSelect={onSelect} />
<LessonRow key={lesson.id} lesson={lesson} byId={byId} onSelect={onSelect} isStaff={isStaff} />
))}
</div>
</div>
@@ -186,10 +197,12 @@ function LessonRow({
lesson,
byId,
onSelect,
isStaff,
}: {
lesson: TreeLesson;
byId: Map<number, TreeLesson>;
onSelect: (id: number) => void;
isStaff: boolean;
}) {
const passed = !!lesson.progress?.passedQuiz;
const locked = lesson.locked;
@@ -254,6 +267,11 @@ function LessonRow({
</div>
<div className="mt-1.5 flex flex-wrap items-center gap-2">
<span className={cn("rounded-full px-2 py-0.5 text-[11px] font-bold", s.pill)}>{s.pillText}</span>
{isStaff && lesson.isPublished === false && (
<span className="rounded-full border border-dashed border-warning/50 bg-warning/10 px-2 py-0.5 text-[11px] font-bold text-warning">
پیش‌نویس
</span>
)}
{inProgress && (
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-muted">
<div className="h-full rounded-full bg-primary" style={{ width: `${pct}%` }} />
+1 -1
View File
@@ -24,7 +24,7 @@ CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-xl font-semibold leading-none", className)} {...props} />
<div ref={ref} className={cn("text-xl font-bold leading-none", className)} {...props} />
)
);
CardTitle.displayName = "CardTitle";
+1 -1
View File
@@ -78,7 +78,7 @@ const DialogTitle = React.forwardRef<
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
className={cn("text-lg font-bold leading-none tracking-tight", className)}
{...props}
/>
));
+2 -1
View File
@@ -16,12 +16,13 @@ const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
return (
<div
ref={ref}
dir="ltr"
className={cn("relative h-2.5 w-full overflow-hidden rounded-full bg-muted", className)}
{...props}
>
<div
className={cn(
"h-full rounded-full will-change-[width] rtl:me-auto",
"h-full rounded-full will-change-[width]",
gradient ? "bg-primary" : "bg-primary",
smooth
? "transition-[width] duration-1000 ease-[cubic-bezier(0.22,1,0.36,1)]"
+93
View File
@@ -0,0 +1,93 @@
"use client";
import { useRef, useState } from "react";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
interface TagInputProps {
value: string[];
onChange: (tags: string[]) => void;
placeholder?: string;
maxTags?: number;
className?: string;
disabled?: boolean;
}
export function TagInput({
value,
onChange,
placeholder = "افزودن برچسب…",
maxTags = 20,
className,
disabled,
}: TagInputProps) {
const [input, setInput] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const add = (raw: string) => {
const tag = raw.trim();
if (!tag) return;
if (value.some((t) => t.toLowerCase() === tag.toLowerCase())) return;
if (value.length >= maxTags) return;
onChange([...value, tag]);
setInput("");
};
const remove = (index: number) => {
onChange(value.filter((_, i) => i !== index));
};
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
add(input);
} else if (e.key === "Backspace" && !input && value.length > 0) {
remove(value.length - 1);
}
};
return (
<div
className={cn(
"flex min-h-9 flex-wrap gap-1.5 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
disabled && "cursor-not-allowed opacity-50",
className,
)}
onClick={() => inputRef.current?.focus()}
>
{value.map((tag, i) => (
<span
key={i}
className="inline-flex items-center gap-1 rounded-md bg-secondary px-2 py-0.5 text-xs font-medium text-secondary-foreground"
>
{tag}
{!disabled && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
remove(i);
}}
className="ml-0.5 rounded-sm opacity-60 transition-opacity hover:opacity-100"
aria-label={`حذف ${tag}`}
>
<X className="h-3 w-3" />
</button>
)}
</span>
))}
{!disabled && value.length < maxTags && (
<input
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={onKeyDown}
onBlur={() => add(input)}
placeholder={value.length === 0 ? placeholder : ""}
className="min-w-[120px] flex-1 bg-transparent outline-none placeholder:text-muted-foreground"
dir="auto"
/>
)}
</div>
);
}
+41 -178
View File
@@ -10,13 +10,10 @@ import {
Minimize,
Pause,
Play,
RotateCcw,
Settings,
SkipBack,
Rewind,
Volume1,
Volume2,
VolumeX,
Zap,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import type Hls from "hls.js";
@@ -35,8 +32,6 @@ const CONTINUOUS_PLAY_MAX_DT = 3;
const ALLOWED_SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2] as const;
type Speed = (typeof ALLOWED_SPEEDS)[number];
const MAX_RETRY_DELAY_MS = 30_000;
const AMBIENT_FPS = 8;
const AMBIENT_INTERVAL = 1000 / AMBIENT_FPS;
const DOUBLE_TAP_MS = 300;
const DOUBLE_TAP_SLOP = 60;
@@ -54,7 +49,6 @@ function writeStorage(key: string, value: unknown) {
}
const isNumber = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
const isBoolean = (v: unknown): v is boolean => typeof v === "boolean";
// ─── Main Component ───────────────────────────────────────────────────────────
export function VideoPlayer({
@@ -73,9 +67,6 @@ export function VideoPlayer({
// ── Refs ────────────────────────────────────────────────────────────────────
const videoRef = useRef<HTMLVideoElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const ambientCanvasRef = useRef<HTMLCanvasElement>(null);
const ambientRafRef = useRef(0);
const ambientLastTickRef = useRef(0);
const hlsRef = useRef<Hls | null>(null);
const lockedSrcRef = useRef(videoUrl);
@@ -98,7 +89,6 @@ export function VideoPlayer({
// ── Persisted prefs ─────────────────────────────────────────────────────────
const [volume, setVolume] = useState(() => readStorage("pargar:volume", 1, isNumber));
const [ambientMode, setAmbientMode] = useState(() => readStorage("pargar:ambient", true, isBoolean));
const [speed, setSpeed] = useState<Speed>(() => {
const s = readStorage("pargar:speed", 1, isNumber);
return (ALLOWED_SPEEDS as readonly number[]).includes(s) ? s as Speed : 1;
@@ -121,12 +111,9 @@ export function VideoPlayer({
const [mediaDuration, setMediaDuration] = useState(duration);
const [fullscreen, setFullscreen] = useState(false);
const [theaterMode, setTheaterMode] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [seekIndicator, setSeekIndicator] = useState<"back" | null>(null);
const hideTimer = useRef<number | null>(null);
const settingsPanelRef = useRef<HTMLDivElement>(null);
const settingsBtnRef = useRef<HTMLButtonElement>(null);
// ── Utilities ───────────────────────────────────────────────────────────────
const warnSeekBlocked = useCallback(() => {
@@ -209,12 +196,6 @@ export function VideoPlayer({
changeSpeed(next);
}, [changeSpeed]);
const toggleAmbient = useCallback(() => {
setAmbientMode((prev) => {
writeStorage("pargar:ambient", !prev);
return !prev;
});
}, []);
// ── HLS init ────────────────────────────────────────────────────────────────
useEffect(() => {
@@ -445,25 +426,6 @@ export function VideoPlayer({
return () => document.removeEventListener("fullscreenchange", onFsChange);
}, []);
// ── Ambient mode rAF loop ───────────────────────────────────────────────────
useEffect(() => {
if (!ambientMode) { cancelAnimationFrame(ambientRafRef.current); return; }
const tick = (now: DOMHighResTimeStamp) => {
ambientRafRef.current = requestAnimationFrame(tick);
if (now - ambientLastTickRef.current < AMBIENT_INTERVAL) return;
ambientLastTickRef.current = now;
const v = videoRef.current;
const canvas = ambientCanvasRef.current;
if (!v || !canvas || v.readyState < 2 || v.paused) return;
try {
const ctx = canvas.getContext("2d");
if (ctx) ctx.drawImage(v, 0, 0, canvas.width, canvas.height);
} catch { setAmbientMode(false); } // CORS taint
};
ambientRafRef.current = requestAnimationFrame(tick);
return () => cancelAnimationFrame(ambientRafRef.current);
}, [ambientMode, playing]);
// ── Keyboard shortcuts ──────────────────────────────────────────────────────
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -492,19 +454,6 @@ export function VideoPlayer({
return () => window.removeEventListener("keydown", onKey);
}, [toggle, skipBack, warnSeekBlocked, poke, toggleFullscreen]);
// ── Settings click-outside close ────────────────────────────────────────────
useEffect(() => {
if (!settingsOpen) return;
const onMouseDown = (e: MouseEvent) => {
const target = e.target as Node;
if (settingsPanelRef.current?.contains(target)) return;
if (settingsBtnRef.current?.contains(target)) return;
setSettingsOpen(false);
};
document.addEventListener("mousedown", onMouseDown);
return () => document.removeEventListener("mousedown", onMouseDown);
}, [settingsOpen]);
// ── Cleanup timers ──────────────────────────────────────────────────────────
useEffect(() => {
return () => {
@@ -611,8 +560,8 @@ export function VideoPlayer({
<div
className={cn(
"space-y-4",
// Theater mode: break out of the page's max-w container with a full-bleed trick
theaterMode && "relative left-1/2 right-1/2 -mx-[50vw] w-screen",
// Theater mode: on mobile remove page padding; on sm+ break out to full-bleed
theaterMode && "max-sm:-mx-4 max-sm:w-[calc(100%+2rem)] sm:relative sm:left-1/2 sm:right-1/2 sm:-mx-[50vw] sm:w-screen",
)}
>
{/* ── Player container ─── */}
@@ -627,24 +576,6 @@ export function VideoPlayer({
onMouseMove={poke}
onPointerDown={handlePointerDown}
>
{/* Ambient canvas (behind video) */}
<div className="pointer-events-none absolute inset-0 z-0 overflow-hidden" aria-hidden>
<canvas
ref={ambientCanvasRef}
width={32}
height={18}
className={cn(
"absolute inset-[-15%] h-[130%] w-[130%] transition-opacity duration-1000",
ambientMode && playing ? "opacity-100" : "opacity-0",
)}
style={{
filter: "blur(55px) saturate(1.4)",
transform: "translate3d(0,0,0)",
willChange: "filter, transform",
}}
/>
</div>
{/* Video element */}
<video
ref={videoRef}
@@ -716,7 +647,7 @@ export function VideoPlayer({
</AnimatePresence>
</div>
{/* Seek indicator (double-tap feedback) */}
{/* Seek indicator (rewind feedback — physical right side) */}
<AnimatePresence>
{seekIndicator && (
<motion.div
@@ -724,10 +655,10 @@ export function VideoPlayer({
initial={{ opacity: 0, scale: 0.7 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.7 }}
className="pointer-events-none absolute start-8 top-1/2 z-30 flex -translate-y-1/2 flex-col items-center gap-1"
className="pointer-events-none absolute right-8 top-1/2 z-30 flex -translate-y-1/2 flex-col items-center gap-1"
>
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm">
<SkipBack className="h-6 w-6 text-white" />
<Rewind className="h-6 w-6 text-white" />
</div>
<span className="text-xs font-bold text-white drop-shadow">۱۰ ثانیه</span>
</motion.div>
@@ -749,159 +680,91 @@ export function VideoPlayer({
<span className="ms-auto tabular-nums">{fmt(position)} / {fmt(mediaDuration)}</span>
</div>
{/* Progress bar with hover tooltip */}
{/* Timeline — unified dir="ltr" coordinate space */}
<div
className="relative mx-4 cursor-pointer"
dir="ltr"
className="relative mx-4 cursor-pointer py-2"
onMouseMove={onProgressHover}
onMouseLeave={() => setHoverTime(null)}
>
{/* Hover timestamp tooltip */}
{hoverTime !== null && (
<div
className="pointer-events-none absolute -top-8 z-10 rounded bg-black/80 px-1.5 py-0.5 text-[11px] font-bold text-white"
className="pointer-events-none absolute -top-6 z-10 rounded bg-black/80 px-1.5 py-0.5 text-[11px] font-bold text-white"
style={{ left: `${hoverX}px`, transform: "translateX(-50%)" }}
>
{fmt(hoverTime)}
</div>
)}
{/* Buffer track */}
<div className="absolute inset-0 overflow-hidden rounded-full">
{/* Track layers stacked bottom-to-top: base → buffer → progress → thumb */}
<div className="relative h-2 overflow-hidden rounded-full bg-white/10">
{/* Buffer layer */}
<div
className="h-full rounded-full bg-white/20 transition-[width] duration-300"
className="absolute left-0 top-0 h-full rounded-full bg-white/25 transition-[width] duration-300"
style={{ width: `${bufferedPct}%` }}
/>
</div>
<Progress value={pct} className="h-2 bg-white/10" gradient />
{/* Playhead thumb */}
{/* Play progress layer */}
<div
className="pointer-events-none absolute top-1/2 h-4 w-4 -translate-y-1/2 rounded-full bg-white shadow-md transition-[inset-inline-start] duration-150"
style={{ insetInlineStart: `calc(${pct}% - 8px)` }}
className="absolute left-0 top-0 h-full rounded-full bg-primary transition-[width] duration-150"
style={{ width: `${pct}%` }}
/>
</div>
{/* Playhead thumb — positioned outside overflow:hidden, same dir="ltr" space */}
<div
className="pointer-events-none absolute top-1/2 h-4 w-4 -translate-y-1/2 rounded-full bg-white shadow-md transition-[left] duration-150"
style={{ left: `calc(${pct}% - 8px)` }}
/>
</div>
{/* Bottom control row */}
<div className="mt-3 flex flex-wrap items-center gap-1.5 px-4 pb-3">
{/* Bottom control row — dir="ltr" for physical left→right placement */}
<div dir="ltr" className="mt-1 flex items-center justify-between gap-1 px-4 pb-3">
{/* Left group: playback controls + volume + speed */}
<div className="flex items-center gap-1">
{/* Play/Pause */}
<button type="button" onClick={toggle} className="rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 min-w-[44px] min-h-[44px] flex items-center justify-center" aria-label="پخش / توقف (Space)">
<button type="button" onClick={toggle} className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20" aria-label="پخش / توقف (Space)">
{playing ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
</button>
{/* Skip back */}
<button type="button" onClick={() => { skipBack(); setSeekIndicator("back"); setTimeout(() => setSeekIndicator(null), 700); }} className="rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 min-w-[44px] min-h-[44px] flex items-center justify-center" aria-label="بازگشت ۱۰ ثانیه (J)" title="۱۰ ثانیه عقب (J/←)">
<SkipBack className="h-5 w-5 scale-x-[-1]" />
</button>
{/* Restart */}
<button type="button" onClick={() => { flushAcc(); seekProgrammatic(0); void videoRef.current?.play().catch(() => undefined); poke(); }} className="inline-flex items-center gap-1.5 rounded-full bg-white/10 px-3 py-2 text-xs font-bold text-white transition hover:bg-white/20 min-h-[44px]" aria-label="شروع از اول">
<RotateCcw className="h-4 w-4" />
<span className="hidden sm:inline">شروع از اول</span>
{/* Rewind 10s */}
<button type="button" onClick={() => { skipBack(); setSeekIndicator("back"); setTimeout(() => setSeekIndicator(null), 700); }} className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20" aria-label="بازگشت ۱۰ ثانیه (J)" title="۱۰ ثانیه عقب (J/←)">
<Rewind className="h-5 w-5" />
</button>
{/* Volume */}
<div className="flex items-center gap-1.5">
<button type="button" onClick={() => setMuted((m) => !m)} className="rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 min-w-[44px] min-h-[44px] flex items-center justify-center" aria-label="قطع صدا (M)" title="قطع/وصل صدا (M)">
<button type="button" onClick={() => setMuted((m) => !m)} className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20" aria-label="قطع صدا (M)" title="قطع/وصل صدا (M)">
<VolumeIcon className="h-5 w-5" />
</button>
<input type="range" min={0} max={1} step={0.05} value={muted ? 0 : volume} onChange={(e) => { const v = parseFloat(e.target.value); setVolume(v); if (v > 0 && muted) setMuted(false); }} className="h-1 w-16 cursor-pointer accent-white opacity-80 hover:opacity-100" aria-label="میزان صدا" />
</div>
<input type="range" min={0} max={1} step={0.05} value={muted ? 0 : volume} onChange={(e) => { const v = parseFloat(e.target.value); setVolume(v); if (v > 0 && muted) setMuted(false); }} className="hidden h-1 w-16 cursor-pointer accent-white opacity-80 hover:opacity-100 sm:block" aria-label="میزان صدا" />
{/* Speed pill — click cycles through speeds */}
{/* Speed pill */}
<button
type="button"
onClick={cycleSpeed}
title={`سرعت پخش: ${speed}× — کلیک برای تغییر`}
className="inline-flex items-center gap-1 rounded-full bg-white/10 px-2.5 py-2 text-xs font-bold text-white transition hover:bg-white/20 min-h-[44px]"
className="inline-flex min-h-[44px] items-center gap-1 rounded-full bg-white/10 px-2.5 py-2 text-xs font-bold text-white transition hover:bg-white/20"
>
<Gauge className="h-4 w-4" />
<span>{speed}×</span>
</button>
</div>
{/* Spacer */}
<span className="flex-1" />
{/* Watched pct */}
{/* Right group: watched%, theater, fullscreen */}
<div className="flex items-center gap-1">
<span className="hidden text-xs text-white/70 sm:inline">{Math.round(watchedPct)}٪</span>
{/* Settings gear — opens ambient / global settings only */}
<button
ref={settingsBtnRef}
type="button"
onClick={() => setSettingsOpen((o) => !o)}
className="rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 min-w-[44px] min-h-[44px] flex items-center justify-center"
title="تنظیمات پخش"
aria-expanded={settingsOpen}
>
<Settings className={cn("h-5 w-5 transition-transform duration-200", settingsOpen && "rotate-45")} />
</button>
{/* Theater mode */}
<button type="button" onClick={() => setTheaterMode((t) => !t)} className="hidden rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 min-w-[44px] min-h-[44px] sm:flex items-center justify-center" title="حالت تئاتر">
<button type="button" onClick={() => setTheaterMode((t) => !t)} className="hidden min-h-[44px] min-w-[44px] items-center justify-center rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 sm:flex" title="حالت تئاتر">
<ChevronDown className={cn("h-5 w-5 transition-transform", theaterMode && "rotate-180")} />
</button>
{/* Fullscreen */}
<button type="button" onClick={toggleFullscreen} className="rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20 min-w-[44px] min-h-[44px] flex items-center justify-center" aria-label="تمام‌صفحه (F)" title="تمام‌صفحه (F)">
<button type="button" onClick={toggleFullscreen} className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded-full bg-white/10 p-2.5 text-white transition hover:bg-white/20" aria-label="تمام‌صفحه (F)" title="تمام‌صفحه (F)">
{fullscreen ? <Minimize className="h-5 w-5" /> : <Maximize className="h-5 w-5" />}
</button>
</div>
</div>
{/* Settings flyout — anchored above the controls bar, closes only on outside click */}
<AnimatePresence>
{settingsOpen && (
<motion.div
ref={settingsPanelRef}
key="settings"
initial={{ opacity: 0, y: 6, scale: 0.97 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 6, scale: 0.97 }}
transition={{ duration: 0.13 }}
className="absolute bottom-[4.5rem] end-3 z-40 min-w-[200px] rounded-xl border border-white/10 bg-neutral-900/95 p-2 text-sm text-white shadow-xl backdrop-blur-md"
onPointerDown={(e) => e.stopPropagation()}
>
<p className="mb-1.5 px-2 text-[10px] font-bold uppercase tracking-widest text-white/40">تنظیمات پخش</p>
{/* Speed picker (full grid) */}
<p className="mb-1 px-2 text-[11px] font-semibold text-white/60">سرعت</p>
<div className="mb-2 grid grid-cols-3 gap-1">
{ALLOWED_SPEEDS.map((s) => (
<button
key={s}
type="button"
onClick={() => { changeSpeed(s); setSettingsOpen(false); }}
className={cn(
"rounded-lg py-1.5 text-xs font-bold transition-colors",
speed === s
? "bg-primary text-primary-foreground"
: "bg-white/10 hover:bg-white/20",
)}
>
{s}×
</button>
))}
</div>
<div className="my-1.5 border-t border-white/10" />
{/* Ambient toggle */}
<button
type="button"
onClick={toggleAmbient}
className={cn(
"flex w-full items-center gap-2 rounded-lg px-2 py-2 text-xs font-bold transition-colors",
ambientMode ? "bg-primary/20 text-primary" : "hover:bg-white/10",
)}
>
<Zap className="h-4 w-4 shrink-0" />
<span>حالت محیطی</span>
<span className={cn("ms-auto text-[10px]", ambientMode ? "text-primary" : "text-white/40")}>
{ambientMode ? "فعال" : "غیرفعال"}
</span>
</button>
</motion.div>
)}
</AnimatePresence>
{/* Quiz unlock CTA */}
<AnimatePresence>
{quizUnlockedNow && (
@@ -933,7 +796,7 @@ export function VideoPlayer({
</div>
<div className="w-40 shrink-0">
<Progress value={watchedPct} gradient smooth />
<p className="mt-1 text-end text-xs text-muted-foreground">{Math.round(watchedPct)}٪</p>
<p className="mt-1 text-right text-xs text-muted-foreground">{Math.round(watchedPct)}٪</p>
</div>
{quizUnlocked ? (
<Button asChild variant="gradient">
+10
View File
@@ -1,5 +1,14 @@
export type Role = "student" | "mentor" | "admin";
export interface Contributor {
name: string;
role: string;
bio: string;
url: string;
avatar: string;
contributions: string[];
}
export interface User {
id: number;
email: string;
@@ -117,6 +126,7 @@ export interface TreeLesson {
xpReward: number;
durationSeconds: number;
chapterId: number;
isPublished?: boolean;
}
export interface TreeChapter extends Chapter {