76 Commits

Author SHA1 Message Date
yohlo
e67f6b073c ready for regionals
All checks were successful
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 44s
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m46s
2026-03-07 01:22:21 -06:00
569ea8833b Merge pull request 'center' (#10) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 3m28s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 11s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 49s
Reviewed-on: #10
2026-03-02 01:13:07 -06:00
yohlo
74d83da466 center
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 3m12s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 43s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 11s
2026-03-02 01:12:42 -06:00
aff5fa2ea4 Merge pull request 'more pwa' (#9) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 3m10s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 51s
Reviewed-on: #9
2026-03-02 01:01:17 -06:00
yohlo
299f32a2b7 more pwa
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m51s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 44s
2026-03-02 01:00:46 -06:00
3f125e5761 Merge pull request 'pwa' (#8) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m28s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 9s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 44s
Reviewed-on: #8
2026-03-02 00:49:50 -06:00
yohlo
fb4f50b851 pwa
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 3m41s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 44s
2026-03-02 00:49:18 -06:00
5305dc37e7 Merge pull request 'center text/whitespace prewrap desc' (#7) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m42s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 47s
Reviewed-on: #7
2026-03-02 00:00:16 -06:00
yohlo
3e5ef04c9f center text/whitespace prewrap desc
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m59s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 50s
2026-03-01 23:59:50 -06:00
e51ff24944 Merge pull request 'fix' (#6) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 3m31s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 53s
Reviewed-on: #6
2026-03-01 21:47:34 -06:00
yohlo
c138442530 fix
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 3m0s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 45s
2026-03-01 21:46:59 -06:00
3baec5ac0f Merge pull request 'regionals' (#5) from development into main
Some checks failed
CI/CD Pipeline / Build and Push App Docker Image (push) Failing after 2m16s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 13s
CI/CD Pipeline / Deploy to Kubernetes (push) Has been skipped
Reviewed-on: #5
2026-03-01 21:23:52 -06:00
yohlo
8f84dddc64 fix team avatars
Some checks failed
CI/CD Pipeline / Build and Push App Docker Image (push) Failing after 2m39s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 16s
CI/CD Pipeline / Deploy to Kubernetes (push) Has been skipped
2026-03-01 20:59:31 -06:00
yohlo
9571980898 fix team avatars 2026-03-01 20:20:24 -06:00
yohlo
1ce8a6a982 fix team avatars 2026-03-01 20:10:06 -06:00
yohlo
f0d8297f34 new badges 2026-03-01 19:58:18 -06:00
yohlo
f49234702c regionals on tournament profile 2026-03-01 19:49:46 -06:00
yohlo
f6da7be404 tiebreakers 2026-03-01 19:43:29 -06:00
yohlo
c7487e37f2 tiebreakers 2026-03-01 19:41:34 -06:00
yohlo
873ca3e4c4 cross mix knockout seeds 2026-03-01 19:36:26 -06:00
yohlo
c5b3ad50ca fixed b2b 2026-03-01 18:04:45 -06:00
yohlo
938418cec5 fixed b2b 2026-03-01 17:52:47 -06:00
yohlo
5d6136a445 new badges 2026-03-01 17:04:06 -06:00
yohlo
9a64f316b9 b2b 2026-03-01 16:30:49 -06:00
yohlo
6199afc687 regionals 2026-03-01 16:21:27 -06:00
yohlo
f83a7d69c8 groups init 2026-02-25 19:54:51 -06:00
yohlo
2dd3e5b170 enrollment polish 2026-02-21 23:30:58 -06:00
yohlo
b9e16e2b64 regionals enrollments 2026-02-21 23:12:21 -06:00
yohlo
7f60b4d200 idk 2026-02-14 15:46:31 -06:00
yohlo
6e9e014fcc cookie and pwa stuff 2026-02-14 12:59:01 -06:00
a54a74d7de Merge pull request 'development' (#4) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m16s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 53s
Reviewed-on: #4
2026-02-10 14:03:25 -06:00
yohlo
236fcda671 session fixes
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m52s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 11s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 44s
2026-02-09 23:53:54 -06:00
yohlo
9ed054e5d0 regionals on tournament form 2026-02-09 23:44:07 -06:00
yohlo
63853f22de regional teams 2026-02-09 23:36:04 -06:00
yohlo
5dd41d8022 fix scroll bug 2026-02-09 22:20:00 -06:00
yohlo
937758bd49 facehash avatars 2026-02-09 14:31:55 -06:00
7b95998b05 Merge pull request 'new prod env' (#3) from development into main
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m43s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 13s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 46s
Reviewed-on: #3
2026-02-09 12:59:07 -06:00
yohlo
f069ba3827 include supertokens api key
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m5s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 49s
2026-02-09 12:14:38 -06:00
yohlo
70a032db20 more env stuff
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m18s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 41s
2026-02-09 12:07:45 -06:00
yohlo
243fb094e1 env
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m19s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 44s
2026-02-09 01:03:30 -06:00
yohlo
84202cdbe9 hopefully fix
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m16s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 6s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 41s
2026-02-09 00:46:36 -06:00
yohlo
6370ebe48a hopefully fix
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m15s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 6s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 43s
2026-02-09 00:42:44 -06:00
yohlo
8b271f93ac hopefully fix
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m15s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 41s
2026-02-09 00:37:01 -06:00
yohlo
2326693bfb hopefully fix
All checks were successful
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m16s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 6s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 43s
2026-02-09 00:06:47 -06:00
yohlo
b209bbf4ef copy server.ts
Some checks failed
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 58s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 6s
CI/CD Pipeline / Deploy to Kubernetes (push) Failing after 5m12s
2026-02-08 23:30:51 -06:00
yohlo
c4bf13744c fix migrations?
Some checks failed
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m45s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 11s
CI/CD Pipeline / Deploy to Kubernetes (push) Failing after 5m9s
2026-02-08 23:21:21 -06:00
yohlo
1e3eaf0c35 server.ts 2026-02-08 23:19:48 -06:00
yohlo
d4b52e762b dist
Some checks failed
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 1m47s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 8s
CI/CD Pipeline / Deploy to Kubernetes (push) Failing after 5m9s
2026-02-08 23:05:31 -06:00
yohlo
a4e618f327 fix
Some checks failed
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Failing after 16m45s
CI/CD Pipeline / Build and Push App Docker Image (push) Failing after 19m23s
CI/CD Pipeline / Deploy to Kubernetes (push) Has been cancelled
2026-02-08 22:32:54 -06:00
yohlo
d1951afb3c testing cicd
Some checks failed
CI/CD Pipeline / Build and Push App Docker Image (push) Failing after 1m30s
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 14s
CI/CD Pipeline / Deploy to Kubernetes (push) Has been skipped
2026-02-08 16:01:21 -06:00
yohlo
dce31905fc fixes 2025-10-18 23:09:57 -05:00
yohlo
e58ed86d3b fixes 2025-10-17 19:22:07 -05:00
yohlo
d833e5f1a1 Merge branch 'caro/badges-stats' 2025-10-16 15:41:36 -05:00
yohlo
15ed78a9c5 name blurbs, skeleton and link 2025-10-16 15:39:46 -05:00
4b66a4bd13 found a little typo? 2025-10-16 13:00:42 -04:00
a04a78fbf8 Merge branch 'main' into caro/badges-stats 2025-10-16 11:51:12 -05:00
7fa3b06673 last I hope 2025-10-16 12:47:24 -04:00
694c58e449 I need to have a word with my autoformatter 2025-10-16 12:46:10 -04:00
7afe40775e goddammit 2025-10-16 12:44:09 -04:00
4f88fdd43a reverting random styling things? 2025-10-16 12:42:26 -04:00
fa98634402 working but sheet styling is ugly 2025-10-16 12:32:26 -04:00
yohlo
470b4ef99c regionals 2025-10-16 09:12:11 -05:00
yohlo
612f1f28bf skeleton for h2h 2025-10-13 14:18:54 -05:00
yohlo
168ef1b05d restore suspense boundary in stats 2025-10-13 13:00:29 -05:00
yohlo
939d1cee90 remove steps 2025-10-11 15:37:37 -05:00
yohlo
b59c7cd7b6 fix tabs on stats table 2025-10-11 15:34:12 -05:00
yohlo
2ed5ab6026 fix stats table 2025-10-11 15:23:33 -05:00
yohlo
d3379e54a4 player h2h 2025-10-11 14:47:03 -05:00
yohlo
43972b6a06 match h2h 2025-10-11 13:40:12 -05:00
yohlo
14c2eb2c02 try something different for stats scroll 2025-10-11 00:45:05 -05:00
yohlo
46943b6971 try something different for stats scroll 2025-10-11 00:43:28 -05:00
yohlo
f74d2daf9c try something different for stats scroll 2025-10-11 00:40:18 -05:00
yohlo
26c6343a89 no devtools 2025-10-11 00:34:58 -05:00
yohlo
127709bb6c more imporvmentes 2025-10-11 00:33:27 -05:00
yohlo
6a7d119d3e more stats 2025-10-11 00:29:29 -05:00
yohlo
4b534c86cd fixes, improvmeents 2025-10-10 23:44:27 -05:00
163 changed files with 9448 additions and 1247 deletions

143
.gitea/workflows/ci-cd.yaml Normal file
View File

@@ -0,0 +1,143 @@
name: CI/CD Pipeline
on:
push:
branches:
- development
- main
jobs:
build-app:
name: Build and Push App Docker Image
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set environment variables
run: |
if [ "${{ github.ref }}" == "refs/heads/main" ]; then
echo "DOCKER_TAG=latest" >> $GITHUB_ENV
echo "ENVIRONMENT=prod" >> $GITHUB_ENV
else
echo "DOCKER_TAG=dev" >> $GITHUB_ENV
echo "ENVIRONMENT=dev" >> $GITHUB_ENV
fi
- name: Build and push app Docker image
run: |
docker login git.yohler.net -u ${{ github.actor }} -p ${{ secrets.PACKAGES_TOKEN }}
docker build \
-f Dockerfile \
-t git.yohler.net/kyle/flxn-app:${{ env.DOCKER_TAG }} \
-t git.yohler.net/kyle/flxn-app:${{ github.sha }} \
.
docker push git.yohler.net/kyle/flxn-app:${{ env.DOCKER_TAG }}
docker push git.yohler.net/kyle/flxn-app:${{ github.sha }}
build-pocketbase:
name: Build and Push PocketBase Docker Image
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check if PocketBase Dockerfile or migrations changed
id: check_changes
run: |
if [ "${{ github.event.before }}" == "0000000000000000000000000000000000000000" ] || ! git cat-file -e ${{ github.event.before }} 2>/dev/null; then
echo "changed=true" >> $GITHUB_OUTPUT
elif git diff --name-only ${{ github.event.before }} ${{ github.sha }} | grep -qE "(Dockerfile.pocketbase|pb_migrations/)"; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
fi
- name: Build and push PocketBase Docker image
if: steps.check_changes.outputs.changed == 'true' || github.event.before == '0000000000000000000000000000000000000000'
run: |
docker login git.yohler.net -u ${{ github.actor }} -p ${{ secrets.PACKAGES_TOKEN }}
docker build \
-f Dockerfile.pocketbase \
-t git.yohler.net/kyle/flxn-pocketbase:latest \
-t git.yohler.net/kyle/flxn-pocketbase:${{ github.sha }} \
.
docker push git.yohler.net/kyle/flxn-pocketbase:latest
docker push git.yohler.net/kyle/flxn-pocketbase:${{ github.sha }}
deploy:
name: Deploy to Kubernetes
needs: [build-app, build-pocketbase]
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set environment variables
run: |
if [ "${{ github.ref }}" == "refs/heads/main" ]; then
echo "ENVIRONMENT=prod" >> $GITHUB_ENV
echo "NAMESPACE=flxn-prod" >> $GITHUB_ENV
else
echo "ENVIRONMENT=dev" >> $GITHUB_ENV
echo "NAMESPACE=flxn-dev" >> $GITHUB_ENV
fi
- name: Install kubectl
run: |
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/
- name: Configure kubectl
run: |
mkdir -p $HOME/.kube
echo "${{ secrets.KUBE_CONFIG }}" | base64 -d > $HOME/.kube/config
chmod 600 $HOME/.kube/config
kubectl config set-cluster local --insecure-skip-tls-verify=true
- name: Verify kubectl access
run: |
kubectl version --client
kubectl get nodes
- name: Deploy shared services (SuperTokens)
run: |
kubectl apply -k k8s/overlays/shared/
- name: Deploy to ${{ env.ENVIRONMENT }}
run: |
kubectl apply -k k8s/overlays/${{ env.ENVIRONMENT }}/
- name: Force rollout to pull latest image
run: |
kubectl rollout restart deployment/flxn-app -n ${{ env.NAMESPACE }}
kubectl rollout restart deployment/flxn-pocketbase -n ${{ env.NAMESPACE }}
- name: Wait for rollout
run: |
kubectl rollout status deployment/flxn-app -n ${{ env.NAMESPACE }} --timeout=5m
kubectl rollout status deployment/flxn-pocketbase -n ${{ env.NAMESPACE }} --timeout=5m
- name: Verify deployment
run: |
kubectl get pods -n ${{ env.NAMESPACE }} -l app=flxn
kubectl get svc -n ${{ env.NAMESPACE }} -l app=flxn
kubectl get ingress -n ${{ env.NAMESPACE }}
- name: Check app health
run: |
sleep 15
APP_POD=$(kubectl get pod -n ${{ env.NAMESPACE }} -l component=app -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n ${{ env.NAMESPACE }} $APP_POD -- wget -O- http://localhost:3000/api/health || echo "Health check failed (endpoint may not exist yet)"
- name: Check PocketBase health
run: |
PB_POD=$(kubectl get pod -n ${{ env.NAMESPACE }} -l component=pocketbase -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n ${{ env.NAMESPACE }} $PB_POD -- wget -O- http://localhost:8090/api/health || echo "PocketBase health check completed"

29
Dockerfile Normal file
View File

@@ -0,0 +1,29 @@
FROM oven/bun:1 AS builder
WORKDIR /app
COPY package.json bun.lockb* ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun run build
FROM oven/bun:1-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/server.ts ./server.ts
EXPOSE 3000
ENV NODE_ENV=production
ENV PORT=3000
ENV NITRO_PORT=3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD bun -e "fetch('http://localhost:3000/api/health').then(r => r.ok ? process.exit(0) : process.exit(1)).catch(() => process.exit(1))"
CMD ["bun", "run", "server.ts"]

View File

@@ -1,16 +1,23 @@
FROM alpine:latest FROM alpine:latest
ARG PB_VERSION=0.29.2 ARG PB_VERSION=0.26.5
RUN apk add --no-cache \ RUN apk add --no-cache \
unzip \ unzip \
ca-certificates ca-certificates
# download and unzip PocketBase
ADD https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_amd64.zip /tmp/pb.zip ADD https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_amd64.zip /tmp/pb.zip
RUN unzip /tmp/pb.zip -d /pb/ RUN unzip /tmp/pb.zip -d /pb/ && \
rm /tmp/pb.zip && \
chmod +x /pb/pocketbase
RUN mkdir -p /pb/pb_data
COPY pb_migrations /pb/pb_migrations
EXPOSE 8090 EXPOSE 8090
# start PocketBase HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["/pb/pocketbase", "serve", "--http=0.0.0.0:8090"] CMD wget --no-verbose --tries=1 --spider http://localhost:8090/api/health || exit 1
CMD ["/pb/pocketbase", "serve", "--http=0.0.0.0:8090", "--dir=/pb/pb_data", "--migrationsDir=/pb/pb_migrations"]

1161
bun.lock

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,6 @@ services:
- .env.docker - .env.docker
volumes: volumes:
- postgres-data:/var/lib/postgresql/data - postgres-data:/var/lib/postgresql/data
- ./.docker-postgres-init:/docker-entrypoint-initdb.d
networks: networks:
- app-network - app-network

View File

@@ -0,0 +1,129 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: flxn-app
labels:
app: flxn
component: app
spec:
replicas: 1
selector:
matchLabels:
app: flxn
component: app
template:
metadata:
labels:
app: flxn
component: app
spec:
containers:
- name: flxn-app
image: git.yohler.net/kyle/flxn-app:latest
imagePullPolicy: Always
ports:
- containerPort: 3000
name: http
protocol: TCP
env:
- name: VITE_API_DOMAIN
valueFrom:
configMapKeyRef:
name: flxn-config
key: vite_api_domain
- name: VITE_WEBSITE_DOMAIN
valueFrom:
configMapKeyRef:
name: flxn-config
key: vite_website_domain
- name: SUPERTOKENS_URI
valueFrom:
configMapKeyRef:
name: flxn-config
key: supertokens_uri
- name: POCKETBASE_URL
valueFrom:
configMapKeyRef:
name: flxn-config
key: pocketbase_url
- name: SUPERTOKENS_API_KEY
valueFrom:
secretKeyRef:
name: flxn-secrets
key: supertokens_api_key
- name: PORT
value: "3000"
- name: NODE_ENV
value: "production"
- name: TWILIO_ACCOUNT_SID
valueFrom:
secretKeyRef:
name: flxn-secrets
key: twilio_account_sid
- name: TWILIO_AUTH_TOKEN
valueFrom:
secretKeyRef:
name: flxn-secrets
key: twilio_auth_token
- name: TWILIO_SERVICE_SID
valueFrom:
secretKeyRef:
name: flxn-secrets
key: twilio_service_sid
- name: POCKETBASE_ADMIN_EMAIL
valueFrom:
secretKeyRef:
name: flxn-secrets
key: pocketbase_admin_email
- name: POCKETBASE_ADMIN_PASSWORD
valueFrom:
secretKeyRef:
name: flxn-secrets
key: pocketbase_admin_password
- name: VITE_SPOTIFY_CLIENT_ID
valueFrom:
configMapKeyRef:
name: flxn-config
key: vite_spotify_client_id
- name: SPOTIFY_CLIENT_SECRET
valueFrom:
secretKeyRef:
name: flxn-secrets
key: spotify_client_secret
- name: VITE_SPOTIFY_REDIRECT_URI
valueFrom:
configMapKeyRef:
name: flxn-config
key: vite_spotify_redirect_uri
- name: COOKIE_DOMAIN
valueFrom:
configMapKeyRef:
name: flxn-config
key: cookie_domain
resources:
requests:
memory: "768Mi"
cpu: "250m"
limits:
memory: "1536Mi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 30
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 10
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3

17
k8s/base/app-service.yaml Normal file
View File

@@ -0,0 +1,17 @@
apiVersion: v1
kind: Service
metadata:
name: flxn-app
labels:
app: flxn
component: app
spec:
type: ClusterIP
ports:
- port: 3000
targetPort: 3000
protocol: TCP
name: http
selector:
app: flxn
component: app

View File

@@ -0,0 +1,12 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- app-deployment.yaml
- app-service.yaml
- pocketbase-deployment.yaml
- pocketbase-service.yaml
- pb-data-pvc.yaml
commonLabels:
app: flxn

13
k8s/base/pb-data-pvc.yaml Normal file
View File

@@ -0,0 +1,13 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: flxn-pb-data
labels:
app: flxn
component: pocketbase
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi

View File

@@ -0,0 +1,57 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: flxn-pocketbase
labels:
app: flxn
component: pocketbase
spec:
replicas: 1
selector:
matchLabels:
app: flxn
component: pocketbase
template:
metadata:
labels:
app: flxn
component: pocketbase
spec:
containers:
- name: pocketbase
image: git.yohler.net/kyle/flxn-pocketbase:latest
imagePullPolicy: Always
ports:
- containerPort: 8090
name: http
protocol: TCP
volumeMounts:
- name: pb-data
mountPath: /pb/pb_data
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /api/health
port: 8090
initialDelaySeconds: 10
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /api/health
port: 8090
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
volumes:
- name: pb-data
persistentVolumeClaim:
claimName: flxn-pb-data

View File

@@ -0,0 +1,18 @@
apiVersion: v1
kind: Service
metadata:
name: flxn-pocketbase
labels:
app: flxn
component: pocketbase
spec:
type: NodePort
ports:
- port: 8090
targetPort: 8090
nodePort: 30090
protocol: TCP
name: http
selector:
app: flxn
component: pocketbase

View File

@@ -0,0 +1,15 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: flxn-config
namespace: flxn-dev
data:
vite_api_domain: "https://dev.flexxon.app"
vite_website_domain: "https://dev.flexxon.app"
supertokens_uri: "http://192.168.0.50:30568"
pocketbase_url: "http://192.168.0.50:30096"
vite_spotify_client_id: "3ffde6b594e84460b3d4b329b8919277"
vite_spotify_redirect_uri: "https://dev.flexxon.app/api/spotify/callback"
s3_endpoint: "https://s3.yohler.net"
s3_bucket: "flxn-dev"
cookie_domain: "dev.flexxon.app"

View File

@@ -0,0 +1,17 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: flxn-app
namespace: flxn-dev
spec:
rules:
- host: dev.flexxon.app
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: flxn-app
port:
number: 3000

View File

@@ -0,0 +1,50 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: flxn-dev
resources:
- namespace.yaml
- ../../base
- configmap.yaml
- ingress.yaml
images:
- name: git.yohler.net/kyle/flxn-app
newTag: dev
- name: git.yohler.net/kyle/flxn-pocketbase
newTag: latest
commonLabels:
environment: dev
patches:
- patch: |-
- op: replace
path: /spec/template/spec/containers/0/resources/requests/memory
value: "768Mi"
- op: replace
path: /spec/template/spec/containers/0/resources/limits/memory
value: "1536Mi"
target:
kind: Deployment
name: flxn-app
- patch: |-
- op: replace
path: /spec/type
value: NodePort
- op: add
path: /spec/ports/0/nodePort
value: 30083
target:
kind: Service
name: flxn-app
- patch: |-
- op: replace
path: /spec/ports/0/nodePort
value: 30096
target:
kind: Service
name: flxn-pocketbase

View File

@@ -0,0 +1,4 @@
apiVersion: v1
kind: Namespace
metadata:
name: flxn-dev

View File

@@ -0,0 +1,15 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: flxn-config
namespace: flxn-prod
data:
vite_api_domain: "https://flexxon.app"
vite_website_domain: "https://flexxon.app"
supertokens_uri: "http://192.168.0.50:30568"
pocketbase_url: "http://192.168.0.50:30097"
vite_spotify_client_id: "3ffde6b594e84460b3d4b329b8919277"
vite_spotify_redirect_uri: "https://flexxon.app/api/spotify/callback"
s3_endpoint: "https://s3.yohler.net"
s3_bucket: "flxn-prod"
cookie_domain: "flexxon.app"

View File

@@ -0,0 +1,17 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: flxn-app
namespace: flxn-prod
spec:
rules:
- host: flexxon.app
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: flxn-app
port:
number: 3000

View File

@@ -0,0 +1,50 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: flxn-prod
resources:
- namespace.yaml
- ../../base
- configmap.yaml
- ingress.yaml
images:
- name: git.yohler.net/kyle/flxn-app
newTag: latest
- name: git.yohler.net/kyle/flxn-pocketbase
newTag: latest
commonLabels:
environment: prod
patches:
- patch: |-
- op: replace
path: /spec/template/spec/containers/0/resources/requests/memory
value: "1536Mi"
- op: replace
path: /spec/template/spec/containers/0/resources/limits/memory
value: "3Gi"
target:
kind: Deployment
name: flxn-app
- patch: |-
- op: replace
path: /spec/type
value: NodePort
- op: add
path: /spec/ports/0/nodePort
value: 30084
target:
kind: Service
name: flxn-app
- patch: |-
- op: replace
path: /spec/ports/0/nodePort
value: 30097
target:
kind: Service
name: flxn-pocketbase

View File

@@ -0,0 +1,4 @@
apiVersion: v1
kind: Namespace
metadata:
name: flxn-prod

View File

@@ -0,0 +1,5 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: supertokens-config
namespace: flxn-shared

View File

@@ -0,0 +1,16 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: flxn-shared
resources:
- namespace.yaml
- supertokens-deployment.yaml
- supertokens-service.yaml
- supertokens-postgres-deployment.yaml
- supertokens-postgres-service.yaml
- supertokens-db-pvc.yaml
labels:
- pairs:
environment: shared

View File

@@ -0,0 +1,4 @@
apiVersion: v1
kind: Namespace
metadata:
name: flxn-shared

View File

@@ -0,0 +1,13 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: supertokens-db-data
labels:
app: flxn
component: supertokens-db
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 2Gi

View File

@@ -0,0 +1,71 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: supertokens
labels:
app: flxn
component: supertokens
spec:
replicas: 1
selector:
matchLabels:
app: flxn
component: supertokens
template:
metadata:
labels:
app: flxn
component: supertokens
spec:
enableServiceLinks: false
containers:
- name: supertokens
image: registry.supertokens.io/supertokens/supertokens-postgresql:latest
ports:
- containerPort: 3567
name: http
protocol: TCP
env:
- name: PORT
value: "3567"
- name: POSTGRESQL_USER
value: supertokens
- name: POSTGRESQL_PASSWORD
valueFrom:
secretKeyRef:
name: supertokens-secrets
key: postgres_password
- name: POSTGRESQL_HOST
value: supertokens-db
- name: POSTGRESQL_PORT
value: "5432"
- name: POSTGRESQL_DATABASE_NAME
value: supertokens
- name: API_KEYS
valueFrom:
secretKeyRef:
name: supertokens-secrets
key: api_keys
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /hello
port: 3567
initialDelaySeconds: 30
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /hello
port: 3567
initialDelaySeconds: 10
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3

View File

@@ -0,0 +1,68 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: supertokens-db
labels:
app: flxn
component: supertokens-db
spec:
replicas: 1
selector:
matchLabels:
app: flxn
component: supertokens-db
template:
metadata:
labels:
app: flxn
component: supertokens-db
spec:
containers:
- name: postgres
image: postgres:16-alpine
ports:
- containerPort: 5432
name: postgres
protocol: TCP
env:
- name: POSTGRES_USER
value: "supertokens"
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: supertokens-secrets
key: postgres_password
- name: POSTGRES_DB
value: "supertokens"
- name: PGDATA
value: "/var/lib/postgresql/data/pgdata"
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql/data
resources:
requests:
memory: "128Mi"
cpu: "50m"
limits:
memory: "256Mi"
cpu: "500m"
livenessProbe:
exec:
command:
- pg_isready
- -U
- supertokens
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
exec:
command:
- pg_isready
- -U
- supertokens
initialDelaySeconds: 5
periodSeconds: 5
volumes:
- name: postgres-data
persistentVolumeClaim:
claimName: supertokens-db-data

View File

@@ -0,0 +1,17 @@
apiVersion: v1
kind: Service
metadata:
name: supertokens-db
labels:
app: flxn
component: supertokens-db
spec:
type: ClusterIP
ports:
- port: 5432
targetPort: 5432
protocol: TCP
name: postgres
selector:
app: flxn
component: supertokens-db

View File

@@ -0,0 +1,18 @@
apiVersion: v1
kind: Service
metadata:
name: supertokens
labels:
app: flxn
component: supertokens
spec:
type: NodePort
ports:
- port: 3567
targetPort: 3567
nodePort: 30568
protocol: TCP
name: http
selector:
app: flxn
component: supertokens

View File

@@ -6,8 +6,7 @@
"scripts": { "scripts": {
"dev": "vite dev --host 0.0.0.0", "dev": "vite dev --host 0.0.0.0",
"build": "vite build && tsc --noEmit", "build": "vite build && tsc --noEmit",
"start": "bun run .output/server/index.mjs", "start": "bun run server.ts"
"start:node": "node .output/server/index.mjs"
}, },
"dependencies": { "dependencies": {
"@hello-pangea/dnd": "^18.0.1", "@hello-pangea/dnd": "^18.0.1",
@@ -20,12 +19,13 @@
"@mantine/tiptap": "^8.2.4", "@mantine/tiptap": "^8.2.4",
"@phosphor-icons/react": "^2.1.10", "@phosphor-icons/react": "^2.1.10",
"@svgmoji/noto": "^3.2.0", "@svgmoji/noto": "^3.2.0",
"@tanstack/react-devtools": "^0.7.6",
"@tanstack/react-query": "^5.66.0", "@tanstack/react-query": "^5.66.0",
"@tanstack/react-query-devtools": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0",
"@tanstack/react-router": "^1.130.12", "@tanstack/react-router": "^1.143.6",
"@tanstack/react-router-devtools": "^1.130.13", "@tanstack/react-router-devtools": "^1.143.6",
"@tanstack/react-router-with-query": "^1.130.12", "@tanstack/react-router-ssr-query": "^1.143.6",
"@tanstack/react-start": "^1.132.2", "@tanstack/react-start": "^1.143.6",
"@tanstack/react-virtual": "^3.13.12", "@tanstack/react-virtual": "^3.13.12",
"@tiptap/pm": "^3.4.3", "@tiptap/pm": "^3.4.3",
"@tiptap/react": "^3.4.3", "@tiptap/react": "^3.4.3",
@@ -35,6 +35,7 @@
"browser-image-compression": "^2.0.2", "browser-image-compression": "^2.0.2",
"dotenv": "^17.2.2", "dotenv": "^17.2.2",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"facehash": "^0.0.7",
"framer-motion": "^12.23.12", "framer-motion": "^12.23.12",
"ioredis": "^5.7.0", "ioredis": "^5.7.0",
"pg": "^8.16.3", "pg": "^8.16.3",
@@ -51,11 +52,11 @@
"supertokens-web-js": "^0.15.0", "supertokens-web-js": "^0.15.0",
"twilio": "^5.8.0", "twilio": "^5.8.0",
"vaul": "^1.1.2", "vaul": "^1.1.2",
"xlsx": "^0.18.5",
"zod": "^4.0.15", "zod": "^4.0.15",
"zustand": "^5.0.7" "zustand": "^5.0.7"
}, },
"devDependencies": { "devDependencies": {
"@tanstack/react-router-ssr-query": "^1.132.2",
"@tanstack/router-plugin": "^1.132.2", "@tanstack/router-plugin": "^1.132.2",
"@types/node": "^22.5.4", "@types/node": "^22.5.4",
"@types/pg": "^8.15.5", "@types/pg": "^8.15.5",
@@ -70,6 +71,8 @@
"tsx": "^4.20.3", "tsx": "^4.20.3",
"typescript": "^5.7.2", "typescript": "^5.7.2",
"vite": "^7.1.7", "vite": "^7.1.7",
"vite-tsconfig-paths": "^5.1.4" "vite-plugin-pwa": "^1.2.0",
"vite-tsconfig-paths": "^5.1.4",
"workbox-window": "^7.4.0"
} }
} }

View File

@@ -1,187 +0,0 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_5062686152");
return app.delete(collection);
}, (app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "pbc_3072146508",
"hidden": false,
"id": "relation2582050271",
"maxSelect": 1,
"minSelect": 0,
"name": "player_id",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"cascadeDelete": false,
"collectionId": "pbc_1340419796",
"hidden": false,
"id": "relation4154639100",
"maxSelect": 1,
"minSelect": 0,
"name": "badge_id",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "_clone_GhrR",
"max": 0,
"min": 0,
"name": "badge_name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "_clone_DEaW",
"max": 0,
"min": 0,
"name": "badge_description",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "_clone_MHmw",
"maxSelect": 1,
"name": "badge_type",
"presentable": false,
"required": true,
"system": false,
"type": "select",
"values": [
"tournament_participation",
"tournament_placement",
"performance",
"overtime",
"match_milestone"
]
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "_clone_11YE",
"max": 50,
"min": 0,
"name": "badge_icon",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "_clone_qAJu",
"max": 50,
"min": 0,
"name": "badge_color",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "_clone_giOf",
"name": "is_progressive",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
},
{
"hidden": false,
"id": "json3212413036",
"maxSize": 1,
"name": "current_progress",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json4171899439",
"maxSize": 1,
"name": "target_progress",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3435813110",
"maxSize": 1,
"name": "is_earned",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "_clone_Q7lC",
"max": "",
"min": "",
"name": "earned_at",
"presentable": false,
"required": false,
"system": false,
"type": "date"
}
],
"id": "pbc_5062686152",
"indexes": [],
"listRule": null,
"name": "player_badges_view",
"system": false,
"type": "view",
"updateRule": null,
"viewQuery": "\n SELECT\n (p.id || '_' || b.id) as id,\n p.id as player_id,\n b.id as badge_id,\n b.name as badge_name,\n b.description as badge_description,\n b.type as badge_type,\n b.icon as badge_icon,\n b.color as badge_color,\n b.is_progressive,\n COALESCE(pbp.current_progress, 0) as current_progress,\n COALESCE(pbp.target_progress, b.progress_target, 1) as target_progress,\n COALESCE(pbp.is_earned, false) as is_earned,\n pbp.earned_at\n FROM players p\n CROSS JOIN badges b\n LEFT JOIN player_badge_progress pbp ON pbp.player_id = p.id AND pbp.badge_id = b.id\n ",
"viewRule": null
});
return app.save(collection);
})

View File

@@ -1,8 +1,12 @@
/// <reference path="../pb_data/types.d.ts" /> /// <reference path="../pb_data/types.d.ts" />
migrate((app) => { migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_4251874343"); try {
const collection = app.findCollectionByNameOrId("pbc_4251874343");
return app.delete(collection); return app.delete(collection);
} catch (e) {
console.log("Collection pbc_4251874343 not found, skipping deletion");
return null;
}
}, (app) => { }, (app) => {
const collection = new Collection({ const collection = new Collection({
"createRule": null, "createRule": null,

View File

@@ -0,0 +1,24 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_1568971955")
// add field
collection.fields.addAt(14, new Field({
"hidden": false,
"id": "bool3523658193",
"name": "private",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_1568971955")
// remove field
collection.fields.removeById("bool3523658193")
return app.save(collection)
})

View File

@@ -0,0 +1,24 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// add field
collection.fields.addAt(12, new Field({
"hidden": false,
"id": "bool3403970290",
"name": "regional",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// remove field
collection.fields.removeById("bool3403970290")
return app.save(collection)
})

View File

@@ -0,0 +1,31 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// add field
collection.fields.addAt(13, new Field({
"hidden": false,
"id": "select3736761055",
"maxSelect": 1,
"name": "format",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"single_elim",
"double_elim",
"groups",
"swiss"
]
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// remove field
collection.fields.removeById("select3736761055")
return app.save(collection)
})

View File

@@ -0,0 +1,165 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "pbc_3072146508",
"hidden": false,
"id": "relation2582050271",
"maxSelect": 1,
"minSelect": 0,
"name": "player_id",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"hidden": false,
"id": "json4231605813",
"maxSize": 1,
"name": "player_name",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "number103159226",
"max": null,
"min": null,
"name": "matches",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "number3837590211",
"max": null,
"min": null,
"name": "tournaments",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "json2732118329",
"maxSize": 1,
"name": "wins",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json724428801",
"maxSize": 1,
"name": "losses",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3154249934",
"maxSize": 1,
"name": "total_cups_made",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3227208027",
"maxSize": 1,
"name": "total_cups_against",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json2379943496",
"maxSize": 1,
"name": "win_percentage",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3165107022",
"maxSize": 1,
"name": "avg_cups_per_match",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3041953980",
"maxSize": 1,
"name": "margin_of_victory",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json1531431708",
"maxSize": 1,
"name": "margin_of_loss",
"presentable": false,
"required": false,
"system": false,
"type": "json"
}
],
"id": "pbc_4086490894",
"indexes": [],
"listRule": null,
"name": "player_regional_stats",
"system": false,
"type": "view",
"updateRule": null,
"viewQuery": "SELECT\n p.id as id,\n p.id as player_id,\n (p.first_name || ' ' || p.last_name) as player_name,\n COUNT(m.id) as matches,\n COUNT(DISTINCT m.tournament) as tournaments,\n SUM(CASE\n WHEN (m.home = t.id AND m.home_cups > m.away_cups) OR\n (m.away = t.id AND m.away_cups > m.home_cups)\n THEN 1 ELSE 0\n END) as wins,\n SUM(CASE\n WHEN (m.home = t.id AND m.home_cups < m.away_cups) OR\n (m.away = t.id AND m.away_cups < m.home_cups)\n THEN 1 ELSE 0\n END) as losses,\n SUM(CASE\n WHEN m.home = t.id THEN m.home_cups\n WHEN m.away = t.id THEN m.away_cups\n ELSE 0\n END) as total_cups_made,\n SUM(CASE\n WHEN m.home = t.id THEN m.away_cups\n WHEN m.away = t.id THEN m.home_cups\n ELSE 0\n END) as total_cups_against,\n -- Win percentage\n ROUND((CAST(SUM(CASE\n WHEN (m.home = t.id AND m.home_cups > m.away_cups) OR\n (m.away = t.id AND m.away_cups > m.home_cups)\n THEN 1 ELSE 0\n END) AS REAL) / COUNT(m.id)) * 100, 2) as win_percentage,\n -- Average cups per match\n ROUND(CAST(SUM(CASE\n WHEN m.home = t.id THEN m.home_cups\n WHEN m.away = t.id THEN m.away_cups\n ELSE 0\n END) AS REAL) / COUNT(m.id), 2) as avg_cups_per_match,\n -- Margin of Victory\n ROUND(AVG(CASE\n WHEN m.home = t.id AND m.home_cups > m.away_cups\n THEN m.home_cups - m.away_cups\n WHEN m.away = t.id AND m.away_cups > m.home_cups\n THEN m.away_cups - m.home_cups\n ELSE NULL\n END), 2) as margin_of_victory,\n -- Margin of Loss\n ROUND(AVG(CASE\n WHEN m.home = t.id AND m.home_cups < m.away_cups\n THEN m.away_cups - m.home_cups\n WHEN m.away = t.id AND m.away_cups < m.home_cups\n THEN m.home_cups - m.away_cups\n ELSE NULL\n END), 2) as margin_of_loss\n FROM players p, teams t, matches m, tournaments tour\n WHERE\n t.players LIKE '%\"' || p.id || '\"%' AND\n (m.home = t.id OR m.away = t.id) AND\n m.tournament = tour.id AND\n m.status = 'ended' AND\n tour.regional = true\n GROUP BY p.id",
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_4086490894");
return app.delete(collection);
})

View File

@@ -0,0 +1,165 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "pbc_3072146508",
"hidden": false,
"id": "relation2582050271",
"maxSelect": 1,
"minSelect": 0,
"name": "player_id",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"hidden": false,
"id": "json4231605813",
"maxSize": 1,
"name": "player_name",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "number103159226",
"max": null,
"min": null,
"name": "matches",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "number3837590211",
"max": null,
"min": null,
"name": "tournaments",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "json2732118329",
"maxSize": 1,
"name": "wins",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json724428801",
"maxSize": 1,
"name": "losses",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3154249934",
"maxSize": 1,
"name": "total_cups_made",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3227208027",
"maxSize": 1,
"name": "total_cups_against",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json2379943496",
"maxSize": 1,
"name": "win_percentage",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3165107022",
"maxSize": 1,
"name": "avg_cups_per_match",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json3041953980",
"maxSize": 1,
"name": "margin_of_victory",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"hidden": false,
"id": "json1531431708",
"maxSize": 1,
"name": "margin_of_loss",
"presentable": false,
"required": false,
"system": false,
"type": "json"
}
],
"id": "pbc_15286826",
"indexes": [],
"listRule": null,
"name": "player_mainline_stats",
"system": false,
"type": "view",
"updateRule": null,
"viewQuery": "SELECT\n p.id as id,\n p.id as player_id,\n (p.first_name || ' ' || p.last_name) as player_name,\n COUNT(m.id) as matches,\n COUNT(DISTINCT m.tournament) as tournaments,\n SUM(CASE\n WHEN (m.home = t.id AND m.home_cups > m.away_cups) OR\n (m.away = t.id AND m.away_cups > m.home_cups)\n THEN 1 ELSE 0\n END) as wins,\n SUM(CASE\n WHEN (m.home = t.id AND m.home_cups < m.away_cups) OR\n (m.away = t.id AND m.away_cups < m.home_cups)\n THEN 1 ELSE 0\n END) as losses,\n SUM(CASE\n WHEN m.home = t.id THEN m.home_cups\n WHEN m.away = t.id THEN m.away_cups\n ELSE 0\n END) as total_cups_made,\n SUM(CASE\n WHEN m.home = t.id THEN m.away_cups\n WHEN m.away = t.id THEN m.home_cups\n ELSE 0\n END) as total_cups_against,\n -- Win percentage\n ROUND((CAST(SUM(CASE\n WHEN (m.home = t.id AND m.home_cups > m.away_cups) OR\n (m.away = t.id AND m.away_cups > m.home_cups)\n THEN 1 ELSE 0\n END) AS REAL) / COUNT(m.id)) * 100, 2) as win_percentage,\n -- Average cups per match\n ROUND(CAST(SUM(CASE\n WHEN m.home = t.id THEN m.home_cups\n WHEN m.away = t.id THEN m.away_cups\n ELSE 0\n END) AS REAL) / COUNT(m.id), 2) as avg_cups_per_match,\n -- Margin of Victory\n ROUND(AVG(CASE\n WHEN m.home = t.id AND m.home_cups > m.away_cups\n THEN m.home_cups - m.away_cups\n WHEN m.away = t.id AND m.away_cups > m.home_cups\n THEN m.away_cups - m.home_cups\n ELSE NULL\n END), 2) as margin_of_victory,\n -- Margin of Loss\n ROUND(AVG(CASE\n WHEN m.home = t.id AND m.home_cups < m.away_cups\n THEN m.away_cups - m.home_cups\n WHEN m.away = t.id AND m.away_cups < m.home_cups\n THEN m.home_cups - m.away_cups\n ELSE NULL\n END), 2) as margin_of_loss\n FROM players p, teams t, matches m, tournaments tour\n WHERE\n t.players LIKE '%\"' || p.id || '\"%' AND\n (m.home = t.id OR m.away = t.id) AND\n m.tournament = tour.id AND\n m.status = 'ended' AND\n (tour.regional = false OR tour.regional IS NULL)\n GROUP BY p.id",
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_15286826");
return app.delete(collection);
})

View File

@@ -0,0 +1,48 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// update field
collection.fields.addAt(13, new Field({
"hidden": false,
"id": "select3736761055",
"maxSelect": 1,
"name": "format",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"single_elim",
"double_elim",
"groups",
"swiss",
"swiss_bracket",
"round_robin"
]
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// update field
collection.fields.addAt(13, new Field({
"hidden": false,
"id": "select3736761055",
"maxSelect": 1,
"name": "format",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"single_elim",
"double_elim",
"groups",
"swiss"
]
}))
return app.save(collection)
})

View File

@@ -0,0 +1,109 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "pbc_340646327",
"hidden": false,
"id": "relation3177167065",
"maxSelect": 1,
"minSelect": 0,
"name": "tournament",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1579384326",
"max": 0,
"min": 0,
"name": "name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "number4113142680",
"max": null,
"min": null,
"name": "order",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"cascadeDelete": false,
"collectionId": "pbc_1568971955",
"hidden": false,
"id": "relation2529305176",
"maxSelect": 999,
"minSelect": 0,
"name": "teams",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_3346940990",
"indexes": [],
"listRule": null,
"name": "groups",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_3346940990");
return app.delete(collection);
})

View File

@@ -0,0 +1,52 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// remove field
collection.fields.removeById("select3736761055")
// add field
collection.fields.addAt(13, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text3736761055",
"max": 0,
"min": 0,
"name": "format",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// add field
collection.fields.addAt(13, new Field({
"hidden": false,
"id": "select3736761055",
"maxSelect": 1,
"name": "format",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"single_elim",
"double_elim",
"groups",
"swiss",
"swiss_bracket",
"round_robin"
]
}))
// remove field
collection.fields.removeById("text3736761055")
return app.save(collection)
})

View File

@@ -0,0 +1,25 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// add field
collection.fields.addAt(14, new Field({
"hidden": false,
"id": "json118290348",
"maxSize": 0,
"name": "group_config",
"presentable": false,
"required": false,
"system": false,
"type": "json"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// remove field
collection.fields.removeById("json118290348")
return app.save(collection)
})

View File

@@ -0,0 +1,29 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// add field
collection.fields.addAt(15, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text2982008523",
"max": 0,
"min": 0,
"name": "phase",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_340646327")
// remove field
collection.fields.removeById("text2982008523")
return app.save(collection)
})

View File

@@ -0,0 +1,47 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_2541054544")
// add field
collection.fields.addAt(22, new Field({
"cascadeDelete": false,
"collectionId": "pbc_3346940990",
"hidden": false,
"id": "relation1841317061",
"maxSelect": 1,
"minSelect": 0,
"name": "group",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
}))
// add field
collection.fields.addAt(23, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "text3987859035",
"max": 0,
"min": 0,
"name": "match_type",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_2541054544")
// remove field
collection.fields.removeById("relation1841317061")
// remove field
collection.fields.removeById("text3987859035")
return app.save(collection)
})

BIN
public/apple-touch-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
public/favicon-16x16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
public/favicon-32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
public/favicon-96x96.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
public/icon-192x192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
public/icon-512x512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

View File

@@ -1,17 +1,28 @@
{ {
"name": "FLXN IX",
"short_name": "FLXN", "short_name": "FLXN",
"name": "FLXN",
"description": "Amicus meus madidus",
"icons": [ "icons": [
{ {
"src": "/favicon.png", "src": "/icon-192x192.png",
"type": "image/png",
"sizes": "192x192", "sizes": "192x192",
"type": "image/png" "purpose": "any maskable"
}, },
{ {
"src": "/favicon.png", "src": "/icon-512x512.png",
"type": "image/png",
"sizes": "512x512", "sizes": "512x512",
"type": "image/png" "purpose": "any maskable"
} }
], ],
"display": "standalone" "start_url": "/",
"display": "standalone",
"theme_color": "#1e293b",
"background_color": "#0f172a",
"orientation": "portrait-primary",
"scope": "/",
"categories": ["games", "social", "beer pong"],
"prefer_related_applications": false,
"shortcuts": []
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

407
server.ts
View File

@@ -16,73 +16,133 @@
* - Server port number * - Server port number
* - Default: 3000 * - Default: 3000
* *
* STATIC_PRELOAD_MAX_BYTES (number) * ASSET_PRELOAD_MAX_SIZE (number)
* - Maximum file size in bytes to preload into memory * - Maximum file size in bytes to preload into memory
* - Files larger than this will be served on-demand from disk * - Files larger than this will be served on-demand from disk
* - Default: 5242880 (5MB) * - Default: 5242880 (5MB)
* - Example: STATIC_PRELOAD_MAX_BYTES=5242880 (5MB) * - Example: ASSET_PRELOAD_MAX_SIZE=5242880 (5MB)
* *
* STATIC_PRELOAD_INCLUDE (string) * ASSET_PRELOAD_INCLUDE_PATTERNS (string)
* - Comma-separated list of glob patterns for files to include * - Comma-separated list of glob patterns for files to include
* - If specified, only matching files are eligible for preloading * - If specified, only matching files are eligible for preloading
* - Patterns are matched against filenames only, not full paths * - Patterns are matched against filenames only, not full paths
* - Example: STATIC_PRELOAD_INCLUDE="*.js,*.css,*.woff2" * - Example: ASSET_PRELOAD_INCLUDE_PATTERNS="*.js,*.css,*.woff2"
* *
* STATIC_PRELOAD_EXCLUDE (string) * ASSET_PRELOAD_EXCLUDE_PATTERNS (string)
* - Comma-separated list of glob patterns for files to exclude * - Comma-separated list of glob patterns for files to exclude
* - Applied after include patterns * - Applied after include patterns
* - Patterns are matched against filenames only, not full paths * - Patterns are matched against filenames only, not full paths
* - Example: STATIC_PRELOAD_EXCLUDE="*.map,*.txt" * - Example: ASSET_PRELOAD_EXCLUDE_PATTERNS="*.map,*.txt"
* *
* STATIC_PRELOAD_VERBOSE (boolean) * ASSET_PRELOAD_VERBOSE_LOGGING (boolean)
* - Enable detailed logging of loaded and skipped files * - Enable detailed logging of loaded and skipped files
* - Default: false * - Default: false
* - Set to "true" to enable verbose output * - Set to "true" to enable verbose output
* *
* ASSET_PRELOAD_ENABLE_ETAG (boolean)
* - Enable ETag generation for preloaded assets
* - Default: true
* - Set to "false" to disable ETag support
*
* ASSET_PRELOAD_ENABLE_GZIP (boolean)
* - Enable Gzip compression for eligible assets
* - Default: true
* - Set to "false" to disable Gzip compression
*
* ASSET_PRELOAD_GZIP_MIN_SIZE (number)
* - Minimum file size in bytes required for Gzip compression
* - Files smaller than this will not be compressed
* - Default: 1024 (1KB)
*
* ASSET_PRELOAD_GZIP_MIME_TYPES (string)
* - Comma-separated list of MIME types eligible for Gzip compression
* - Supports partial matching for types ending with "/"
* - Default: text/,application/javascript,application/json,application/xml,image/svg+xml
*
* Usage: * Usage:
* bun run server.ts * bun run server.ts
*/ */
import { readdir } from 'node:fs/promises' import path from 'node:path'
import { join } from 'node:path'
// Configuration // Configuration
const PORT = Number(process.env.PORT ?? 3000) const SERVER_PORT = Number(process.env.PORT ?? 3000)
const CLIENT_DIR = './dist/client' const CLIENT_DIRECTORY = './dist/client'
const SERVER_ENTRY = './dist/server/server.js' const SERVER_ENTRY_POINT = './dist/server/server.js'
// Logging utilities for professional output
const log = {
info: (message: string) => {
console.log(`[INFO] ${message}`)
},
success: (message: string) => {
console.log(`[SUCCESS] ${message}`)
},
warning: (message: string) => {
console.log(`[WARNING] ${message}`)
},
error: (message: string) => {
console.log(`[ERROR] ${message}`)
},
header: (message: string) => {
console.log(`\n${message}\n`)
},
}
// Preloading configuration from environment variables // Preloading configuration from environment variables
const MAX_PRELOAD_BYTES = Number( const MAX_PRELOAD_BYTES = Number(
process.env.STATIC_PRELOAD_MAX_BYTES ?? 5 * 1024 * 1024, // 5MB default process.env.ASSET_PRELOAD_MAX_SIZE ?? 5 * 1024 * 1024, // 5MB default
) )
// Parse comma-separated include patterns (no defaults) // Parse comma-separated include patterns (no defaults)
const INCLUDE_PATTERNS = (process.env.STATIC_PRELOAD_INCLUDE ?? '') const INCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '')
.split(',') .split(',')
.map((s) => s.trim()) .map((s) => s.trim())
.filter(Boolean) .filter(Boolean)
.map(globToRegExp) .map((pattern: string) => convertGlobToRegExp(pattern))
// Parse comma-separated exclude patterns (no defaults) // Parse comma-separated exclude patterns (no defaults)
const EXCLUDE_PATTERNS = (process.env.STATIC_PRELOAD_EXCLUDE ?? '') const EXCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? '')
.split(',') .split(',')
.map((s) => s.trim()) .map((s) => s.trim())
.filter(Boolean) .filter(Boolean)
.map(globToRegExp) .map((pattern: string) => convertGlobToRegExp(pattern))
// Verbose logging flag // Verbose logging flag
const VERBOSE = process.env.STATIC_PRELOAD_VERBOSE === 'true' const VERBOSE = process.env.ASSET_PRELOAD_VERBOSE_LOGGING === 'true'
// Optional ETag feature
const ENABLE_ETAG = (process.env.ASSET_PRELOAD_ENABLE_ETAG ?? 'true') === 'true'
// Optional Gzip feature
const ENABLE_GZIP = (process.env.ASSET_PRELOAD_ENABLE_GZIP ?? 'true') === 'true'
const GZIP_MIN_BYTES = Number(process.env.ASSET_PRELOAD_GZIP_MIN_SIZE ?? 1024) // 1KB
const GZIP_TYPES = (
process.env.ASSET_PRELOAD_GZIP_MIME_TYPES ??
'text/,application/javascript,application/json,application/xml,image/svg+xml'
)
.split(',')
.map((v) => v.trim())
.filter(Boolean)
/** /**
* Convert a simple glob pattern to a regular expression * Convert a simple glob pattern to a regular expression
* Supports * wildcard for matching any characters * Supports * wildcard for matching any characters
*/ */
function globToRegExp(glob: string): RegExp { function convertGlobToRegExp(globPattern: string): RegExp {
// Escape regex special chars except *, then replace * with .* // Escape regex special chars except *, then replace * with .*
const escaped = glob const escapedPattern = globPattern
.replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&') .replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&')
.replace(/\*/g, '.*') .replace(/\*/g, '.*')
return new RegExp(`^${escaped}$`, 'i') return new RegExp(`^${escapedPattern}$`, 'i')
}
/**
* Compute ETag for a given data buffer
*/
function computeEtag(data: Uint8Array): string {
const hash = Bun.hash(data)
return `W/"${hash.toString(16)}-${data.byteLength.toString()}"`
} }
/** /**
@@ -95,18 +155,30 @@ interface AssetMetadata {
} }
/** /**
* Result of static asset preloading process * In-memory asset with ETag and Gzip support
*/ */
interface PreloadResult { interface InMemoryAsset {
routes: Record<string, () => Response> raw: Uint8Array
loaded: Array<AssetMetadata> gz?: Uint8Array
skipped: Array<AssetMetadata> etag?: string
type: string
immutable: boolean
size: number
} }
/** /**
* Check if a file should be included based on configured patterns * Result of static asset preloading process
*/ */
function shouldInclude(relativePath: string): boolean { interface PreloadResult {
routes: Record<string, (req: Request) => Response | Promise<Response>>
loaded: AssetMetadata[]
skipped: AssetMetadata[]
}
/**
* Check if a file is eligible for preloading based on configured patterns
*/
function isFileEligibleForPreloading(relativePath: string): boolean {
const fileName = relativePath.split(/[/\\]/).pop() ?? relativePath const fileName = relativePath.split(/[/\\]/).pop() ?? relativePath
// If include patterns are specified, file must match at least one // If include patterns are specified, file must match at least one
@@ -125,38 +197,122 @@ function shouldInclude(relativePath: string): boolean {
} }
/** /**
* Build static routes with intelligent preloading strategy * Check if a MIME type is compressible
*/
function isMimeTypeCompressible(mimeType: string): boolean {
return GZIP_TYPES.some((type) =>
type.endsWith('/') ? mimeType.startsWith(type) : mimeType === type,
)
}
/**
* Conditionally compress data based on size and MIME type
*/
function compressDataIfAppropriate(
data: Uint8Array,
mimeType: string,
): Uint8Array | undefined {
if (!ENABLE_GZIP) return undefined
if (data.byteLength < GZIP_MIN_BYTES) return undefined
if (!isMimeTypeCompressible(mimeType)) return undefined
try {
return Bun.gzipSync(data.buffer as ArrayBuffer)
} catch {
return undefined
}
}
/**
* Create response handler function with ETag and Gzip support
*/
function createResponseHandler(
asset: InMemoryAsset,
): (req: Request) => Response {
return (req: Request) => {
const headers: Record<string, string> = {
'Content-Type': asset.type,
'Cache-Control': asset.immutable
? 'public, max-age=31536000, immutable'
: 'public, max-age=3600',
}
if (ENABLE_ETAG && asset.etag) {
const ifNone = req.headers.get('if-none-match')
if (ifNone && ifNone === asset.etag) {
return new Response(null, {
status: 304,
headers: { ETag: asset.etag },
})
}
headers.ETag = asset.etag
}
if (
ENABLE_GZIP &&
asset.gz &&
req.headers.get('accept-encoding')?.includes('gzip')
) {
headers['Content-Encoding'] = 'gzip'
headers['Content-Length'] = String(asset.gz.byteLength)
const gzCopy = new Uint8Array(asset.gz)
return new Response(gzCopy, { status: 200, headers })
}
headers['Content-Length'] = String(asset.raw.byteLength)
const rawCopy = new Uint8Array(asset.raw)
return new Response(rawCopy, { status: 200, headers })
}
}
/**
* Create composite glob pattern from include patterns
*/
function createCompositeGlobPattern(): Bun.Glob {
const raw = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
if (raw.length === 0) return new Bun.Glob('**/*')
if (raw.length === 1) return new Bun.Glob(raw[0])
return new Bun.Glob(`{${raw.join(',')}}`)
}
/**
* Initialize static routes with intelligent preloading strategy
* Small files are loaded into memory, large files are served on-demand * Small files are loaded into memory, large files are served on-demand
*/ */
async function buildStaticRoutes(clientDir: string): Promise<PreloadResult> { async function initializeStaticRoutes(
const routes: Record<string, () => Response> = {} clientDirectory: string,
const loaded: Array<AssetMetadata> = [] ): Promise<PreloadResult> {
const skipped: Array<AssetMetadata> = [] const routes: Record<string, (req: Request) => Response | Promise<Response>> =
{}
const loaded: AssetMetadata[] = []
const skipped: AssetMetadata[] = []
console.log(`📦 Loading static assets from ${clientDir}...`) log.info(`Loading static assets from ${clientDirectory}...`)
console.log( if (VERBOSE) {
` Max preload size: ${(MAX_PRELOAD_BYTES / 1024 / 1024).toFixed(2)} MB`,
)
if (INCLUDE_PATTERNS.length > 0) {
console.log( console.log(
` Include patterns: ${process.env.STATIC_PRELOAD_INCLUDE ?? ''}`, `Max preload size: ${(MAX_PRELOAD_BYTES / 1024 / 1024).toFixed(2)} MB`,
)
}
if (EXCLUDE_PATTERNS.length > 0) {
console.log(
` Exclude patterns: ${process.env.STATIC_PRELOAD_EXCLUDE ?? ''}`,
) )
if (INCLUDE_PATTERNS.length > 0) {
console.log(
`Include patterns: ${process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? ''}`,
)
}
if (EXCLUDE_PATTERNS.length > 0) {
console.log(
`Exclude patterns: ${process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? ''}`,
)
}
} }
let totalPreloadedBytes = 0 let totalPreloadedBytes = 0
try { try {
// Read all files recursively const glob = createCompositeGlobPattern()
const files = await readdir(clientDir, { recursive: true }) for await (const relativePath of glob.scan({ cwd: clientDirectory })) {
const filepath = path.join(clientDirectory, relativePath)
for (const relativePath of files) { const route = `/${relativePath.split(path.sep).join(path.posix.sep)}`
const filepath = join(clientDir, relativePath)
const route = '/' + relativePath.replace(/\\/g, '/') // Handle Windows paths
try { try {
// Get file metadata // Get file metadata
@@ -174,20 +330,23 @@ async function buildStaticRoutes(clientDir: string): Promise<PreloadResult> {
} }
// Determine if file should be preloaded // Determine if file should be preloaded
const matchesPattern = shouldInclude(relativePath) const matchesPattern = isFileEligibleForPreloading(relativePath)
const withinSizeLimit = file.size <= MAX_PRELOAD_BYTES const withinSizeLimit = file.size <= MAX_PRELOAD_BYTES
if (matchesPattern && withinSizeLimit) { if (matchesPattern && withinSizeLimit) {
// Preload small files into memory // Preload small files into memory with ETag and Gzip support
const bytes = await file.bytes() const bytes = new Uint8Array(await file.arrayBuffer())
const gz = compressDataIfAppropriate(bytes, metadata.type)
routes[route] = () => const etag = ENABLE_ETAG ? computeEtag(bytes) : undefined
new Response(bytes, { const asset: InMemoryAsset = {
headers: { raw: bytes,
'Content-Type': metadata.type, gz,
'Cache-Control': 'public, max-age=31536000, immutable', etag,
}, type: metadata.type,
}) immutable: true,
size: bytes.byteLength,
}
routes[route] = createResponseHandler(asset)
loaded.push({ ...metadata, size: bytes.byteLength }) loaded.push({ ...metadata, size: bytes.byteLength })
totalPreloadedBytes += bytes.byteLength totalPreloadedBytes += bytes.byteLength
@@ -207,13 +366,13 @@ async function buildStaticRoutes(clientDir: string): Promise<PreloadResult> {
} }
} catch (error: unknown) { } catch (error: unknown) {
if (error instanceof Error && error.name !== 'EISDIR') { if (error instanceof Error && error.name !== 'EISDIR') {
console.error(`Failed to load ${filepath}:`, error) log.error(`Failed to load ${filepath}: ${error.message}`)
} }
} }
} }
// Always show file overview in Vite-like format first // Show detailed file overview only when verbose mode is enabled
if (loaded.length > 0 || skipped.length > 0) { if (VERBOSE && (loaded.length > 0 || skipped.length > 0)) {
const allFiles = [...loaded, ...skipped].sort((a, b) => const allFiles = [...loaded, ...skipped].sort((a, b) =>
a.route.localeCompare(b.route), a.route.localeCompare(b.route),
) )
@@ -224,124 +383,162 @@ async function buildStaticRoutes(clientDir: string): Promise<PreloadResult> {
60, 60,
) )
// Format file size with KB and gzip estimation // Format file size with KB and actual gzip size
const formatFileSize = (bytes: number) => { const formatFileSize = (bytes: number, gzBytes?: number) => {
const kb = bytes / 1024 const kb = bytes / 1024
// Rough gzip estimation (typically 30-70% compression) const sizeStr = kb < 100 ? kb.toFixed(2) : kb.toFixed(1)
if (gzBytes !== undefined) {
const gzKb = gzBytes / 1024
const gzStr = gzKb < 100 ? gzKb.toFixed(2) : gzKb.toFixed(1)
return {
size: sizeStr,
gzip: gzStr,
}
}
// Rough gzip estimation (typically 30-70% compression) if no actual gzip data
const gzipKb = kb * 0.35 const gzipKb = kb * 0.35
return { return {
size: kb < 100 ? kb.toFixed(2) : kb.toFixed(1), size: sizeStr,
gzip: gzipKb < 100 ? gzipKb.toFixed(2) : gzipKb.toFixed(1), gzip: gzipKb < 100 ? gzipKb.toFixed(2) : gzipKb.toFixed(1),
} }
} }
if (loaded.length > 0) { if (loaded.length > 0) {
console.log('\n📁 Preloaded into memory:') console.log('\n📁 Preloaded into memory:')
console.log(
'Path │ Size │ Gzip Size',
)
loaded loaded
.sort((a, b) => a.route.localeCompare(b.route)) .sort((a, b) => a.route.localeCompare(b.route))
.forEach((file) => { .forEach((file) => {
const { size, gzip } = formatFileSize(file.size) const { size, gzip } = formatFileSize(file.size)
const paddedPath = file.route.padEnd(maxPathLength) const paddedPath = file.route.padEnd(maxPathLength)
const sizeStr = `${size.padStart(7)} kB` const sizeStr = `${size.padStart(7)} kB`
const gzipStr = `gzip: ${gzip.padStart(6)} kB` const gzipStr = `${gzip.padStart(7)} kB`
console.log(` ${paddedPath} ${sizeStr}${gzipStr}`) console.log(`${paddedPath} ${sizeStr} ${gzipStr}`)
}) })
} }
if (skipped.length > 0) { if (skipped.length > 0) {
console.log('\n💾 Served on-demand:') console.log('\n💾 Served on-demand:')
console.log(
'Path │ Size │ Gzip Size',
)
skipped skipped
.sort((a, b) => a.route.localeCompare(b.route)) .sort((a, b) => a.route.localeCompare(b.route))
.forEach((file) => { .forEach((file) => {
const { size, gzip } = formatFileSize(file.size) const { size, gzip } = formatFileSize(file.size)
const paddedPath = file.route.padEnd(maxPathLength) const paddedPath = file.route.padEnd(maxPathLength)
const sizeStr = `${size.padStart(7)} kB` const sizeStr = `${size.padStart(7)} kB`
const gzipStr = `gzip: ${gzip.padStart(6)} kB` const gzipStr = `${gzip.padStart(7)} kB`
console.log(` ${paddedPath} ${sizeStr}${gzipStr}`) console.log(`${paddedPath} ${sizeStr} ${gzipStr}`)
}) })
} }
}
// Show detailed verbose info if enabled // Show detailed verbose info if enabled
if (VERBOSE) { if (VERBOSE) {
if (loaded.length > 0 || skipped.length > 0) {
const allFiles = [...loaded, ...skipped].sort((a, b) =>
a.route.localeCompare(b.route),
)
console.log('\n📊 Detailed file information:') console.log('\n📊 Detailed file information:')
console.log(
'Status │ Path │ MIME Type │ Reason',
)
allFiles.forEach((file) => { allFiles.forEach((file) => {
const isPreloaded = loaded.includes(file) const isPreloaded = loaded.includes(file)
const status = isPreloaded ? '[MEMORY]' : '[ON-DEMAND]' const status = isPreloaded ? 'MEMORY' : 'ON-DEMAND'
const reason = const reason =
!isPreloaded && file.size > MAX_PRELOAD_BYTES !isPreloaded && file.size > MAX_PRELOAD_BYTES
? ' (too large)' ? 'too large'
: !isPreloaded : !isPreloaded
? ' (filtered)' ? 'filtered'
: '' : 'preloaded'
const route =
file.route.length > 30
? file.route.substring(0, 27) + '...'
: file.route
console.log( console.log(
` ${status.padEnd(12)} ${file.route} - ${file.type}${reason}`, `${status.padEnd(12)} ${route.padEnd(30)} ${file.type.padEnd(28)}${reason.padEnd(10)}`,
) )
}) })
} else {
console.log('\n📊 No files found to display')
} }
} }
// Log summary after the file list // Log summary after the file list
console.log() // Empty line for separation console.log() // Empty line for separation
if (loaded.length > 0) { if (loaded.length > 0) {
console.log( log.success(
`Preloaded ${String(loaded.length)} files (${(totalPreloadedBytes / 1024 / 1024).toFixed(2)} MB) into memory`, `Preloaded ${String(loaded.length)} files (${(totalPreloadedBytes / 1024 / 1024).toFixed(2)} MB) into memory`,
) )
} else { } else {
console.log(' No files preloaded into memory') log.info('No files preloaded into memory')
} }
if (skipped.length > 0) { if (skipped.length > 0) {
const tooLarge = skipped.filter((f) => f.size > MAX_PRELOAD_BYTES).length const tooLarge = skipped.filter((f) => f.size > MAX_PRELOAD_BYTES).length
const filtered = skipped.length - tooLarge const filtered = skipped.length - tooLarge
console.log( log.info(
` ${String(skipped.length)} files will be served on-demand (${String(tooLarge)} too large, ${String(filtered)} filtered)`, `${String(skipped.length)} files will be served on-demand (${String(tooLarge)} too large, ${String(filtered)} filtered)`,
) )
} }
} catch (error) { } catch (error) {
console.error(`❌ Failed to load static files from ${clientDir}:`, error) log.error(
`Failed to load static files from ${clientDirectory}: ${String(error)}`,
)
} }
return { routes, loaded, skipped } return { routes, loaded, skipped }
} }
/** /**
* Start the production server * Initialize the server
*/ */
async function startServer() { async function initializeServer() {
console.log('🚀 Starting production server...') log.header('Starting Production Server')
// Load TanStack Start server handler // Load TanStack Start server handler
let handler: { fetch: (request: Request) => Response | Promise<Response> } let handler: { fetch: (request: Request) => Response | Promise<Response> }
try { try {
const serverModule = (await import(SERVER_ENTRY)) as { const serverModule = (await import(SERVER_ENTRY_POINT)) as {
default: { fetch: (request: Request) => Response | Promise<Response> } default: { fetch: (request: Request) => Response | Promise<Response> }
} }
handler = serverModule.default handler = serverModule.default
console.log('TanStack Start handler loaded') log.success('TanStack Start application handler initialized')
} catch (error) { } catch (error) {
console.error('❌ Failed to load server handler:', error) log.error(`Failed to load server handler: ${String(error)}`)
process.exit(1) process.exit(1)
} }
// Build static routes with intelligent preloading // Build static routes with intelligent preloading
const { routes } = await buildStaticRoutes(CLIENT_DIR) const { routes } = await initializeStaticRoutes(CLIENT_DIRECTORY)
// Create Bun server // Create Bun server
const server = Bun.serve({ const server = Bun.serve({
port: PORT, port: SERVER_PORT,
idleTimeout: 255,
routes: { routes: {
// Serve static assets (preloaded or on-demand) // Serve static assets (preloaded or on-demand)
...routes, ...routes,
// Fallback to TanStack Start handler for all other routes // Fallback to TanStack Start handler for all other routes
'/*': (request) => { '/*': async (req: Request) => {
try { try {
return handler.fetch(request) const h3Response = await handler.fetch(req)
const body = await h3Response.arrayBuffer()
return new Response(body, {
status: h3Response.status,
statusText: h3Response.statusText,
headers: h3Response.headers,
})
} catch (error) { } catch (error) {
console.error('Server handler error:', error) log.error(`Server handler error: ${String(error)}`)
return new Response('Internal Server Error', { status: 500 }) return new Response('Internal Server Error', { status: 500 })
} }
}, },
@@ -349,18 +546,18 @@ async function startServer() {
// Global error handler // Global error handler
error(error) { error(error) {
console.error('Uncaught server error:', error) log.error(
`Uncaught server error: ${error instanceof Error ? error.message : String(error)}`,
)
return new Response('Internal Server Error', { status: 500 }) return new Response('Internal Server Error', { status: 500 })
}, },
}) })
console.log( log.success(`Server listening on http://localhost:${String(server.port)}`)
`\n🚀 Server running at http://localhost:${String(server.port)}\n`,
)
} }
// Start the server // Initialize the server
startServer().catch((error: unknown) => { initializeServer().catch((error: unknown) => {
console.error('Failed to start server:', error) log.error(`Failed to start server: ${String(error)}`)
process.exit(1) process.exit(1)
}) })

View File

@@ -14,8 +14,10 @@ import { Route as LogoutRouteImport } from './routes/logout'
import { Route as LoginRouteImport } from './routes/login' import { Route as LoginRouteImport } from './routes/login'
import { Route as AuthedRouteImport } from './routes/_authed' import { Route as AuthedRouteImport } from './routes/_authed'
import { Route as AuthedIndexRouteImport } from './routes/_authed/index' import { Route as AuthedIndexRouteImport } from './routes/_authed/index'
import { Route as ApiHealthRouteImport } from './routes/api/health'
import { Route as AuthedStatsRouteImport } from './routes/_authed/stats' import { Route as AuthedStatsRouteImport } from './routes/_authed/stats'
import { Route as AuthedSettingsRouteImport } from './routes/_authed/settings' import { Route as AuthedSettingsRouteImport } from './routes/_authed/settings'
import { Route as AuthedBadgesRouteImport } from './routes/_authed/badges'
import { Route as AuthedAdminRouteImport } from './routes/_authed/admin' import { Route as AuthedAdminRouteImport } from './routes/_authed/admin'
import { Route as AuthedTournamentsIndexRouteImport } from './routes/_authed/tournaments/index' import { Route as AuthedTournamentsIndexRouteImport } from './routes/_authed/tournaments/index'
import { Route as AuthedAdminIndexRouteImport } from './routes/_authed/admin/index' import { Route as AuthedAdminIndexRouteImport } from './routes/_authed/admin/index'
@@ -36,11 +38,13 @@ import { Route as AuthedAdminPreviewRouteImport } from './routes/_authed/admin/p
import { Route as AuthedAdminBadgesRouteImport } from './routes/_authed/admin/badges' import { Route as AuthedAdminBadgesRouteImport } from './routes/_authed/admin/badges'
import { Route as AuthedAdminActivitiesRouteImport } from './routes/_authed/admin/activities' import { Route as AuthedAdminActivitiesRouteImport } from './routes/_authed/admin/activities'
import { Route as AuthedAdminTournamentsIndexRouteImport } from './routes/_authed/admin/tournaments/index' import { Route as AuthedAdminTournamentsIndexRouteImport } from './routes/_authed/admin/tournaments/index'
import { Route as AuthedTournamentsIdGroupsRouteImport } from './routes/_authed/tournaments/$id.groups'
import { Route as AuthedTournamentsIdBracketRouteImport } from './routes/_authed/tournaments/$id.bracket' import { Route as AuthedTournamentsIdBracketRouteImport } from './routes/_authed/tournaments/$id.bracket'
import { Route as AuthedAdminTournamentsIdIndexRouteImport } from './routes/_authed/admin/tournaments/$id/index' import { Route as AuthedAdminTournamentsIdIndexRouteImport } from './routes/_authed/admin/tournaments/$id/index'
import { Route as ApiFilesCollectionRecordIdFileRouteImport } from './routes/api/files/$collection/$recordId/$file' import { Route as ApiFilesCollectionRecordIdFileRouteImport } from './routes/api/files/$collection/$recordId/$file'
import { Route as AuthedAdminTournamentsRunIdRouteImport } from './routes/_authed/admin/tournaments/run.$id' import { Route as AuthedAdminTournamentsRunIdRouteImport } from './routes/_authed/admin/tournaments/run.$id'
import { Route as AuthedAdminTournamentsIdTeamsRouteImport } from './routes/_authed/admin/tournaments/$id/teams' import { Route as AuthedAdminTournamentsIdTeamsRouteImport } from './routes/_authed/admin/tournaments/$id/teams'
import { Route as AuthedAdminTournamentsIdAssignPartnersRouteImport } from './routes/_authed/admin/tournaments/$id/assign-partners'
const RefreshSessionRoute = RefreshSessionRouteImport.update({ const RefreshSessionRoute = RefreshSessionRouteImport.update({
id: '/refresh-session', id: '/refresh-session',
@@ -66,6 +70,11 @@ const AuthedIndexRoute = AuthedIndexRouteImport.update({
path: '/', path: '/',
getParentRoute: () => AuthedRoute, getParentRoute: () => AuthedRoute,
} as any) } as any)
const ApiHealthRoute = ApiHealthRouteImport.update({
id: '/api/health',
path: '/api/health',
getParentRoute: () => rootRouteImport,
} as any)
const AuthedStatsRoute = AuthedStatsRouteImport.update({ const AuthedStatsRoute = AuthedStatsRouteImport.update({
id: '/stats', id: '/stats',
path: '/stats', path: '/stats',
@@ -76,6 +85,11 @@ const AuthedSettingsRoute = AuthedSettingsRouteImport.update({
path: '/settings', path: '/settings',
getParentRoute: () => AuthedRoute, getParentRoute: () => AuthedRoute,
} as any) } as any)
const AuthedBadgesRoute = AuthedBadgesRouteImport.update({
id: '/badges',
path: '/badges',
getParentRoute: () => AuthedRoute,
} as any)
const AuthedAdminRoute = AuthedAdminRouteImport.update({ const AuthedAdminRoute = AuthedAdminRouteImport.update({
id: '/admin', id: '/admin',
path: '/admin', path: '/admin',
@@ -179,6 +193,12 @@ const AuthedAdminTournamentsIndexRoute =
path: '/tournaments/', path: '/tournaments/',
getParentRoute: () => AuthedAdminRoute, getParentRoute: () => AuthedAdminRoute,
} as any) } as any)
const AuthedTournamentsIdGroupsRoute =
AuthedTournamentsIdGroupsRouteImport.update({
id: '/tournaments/$id/groups',
path: '/tournaments/$id/groups',
getParentRoute: () => AuthedRoute,
} as any)
const AuthedTournamentsIdBracketRoute = const AuthedTournamentsIdBracketRoute =
AuthedTournamentsIdBracketRouteImport.update({ AuthedTournamentsIdBracketRouteImport.update({
id: '/tournaments/$id/bracket', id: '/tournaments/$id/bracket',
@@ -209,15 +229,23 @@ const AuthedAdminTournamentsIdTeamsRoute =
path: '/tournaments/$id/teams', path: '/tournaments/$id/teams',
getParentRoute: () => AuthedAdminRoute, getParentRoute: () => AuthedAdminRoute,
} as any) } as any)
const AuthedAdminTournamentsIdAssignPartnersRoute =
AuthedAdminTournamentsIdAssignPartnersRouteImport.update({
id: '/tournaments/$id/assign-partners',
path: '/tournaments/$id/assign-partners',
getParentRoute: () => AuthedAdminRoute,
} as any)
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
'/': typeof AuthedIndexRoute
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/logout': typeof LogoutRoute '/logout': typeof LogoutRoute
'/refresh-session': typeof RefreshSessionRoute '/refresh-session': typeof RefreshSessionRoute
'/admin': typeof AuthedAdminRouteWithChildren '/admin': typeof AuthedAdminRouteWithChildren
'/badges': typeof AuthedBadgesRoute
'/settings': typeof AuthedSettingsRoute '/settings': typeof AuthedSettingsRoute
'/stats': typeof AuthedStatsRoute '/stats': typeof AuthedStatsRoute
'/': typeof AuthedIndexRoute '/api/health': typeof ApiHealthRoute
'/admin/activities': typeof AuthedAdminActivitiesRoute '/admin/activities': typeof AuthedAdminActivitiesRoute
'/admin/badges': typeof AuthedAdminBadgesRoute '/admin/badges': typeof AuthedAdminBadgesRoute
'/admin/preview': typeof AuthedAdminPreviewRoute '/admin/preview': typeof AuthedAdminPreviewRoute
@@ -235,20 +263,24 @@ export interface FileRoutesByFullPath {
'/api/teams/upload-logo': typeof ApiTeamsUploadLogoRoute '/api/teams/upload-logo': typeof ApiTeamsUploadLogoRoute
'/api/tournaments/upload-logo': typeof ApiTournamentsUploadLogoRoute '/api/tournaments/upload-logo': typeof ApiTournamentsUploadLogoRoute
'/admin/': typeof AuthedAdminIndexRoute '/admin/': typeof AuthedAdminIndexRoute
'/tournaments': typeof AuthedTournamentsIndexRoute '/tournaments/': typeof AuthedTournamentsIndexRoute
'/tournaments/$id/bracket': typeof AuthedTournamentsIdBracketRoute '/tournaments/$id/bracket': typeof AuthedTournamentsIdBracketRoute
'/admin/tournaments': typeof AuthedAdminTournamentsIndexRoute '/tournaments/$id/groups': typeof AuthedTournamentsIdGroupsRoute
'/admin/tournaments/': typeof AuthedAdminTournamentsIndexRoute
'/admin/tournaments/$id/assign-partners': typeof AuthedAdminTournamentsIdAssignPartnersRoute
'/admin/tournaments/$id/teams': typeof AuthedAdminTournamentsIdTeamsRoute '/admin/tournaments/$id/teams': typeof AuthedAdminTournamentsIdTeamsRoute
'/admin/tournaments/run/$id': typeof AuthedAdminTournamentsRunIdRoute '/admin/tournaments/run/$id': typeof AuthedAdminTournamentsRunIdRoute
'/api/files/$collection/$recordId/$file': typeof ApiFilesCollectionRecordIdFileRoute '/api/files/$collection/$recordId/$file': typeof ApiFilesCollectionRecordIdFileRoute
'/admin/tournaments/$id': typeof AuthedAdminTournamentsIdIndexRoute '/admin/tournaments/$id/': typeof AuthedAdminTournamentsIdIndexRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/logout': typeof LogoutRoute '/logout': typeof LogoutRoute
'/refresh-session': typeof RefreshSessionRoute '/refresh-session': typeof RefreshSessionRoute
'/badges': typeof AuthedBadgesRoute
'/settings': typeof AuthedSettingsRoute '/settings': typeof AuthedSettingsRoute
'/stats': typeof AuthedStatsRoute '/stats': typeof AuthedStatsRoute
'/api/health': typeof ApiHealthRoute
'/': typeof AuthedIndexRoute '/': typeof AuthedIndexRoute
'/admin/activities': typeof AuthedAdminActivitiesRoute '/admin/activities': typeof AuthedAdminActivitiesRoute
'/admin/badges': typeof AuthedAdminBadgesRoute '/admin/badges': typeof AuthedAdminBadgesRoute
@@ -269,7 +301,9 @@ export interface FileRoutesByTo {
'/admin': typeof AuthedAdminIndexRoute '/admin': typeof AuthedAdminIndexRoute
'/tournaments': typeof AuthedTournamentsIndexRoute '/tournaments': typeof AuthedTournamentsIndexRoute
'/tournaments/$id/bracket': typeof AuthedTournamentsIdBracketRoute '/tournaments/$id/bracket': typeof AuthedTournamentsIdBracketRoute
'/tournaments/$id/groups': typeof AuthedTournamentsIdGroupsRoute
'/admin/tournaments': typeof AuthedAdminTournamentsIndexRoute '/admin/tournaments': typeof AuthedAdminTournamentsIndexRoute
'/admin/tournaments/$id/assign-partners': typeof AuthedAdminTournamentsIdAssignPartnersRoute
'/admin/tournaments/$id/teams': typeof AuthedAdminTournamentsIdTeamsRoute '/admin/tournaments/$id/teams': typeof AuthedAdminTournamentsIdTeamsRoute
'/admin/tournaments/run/$id': typeof AuthedAdminTournamentsRunIdRoute '/admin/tournaments/run/$id': typeof AuthedAdminTournamentsRunIdRoute
'/api/files/$collection/$recordId/$file': typeof ApiFilesCollectionRecordIdFileRoute '/api/files/$collection/$recordId/$file': typeof ApiFilesCollectionRecordIdFileRoute
@@ -282,8 +316,10 @@ export interface FileRoutesById {
'/logout': typeof LogoutRoute '/logout': typeof LogoutRoute
'/refresh-session': typeof RefreshSessionRoute '/refresh-session': typeof RefreshSessionRoute
'/_authed/admin': typeof AuthedAdminRouteWithChildren '/_authed/admin': typeof AuthedAdminRouteWithChildren
'/_authed/badges': typeof AuthedBadgesRoute
'/_authed/settings': typeof AuthedSettingsRoute '/_authed/settings': typeof AuthedSettingsRoute
'/_authed/stats': typeof AuthedStatsRoute '/_authed/stats': typeof AuthedStatsRoute
'/api/health': typeof ApiHealthRoute
'/_authed/': typeof AuthedIndexRoute '/_authed/': typeof AuthedIndexRoute
'/_authed/admin/activities': typeof AuthedAdminActivitiesRoute '/_authed/admin/activities': typeof AuthedAdminActivitiesRoute
'/_authed/admin/badges': typeof AuthedAdminBadgesRoute '/_authed/admin/badges': typeof AuthedAdminBadgesRoute
@@ -304,7 +340,9 @@ export interface FileRoutesById {
'/_authed/admin/': typeof AuthedAdminIndexRoute '/_authed/admin/': typeof AuthedAdminIndexRoute
'/_authed/tournaments/': typeof AuthedTournamentsIndexRoute '/_authed/tournaments/': typeof AuthedTournamentsIndexRoute
'/_authed/tournaments/$id/bracket': typeof AuthedTournamentsIdBracketRoute '/_authed/tournaments/$id/bracket': typeof AuthedTournamentsIdBracketRoute
'/_authed/tournaments/$id/groups': typeof AuthedTournamentsIdGroupsRoute
'/_authed/admin/tournaments/': typeof AuthedAdminTournamentsIndexRoute '/_authed/admin/tournaments/': typeof AuthedAdminTournamentsIndexRoute
'/_authed/admin/tournaments/$id/assign-partners': typeof AuthedAdminTournamentsIdAssignPartnersRoute
'/_authed/admin/tournaments/$id/teams': typeof AuthedAdminTournamentsIdTeamsRoute '/_authed/admin/tournaments/$id/teams': typeof AuthedAdminTournamentsIdTeamsRoute
'/_authed/admin/tournaments/run/$id': typeof AuthedAdminTournamentsRunIdRoute '/_authed/admin/tournaments/run/$id': typeof AuthedAdminTournamentsRunIdRoute
'/api/files/$collection/$recordId/$file': typeof ApiFilesCollectionRecordIdFileRoute '/api/files/$collection/$recordId/$file': typeof ApiFilesCollectionRecordIdFileRoute
@@ -313,13 +351,15 @@ export interface FileRoutesById {
export interface FileRouteTypes { export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: fullPaths:
| '/'
| '/login' | '/login'
| '/logout' | '/logout'
| '/refresh-session' | '/refresh-session'
| '/admin' | '/admin'
| '/badges'
| '/settings' | '/settings'
| '/stats' | '/stats'
| '/' | '/api/health'
| '/admin/activities' | '/admin/activities'
| '/admin/badges' | '/admin/badges'
| '/admin/preview' | '/admin/preview'
@@ -337,20 +377,24 @@ export interface FileRouteTypes {
| '/api/teams/upload-logo' | '/api/teams/upload-logo'
| '/api/tournaments/upload-logo' | '/api/tournaments/upload-logo'
| '/admin/' | '/admin/'
| '/tournaments' | '/tournaments/'
| '/tournaments/$id/bracket' | '/tournaments/$id/bracket'
| '/admin/tournaments' | '/tournaments/$id/groups'
| '/admin/tournaments/'
| '/admin/tournaments/$id/assign-partners'
| '/admin/tournaments/$id/teams' | '/admin/tournaments/$id/teams'
| '/admin/tournaments/run/$id' | '/admin/tournaments/run/$id'
| '/api/files/$collection/$recordId/$file' | '/api/files/$collection/$recordId/$file'
| '/admin/tournaments/$id' | '/admin/tournaments/$id/'
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: to:
| '/login' | '/login'
| '/logout' | '/logout'
| '/refresh-session' | '/refresh-session'
| '/badges'
| '/settings' | '/settings'
| '/stats' | '/stats'
| '/api/health'
| '/' | '/'
| '/admin/activities' | '/admin/activities'
| '/admin/badges' | '/admin/badges'
@@ -371,7 +415,9 @@ export interface FileRouteTypes {
| '/admin' | '/admin'
| '/tournaments' | '/tournaments'
| '/tournaments/$id/bracket' | '/tournaments/$id/bracket'
| '/tournaments/$id/groups'
| '/admin/tournaments' | '/admin/tournaments'
| '/admin/tournaments/$id/assign-partners'
| '/admin/tournaments/$id/teams' | '/admin/tournaments/$id/teams'
| '/admin/tournaments/run/$id' | '/admin/tournaments/run/$id'
| '/api/files/$collection/$recordId/$file' | '/api/files/$collection/$recordId/$file'
@@ -383,8 +429,10 @@ export interface FileRouteTypes {
| '/logout' | '/logout'
| '/refresh-session' | '/refresh-session'
| '/_authed/admin' | '/_authed/admin'
| '/_authed/badges'
| '/_authed/settings' | '/_authed/settings'
| '/_authed/stats' | '/_authed/stats'
| '/api/health'
| '/_authed/' | '/_authed/'
| '/_authed/admin/activities' | '/_authed/admin/activities'
| '/_authed/admin/badges' | '/_authed/admin/badges'
@@ -405,7 +453,9 @@ export interface FileRouteTypes {
| '/_authed/admin/' | '/_authed/admin/'
| '/_authed/tournaments/' | '/_authed/tournaments/'
| '/_authed/tournaments/$id/bracket' | '/_authed/tournaments/$id/bracket'
| '/_authed/tournaments/$id/groups'
| '/_authed/admin/tournaments/' | '/_authed/admin/tournaments/'
| '/_authed/admin/tournaments/$id/assign-partners'
| '/_authed/admin/tournaments/$id/teams' | '/_authed/admin/tournaments/$id/teams'
| '/_authed/admin/tournaments/run/$id' | '/_authed/admin/tournaments/run/$id'
| '/api/files/$collection/$recordId/$file' | '/api/files/$collection/$recordId/$file'
@@ -417,6 +467,7 @@ export interface RootRouteChildren {
LoginRoute: typeof LoginRoute LoginRoute: typeof LoginRoute
LogoutRoute: typeof LogoutRoute LogoutRoute: typeof LogoutRoute
RefreshSessionRoute: typeof RefreshSessionRoute RefreshSessionRoute: typeof RefreshSessionRoute
ApiHealthRoute: typeof ApiHealthRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute ApiAuthSplatRoute: typeof ApiAuthSplatRoute
ApiEventsSplatRoute: typeof ApiEventsSplatRoute ApiEventsSplatRoute: typeof ApiEventsSplatRoute
ApiSpotifyCallbackRoute: typeof ApiSpotifyCallbackRoute ApiSpotifyCallbackRoute: typeof ApiSpotifyCallbackRoute
@@ -456,7 +507,7 @@ declare module '@tanstack/react-router' {
'/_authed': { '/_authed': {
id: '/_authed' id: '/_authed'
path: '' path: ''
fullPath: '' fullPath: '/'
preLoaderRoute: typeof AuthedRouteImport preLoaderRoute: typeof AuthedRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
@@ -467,6 +518,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthedIndexRouteImport preLoaderRoute: typeof AuthedIndexRouteImport
parentRoute: typeof AuthedRoute parentRoute: typeof AuthedRoute
} }
'/api/health': {
id: '/api/health'
path: '/api/health'
fullPath: '/api/health'
preLoaderRoute: typeof ApiHealthRouteImport
parentRoute: typeof rootRouteImport
}
'/_authed/stats': { '/_authed/stats': {
id: '/_authed/stats' id: '/_authed/stats'
path: '/stats' path: '/stats'
@@ -481,6 +539,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthedSettingsRouteImport preLoaderRoute: typeof AuthedSettingsRouteImport
parentRoute: typeof AuthedRoute parentRoute: typeof AuthedRoute
} }
'/_authed/badges': {
id: '/_authed/badges'
path: '/badges'
fullPath: '/badges'
preLoaderRoute: typeof AuthedBadgesRouteImport
parentRoute: typeof AuthedRoute
}
'/_authed/admin': { '/_authed/admin': {
id: '/_authed/admin' id: '/_authed/admin'
path: '/admin' path: '/admin'
@@ -491,7 +556,7 @@ declare module '@tanstack/react-router' {
'/_authed/tournaments/': { '/_authed/tournaments/': {
id: '/_authed/tournaments/' id: '/_authed/tournaments/'
path: '/tournaments' path: '/tournaments'
fullPath: '/tournaments' fullPath: '/tournaments/'
preLoaderRoute: typeof AuthedTournamentsIndexRouteImport preLoaderRoute: typeof AuthedTournamentsIndexRouteImport
parentRoute: typeof AuthedRoute parentRoute: typeof AuthedRoute
} }
@@ -617,10 +682,17 @@ declare module '@tanstack/react-router' {
'/_authed/admin/tournaments/': { '/_authed/admin/tournaments/': {
id: '/_authed/admin/tournaments/' id: '/_authed/admin/tournaments/'
path: '/tournaments' path: '/tournaments'
fullPath: '/admin/tournaments' fullPath: '/admin/tournaments/'
preLoaderRoute: typeof AuthedAdminTournamentsIndexRouteImport preLoaderRoute: typeof AuthedAdminTournamentsIndexRouteImport
parentRoute: typeof AuthedAdminRoute parentRoute: typeof AuthedAdminRoute
} }
'/_authed/tournaments/$id/groups': {
id: '/_authed/tournaments/$id/groups'
path: '/tournaments/$id/groups'
fullPath: '/tournaments/$id/groups'
preLoaderRoute: typeof AuthedTournamentsIdGroupsRouteImport
parentRoute: typeof AuthedRoute
}
'/_authed/tournaments/$id/bracket': { '/_authed/tournaments/$id/bracket': {
id: '/_authed/tournaments/$id/bracket' id: '/_authed/tournaments/$id/bracket'
path: '/tournaments/$id/bracket' path: '/tournaments/$id/bracket'
@@ -631,7 +703,7 @@ declare module '@tanstack/react-router' {
'/_authed/admin/tournaments/$id/': { '/_authed/admin/tournaments/$id/': {
id: '/_authed/admin/tournaments/$id/' id: '/_authed/admin/tournaments/$id/'
path: '/tournaments/$id' path: '/tournaments/$id'
fullPath: '/admin/tournaments/$id' fullPath: '/admin/tournaments/$id/'
preLoaderRoute: typeof AuthedAdminTournamentsIdIndexRouteImport preLoaderRoute: typeof AuthedAdminTournamentsIdIndexRouteImport
parentRoute: typeof AuthedAdminRoute parentRoute: typeof AuthedAdminRoute
} }
@@ -656,6 +728,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthedAdminTournamentsIdTeamsRouteImport preLoaderRoute: typeof AuthedAdminTournamentsIdTeamsRouteImport
parentRoute: typeof AuthedAdminRoute parentRoute: typeof AuthedAdminRoute
} }
'/_authed/admin/tournaments/$id/assign-partners': {
id: '/_authed/admin/tournaments/$id/assign-partners'
path: '/tournaments/$id/assign-partners'
fullPath: '/admin/tournaments/$id/assign-partners'
preLoaderRoute: typeof AuthedAdminTournamentsIdAssignPartnersRouteImport
parentRoute: typeof AuthedAdminRoute
}
} }
} }
@@ -665,6 +744,7 @@ interface AuthedAdminRouteChildren {
AuthedAdminPreviewRoute: typeof AuthedAdminPreviewRoute AuthedAdminPreviewRoute: typeof AuthedAdminPreviewRoute
AuthedAdminIndexRoute: typeof AuthedAdminIndexRoute AuthedAdminIndexRoute: typeof AuthedAdminIndexRoute
AuthedAdminTournamentsIndexRoute: typeof AuthedAdminTournamentsIndexRoute AuthedAdminTournamentsIndexRoute: typeof AuthedAdminTournamentsIndexRoute
AuthedAdminTournamentsIdAssignPartnersRoute: typeof AuthedAdminTournamentsIdAssignPartnersRoute
AuthedAdminTournamentsIdTeamsRoute: typeof AuthedAdminTournamentsIdTeamsRoute AuthedAdminTournamentsIdTeamsRoute: typeof AuthedAdminTournamentsIdTeamsRoute
AuthedAdminTournamentsRunIdRoute: typeof AuthedAdminTournamentsRunIdRoute AuthedAdminTournamentsRunIdRoute: typeof AuthedAdminTournamentsRunIdRoute
AuthedAdminTournamentsIdIndexRoute: typeof AuthedAdminTournamentsIdIndexRoute AuthedAdminTournamentsIdIndexRoute: typeof AuthedAdminTournamentsIdIndexRoute
@@ -676,6 +756,8 @@ const AuthedAdminRouteChildren: AuthedAdminRouteChildren = {
AuthedAdminPreviewRoute: AuthedAdminPreviewRoute, AuthedAdminPreviewRoute: AuthedAdminPreviewRoute,
AuthedAdminIndexRoute: AuthedAdminIndexRoute, AuthedAdminIndexRoute: AuthedAdminIndexRoute,
AuthedAdminTournamentsIndexRoute: AuthedAdminTournamentsIndexRoute, AuthedAdminTournamentsIndexRoute: AuthedAdminTournamentsIndexRoute,
AuthedAdminTournamentsIdAssignPartnersRoute:
AuthedAdminTournamentsIdAssignPartnersRoute,
AuthedAdminTournamentsIdTeamsRoute: AuthedAdminTournamentsIdTeamsRoute, AuthedAdminTournamentsIdTeamsRoute: AuthedAdminTournamentsIdTeamsRoute,
AuthedAdminTournamentsRunIdRoute: AuthedAdminTournamentsRunIdRoute, AuthedAdminTournamentsRunIdRoute: AuthedAdminTournamentsRunIdRoute,
AuthedAdminTournamentsIdIndexRoute: AuthedAdminTournamentsIdIndexRoute, AuthedAdminTournamentsIdIndexRoute: AuthedAdminTournamentsIdIndexRoute,
@@ -687,6 +769,7 @@ const AuthedAdminRouteWithChildren = AuthedAdminRoute._addFileChildren(
interface AuthedRouteChildren { interface AuthedRouteChildren {
AuthedAdminRoute: typeof AuthedAdminRouteWithChildren AuthedAdminRoute: typeof AuthedAdminRouteWithChildren
AuthedBadgesRoute: typeof AuthedBadgesRoute
AuthedSettingsRoute: typeof AuthedSettingsRoute AuthedSettingsRoute: typeof AuthedSettingsRoute
AuthedStatsRoute: typeof AuthedStatsRoute AuthedStatsRoute: typeof AuthedStatsRoute
AuthedIndexRoute: typeof AuthedIndexRoute AuthedIndexRoute: typeof AuthedIndexRoute
@@ -695,10 +778,12 @@ interface AuthedRouteChildren {
AuthedTournamentsTournamentIdRoute: typeof AuthedTournamentsTournamentIdRoute AuthedTournamentsTournamentIdRoute: typeof AuthedTournamentsTournamentIdRoute
AuthedTournamentsIndexRoute: typeof AuthedTournamentsIndexRoute AuthedTournamentsIndexRoute: typeof AuthedTournamentsIndexRoute
AuthedTournamentsIdBracketRoute: typeof AuthedTournamentsIdBracketRoute AuthedTournamentsIdBracketRoute: typeof AuthedTournamentsIdBracketRoute
AuthedTournamentsIdGroupsRoute: typeof AuthedTournamentsIdGroupsRoute
} }
const AuthedRouteChildren: AuthedRouteChildren = { const AuthedRouteChildren: AuthedRouteChildren = {
AuthedAdminRoute: AuthedAdminRouteWithChildren, AuthedAdminRoute: AuthedAdminRouteWithChildren,
AuthedBadgesRoute: AuthedBadgesRoute,
AuthedSettingsRoute: AuthedSettingsRoute, AuthedSettingsRoute: AuthedSettingsRoute,
AuthedStatsRoute: AuthedStatsRoute, AuthedStatsRoute: AuthedStatsRoute,
AuthedIndexRoute: AuthedIndexRoute, AuthedIndexRoute: AuthedIndexRoute,
@@ -707,6 +792,7 @@ const AuthedRouteChildren: AuthedRouteChildren = {
AuthedTournamentsTournamentIdRoute: AuthedTournamentsTournamentIdRoute, AuthedTournamentsTournamentIdRoute: AuthedTournamentsTournamentIdRoute,
AuthedTournamentsIndexRoute: AuthedTournamentsIndexRoute, AuthedTournamentsIndexRoute: AuthedTournamentsIndexRoute,
AuthedTournamentsIdBracketRoute: AuthedTournamentsIdBracketRoute, AuthedTournamentsIdBracketRoute: AuthedTournamentsIdBracketRoute,
AuthedTournamentsIdGroupsRoute: AuthedTournamentsIdGroupsRoute,
} }
const AuthedRouteWithChildren = const AuthedRouteWithChildren =
@@ -717,6 +803,7 @@ const rootRouteChildren: RootRouteChildren = {
LoginRoute: LoginRoute, LoginRoute: LoginRoute,
LogoutRoute: LogoutRoute, LogoutRoute: LogoutRoute,
RefreshSessionRoute: RefreshSessionRoute, RefreshSessionRoute: RefreshSessionRoute,
ApiHealthRoute: ApiHealthRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute, ApiAuthSplatRoute: ApiAuthSplatRoute,
ApiEventsSplatRoute: ApiEventsSplatRoute, ApiEventsSplatRoute: ApiEventsSplatRoute,
ApiSpotifyCallbackRoute: ApiSpotifyCallbackRoute, ApiSpotifyCallbackRoute: ApiSpotifyCallbackRoute,

View File

@@ -11,6 +11,8 @@ import { type QueryClient } from "@tanstack/react-query";
import { ensureSuperTokensFrontend } from "@/lib/supertokens/client"; import { ensureSuperTokensFrontend } from "@/lib/supertokens/client";
import { AuthContextType } from "@/contexts/auth-context"; import { AuthContextType } from "@/contexts/auth-context";
import Providers from "@/features/core/components/providers"; import Providers from "@/features/core/components/providers";
import { SessionMonitor } from "@/components/session-monitor";
import { IOSInstallPrompt } from "@/components/ios-install-prompt";
import { ColorSchemeScript, mantineHtmlProps } from "@mantine/core"; import { ColorSchemeScript, mantineHtmlProps } from "@mantine/core";
import { HeaderConfig } from "@/features/core/types/header-config"; import { HeaderConfig } from "@/features/core/types/header-config";
import { playerQueries } from "@/features/players/queries"; import { playerQueries } from "@/features/players/queries";
@@ -40,30 +42,45 @@ export const Route = createRootRouteWithContext<{
content: content:
"width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, interactive-widget=resizes-content", "width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, interactive-widget=resizes-content",
}, },
{ property: 'og:title', content: 'FLXN IX' }, { name: 'description', content: 'Amicus meus madidus' },
{ property: 'og:description', content: 'Register for FLXN IX and view FLXN stats' }, { name: 'keywords', content: 'FLXN, beer pong, tournament, sports, statistics, pong' },
{ name: 'theme-color', content: '#1e293b' },
{ property: 'og:title', content: 'FLXN' },
{ property: 'og:description', content: 'Amicus meus madidus' },
{ property: 'og:url', content: 'https://flexxon.app' }, { property: 'og:url', content: 'https://flexxon.app' },
{ property: 'og:type', content: 'website' }, { property: 'og:type', content: 'website' },
{ property: 'og:site_name', content: 'FLXN IX' }, { property: 'og:site_name', content: 'FLXN' },
{ property: 'og:image', content: 'https://flexxon.app/favicon.png' }, { property: 'og:image', content: 'https://flexxon.app/favicon.png' },
{ property: 'og:image:width', content: '512' },
{ property: 'og:image:height', content: '512' },
{ property: 'og:image:alt', content: 'FLXN logo' },
{ property: 'og:locale', content: 'en_US' },
{ name: 'twitter:card', content: 'summary' },
{ name: 'twitter:title', content: 'FLXN' },
{ name: 'twitter:description', content: 'Amicus meus madidus' },
{ name: 'twitter:image', content: 'https://flexxon.app/favicon.png' },
{ name: 'mobile-web-app-capable', content: 'yes' },
{ name: 'apple-mobile-web-app-capable', content: 'yes' },
{ name: 'apple-mobile-web-app-status-bar-style', content: 'black-translucent' },
{ name: 'apple-mobile-web-app-title', content: 'FLXN' },
], ],
links: [ links: [
{ {
rel: "apple-touch-icon", rel: "apple-touch-icon",
sizes: "180x180", sizes: "180x180",
href: "/favicon.png", href: "/apple-touch-icon.png",
}, },
{ {
rel: "icon", rel: "icon",
type: "image/png", type: "image/png",
sizes: "32x32", sizes: "32x32",
href: "/favicon.png", href: "/favicon-32x32.png",
}, },
{ {
rel: "icon", rel: "icon",
type: "image/png", type: "image/png",
sizes: "16x16", sizes: "16x16",
href: "/favicon.png", href: "/favicon-16x16.png",
}, },
{ rel: "manifest", href: "/site.webmanifest" }, { rel: "manifest", href: "/site.webmanifest" },
{ rel: "icon", href: "/favicon.ico" }, { rel: "icon", href: "/favicon.ico" },
@@ -95,23 +112,35 @@ export const Route = createRootRouteWithContext<{
component: RootComponent, component: RootComponent,
notFoundComponent: () => <Navigate to="/" />, notFoundComponent: () => <Navigate to="/" />,
beforeLoad: async ({ context, location }) => { beforeLoad: async ({ context, location }) => {
// Skip auth check for refresh-session route to avoid infinite loops const publicRoutes = ['/login', '/logout', '/refresh-session'];
if (location.pathname === '/refresh-session') { if (publicRoutes.some(route => location.pathname.startsWith(route))) {
return {};
}
if (location.pathname === '/login' || location.pathname === '/logout') {
return {}; return {};
} }
try { try {
// https://github.com/TanStack/router/discussions/3531
const auth = await ensureServerQueryData( const auth = await ensureServerQueryData(
context.queryClient, context.queryClient,
playerQueries.auth() playerQueries.auth()
); );
return { auth }; return { auth };
} catch (error) { } catch (error: any) {
if (typeof window !== 'undefined') {
const { doesSessionExist, attemptRefreshingSession } = await import('supertokens-web-js/recipe/session');
const sessionExists = await doesSessionExist();
if (sessionExists) {
try {
await attemptRefreshingSession();
const auth = await ensureServerQueryData(
context.queryClient,
playerQueries.auth()
);
return { auth };
} catch {
return {};
}
}
}
return {}; return {};
} }
}, },
@@ -126,6 +155,8 @@ function RootComponent() {
return ( return (
<RootDocument> <RootDocument>
<Providers> <Providers>
<SessionMonitor />
<IOSInstallPrompt />
<Outlet /> <Outlet />
</Providers> </Providers>
</RootDocument> </RootDocument>

View File

@@ -0,0 +1,167 @@
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import { tournamentQueries, useFreeAgents, useTournament } from "@/features/tournaments/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import { Stack, Text, Button, Alert, LoadingOverlay, Group } from "@mantine/core";
import { useState } from "react";
import useGenerateRandomTeams from "@/features/tournaments/hooks/use-generate-random-teams";
import useConfirmTeamAssignments from "@/features/tournaments/hooks/use-confirm-team-assignments";
import TeamAssignmentPreview from "@/features/tournaments/components/team-assignment-preview";
import { WarningCircleIcon, ShuffleIcon, CheckCircleIcon } from "@phosphor-icons/react";
import { PlayerInfo } from "@/features/players/types";
import { useQueryClient } from "@tanstack/react-query";
export const Route = createFileRoute("/_authed/admin/tournaments/$id/assign-partners")({
beforeLoad: async ({ context, params }) => {
const { queryClient } = context;
const tournament = await ensureServerQueryData(
queryClient,
tournamentQueries.details(params.id)
);
if (!tournament) throw redirect({ to: "/admin/tournaments" });
return { tournament };
},
loader: ({ context }) => ({
header: {
withBackButton: true,
title: `Manage ${context.tournament.name}`,
},
}),
component: RouteComponent,
});
interface TeamAssignment {
player1: PlayerInfo;
player2: PlayerInfo;
teamName: string;
}
function RouteComponent() {
const { id } = Route.useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { data: freeAgents } = useFreeAgents(id);
const [assignments, setAssignments] = useState<TeamAssignment[] | null>(null);
const [currentSeed, setCurrentSeed] = useState<number | undefined>(undefined);
const generateMutation = useGenerateRandomTeams();
const confirmMutation = useConfirmTeamAssignments();
const hasOddPlayers = freeAgents.length % 2 !== 0;
const hasEnoughPlayers = freeAgents.length >= 2;
const handleGenerate = () => {
generateMutation.mutate(
{ data: { tournamentId: id, seed: currentSeed } },
{
onSuccess: (result) => {
setAssignments(result.assignments);
setCurrentSeed(result.seed);
},
}
);
};
const handleReroll = () => {
if (currentSeed === undefined) return;
generateMutation.mutate(
{ data: { tournamentId: id, seed: currentSeed + 1 } },
{
onSuccess: (result) => {
setAssignments(result.assignments);
setCurrentSeed(result.seed);
},
}
);
};
const handleConfirm = () => {
if (!assignments) return;
const formattedAssignments = assignments.map((a) => ({
player1Id: a.player1.id,
player2Id: a.player2.id,
teamName: a.teamName,
}));
confirmMutation.mutate(
{ data: { tournamentId: id, assignments: formattedAssignments } },
{
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: tournamentQueries.details(id).queryKey });
queryClient.invalidateQueries({ queryKey: tournamentQueries.free_agents(id).queryKey });
navigate({ to: "/admin/tournaments/$id", params: { id } });
},
}
);
};
return (
<Stack gap="lg" pos="relative">
<LoadingOverlay visible={confirmMutation.isPending} />
<Stack gap="xs">
<Group gap="xs" align="baseline">
<Text size="xl" fw={700}>
{freeAgents.length}
</Text>
<Text size="sm" c="dimmed">
{freeAgents.length === 1 ? "player enrolled" : "players enrolled"}
</Text>
</Group>
{!hasEnoughPlayers && (
<Alert color="yellow" icon={<WarningCircleIcon size={16} />}>
Need at least 2 players to create teams
</Alert>
)}
{hasOddPlayers && (
<Alert color="red" icon={<WarningCircleIcon size={16} />}>
Cannot create teams with an odd number of players. Please have one player unenroll.
</Alert>
)}
{!assignments && hasEnoughPlayers && !hasOddPlayers && (
<Button
leftSection={<ShuffleIcon size={18} />}
onClick={handleGenerate}
loading={generateMutation.isPending}
>
Generate Random Pairings
</Button>
)}
</Stack>
{assignments && (
<Stack gap="md">
<Group justify="space-between" align="center">
<Text size="lg" fw={600}>
Partner Assignments
</Text>
<Group gap="sm">
<Button
variant="subtle"
leftSection={<ShuffleIcon size={16} />}
onClick={handleReroll}
loading={generateMutation.isPending}
size="sm"
>
Re-roll
</Button>
<Button
leftSection={<CheckCircleIcon size={18} />}
onClick={handleConfirm}
loading={confirmMutation.isPending}
size="sm"
>
Confirm & Create Teams
</Button>
</Group>
</Group>
<TeamAssignmentPreview assignments={assignments} />
</Stack>
)}
</Stack>
);
}

View File

@@ -5,7 +5,9 @@ import {
} from "@/features/tournaments/queries"; } from "@/features/tournaments/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure"; import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import SeedTournament from "@/features/tournaments/components/seed-tournament"; import SeedTournament from "@/features/tournaments/components/seed-tournament";
import { Container } from "@mantine/core"; import SetupGroupStage from "@/features/tournaments/components/setup-group-stage";
import GroupStageView from "@/features/tournaments/components/group-stage-view";
import { Container, Stack, Divider, Title } from "@mantine/core";
import { useMemo } from "react"; import { useMemo } from "react";
import { BracketData } from "@/features/bracket/types"; import { BracketData } from "@/features/bracket/types";
import { Match } from "@/features/matches/types"; import { Match } from "@/features/matches/types";
@@ -43,6 +45,20 @@ function RouteComponent() {
const { roles } = useAuth(); const { roles } = useAuth();
const isAdmin = roles?.includes('Admin') || false; const isAdmin = roles?.includes('Admin') || false;
const hasGroupStage = useMemo(() => {
return tournament.matches?.some((match) => match.round === -1) || false;
}, [tournament.matches]);
const hasKnockout = useMemo(() => {
return tournament.matches?.some((match) => match.round !== -1) || false;
}, [tournament.matches]);
const knockoutBracketPopulated = useMemo(() => {
return tournament.matches?.some((match) =>
match.round === 0 && match.lid >= 0 && (match.home || match.away)
) || false;
}, [tournament.matches]);
const bracket: BracketData = useMemo(() => { const bracket: BracketData = useMemo(() => {
if (!tournament.matches || tournament.matches.length === 0) { if (!tournament.matches || tournament.matches.length === 0) {
return { winners: [], losers: [] }; return { winners: [], losers: [] };
@@ -52,6 +68,7 @@ function RouteComponent() {
const losersMap = new Map<number, Match[]>(); const losersMap = new Map<number, Match[]>();
tournament.matches tournament.matches
.filter((match) => match.round !== -1)
.sort((a, b) => a.lid - b.lid) .sort((a, b) => a.lid - b.lid)
.forEach((match) => { .forEach((match) => {
if (!match.is_losers_bracket) { if (!match.is_losers_bracket) {
@@ -79,14 +96,51 @@ function RouteComponent() {
return ( return (
<Container size="md" px={0}> <Container size="md" px={0}>
{ isAdmin && <SpotifyControlsBar />} { isAdmin && !tournament.regional && <SpotifyControlsBar />}
{tournament.matches?.length ? ( {tournament.matches?.length ? (
<BracketView bracket={bracket} showControls /> hasGroupStage && hasKnockout ? (
<Stack gap="xl">
<GroupStageView
groups={tournament.groups || []}
matches={tournament.matches}
showControls
tournamentId={tournament.id}
hasKnockoutBracket={knockoutBracketPopulated}
isRegional={tournament.regional}
groupConfig={tournament.group_config}
/>
<Divider />
<div>
<Title order={3} ta="center" mb="md">Knockout Bracket</Title>
<BracketView bracket={bracket} showControls groupConfig={tournament.group_config} />
</div>
</Stack>
) : hasGroupStage ? (
<GroupStageView
groups={tournament.groups || []}
matches={tournament.matches}
showControls
tournamentId={tournament.id}
hasKnockoutBracket={knockoutBracketPopulated}
isRegional={tournament.regional}
groupConfig={tournament.group_config}
/>
) : (
<BracketView bracket={bracket} showControls groupConfig={tournament.group_config} />
)
) : ( ) : (
<SeedTournament tournament.regional === true ? (
tournamentId={tournament.id} <SetupGroupStage
teams={tournament.teams || []} tournamentId={tournament.id}
/> teams={tournament.teams || []}
/>
) : (
<SeedTournament
tournamentId={tournament.id}
teams={tournament.teams || []}
isRegional={tournament.regional}
/>
)
)} )}
</Container> </Container>
); );

View File

@@ -0,0 +1,34 @@
import BadgeStatsTable from '@/features/badges/components/badge-stats-table';
import BadgeStatsTableSkeleton from '@/features/badges/components/badge-stats-table-skeleton';
import { badgeQueries, useAllBadges } from '@/features/badges/queries';
import PlayerStatsTableSkeleton from '@/features/players/components/player-stats-table-skeleton';
import { prefetchServerQuery } from '@/lib/tanstack-query/utils/prefetch';
import { createFileRoute } from '@tanstack/react-router';
import { Suspense } from 'react';
export const Route = createFileRoute('/_authed/badges')({
component: Badges,
beforeLoad: ({ context }) => {
const queryClient = context.queryClient;
prefetchServerQuery(queryClient, badgeQueries.allBadges());
},
loader: () => ({
withPadding: false,
fullWidth: true,
header: {
title: 'All Badges',
withBackButton: true,
},
refresh: [badgeQueries.allBadges().queryKey],
}),
});
function Badges() {
return (
<Suspense fallback={<BadgeStatsTableSkeleton />}>
<div>
<BadgeStatsTable />
</div>
</Suspense>
);
}

View File

@@ -1,15 +1,19 @@
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
import { playerQueries } from "@/features/players/queries"; import { playerQueries } from "@/features/players/queries";
import PlayerStatsTable from "@/features/players/components/player-stats-table"; import PlayerStatsTable from "@/features/players/components/player-stats-table";
import { Suspense } from "react"; import { Suspense, useState, useDeferredValue } from "react";
import PlayerStatsTableSkeleton from "@/features/players/components/player-stats-table-skeleton"; import PlayerStatsTableSkeleton from "@/features/players/components/player-stats-table-skeleton";
import { prefetchServerQuery } from "@/lib/tanstack-query/utils/prefetch"; import { prefetchServerQuery } from "@/lib/tanstack-query/utils/prefetch";
import LeagueHeadToHead from "@/features/players/components/league-head-to-head";
import { Box, Loader, Tabs, Button, Group, Container, Stack } from "@mantine/core";
export const Route = createFileRoute("/_authed/stats")({ export const Route = createFileRoute("/_authed/stats")({
component: Stats, component: Stats,
beforeLoad: ({ context }) => { beforeLoad: ({ context }) => {
const queryClient = context.queryClient; const queryClient = context.queryClient;
prefetchServerQuery(queryClient, playerQueries.allStats()); prefetchServerQuery(queryClient, playerQueries.allStats('all'));
prefetchServerQuery(queryClient, playerQueries.allStats('mainline'));
prefetchServerQuery(queryClient, playerQueries.allStats('regional'));
}, },
loader: () => ({ loader: () => ({
withPadding: false, withPadding: false,
@@ -17,12 +21,62 @@ export const Route = createFileRoute("/_authed/stats")({
header: { header: {
title: "Player Stats" title: "Player Stats"
}, },
refresh: [playerQueries.allStats().queryKey], refresh: [playerQueries.allStats().queryKey],
}), }),
}); });
function Stats() { function Stats() {
return <Suspense fallback={<PlayerStatsTableSkeleton />}> const [viewType, setViewType] = useState<'all' | 'mainline' | 'regional'>('all');
<PlayerStatsTable /> const deferredViewType = useDeferredValue(viewType);
</Suspense>; const isStale = viewType !== deferredViewType;
return (
<Tabs defaultValue="stats">
<Tabs.List grow>
<Tabs.Tab value="stats">Stats</Tabs.Tab>
<Tabs.Tab value="h2h">Head to Head</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="stats">
<Container size="100%" px={0} mt="md">
<Stack gap="xs">
<Group gap="xs" px="md" justify="center">
<Button
variant={viewType === 'all' ? 'filled' : 'light'}
size="compact-xs"
onClick={() => setViewType('all')}
>
All
</Button>
<Button
variant={viewType === 'mainline' ? 'filled' : 'light'}
size="compact-xs"
onClick={() => setViewType('mainline')}
>
Mainline
</Button>
<Button
variant={viewType === 'regional' ? 'filled' : 'light'}
size="compact-xs"
onClick={() => setViewType('regional')}
>
Regional
</Button>
</Group>
<Box style={{ opacity: isStale ? 0.6 : 1, transition: 'opacity 150ms' }}>
<Suspense key={deferredViewType} fallback={<PlayerStatsTableSkeleton hideFilters />}>
<PlayerStatsTable viewType={deferredViewType} />
</Suspense>
</Box>
</Stack>
</Container>
</Tabs.Panel>
<Tabs.Panel value="h2h">
<Suspense fallback={<Box w='100vw' py='xl'><Loader ml='45vw' /></Box>}>
<LeagueHeadToHead />
</Suspense>
</Tabs.Panel>
</Tabs>
);
} }

View File

@@ -4,7 +4,6 @@ import {
useTournament, useTournament,
} from "@/features/tournaments/queries"; } from "@/features/tournaments/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure"; import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import SeedTournament from "@/features/tournaments/components/seed-tournament";
import { Container } from "@mantine/core"; import { Container } from "@mantine/core";
import { useMemo } from "react"; import { useMemo } from "react";
import { BracketData } from "@/features/bracket/types"; import { BracketData } from "@/features/bracket/types";
@@ -18,7 +17,7 @@ export const Route = createFileRoute("/_authed/tournaments/$id/bracket")({
queryClient, queryClient,
tournamentQueries.details(params.id) tournamentQueries.details(params.id)
); );
if (!tournament) throw redirect({ to: "/admin/tournaments" }); if (!tournament) throw redirect({ to: "/tournaments" });
return { return {
tournament, tournament,
}; };
@@ -26,7 +25,6 @@ export const Route = createFileRoute("/_authed/tournaments/$id/bracket")({
loader: ({ context }) => ({ loader: ({ context }) => ({
fullWidth: true, fullWidth: true,
withPadding: false, withPadding: false,
showSpotifyPanel: true,
header: { header: {
withBackButton: true, withBackButton: true,
title: `${context.tournament.name}`, title: `${context.tournament.name}`,
@@ -48,6 +46,7 @@ function RouteComponent() {
const losersMap = new Map<number, Match[]>(); const losersMap = new Map<number, Match[]>();
tournament.matches tournament.matches
.filter((match) => match.round !== -1)
.sort((a, b) => a.lid - b.lid) .sort((a, b) => a.lid - b.lid)
.forEach((match) => { .forEach((match) => {
if (!match.is_losers_bracket) { if (!match.is_losers_bracket) {
@@ -75,7 +74,7 @@ function RouteComponent() {
return ( return (
<Container size="md" px={0}> <Container size="md" px={0}>
<BracketView bracket={bracket} /> <BracketView bracket={bracket} groupConfig={tournament.group_config} />
</Container> </Container>
); );
} }

View File

@@ -0,0 +1,47 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import {
tournamentQueries,
useTournament,
} from "@/features/tournaments/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import GroupStageView from "@/features/tournaments/components/group-stage-view";
import { Container } from "@mantine/core";
export const Route = createFileRoute("/_authed/tournaments/$id/groups")({
beforeLoad: async ({ context, params }) => {
const { queryClient } = context;
const tournament = await ensureServerQueryData(
queryClient,
tournamentQueries.details(params.id)
);
if (!tournament) throw redirect({ to: "/tournaments" });
return {
tournament,
};
},
loader: ({ context }) => ({
fullWidth: true,
withPadding: false,
header: {
withBackButton: true,
title: `${context.tournament.name}`,
},
}),
component: RouteComponent,
});
function RouteComponent() {
const { id } = Route.useParams();
const { data: tournament } = useTournament(id);
return (
<Container size="md" px={0}>
<GroupStageView
groups={tournament.groups || []}
matches={tournament.matches || []}
isRegional={tournament.regional}
groupConfig={tournament.group_config}
/>
</Container>
);
}

View File

@@ -0,0 +1,22 @@
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/api/health")({
server: {
handlers: {
GET: () => {
return new Response(
JSON.stringify({
status: "ok",
timestamp: new Date().toISOString(),
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
}
);
},
},
},
});

View File

@@ -2,7 +2,8 @@ import { createFileRoute } from '@tanstack/react-router'
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import FullScreenLoader from '@/components/full-screen-loader' import FullScreenLoader from '@/components/full-screen-loader'
import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session' import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session'
import { resetRefreshFlag } from '@/lib/supertokens/client' import { resetRefreshFlag, getOrCreateRefreshPromise } from '@/lib/supertokens/client'
import { logger } from '@/lib/supertokens'
export const Route = createFileRoute('/refresh-session')({ export const Route = createFileRoute('/refresh-session')({
component: RouteComponent, component: RouteComponent,
@@ -17,23 +18,31 @@ function RouteComponent() {
const handleRefresh = async () => { const handleRefresh = async () => {
try { try {
resetRefreshFlag(); logger.info("Refresh session route: starting refresh");
const refreshed = await attemptRefreshingSession()
const refreshed = await getOrCreateRefreshPromise(async () => {
return await attemptRefreshingSession();
});
if (refreshed) { if (refreshed) {
const urlParams = new URLSearchParams(window.location.search) logger.info("Refresh session route: refresh successful");
const redirect = urlParams.get('redirect') const urlParams = new URLSearchParams(window.location.search);
const redirect = urlParams.get('redirect');
if (redirect && !redirect.includes('_serverFn') && !redirect.includes('/api/')) { if (redirect && !redirect.includes('_serverFn') && !redirect.includes('/api/')) {
window.location.href = decodeURIComponent(redirect) logger.info("Refresh session route: redirecting to", redirect);
window.location.href = decodeURIComponent(redirect);
} else { } else {
logger.info("Refresh session route: redirecting to home");
window.location.href = '/'; window.location.href = '/';
} }
} else { } else {
window.location.href = '/login' logger.warn("Refresh session route: refresh failed, redirecting to login");
window.location.href = '/login';
} }
} catch (error) { } catch (error) {
window.location.href = '/login' logger.error("Refresh session route: error during refresh", error);
window.location.href = '/login';
} }
} }

View File

@@ -13,7 +13,7 @@ import { XIcon } from "@phosphor-icons/react";
interface AvatarProps interface AvatarProps
extends Omit<MantineAvatarProps, "radius" | "color" | "size"> { extends Omit<MantineAvatarProps, "radius" | "color" | "size"> {
name: string; name?: string;
size?: number; size?: number;
radius?: string | number; radius?: string | number;
withBorder?: boolean; withBorder?: boolean;

View File

@@ -0,0 +1,59 @@
import { useEffect, useState } from 'react'
import { Box, Paper, Group, Text, ActionIcon } from '@mantine/core'
import { DownloadIcon, XIcon } from '@phosphor-icons/react'
export function IOSInstallPrompt() {
const [show, setShow] = useState(false)
const [platform, setPlatform] = useState<'ios' | 'android' | null>(null)
useEffect(() => {
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)
const isAndroid = /Android/.test(navigator.userAgent)
const isInStandaloneMode =
window.matchMedia('(display-mode: standalone)').matches ||
('standalone' in window.navigator && (window.navigator as any).standalone)
const hasBeenDismissed = localStorage.getItem('pwa-install-prompt-dismissed') === 'true'
if ((isIOS || isAndroid) && !isInStandaloneMode && !hasBeenDismissed) {
setPlatform(isIOS ? 'ios' : 'android')
const timer = setTimeout(() => setShow(true), 3000)
return () => clearTimeout(timer)
}
}, [])
const handleDismiss = () => {
localStorage.setItem('pwa-install-prompt-dismissed', 'true')
setShow(false)
}
if (!show || !platform) return null
const instructions = platform === 'ios'
? 'Tap Share → Add to Home Screen'
: 'Tap Menu (⋮) → Add to Home screen'
return (
<Box style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 1000, padding: '8px' }}>
<Paper shadow="lg" p="sm" style={{ background: 'var(--mantine-color-blue-9)', color: 'white' }}>
<Group justify="space-between" wrap="nowrap">
<Group gap="xs" wrap="nowrap" style={{ flex: 1 }}>
<DownloadIcon size={20} style={{ flexShrink: 0 }} />
<Box style={{ flex: 1, minWidth: 0 }}>
<Text size="sm" fw={500} style={{ lineHeight: 1.3 }}>
Please install FLXN This will save me Twilio credits as you won't be signed out!
</Text>
<Text size="xs" opacity={0.9} style={{ lineHeight: 1.2 }}>
{instructions}
</Text>
</Box>
</Group>
<ActionIcon variant="subtle" color="white" onClick={handleDismiss}>
<XIcon size={18} />
</ActionIcon>
</Group>
</Paper>
</Box>
)
}

View File

@@ -0,0 +1,85 @@
import { Paper, useMantineTheme } from "@mantine/core";
import { Facehash } from "facehash";
interface PlayerAvatarProps {
name?: string;
size?: number;
disableFullscreen?: boolean;
style?: React.CSSProperties;
}
const PlayerAvatar = ({
name = "",
size = 35,
disableFullscreen = false,
style,
}: PlayerAvatarProps) => {
const theme = useMantineTheme();
const getFacehashSize = (size: number): 32 | 48 | 64 | 80 => {
if (size <= 40) return 32;
if (size <= 56) return 48;
if (size <= 72) return 64;
return 80;
};
const facehashSize = getFacehashSize(size);
const colors = [
"hsla(314, 100%, 80%, 1)",
"hsla(58, 93%, 72%, 1)",
"hsla(218, 92%, 72%, 1)",
"hsla(19, 99%, 44%, 1)",
"hsla(156, 86%, 40%, 1)",
"hsla(314, 100%, 85%, 1)",
"hsla(58, 92%, 79%, 1)",
"hsla(218, 91%, 78%, 1)",
"hsla(19, 99%, 50%, 1)",
"hsla(156, 86%, 64%, 1)",
];
return (
<Paper
p={size / 20}
radius="100%"
withBorder
style={{
cursor: !disableFullscreen ? 'pointer' : 'default',
transition: 'transform 0.15s ease',
...style,
}}
onMouseEnter={(e) => {
if (!disableFullscreen) {
e.currentTarget.style.transform = 'scale(1.02)';
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
<div
style={{
width: size,
height: size,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
borderRadius: '100%',
}}
>
<Facehash
name={name}
size={size}
variant="solid"
colors={colors}
intensity3d="dramatic"
enableBlink
style={{ borderRadius: '100%', overflow: 'hidden', color: 'black' }}
/>
</div>
</Paper>
);
};
export default PlayerAvatar;

View File

@@ -0,0 +1,64 @@
import { useEffect, useRef } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { doesSessionExist } from 'supertokens-web-js/recipe/session';
import { getOrCreateRefreshPromise } from '@/lib/supertokens/client';
import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session';
import { logger } from '@/lib/supertokens';
export function SessionMonitor() {
const navigate = useNavigate();
const lastRefreshTimeRef = useRef<number>(0);
const REFRESH_COOLDOWN = 30 * 1000;
useEffect(() => {
if (typeof window === 'undefined') return;
const handleVisibilityChange = async () => {
if (document.visibilityState !== 'visible') return;
const publicRoutes = ['/login', '/logout', '/refresh-session'];
if (publicRoutes.some(route => window.location.pathname === route)) {
return;
}
const now = Date.now();
if (now - lastRefreshTimeRef.current < REFRESH_COOLDOWN) {
logger.info('Session monitor: skipping refresh (cooldown)');
return;
}
try {
const sessionExists = await doesSessionExist();
if (!sessionExists) {
logger.info('Session monitor: no session exists, skipping refresh');
return;
}
logger.info('Session monitor: tab became visible, refreshing session');
const refreshed = await getOrCreateRefreshPromise(async () => {
return await attemptRefreshingSession();
});
if (refreshed) {
lastRefreshTimeRef.current = Date.now();
logger.info('Session monitor: session refreshed successfully');
} else {
logger.warn('Session monitor: refresh returned false');
}
} catch (error) {
logger.error('Session monitor: error refreshing session', error);
}
};
handleVisibilityChange();
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [navigate]);
return null;
}

View File

@@ -1,5 +1,10 @@
import { Box, Container, Flex, Loader, Title, useComputedColorScheme } from "@mantine/core"; import {
import { PropsWithChildren, Suspense, useEffect, useRef } from "react"; Box,
Container,
Title,
useComputedColorScheme,
} from "@mantine/core";
import { PropsWithChildren, useEffect, useRef } from "react";
import { Drawer as VaulDrawer } from "vaul"; import { Drawer as VaulDrawer } from "vaul";
import styles from "./styles.module.css"; import styles from "./styles.module.css";
@@ -17,6 +22,11 @@ const Drawer: React.FC<DrawerProps> = ({
}) => { }) => {
const colorScheme = useComputedColorScheme("light"); const colorScheme = useComputedColorScheme("light");
const contentRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null);
const openedRef = useRef(opened);
useEffect(() => {
openedRef.current = opened;
}, [opened]);
useEffect(() => { useEffect(() => {
const appElement = document.querySelector(".app") as HTMLElement; const appElement = document.querySelector(".app") as HTMLElement;
@@ -57,7 +67,7 @@ const Drawer: React.FC<DrawerProps> = ({
appElement.classList.remove("drawer-scaling"); appElement.classList.remove("drawer-scaling");
themeColorMeta.content = currentColors.normal; themeColorMeta.content = currentColors.normal;
}; };
}, [opened, colorScheme]); }, [opened]);
useEffect(() => { useEffect(() => {
if (!opened || !contentRef.current) return; if (!opened || !contentRef.current) return;
@@ -69,46 +79,44 @@ const Drawer: React.FC<DrawerProps> = ({
if (visualViewport) { if (visualViewport) {
const availableHeight = visualViewport.height; const availableHeight = visualViewport.height;
const maxDrawerHeight = Math.min(availableHeight * 0.75, window.innerHeight * 0.75); const maxDrawerHeight = Math.min(
availableHeight * 0.75,
window.innerHeight * 0.75
);
drawerContent.style.maxHeight = `${maxDrawerHeight}px`; drawerContent.style.maxHeight = `${maxDrawerHeight}px`;
} else { } else {
drawerContent.style.maxHeight = '75vh'; drawerContent.style.maxHeight = "75vh";
} }
} }
}; };
const resizeObserver = new ResizeObserver(() => {
if (contentRef.current) {
const drawerContent = contentRef.current.closest('[data-vaul-drawer-wrapper]');
if (drawerContent) {
(drawerContent as HTMLElement).style.height = 'auto';
(drawerContent as HTMLElement).offsetHeight;
}
}
});
updateDrawerHeight(); updateDrawerHeight();
if (window.visualViewport) { if (window.visualViewport) {
window.visualViewport.addEventListener('resize', updateDrawerHeight); window.visualViewport.addEventListener("resize", updateDrawerHeight);
} }
resizeObserver.observe(contentRef.current);
return () => { return () => {
resizeObserver.disconnect();
if (window.visualViewport) { if (window.visualViewport) {
window.visualViewport.removeEventListener('resize', updateDrawerHeight); window.visualViewport.removeEventListener("resize", updateDrawerHeight);
} }
}; };
}, [opened, children]); }, [opened]);
return ( return (
<VaulDrawer.Root repositionInputs={false} open={opened} onOpenChange={onChange}> <VaulDrawer.Root
repositionInputs={false}
open={opened}
onOpenChange={onChange}
>
<VaulDrawer.Portal> <VaulDrawer.Portal>
<VaulDrawer.Overlay className={styles.drawerOverlay} /> <VaulDrawer.Overlay className={styles.drawerOverlay} />
<VaulDrawer.Content className={styles.drawerContent} aria-describedby="drawer" ref={contentRef}> <VaulDrawer.Content
className={styles.drawerContent}
aria-describedby="drawer"
ref={contentRef}
>
<Container flex={1} p="md"> <Container flex={1} p="md">
<Box <Box
mb="sm" mb="sm"
@@ -120,14 +128,10 @@ const Drawer: React.FC<DrawerProps> = ({
style={{ borderRadius: "9999px" }} style={{ borderRadius: "9999px" }}
/> />
<Container mx="auto" maw="28rem" px={0}> <Container mx="auto" maw="28rem" px={0}>
<VaulDrawer.Title><Title order={2}>{title}</Title></VaulDrawer.Title> <VaulDrawer.Title>
<Suspense fallback={ <Title order={2}>{title}</Title>
<Flex justify='center' align='center' w='100%' h={400}> </VaulDrawer.Title>
<Loader size='lg' /> {children}
</Flex>
}>
{children}
</Suspense>
</Container> </Container>
</Container> </Container>
</VaulDrawer.Content> </VaulDrawer.Content>

View File

@@ -1,8 +1,8 @@
import { PropsWithChildren, useCallback } from "react"; import { PropsWithChildren, Suspense, useCallback } from "react";
import { useIsMobile } from "@/hooks/use-is-mobile"; import { useIsMobile } from "@/hooks/use-is-mobile";
import Drawer from "./drawer"; import Drawer from "./drawer";
import Modal from "./modal"; import Modal from "./modal";
import { ScrollArea } from "@mantine/core"; import { ScrollArea, Flex, Loader } from "@mantine/core";
interface SheetProps extends PropsWithChildren { interface SheetProps extends PropsWithChildren {
title?: string; title?: string;
@@ -16,6 +16,8 @@ const Sheet: React.FC<SheetProps> = ({ title, children, opened, onChange }) => {
const SheetComponent = isMobile ? Drawer : Modal; const SheetComponent = isMobile ? Drawer : Modal;
if (!opened) return null;
return ( return (
<SheetComponent <SheetComponent
title={title} title={title}
@@ -23,14 +25,20 @@ const Sheet: React.FC<SheetProps> = ({ title, children, opened, onChange }) => {
onChange={onChange} onChange={onChange}
onClose={handleClose} onClose={handleClose}
> >
<ScrollArea.Autosize <Suspense fallback={
style={{ flex: 1, maxHeight: '75dvh' }} <Flex justify='center' align='center' w='100%' style={{ minHeight: '25vh' }}>
scrollbarSize={8} <Loader size='lg' />
scrollbars="y" </Flex>
type="scroll" }>
> <ScrollArea.Autosize
{children} style={{ flex: 1, maxHeight: '75dvh' }}
</ScrollArea.Autosize> scrollbarSize={8}
scrollbars="y"
type="scroll"
>
{children}
</ScrollArea.Autosize>
</Suspense>
</SheetComponent> </SheetComponent>
); );
}; };

View File

@@ -101,7 +101,7 @@ const StatsOverview = ({ statsData, isLoading = false }: StatsOverviewProps) =>
{ label: "Losses", value: overallStats.losses, Icon: XIcon }, { label: "Losses", value: overallStats.losses, Icon: XIcon },
{ label: "Cups Made", value: overallStats.total_cups_made, Icon: FireIcon }, { label: "Cups Made", value: overallStats.total_cups_made, Icon: FireIcon },
{ label: "Cups Against", value: overallStats.total_cups_against, Icon: ShieldIcon }, { label: "Cups Against", value: overallStats.total_cups_against, Icon: ShieldIcon },
{ label: "Avg Cups Per Game", value: avgCupsPerMatch >= 0 ? avgCupsPerMatch : null, Icon: ChartLineUpIcon }, { label: "Avg Cups Per Match", value: avgCupsPerMatch >= 0 ? avgCupsPerMatch : null, Icon: ChartLineUpIcon },
{ label: "Avg Cups Against", value: avgCupsAgainstPerMatch >= 0 ? avgCupsAgainstPerMatch : null, Icon: ShieldCheckIcon }, { label: "Avg Cups Against", value: avgCupsAgainstPerMatch >= 0 ? avgCupsAgainstPerMatch : null, Icon: ShieldCheckIcon },
{ label: "Avg Win Margin", value: avgMarginOfVictory >= 0 ? avgMarginOfVictory : null, Icon: ArrowUpIcon }, { label: "Avg Win Margin", value: avgMarginOfVictory >= 0 ? avgMarginOfVictory : null, Icon: ArrowUpIcon },
{ label: "Avg Loss Margin", value: avgMarginOfLoss >= 0 ? avgMarginOfLoss : null, Icon: ArrowDownIcon }, { label: "Avg Loss Margin", value: avgMarginOfLoss >= 0 ? avgMarginOfLoss : null, Icon: ArrowDownIcon },
@@ -133,7 +133,7 @@ export const StatsSkeleton = () => {
{ label: "Losses", Icon: XIcon }, { label: "Losses", Icon: XIcon },
{ label: "Cups Made", Icon: FireIcon }, { label: "Cups Made", Icon: FireIcon },
{ label: "Cups Against", Icon: ShieldIcon }, { label: "Cups Against", Icon: ShieldIcon },
{ label: "Avg Cups Per Game", Icon: ChartLineUpIcon }, { label: "Avg Cups Per Match", Icon: ChartLineUpIcon },
{ label: "Avg Cups Against", Icon: ShieldCheckIcon }, { label: "Avg Cups Against", Icon: ShieldCheckIcon },
{ label: "Avg Win Margin", Icon: ArrowUpIcon }, { label: "Avg Win Margin", Icon: ArrowUpIcon },
{ label: "Avg Loss Margin", Icon: ArrowDownIcon }, { label: "Avg Loss Margin", Icon: ArrowDownIcon },

View File

@@ -18,6 +18,7 @@ interface TabItem {
interface SwipeableTabsProps { interface SwipeableTabsProps {
tabs: TabItem[]; tabs: TabItem[];
defaultTab?: number; defaultTab?: number;
mb?: string | number;
onTabChange?: (index: number, tab: TabItem) => void; onTabChange?: (index: number, tab: TabItem) => void;
} }
@@ -25,6 +26,7 @@ function SwipeableTabs({
tabs, tabs,
defaultTab = 0, defaultTab = 0,
onTabChange, onTabChange,
mb,
}: SwipeableTabsProps) { }: SwipeableTabsProps) {
const router = useRouter(); const router = useRouter();
const search = router.state.location.search as any; const search = router.state.location.search as any;
@@ -144,7 +146,7 @@ function SwipeableTabs({
style={{ style={{
display: "flex", display: "flex",
paddingInline: "var(--mantine-spacing-md)", paddingInline: "var(--mantine-spacing-md)",
marginBottom: "var(--mantine-spacing-md)", marginBottom: mb !== undefined ? mb : "var(--mantine-spacing-md)",
zIndex: 100, zIndex: 100,
backgroundColor: "var(--mantine-color-body)", backgroundColor: "var(--mantine-color-body)",
}} }}
@@ -205,11 +207,13 @@ function SwipeableTabs({
height: carouselHeight === "auto" ? "auto" : `${carouselHeight}px`, height: carouselHeight === "auto" ? "auto" : `${carouselHeight}px`,
transition: "height 300ms ease", transition: "height 300ms ease",
touchAction: "pan-y", touchAction: "pan-y",
width: "100%",
maxWidth: "100vw",
}} }}
> >
{tabs.map((tab, index) => ( {tabs.map((tab, index) => (
<Carousel.Slide key={`${tab.label}-content-${index}`}> <Carousel.Slide key={`${tab.label}-content-${index}`}>
<Box ref={setSlideRef(index)} style={{ height: "auto" }}> <Box ref={setSlideRef(index)} style={{ height: "auto", width: "100%", maxWidth: "100vw", overflow: "hidden" }}>
{tab.content} {tab.content}
</Box> </Box>
</Carousel.Slide> </Carousel.Slide>

View File

@@ -0,0 +1,129 @@
import { Box, AvatarGroup } from "@mantine/core";
import { CrownIcon } from "@phosphor-icons/react";
import { TeamInfo } from "@/features/teams/types";
import Avatar from "./avatar";
import PlayerAvatar from "./player-avatar";
interface TeamAvatarProps {
team: TeamInfo;
size?: number;
radius?: string | number;
withBorder?: boolean;
disableFullscreen?: boolean;
contain?: boolean;
style?: React.CSSProperties;
winner?: boolean;
isRegional?: boolean;
}
const TeamAvatar = ({
team,
size = 35,
radius = "sm",
withBorder = true,
disableFullscreen = false,
contain = false,
style,
winner = false,
isRegional,
}: TeamAvatarProps) => {
const hasNoLogo = !team.logo;
const hasTwoPlayers = team.players?.length === 2;
const shouldShowPlayerAvatars = isRegional === true && hasTwoPlayers && hasNoLogo;
if (shouldShowPlayerAvatars && team.players?.length === 2) {
const playerSize = size * 0.6;
const crownSize = Math.max(12, size * 0.35);
return (
<Box
style={{
position: "relative",
width: size,
height: size,
display: "flex",
alignItems: "center",
justifyContent: "center",
...style,
}}
>
<AvatarGroup spacing={size * -0.25}>
<Box style={{ position: "relative" }}>
<PlayerAvatar
name={`${team.players[0].first_name} ${team.players[0].last_name}`}
size={playerSize}
disableFullscreen={disableFullscreen}
/>
{winner && (
<Box
style={{
position: "absolute",
top: -crownSize * 1.1,
left: "45%",
transform: "translateX(-50%)",
color: "gold",
rotate: "-5deg",
}}
>
<CrownIcon size={crownSize} weight="fill" />
</Box>
)}
</Box>
<Box style={{ position: "relative" }}>
<PlayerAvatar
name={`${team.players[1].first_name} ${team.players[1].last_name}`}
size={playerSize}
disableFullscreen={disableFullscreen}
/>
{winner && (
<Box
style={{
position: "absolute",
top: -crownSize * 0.95,
left: "65%",
transform: "translateX(-50%)",
color: "gold",
rotate: "10deg",
}}
>
<CrownIcon size={crownSize} weight="fill" />
</Box>
)}
</Box>
</AvatarGroup>
</Box>
);
}
const crownSize = Math.max(14, size * 0.4);
return (
<Box style={{ position: "relative", ...style }}>
<Avatar
name={team.name}
size={size}
radius={radius}
withBorder={withBorder}
disableFullscreen={disableFullscreen}
contain={contain}
src={team.logo ? `/api/files/teams/${team.id}/${team.logo}` : undefined}
/>
{winner && (
<Box
style={{
position: "absolute",
top: -crownSize * 0.6,
left: -crownSize * 0.25,
transform: "rotate(-25deg)",
color: "gold",
}}
>
<CrownIcon size={crownSize} weight="fill" />
</Box>
)}
</Box>
);
};
export default TeamAvatar;

View File

@@ -1,6 +1,7 @@
import { createContext, useCallback, useEffect, useState, PropsWithChildren } from 'react'; import { createContext, useCallback, useEffect, useState, PropsWithChildren } from 'react';
import { SpotifyAuth } from '@/lib/spotify/auth'; import { SpotifyAuth } from '@/lib/spotify/auth';
import { useAuth } from './auth-context'; import { useAuth } from './auth-context';
import { useConfig } from '@/hooks/use-config';
import type { import type {
SpotifyContextType, SpotifyContextType,
SpotifyAuthState, SpotifyAuthState,
@@ -23,6 +24,7 @@ export const SpotifyContext = createContext<SpotifyContextType | null>(null);
export const SpotifyProvider: React.FC<PropsWithChildren> = ({ children }) => { export const SpotifyProvider: React.FC<PropsWithChildren> = ({ children }) => {
const { roles } = useAuth(); const { roles } = useAuth();
const isAdmin = roles?.includes('Admin') || false; const isAdmin = roles?.includes('Admin') || false;
const config = useConfig();
const [authState, setAuthState] = useState<SpotifyAuthState>(defaultSpotifyState); const [authState, setAuthState] = useState<SpotifyAuthState>(defaultSpotifyState);
@@ -40,8 +42,8 @@ export const SpotifyProvider: React.FC<PropsWithChildren> = ({ children }) => {
const [isResumeLoading, setIsResumeLoading] = useState(false); const [isResumeLoading, setIsResumeLoading] = useState(false);
const spotifyAuth = new SpotifyAuth( const spotifyAuth = new SpotifyAuth(
import.meta.env.VITE_SPOTIFY_CLIENT_ID!, config.spotifyClientId,
import.meta.env.VITE_SPOTIFY_REDIRECT_URI! config.spotifyRedirectUri
); );
useEffect(() => { useEffect(() => {

View File

@@ -18,15 +18,15 @@ interface BadgeDisplay {
interface BadgeIconProps { interface BadgeIconProps {
badge: Badge; badge: Badge;
earned: boolean; filled: boolean;
} }
const BadgeIcon = ({ badge, earned, size = 48 }: BadgeIconProps & { size?: number }) => { export const BadgeIcon = ({ badge, filled, size = 48 }: BadgeIconProps & { size?: number }) => {
const [imageError, setImageError] = useState(false); const [imageError, setImageError] = useState(false);
const imagePath = `/static/img/${badge.key}.png`; const imagePath = `/static/img/${badge.key}.png`;
if (imageError) { if (imageError) {
return earned ? ( return filled ? (
<MedalIcon <MedalIcon
size={size} size={size}
weight="fill" weight="fill"
@@ -50,7 +50,7 @@ const BadgeIcon = ({ badge, earned, size = 48 }: BadgeIconProps & { size?: numbe
onError={() => setImageError(true)} onError={() => setImageError(true)}
style={{ style={{
objectFit: 'contain', objectFit: 'contain',
opacity: earned ? 1 : 0.4, opacity: filled ? 1 : 0.4,
}} }}
/> />
); );
@@ -218,7 +218,7 @@ const BadgeShowcase = ({ playerId }: BadgeShowcaseProps) => {
zIndex: 1, zIndex: 1,
}} }}
> >
<BadgeIcon badge={display.badge} earned={display.earned} /> <BadgeIcon badge={display.badge} filled={display.earned} />
{showStack && ( {showStack && (
<Box <Box
@@ -256,7 +256,7 @@ const BadgeShowcase = ({ playerId }: BadgeShowcaseProps) => {
<Popover.Dropdown> <Popover.Dropdown>
<Stack gap={4} align="center"> <Stack gap={4} align="center">
<Box style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <Box style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<BadgeIcon badge={display.badge} earned={display.earned} size={80} /> <BadgeIcon badge={display.badge} filled={display.earned} size={80} />
</Box> </Box>
<Title order={5} ta="center"> <Title order={5} ta="center">

View File

@@ -0,0 +1,67 @@
import {
Stack,
Container,
Box,
Divider,
Grid,
Skeleton,
} from '@mantine/core';
const BadgeStatsTableSkeleton = () => {
return (
<Container size='100%' px={0}>
<Stack gap='xs'>
<Stack gap={0}>
{Array.from({ length: 15 }).map((_, index) => (
<BadgeStatRowSkeleton
key={`skeleton-${index}`}
isLastRow={index >= 14}
/>
))}
</Stack>
</Stack>
</Container>
);
};
export default BadgeStatsTableSkeleton;
interface BadgeStatRowSkeletonProps {
isLastRow: boolean;
}
const BadgeStatRowSkeleton: React.FC<BadgeStatRowSkeletonProps> = ({
isLastRow,
}) => {
return (
<Box>
<Grid p={'xs'} align='center'>
<Grid.Col span={2} style={{ display: 'flex', alignItems: 'center' }}>
<Skeleton circle height={48} width={48} />
</Grid.Col>
<Grid.Col span={'auto'}>
<Stack gap={8}>
<Skeleton height={16} width='60%' />
<Skeleton height={14} width='80%' />
<Skeleton height={12} width='50%' mt={4} />
</Stack>
</Grid.Col>
<Grid.Col
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
width: '73px',
flexBasis: '73px',
}}
>
<Stack gap={4} align='center'>
<Skeleton height={20} width={40} />
<Skeleton height={12} width={50} />
</Stack>
</Grid.Col>
</Grid>
{!isLastRow && <Divider />}
</Box>
);
};

View File

@@ -0,0 +1,177 @@
import {
Stack,
Container,
Title,
Box,
Divider,
Text,
Grid,
UnstyledButton,
} from '@mantine/core';
import { useAllBadges, useAllEarnedBadges } from '../queries';
import { BadgeIcon } from './badge-showcase';
import { useMemo } from 'react';
import { Badge, EarnedBadge } from '../types';
import { useAllPlayers } from '@/features/teams/hooks/use-available-players';
import { useSheet } from '@/hooks/use-sheet';
import Sheet from '@/components/sheet/sheet';
import PlayerList from '@/features/players/components/player-list';
import { useAuth } from '@/contexts/auth-context';
import { Player } from '@/features/players/types';
const BadgeStatsTable = () => {
const { data: allBadges } = useAllBadges();
const { data: allEarnedBadges } = useAllEarnedBadges();
const { data: allPlayers } = useAllPlayers();
const totalNumPlayers = allPlayers?.length || 0;
const groupedEarnedBadges = useMemo(() => {
const returnDict = new Map<string, EarnedBadge[]>();
allEarnedBadges?.forEach((earnedBadge) => {
if (!returnDict.has(earnedBadge.badge)) {
returnDict.set(earnedBadge.badge, []);
}
returnDict.get(earnedBadge.badge)!.push(earnedBadge);
});
return returnDict;
}, [allEarnedBadges]);
if (allBadges.length === 0) {
return (
<Container px={0} size='md'>
<Stack align='center' gap='md' py='xl'>
<Title order={3} c='dimmed'>
No Badges Available
</Title>
</Stack>
</Container>
);
}
return (
<Container size='100%' px={0}>
<Stack gap='xs'>
<Stack gap={0}>
{allBadges.map((badge, index) => (
<BadgeStatRow
badge={badge}
totalNumPlayers={totalNumPlayers}
earnedBadges={groupedEarnedBadges.get(badge.id) || []}
isLastRow={index >= allBadges.length - 1}
/>
))}
</Stack>
</Stack>
</Container>
);
};
export default BadgeStatsTable;
interface BadgeStatRowProps {
badge: Badge;
totalNumPlayers: number;
earnedBadges: EarnedBadge[];
isLastRow: boolean;
}
const BadgeStatRow: React.FC<BadgeStatRowProps> = ({
badge,
totalNumPlayers,
earnedBadges,
isLastRow,
}) => {
const badgeSheet = useSheet();
const { user } = useAuth();
const playerNamesBlurb = useMemo(() => {
if (earnedBadges.length === 0) return 'No players yet';
const currentUserHasBadge = earnedBadges.some(
(eb) => eb.player.id === user?.id
);
const otherPlayers = earnedBadges.filter(
(eb) => eb.player.id !== user?.id
);
const displayPlayers = currentUserHasBadge
? otherPlayers.slice(0, 2)
: earnedBadges.slice(0, 3);
const names = displayPlayers.map((eb) => eb.player.first_name);
if (currentUserHasBadge) {
const remaining = earnedBadges.length - 1 - names.length;
if (names.length === 0 && remaining === 0) {
return 'You';
} else if (names.length === 0 && remaining > 0) {
return `You and ${remaining} other${remaining > 1 ? 's' : ''}`;
} else if (remaining > 0) {
return `You, ${names.join(', ')} and ${remaining} other${remaining > 1 ? 's' : ''}`;
} else {
return `You${names.length > 0 ? ` and ${names.join(', ')}` : ''}`;
}
} else {
const remaining = earnedBadges.length - names.length;
if (remaining > 0) {
return `${names.join(', ')} and ${remaining} other${remaining > 1 ? 's' : ''}`;
} else {
return names.join(', ');
}
}
}, [earnedBadges, user?.id]);
const playersForList: Player[] = useMemo(() => {
return earnedBadges.map((eb) => ({
id: eb.player.id,
first_name: eb.player.first_name,
last_name: eb.player.last_name,
} as Player));
}, [earnedBadges]);
return (
<Box key={badge.id}>
<UnstyledButton onClick={badgeSheet.open} w='100%'>
<Grid p={'xs'} align='center'>
<Grid.Col span={2} style={{ display: 'flex', alignItems: 'center' }}>
<BadgeIcon badge={badge} filled={true} />
</Grid.Col>
<Grid.Col span={'auto'}>
<Stack gap={2}>
<Text fw={700}>{badge.name}</Text>
<Text size="sm" fw={500}>{badge.description}</Text>
<Text size='xs' c='dimmed' mt={4}>
{playerNamesBlurb}
</Text>
</Stack>
</Grid.Col>
<Grid.Col
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
width: '73px',
flexBasis: '73px', // ensures the width is respected
}}
>
<Stack gap={0} align='center'>
<Text c="dimmed" size='lg' fw={700}>
{(
((earnedBadges?.length ?? 0) / totalNumPlayers) *
100
).toFixed(0)}
%
</Text>
<Text c="dimmed" size='xs'>of players</Text>
</Stack>
</Grid.Col>
</Grid>
</UnstyledButton>
<Sheet title={badge.name + ' Badge Holders'} {...badgeSheet.props}>
<PlayerList players={playersForList} />
</Sheet>
{!isLastRow && <Divider />}
</Box>
);
};

View File

@@ -1,9 +1,10 @@
import { useServerSuspenseQuery } from "@/lib/tanstack-query/hooks"; import { useServerSuspenseQuery } from "@/lib/tanstack-query/hooks";
import { getPlayerBadges, getAllBadges } from "./server"; import { getPlayerBadges, getAllBadges, getAllEarnedBadges } from "./server";
export const badgeKeys = { export const badgeKeys = {
playerBadges: (playerId: string) => ['badges', 'player', playerId], playerBadges: (playerId: string) => ['badges', 'player', playerId],
allBadges: () => ['badges', 'all'], allBadges: () => ['badges', 'all'],
allEarnedBadges: () => ['badges', 'earned'],
}; };
export const badgeQueries = { export const badgeQueries = {
@@ -15,6 +16,10 @@ export const badgeQueries = {
queryKey: badgeKeys.allBadges(), queryKey: badgeKeys.allBadges(),
queryFn: async () => await getAllBadges() queryFn: async () => await getAllBadges()
}), }),
allEarnedBadges: () => ({
queryKey: badgeKeys.allEarnedBadges(),
queryFn: async () => await getAllEarnedBadges(),
}),
}; };
export const usePlayerBadges = (playerId: string) => export const usePlayerBadges = (playerId: string) =>
@@ -22,3 +27,6 @@ export const usePlayerBadges = (playerId: string) =>
export const useAllBadges = () => export const useAllBadges = () =>
useServerSuspenseQuery(badgeQueries.allBadges()); useServerSuspenseQuery(badgeQueries.allBadges());
export const useAllEarnedBadges = () =>
useServerSuspenseQuery(badgeQueries.allEarnedBadges());

View File

@@ -23,6 +23,10 @@ export const getAllBadges = createServerFn()
toServerResult(() => pbAdmin.listBadges()) toServerResult(() => pbAdmin.listBadges())
); );
export const getAllEarnedBadges = createServerFn()
.middleware([superTokensFunctionMiddleware])
.handler(async () => toServerResult(() => pbAdmin.listEarnedBadges()));
export const awardManualBadge = createServerFn() export const awardManualBadge = createServerFn()
.inputValidator(z.object({ .inputValidator(z.object({
playerId: z.string(), playerId: z.string(),

View File

@@ -1,3 +1,5 @@
import { PlayerInfo } from '../players/types';
export interface BadgeInfo { export interface BadgeInfo {
id: string; id: string;
name: string; name: string;
@@ -23,3 +25,13 @@ export interface BadgeProgress {
created: string; created: string;
updated: string; updated: string;
} }
export interface EarnedBadge {
id: string;
badge: string;
player: PlayerInfo;
progress: number;
earned: boolean;
created: string;
updated: string;
}

View File

@@ -7,10 +7,14 @@ import { Match } from "@/features/matches/types";
interface BracketViewProps { interface BracketViewProps {
bracket: BracketData; bracket: BracketData;
showControls?: boolean showControls?: boolean;
groupConfig?: {
num_groups: number;
advance_per_group: number;
};
} }
const BracketView: React.FC<BracketViewProps> = ({ bracket, showControls }) => { const BracketView: React.FC<BracketViewProps> = ({ bracket, showControls, groupConfig }) => {
const height = useAppShellHeight(); const height = useAppShellHeight();
const orders = useMemo(() => { const orders = useMemo(() => {
const map: Record<number, number> = {}; const map: Record<number, number> = {};
@@ -32,14 +36,14 @@ const BracketView: React.FC<BracketViewProps> = ({ bracket, showControls }) => {
<Text fw={600} size="md" m={16}> <Text fw={600} size="md" m={16}>
Winners Bracket Winners Bracket
</Text> </Text>
<Bracket rounds={bracket.winners} orders={orders} showControls={showControls} /> <Bracket rounds={bracket.winners} orders={orders} showControls={showControls} groupConfig={groupConfig} />
</div> </div>
{bracket.losers && ( {bracket.losers && bracket.losers.length > 0 && bracket.losers.some(round => round.length > 0) && (
<div> <div>
<Text fw={600} size="md" m={16}> <Text fw={600} size="md" m={16}>
Losers Bracket Losers Bracket
</Text> </Text>
<Bracket rounds={bracket.losers} orders={orders} showControls={showControls} /> <Bracket rounds={bracket.losers} orders={orders} showControls={showControls} groupConfig={groupConfig} />
</div> </div>
)} )}
</ScrollArea> </ScrollArea>

View File

@@ -7,12 +7,17 @@ interface BracketProps {
rounds: Match[][]; rounds: Match[][];
orders: Record<number, number>; orders: Record<number, number>;
showControls?: boolean; showControls?: boolean;
groupConfig?: {
num_groups: number;
advance_per_group: number;
};
} }
export const Bracket: React.FC<BracketProps> = ({ export const Bracket: React.FC<BracketProps> = ({
rounds, rounds,
orders, orders,
showControls, showControls,
groupConfig,
}) => { }) => {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const svgRef = useRef<SVGSVGElement>(null); const svgRef = useRef<SVGSVGElement>(null);
@@ -132,6 +137,7 @@ export const Bracket: React.FC<BracketProps> = ({
match={match} match={match}
orders={orders} orders={orders}
showControls={showControls} showControls={showControls}
groupConfig={groupConfig}
/> />
</div> </div>
) )

View File

@@ -17,16 +17,62 @@ interface MatchCardProps {
match: Match; match: Match;
orders: Record<number, number>; orders: Record<number, number>;
showControls?: boolean; showControls?: boolean;
groupConfig?: {
num_groups: number;
advance_per_group: number;
};
} }
export const MatchCard: React.FC<MatchCardProps> = ({ export const MatchCard: React.FC<MatchCardProps> = ({
match, match,
orders, orders,
showControls, showControls,
groupConfig,
}) => { }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const editSheet = useSheet(); const editSheet = useSheet();
const { playTrack, pause } = useSpotifyPlayback(); const { playTrack, pause } = useSpotifyPlayback();
const getGroupLabel = useCallback((seed: number | undefined) => {
if (!seed || !groupConfig) return undefined;
const groupNames = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
const numGroups = groupConfig.num_groups;
const advancePerGroup = groupConfig.advance_per_group;
const totalQualifiedTeams = numGroups * advancePerGroup;
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(totalQualifiedTeams)));
const wildcardsNeeded = nextPowerOf2 - totalQualifiedTeams;
if (seed > totalQualifiedTeams && wildcardsNeeded > 0) {
const wildcardNumber = seed - totalQualifiedTeams;
return `Wildcard ${wildcardNumber}`;
}
const pairIndex = Math.floor((seed - 1) / 2);
const isFirstInPair = (seed - 1) % 2 === 0;
if (isFirstInPair) {
const groupIndex = pairIndex % numGroups;
const rankIndex = Math.floor(pairIndex / numGroups);
const rank = rankIndex + 1;
const groupName = groupNames[groupIndex] || `${groupIndex + 1}`;
const rankSuffix = rank === 1 ? '1st' : rank === 2 ? '2nd' : rank === 3 ? '3rd' : `${rank}th`;
return `${groupName} ${rankSuffix}`;
} else {
const groupIndex = (pairIndex + 1) % numGroups;
const rankIndex = advancePerGroup - 1 - Math.floor(pairIndex / numGroups);
const rank = rankIndex + 1;
const groupName = groupNames[groupIndex] || `${groupIndex + 1}`;
const rankSuffix = rank === 1 ? '1st' : rank === 2 ? '2nd' : rank === 3 ? '3rd' : `${rank}th`;
return `${groupName} ${rankSuffix}`;
}
}, [groupConfig]);
const homeSlot = useMemo( const homeSlot = useMemo(
() => ({ () => ({
from: orders[match.home_from_lid], from: orders[match.home_from_lid],
@@ -39,8 +85,9 @@ export const MatchCard: React.FC<MatchCardProps> = ({
match.home_cups !== undefined && match.home_cups !== undefined &&
match.away_cups !== undefined && match.away_cups !== undefined &&
match.home_cups > match.away_cups, match.home_cups > match.away_cups,
groupLabel: !match.home && match.home_seed ? getGroupLabel(match.home_seed) : undefined,
}), }),
[match] [match, getGroupLabel]
); );
const awaySlot = useMemo( const awaySlot = useMemo(
() => ({ () => ({
@@ -54,8 +101,9 @@ export const MatchCard: React.FC<MatchCardProps> = ({
match.away_cups !== undefined && match.away_cups !== undefined &&
match.home_cups !== undefined && match.home_cups !== undefined &&
match.away_cups > match.home_cups, match.away_cups > match.home_cups,
groupLabel: !match.away && match.away_seed ? getGroupLabel(match.away_seed) : undefined,
}), }),
[match] [match, getGroupLabel]
); );
const showToolbar = useMemo( const showToolbar = useMemo(
@@ -179,8 +227,11 @@ export const MatchCard: React.FC<MatchCardProps> = ({
data: match.id, data: match.id,
}); });
// Play walkout sequence after starting the match // Skip announcements for regional tournaments
if (hasWalkoutData && match.home?.name && match.away?.name) { const isRegional = match.tournament?.regional === true;
// Play walkout sequence after starting the match (only for non-regional tournaments)
if (!isRegional && hasWalkoutData && match.home?.name && match.away?.name) {
try { try {
const homeTeam = match.home as Team; const homeTeam = match.home as Team;
const awayTeam = match.away as Team; const awayTeam = match.away as Team;

View File

@@ -11,6 +11,7 @@ interface MatchSlotProps {
seed?: number; seed?: number;
cups?: number; cups?: number;
isWinner?: boolean; isWinner?: boolean;
groupLabel?: string;
} }
export const MatchSlot: React.FC<MatchSlotProps> = ({ export const MatchSlot: React.FC<MatchSlotProps> = ({
@@ -19,7 +20,8 @@ export const MatchSlot: React.FC<MatchSlotProps> = ({
team, team,
seed, seed,
cups, cups,
isWinner isWinner,
groupLabel
}) => ( }) => (
<Flex <Flex
align="stretch" align="stretch"
@@ -55,6 +57,10 @@ export const MatchSlot: React.FC<MatchSlotProps> = ({
/> />
)} )}
</> </>
) : groupLabel ? (
<Text c="dimmed" size="xs" truncate style={{ minWidth: 0, flex: 1 }}>
{groupLabel}
</Text>
) : from ? ( ) : from ? (
<Text c="dimmed" size="xs" truncate style={{ minWidth: 0, flex: 1 }}> <Text c="dimmed" size="xs" truncate style={{ minWidth: 0, flex: 1 }}>
{from_loser ? "Loser" : "Winner"} of Match {from} {from_loser ? "Loser" : "Winner"} of Match {from}

View File

@@ -1,15 +1,16 @@
import { AppShell, ScrollArea, Stack, Group, Paper, useMantineColorScheme } from "@mantine/core"; import { AppShell, ScrollArea, Stack, Group, Paper, useMantineColorScheme } from "@mantine/core";
import { Link } from "@tanstack/react-router";
import { NavLink } from "./nav-link"; import { NavLink } from "./nav-link";
import { useIsMobile } from "@/hooks/use-is-mobile"; import { useIsMobile } from "@/hooks/use-is-mobile";
import { useAuth } from "@/contexts/auth-context"; import { useAuth } from "@/contexts/auth-context";
import { useLinks } from "../hooks/use-links"; import { useLinks } from "../hooks/use-links";
import { memo } from "react"; import { memo } from "react";
import { useIsPWA } from "@/hooks/use-is-pwa";
const Navbar = () => { const Navbar = () => {
const { user, roles } = useAuth() const { user, roles } = useAuth()
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const { colorScheme } = useMantineColorScheme(); const { colorScheme } = useMantineColorScheme();
const isPWA = useIsPWA();
const links = useLinks(user?.id, roles); const links = useLinks(user?.id, roles);
@@ -19,7 +20,7 @@ const Navbar = () => {
// boxShadow: `5px 5px ${boxShadowColor}`, borderColor // boxShadow: `5px 5px ${boxShadowColor}`, borderColor
if (isMobile) return ( if (isMobile) return (
<Paper component='nav' role='navigation' withBorder shadow="sm" radius='lg' h='4rem' w='calc(100% - 1rem)' pos='fixed' m='0.5rem' bottom='0' style={{ zIndex: 10 }}> <Paper component='nav' role='navigation' withBorder shadow="sm" radius='lg' h='4rem' w='calc(100% - 1rem)' pos='fixed' m='0.5rem' bottom={isPWA ? '1rem' : '0'} style={{ zIndex: 10 }}>
<Group gap='xs' justify='space-around' h='100%' w='100%' px={{ base: 12, sm: 0 }}> <Group gap='xs' justify='space-around' h='100%' w='100%' px={{ base: 12, sm: 0 }}>
{links.map((link) => ( {links.map((link) => (
<NavLink key={link.href} {...link} /> <NavLink key={link.href} {...link} />

View File

@@ -1,6 +1,9 @@
import { AuthProvider } from "@/contexts/auth-context" import { AuthProvider } from "@/contexts/auth-context"
import { SpotifyProvider } from "@/contexts/spotify-context" import { SpotifyProvider } from "@/contexts/spotify-context"
import MantineProvider from "@/lib/mantine/mantine-provider" import MantineProvider from "@/lib/mantine/mantine-provider"
//import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
//import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
//import { TanStackDevtools } from '@tanstack/react-devtools'
import { Toaster } from "sonner" import { Toaster } from "sonner"
const Providers = ({ children }: { children: React.ReactNode }) => { const Providers = ({ children }: { children: React.ReactNode }) => {
@@ -8,6 +11,22 @@ const Providers = ({ children }: { children: React.ReactNode }) => {
<AuthProvider> <AuthProvider>
<SpotifyProvider> <SpotifyProvider>
<MantineProvider> <MantineProvider>
{/*<TanStackDevtools
eventBusConfig={{
debug: false,
connectToServerBus: true,
}}
plugins={[
{
name: 'TanStack Query',
render: <ReactQueryDevtoolsPanel />,
},
{
name: 'TanStack Router',
render: <TanStackRouterDevtoolsPanel />,
}
]}
/>*/}
<Toaster position='top-center' /> <Toaster position='top-center' />
{children} {children}
</MantineProvider> </MantineProvider>

View File

@@ -32,7 +32,10 @@ const Pullable: React.FC<PullableProps> = ({ children, scrollPosition, onScrollP
if (refresh.length > 0) { if (refresh.length > 0) {
// TODO: Remove this after testing - or does the delay help ux? // TODO: Remove this after testing - or does the delay help ux?
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise(resolve => setTimeout(resolve, 1000));
await queryClient.refetchQueries({ queryKey: refresh, exact: true}); refresh.forEach(async (queryKey) => {
const keyArray = Array.isArray(queryKey) ? queryKey : [queryKey];
await queryClient.refetchQueries({ queryKey: keyArray, exact: true });
});
} }
setIsRefreshing(false); setIsRefreshing(false);
}, [refresh]); }, [refresh]);
@@ -82,6 +85,55 @@ const Pullable: React.FC<PullableProps> = ({ children, scrollPosition, onScrollP
return () => void ac.abort(); return () => void ac.abort();
}, []); }, []);
// Fix wheel scrolling over child elements
useEffect(() => {
const scrollWrapper = document.getElementById('scroll-wrapper');
if (!scrollWrapper) return;
const viewport = scrollWrapper.querySelector('.mantine-ScrollArea-viewport') as HTMLElement;
if (!viewport) return;
const handleWheel = (e: WheelEvent) => {
const target = e.target as HTMLElement;
// Check if the target is inside a nested scrollable container
let element = target;
while (element && element !== viewport) {
const overflow = window.getComputedStyle(element).overflow;
const overflowY = window.getComputedStyle(element).overflowY;
const overflowX = window.getComputedStyle(element).overflowX;
// If we found a scrollable ancestor (not the main viewport), don't interfere
if (
(overflow === 'auto' || overflow === 'scroll' ||
overflowY === 'auto' || overflowY === 'scroll' ||
overflowX === 'auto' || overflowX === 'scroll') &&
element !== viewport
) {
// Check if this element can actually scroll in the wheel direction
const canScrollY = element.scrollHeight > element.clientHeight;
const canScrollX = element.scrollWidth > element.clientWidth;
if ((e.deltaY !== 0 && canScrollY) || (e.deltaX !== 0 && canScrollX)) {
return; // Let the nested scroller handle it
}
}
element = element.parentElement as HTMLElement;
}
// No nested scroller found, scroll the main viewport
viewport.scrollTop += e.deltaY;
viewport.scrollLeft += e.deltaX;
};
scrollWrapper.addEventListener('wheel', handleWheel, { passive: true });
return () => {
scrollWrapper.removeEventListener('wheel', handleWheel);
};
}, []);
useEffect(() => { useEffect(() => {
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
if (scrollAreaRef.current) { if (scrollAreaRef.current) {
@@ -126,8 +178,15 @@ const Pullable: React.FC<PullableProps> = ({ children, scrollPosition, onScrollP
onScrollPositionChange={onScrollPositionChange} onScrollPositionChange={onScrollPositionChange}
type='never' mah='100%' h='100%' type='never' mah='100%' h='100%'
pt={(scrolling || scrollY > 40) || !isRefreshing ? 0 : 40 - scrollY} pt={(scrolling || scrollY > 40) || !isRefreshing ? 0 : 40 - scrollY}
styles={{
viewport: {
'& > *': {
pointerEvents: 'auto'
}
}
}}
> >
<Box pt='1rem'pb='0.285rem' mih={height} style={{ boxSizing: 'content-box' }}> <Box pt='1rem'pb='0.285rem' mih={height} style={{ boxSizing: 'content-box', pointerEvents: 'auto' }}>
{children} {children}
</Box> </Box>
</ScrollArea> </ScrollArea>

View File

@@ -1,20 +1,26 @@
import { Text, Group, Stack, Paper, Indicator, Box, Tooltip } from "@mantine/core"; import { Text, Group, Stack, Paper, Indicator, Box, Tooltip, ActionIcon } from "@mantine/core";
import { CrownIcon } from "@phosphor-icons/react"; import { FootballHelmetIcon } from "@phosphor-icons/react";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { Match } from "../types"; import { Match } from "../types";
import Avatar from "@/components/avatar"; import TeamAvatar from "@/components/team-avatar";
import EmojiBar from "@/features/reactions/components/emoji-bar"; import EmojiBar from "@/features/reactions/components/emoji-bar";
import { Suspense } from "react"; import { Suspense } from "react";
import { useSheet } from "@/hooks/use-sheet";
import Sheet from "@/components/sheet/sheet";
import TeamHeadToHeadSheet from "./team-head-to-head-sheet";
interface MatchCardProps { interface MatchCardProps {
match: Match; match: Match;
hideH2H?: boolean;
} }
const MatchCard = ({ match }: MatchCardProps) => { const MatchCard = ({ match, hideH2H = false }: MatchCardProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
const h2hSheet = useSheet();
const isHomeWin = match.home_cups > match.away_cups; const isHomeWin = match.home_cups > match.away_cups;
const isAwayWin = match.away_cups > match.home_cups; const isAwayWin = match.away_cups > match.home_cups;
const isStarted = match.status === "started"; const isStarted = match.status === "started";
const hasPrivate = match.home?.private || match.away?.private;
const handleHomeTeamClick = (e: React.MouseEvent) => { const handleHomeTeamClick = (e: React.MouseEvent) => {
e.stopPropagation(); e.stopPropagation();
@@ -30,15 +36,13 @@ const MatchCard = ({ match }: MatchCardProps) => {
} }
}; };
const handleH2HClick = (e: React.MouseEvent) => {
e.stopPropagation();
h2hSheet.open();
};
return ( return (
<Indicator <>
disabled={!isStarted}
size={12}
color="red"
processing
position="top-end"
offset={24}
>
<Box style={{ position: "relative" }}> <Box style={{ position: "relative" }}>
<Paper <Paper
px="md" px="md"
@@ -48,46 +52,77 @@ const MatchCard = ({ match }: MatchCardProps) => {
style={{ position: "relative", zIndex: 2 }} style={{ position: "relative", zIndex: 2 }}
> >
<Stack gap="sm"> <Stack gap="sm">
<Group gap="xs"> <Group gap="xs" justify="space-between">
<Text size="xs" fw={600} lineClamp={1} c="dimmed"> <Group gap="xs" style={{ flex: 1 }}>
{match.tournament.name} {isStarted && (
</Text> <Indicator
<Text c="dimmed">-</Text> size={8}
<Text size="xs" c="dimmed"> color="red"
Round {match.round + 1} processing
{match.is_losers_bracket && " (Losers)"} position="middle-start"
</Text> offset={0}
/>
)}
<Text size="xs" fw={600} lineClamp={1} c="dimmed">
{match.tournament.name}
</Text>
{!match.tournament.regional && (
<>
<Text c="dimmed">-</Text>
<Text size="xs" c="dimmed">
Round {match.round + 1}
{match.is_losers_bracket && " (Losers)"}
</Text>
</>
)}
</Group>
{match.home && match.away && !hideH2H && !hasPrivate && (
<Tooltip label="Head to Head" withArrow position="left">
<ActionIcon
variant="subtle"
size="sm"
onClick={handleH2HClick}
aria-label="View head-to-head"
w={40}
>
<Group style={{ position: 'relative', width: 27.5, height: 16 }}>
<FootballHelmetIcon
size={14}
style={{
position: 'absolute',
left: 0,
top: 0,
transform: 'rotate(25deg)',
}}
/>
<FootballHelmetIcon
size={14}
style={{
position: 'absolute',
right: 0,
top: 0,
transform: 'scaleX(-1) rotate(25deg)',
}}
/>
</Group>
</ActionIcon>
</Tooltip>
)}
</Group> </Group>
<Group justify="space-between" align="center"> <Group justify="space-between" align="center">
<Group gap="sm" style={{ flex: 1 }}> <Group gap="sm" style={{ flex: 1 }}>
<Box <Box
style={{ position: "relative", cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={handleHomeTeamClick} onClick={handleHomeTeamClick}
> >
<Avatar <TeamAvatar
team={match.home!}
size={40} size={40}
name={match.home?.name!}
radius="sm" radius="sm"
src={ winner={isHomeWin}
match.home?.logo isRegional={match.tournament.regional}
? `/api/files/teams/${match.home?.id}/${match.home?.logo}`
: undefined
}
/> />
{isHomeWin && (
<Box
style={{
position: "absolute",
top: -10,
left: -4,
transform: "rotate(-25deg)",
color: "gold",
}}
>
<CrownIcon size={16} weight="fill" />
</Box>
)}
</Box> </Box>
<Tooltip <Tooltip
label={match.home?.name!} label={match.home?.name!}
@@ -124,32 +159,16 @@ const MatchCard = ({ match }: MatchCardProps) => {
<Group justify="space-between" align="center"> <Group justify="space-between" align="center">
<Group gap="sm" style={{ flex: 1 }}> <Group gap="sm" style={{ flex: 1 }}>
<Box <Box
style={{ position: "relative", cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={handleAwayTeamClick} onClick={handleAwayTeamClick}
> >
<Avatar <TeamAvatar
team={match.away!}
size={40} size={40}
name={match.away?.name!}
radius="sm" radius="sm"
src={ winner={isAwayWin}
match.away?.logo isRegional={match.tournament.regional}
? `/api/files/teams/${match.away?.id}/${match.away?.logo}`
: undefined
}
/> />
{isAwayWin && (
<Box
style={{
position: "absolute",
top: -10,
left: -4,
transform: "rotate(-25deg)",
color: "gold",
}}
>
<CrownIcon size={16} weight="fill" />
</Box>
)}
</Box> </Box>
<Tooltip <Tooltip
label={match.away?.name} label={match.away?.name}
@@ -205,7 +224,16 @@ const MatchCard = ({ match }: MatchCardProps) => {
</Suspense> </Suspense>
</Paper> </Paper>
</Box> </Box>
</Indicator>
{match.home && match.away && !hideH2H && h2hSheet.isOpen && (
<Sheet
title="Head to Head"
{...h2hSheet.props}
>
<TeamHeadToHeadSheet team1={match.home} team2={match.away} isOpen={h2hSheet.props.opened} />
</Sheet>
)}
</>
); );
}; };

View File

@@ -1,12 +1,13 @@
import { Stack } from "@mantine/core"; import { Stack, Text } from "@mantine/core";
import { Match } from "../types"; import { Match } from "../types";
import MatchCard from "./match-card"; import MatchCard from "./match-card";
interface MatchListProps { interface MatchListProps {
matches: Match[]; matches: Match[];
hideH2H?: boolean;
} }
const MatchList = ({ matches }: MatchListProps) => { const MatchList = ({ matches, hideH2H = false }: MatchListProps) => {
const filteredMatches = matches?.filter(match => const filteredMatches = matches?.filter(match =>
match.home && match.away && !match.bye && match.status != "tbd" match.home && match.away && !match.bye && match.status != "tbd"
).sort((a, b) => a.start_time < b.start_time ? 1 : -1) || []; ).sort((a, b) => a.start_time < b.start_time ? 1 : -1) || [];
@@ -15,13 +16,20 @@ const MatchList = ({ matches }: MatchListProps) => {
return undefined; return undefined;
} }
const isRegional = filteredMatches[0]?.tournament?.regional;
return ( return (
<Stack p="md" gap="sm"> <Stack p="md" gap="sm">
{isRegional && (
<Text size="xs" c="dimmed" ta="center" px="md">
Matches for regionals are unordered
</Text>
)}
{filteredMatches.map((match, index) => ( {filteredMatches.map((match, index) => (
<div <div
key={`match-${match.id}-${index}`} key={`match-${match.id}-${index}`}
> >
<MatchCard match={match} /> <MatchCard match={match} hideH2H={hideH2H} />
</div> </div>
))} ))}
</Stack> </Stack>

View File

@@ -0,0 +1,217 @@
import { Stack, Text, Group, Box, Divider, Paper } from "@mantine/core";
import { TeamInfo } from "@/features/teams/types";
import { useTeamHeadToHead } from "../queries";
import { useMemo, useEffect, useState, Suspense } from "react";
import { CrownIcon } from "@phosphor-icons/react";
import MatchList from "./match-list";
import TeamHeadToHeadSkeleton from "./team-head-to-head-skeleton";
interface TeamHeadToHeadSheetProps {
team1: TeamInfo;
team2: TeamInfo;
isOpen?: boolean;
}
const TeamHeadToHeadContent = ({ team1, team2, isOpen = true }: TeamHeadToHeadSheetProps) => {
const [shouldFetch, setShouldFetch] = useState(false);
useEffect(() => {
if (isOpen && !shouldFetch) {
setShouldFetch(true);
}
}, [isOpen, shouldFetch]);
const { data: matches, isLoading } = useTeamHeadToHead(team1.id, team2.id, shouldFetch);
const stats = useMemo(() => {
if (!matches || matches.length === 0) {
return {
team1Wins: 0,
team2Wins: 0,
team1CupsFor: 0,
team2CupsFor: 0,
team1CupsAgainst: 0,
team2CupsAgainst: 0,
team1AvgMargin: 0,
team2AvgMargin: 0,
};
}
let team1Wins = 0;
let team2Wins = 0;
let team1CupsFor = 0;
let team2CupsFor = 0;
let team1CupsAgainst = 0;
let team2CupsAgainst = 0;
let team1TotalWinMargin = 0;
let team2TotalWinMargin = 0;
matches.forEach((match) => {
const isTeam1Home = match.home?.id === team1.id;
const team1Cups = isTeam1Home ? match.home_cups : match.away_cups;
const team2Cups = isTeam1Home ? match.away_cups : match.home_cups;
if (team1Cups > team2Cups) {
team1Wins++;
team1TotalWinMargin += (team1Cups - team2Cups);
} else if (team2Cups > team1Cups) {
team2Wins++;
team2TotalWinMargin += (team2Cups - team1Cups);
}
team1CupsFor += team1Cups;
team2CupsFor += team2Cups;
team1CupsAgainst += team2Cups;
team2CupsAgainst += team1Cups;
});
const team1AvgMargin = team1Wins > 0
? team1TotalWinMargin / team1Wins
: 0;
const team2AvgMargin = team2Wins > 0
? team2TotalWinMargin / team2Wins
: 0;
return {
team1Wins,
team2Wins,
team1CupsFor,
team2CupsFor,
team1CupsAgainst,
team2CupsAgainst,
team1AvgMargin,
team2AvgMargin,
};
}, [matches, team1.id]);
if (isLoading) {
return (
<Stack p="md" gap="md">
<Text size="sm" c="dimmed" ta="center">Loading...</Text>
</Stack>
);
}
if (!matches || matches.length === 0) {
return (
<Stack p="md" gap="md">
<Text size="sm" c="dimmed" ta="center">
These teams have not faced each other yet.
</Text>
</Stack>
);
}
const totalMatches = stats.team1Wins + stats.team2Wins;
const leader = stats.team1Wins > stats.team2Wins ? team1 : stats.team2Wins > stats.team1Wins ? team2 : null;
return (
<Stack gap="md">
<Paper p="md" withBorder radius="md">
<Stack gap="sm">
<Group justify="center" gap="xs">
<Text size="lg" fw={700}>{team1.name}</Text>
<Text size="sm" c="dimmed">vs</Text>
<Text size="lg" fw={700}>{team2.name}</Text>
</Group>
<Group justify="center" gap="lg">
<Stack gap={0} align="center">
<Text size="xl" fw={700}>{stats.team1Wins}</Text>
<Text size="xs" c="dimmed">{team1.name}</Text>
</Stack>
<Text size="md" c="dimmed">-</Text>
<Stack gap={0} align="center">
<Text size="xl" fw={700}>{stats.team2Wins}</Text>
<Text size="xs" c="dimmed">{team2.name}</Text>
</Stack>
</Group>
{leader && (
<Group justify="center" gap="xs">
<CrownIcon size={16} weight="fill" color="gold" />
<Text size="xs" c="dimmed">
{leader.name} leads the series
</Text>
</Group>
)}
{!leader && totalMatches > 0 && (
<Text size="xs" c="dimmed" ta="center">
Series is tied
</Text>
)}
</Stack>
</Paper>
<Stack gap={0}>
<Text size="sm" fw={600} px="md" mb="xs">Stats Comparison</Text>
<Paper withBorder>
<Stack gap={0}>
<Group justify="space-between" px="md" py="sm">
<Group gap="xs">
<Text size="sm" fw={600}>{stats.team1CupsFor}</Text>
<Text size="xs" c="dimmed">cups</Text>
</Group>
<Text size="xs" fw={500}>Total Cups</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">cups</Text>
<Text size="sm" fw={600}>{stats.team2CupsFor}</Text>
</Group>
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Group gap="xs">
<Text size="sm" fw={600}>
{totalMatches > 0 ? (stats.team1CupsFor / totalMatches).toFixed(1) : '0.0'}
</Text>
<Text size="xs" c="dimmed">avg</Text>
</Group>
<Text size="xs" fw={500}>Avg Cups/Match</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">avg</Text>
<Text size="sm" fw={600}>
{totalMatches > 0 ? (stats.team2CupsFor / totalMatches).toFixed(1) : '0.0'}
</Text>
</Group>
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Group gap="xs">
<Text size="sm" fw={600}>
{!isNaN(stats.team1AvgMargin) ? stats.team1AvgMargin.toFixed(1) : '0.0'}
</Text>
<Text size="xs" c="dimmed">margin</Text>
</Group>
<Text size="xs" fw={500}>Avg Win Margin</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">margin</Text>
<Text size="sm" fw={600}>
{!isNaN(stats.team2AvgMargin) ? stats.team2AvgMargin.toFixed(1) : '0.0'}
</Text>
</Group>
</Group>
</Stack>
</Paper>
</Stack>
<Stack gap="xs">
<Text size="sm" fw={600} px="md">Match History ({totalMatches} match{totalMatches !== 1 ? 'es' : ''})</Text>
<MatchList matches={matches} hideH2H />
</Stack>
</Stack>
);
};
const TeamHeadToHeadSheet = (props: TeamHeadToHeadSheetProps) => {
return (
<Suspense fallback={<TeamHeadToHeadSkeleton />}>
<TeamHeadToHeadContent {...props} />
</Suspense>
);
};
export default TeamHeadToHeadSheet;

View File

@@ -0,0 +1,72 @@
import { Stack, Skeleton, Group, Paper, Divider } from "@mantine/core";
const TeamHeadToHeadSkeleton = () => {
return (
<Stack gap="md">
<Paper p="md" withBorder radius="md">
<Stack gap="sm">
<Group justify="center" gap="xs">
<Skeleton height={28} width={140} />
<Skeleton height={20} width={20} />
<Skeleton height={28} width={140} />
</Group>
<Group justify="center" gap="lg">
<Stack gap={0} align="center">
<Skeleton height={32} width={40} />
<Skeleton height={16} width={100} mt={4} />
</Stack>
<Skeleton height={24} width={10} />
<Stack gap={0} align="center">
<Skeleton height={32} width={40} />
<Skeleton height={16} width={100} mt={4} />
</Stack>
</Group>
<Group justify="center">
<Skeleton height={16} width={150} />
</Group>
</Stack>
</Paper>
<Stack gap={0}>
<Skeleton height={18} width={130} ml="md" mb="xs" />
<Paper withBorder>
<Stack gap={0}>
<Group justify="space-between" px="md" py="sm">
<Skeleton height={20} width={60} />
<Skeleton height={16} width={80} />
<Skeleton height={20} width={60} />
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Skeleton height={20} width={60} />
<Skeleton height={16} width={100} />
<Skeleton height={20} width={60} />
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Skeleton height={20} width={60} />
<Skeleton height={16} width={110} />
<Skeleton height={20} width={60} />
</Group>
</Stack>
</Paper>
</Stack>
<Stack gap="xs">
<Skeleton height={18} width={150} ml="md" />
<Stack gap="sm" p="md">
<Skeleton height={100} />
<Skeleton height={100} />
<Skeleton height={100} />
</Stack>
</Stack>
</Stack>
);
};
export default TeamHeadToHeadSkeleton;

View File

@@ -0,0 +1,30 @@
import { useServerSuspenseQuery } from "@/lib/tanstack-query/hooks";
import { getMatchesBetweenTeams, getMatchesBetweenPlayers } from "./server";
export const matchKeys = {
headToHeadTeams: (team1Id: string, team2Id: string) => ['matches', 'headToHead', 'teams', team1Id, team2Id] as const,
headToHeadPlayers: (player1Id: string, player2Id: string) => ['matches', 'headToHead', 'players', player1Id, player2Id] as const,
};
export const matchQueries = {
headToHeadTeams: (team1Id: string, team2Id: string) => ({
queryKey: matchKeys.headToHeadTeams(team1Id, team2Id),
queryFn: () => getMatchesBetweenTeams({ data: { team1Id, team2Id } }),
}),
headToHeadPlayers: (player1Id: string, player2Id: string) => ({
queryKey: matchKeys.headToHeadPlayers(player1Id, player2Id),
queryFn: () => getMatchesBetweenPlayers({ data: { player1Id, player2Id } }),
}),
};
export const useTeamHeadToHead = (team1Id: string, team2Id: string, enabled = true) =>
useServerSuspenseQuery({
...matchQueries.headToHeadTeams(team1Id, team2Id),
enabled,
});
export const usePlayerHeadToHead = (player1Id: string, player2Id: string, enabled = true) =>
useServerSuspenseQuery({
...matchQueries.headToHeadPlayers(player1Id, player2Id),
enabled,
});

View File

@@ -5,7 +5,7 @@ import { logger } from "@/lib/logger";
import { z } from "zod"; import { z } from "zod";
import { toServerResult } from "@/lib/tanstack-query/utils/to-server-result"; import { toServerResult } from "@/lib/tanstack-query/utils/to-server-result";
import brackets from "@/features/bracket/utils"; import brackets from "@/features/bracket/utils";
import { MatchInput } from "@/features/matches/types"; import { Match, MatchInput } from "@/features/matches/types";
import { serverEvents } from "@/lib/events/emitter"; import { serverEvents } from "@/lib/events/emitter";
import { superTokensFunctionMiddleware } from "@/utils/supertokens"; import { superTokensFunctionMiddleware } from "@/utils/supertokens";
import { PlayerInfo } from "../players/types"; import { PlayerInfo } from "../players/types";
@@ -164,6 +164,294 @@ export const startMatch = createServerFn()
}) })
); );
export const populateKnockoutBracket = createServerFn()
.inputValidator(z.object({
tournamentId: z.string(),
}))
.middleware([superTokensAdminFunctionMiddleware, serverFnLoggingMiddleware])
.handler(async ({ data: { tournamentId } }) =>
toServerResult(async () => {
const tournament = await pbAdmin.getTournament(tournamentId);
if (!tournament) {
throw new Error("Tournament not found");
}
if (!tournament.group_config) {
throw new Error("Tournament must have group_config");
}
return await populateKnockoutBracketInternal(tournamentId, tournament.group_config);
})
);
async function populateKnockoutBracketInternal(tournamentId: string, groupConfig: { num_groups: number; advance_per_group: number }) {
logger.info('Populating knockout bracket', { tournamentId });
const groups = await pbAdmin.getGroupsByTournament(tournamentId);
if (!groups || groups.length === 0) {
throw new Error("No groups found for tournament");
}
const qualifiedTeams: { teamId: string; groupOrder: number; rank: number }[] = [];
for (const group of groups) {
logger.info('Processing group', {
groupId: group.id,
groupOrder: group.order,
teamsCount: group.teams?.length,
teams: group.teams
});
const groupMatches = await pbAdmin.getMatchesByGroup(group.id);
const completedMatches = groupMatches.filter(m => m.status === "ended");
const standings = new Map<string, { teamId: string; wins: number; losses: number; cups_for: number; cups_against: number; cup_differential: number }>();
for (const team of group.teams || []) {
// group.teams can be either team objects or just team ID strings
const teamId = typeof team === 'string' ? team : team.id;
standings.set(teamId, {
teamId,
wins: 0,
losses: 0,
cups_for: 0,
cups_against: 0,
cup_differential: 0,
});
}
for (const match of completedMatches) {
if (!match.home || !match.away) continue;
const homeStanding = standings.get(match.home.id);
const awayStanding = standings.get(match.away.id);
if (homeStanding && awayStanding) {
homeStanding.cups_for += match.home_cups;
homeStanding.cups_against += match.away_cups;
awayStanding.cups_for += match.away_cups;
awayStanding.cups_against += match.home_cups;
if (match.home_cups > match.away_cups) {
homeStanding.wins++;
awayStanding.losses++;
} else {
awayStanding.wins++;
homeStanding.losses++;
}
homeStanding.cup_differential = homeStanding.cups_for - homeStanding.cups_against;
awayStanding.cup_differential = awayStanding.cups_for - awayStanding.cups_against;
}
}
const sortedStandings = Array.from(standings.values()).sort((a, b) => {
if (b.wins !== a.wins) return b.wins - a.wins;
if (b.cup_differential !== a.cup_differential) return b.cup_differential - a.cup_differential;
return b.cups_for - a.cups_for;
});
const topTeams = sortedStandings.slice(0, groupConfig.advance_per_group);
logger.info('Top teams from group', {
groupId: group.id,
topTeams: topTeams.map(t => ({ teamId: t.teamId, wins: t.wins, cupDiff: t.cup_differential }))
});
topTeams.forEach((standing, index) => {
qualifiedTeams.push({
teamId: standing.teamId,
groupOrder: group.order,
rank: index + 1,
});
});
}
logger.info('Qualified teams', { qualifiedTeams });
const orderedTeamIds: string[] = [];
const maxRank = groupConfig.advance_per_group;
const numGroups = groupConfig.num_groups;
const teamsByGroup: string[][] = [];
for (let g = 0; g < numGroups; g++) {
teamsByGroup[g] = [];
}
for (const qualified of qualifiedTeams) {
teamsByGroup[qualified.groupOrder][qualified.rank - 1] = qualified.teamId;
}
const totalQualifiedTeams = numGroups * maxRank;
for (let i = 0; i < totalQualifiedTeams / 2; i++) {
const group1 = i % numGroups;
const rankIndex1 = Math.floor(i / numGroups);
const group2 = (i + 1) % numGroups;
const rankIndex2 = maxRank - 1 - rankIndex1;
const team1 = teamsByGroup[group1]?.[rankIndex1];
const team2 = teamsByGroup[group2]?.[rankIndex2];
if (team1) orderedTeamIds.push(team1);
if (team2) orderedTeamIds.push(team2);
}
const knockoutTeamCount = orderedTeamIds.length;
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(knockoutTeamCount)));
const wildcardsNeeded = nextPowerOf2 - knockoutTeamCount;
if (wildcardsNeeded > 0) {
logger.info('Wildcards needed', { knockoutTeamCount, nextPowerOf2, wildcardsNeeded });
const allNonQualifiedTeams: Array<{ teamId: string; wins: number; losses: number; cups_for: number; cups_against: number; cup_differential: number }> = [];
const qualifiedTeamIds = new Set(qualifiedTeams.map(t => t.teamId));
for (const group of groups) {
const groupMatches = await pbAdmin.getMatchesByGroup(group.id);
const completedMatches = groupMatches.filter(m => m.status === "ended");
const standings = new Map<string, { teamId: string; wins: number; losses: number; cups_for: number; cups_against: number; cup_differential: number }>();
for (const team of group.teams || []) {
const teamId = typeof team === 'string' ? team : team.id;
if (qualifiedTeamIds.has(teamId)) continue;
standings.set(teamId, {
teamId,
wins: 0,
losses: 0,
cups_for: 0,
cups_against: 0,
cup_differential: 0,
});
}
for (const match of completedMatches) {
if (!match.home || !match.away) continue;
const homeStanding = standings.get(match.home.id);
const awayStanding = standings.get(match.away.id);
if (homeStanding) {
homeStanding.cups_for += match.home_cups;
homeStanding.cups_against += match.away_cups;
homeStanding.cup_differential = homeStanding.cups_for - homeStanding.cups_against;
if (match.home_cups > match.away_cups) {
homeStanding.wins++;
} else {
homeStanding.losses++;
}
}
if (awayStanding) {
awayStanding.cups_for += match.away_cups;
awayStanding.cups_against += match.home_cups;
awayStanding.cup_differential = awayStanding.cups_for - awayStanding.cups_against;
if (match.away_cups > match.home_cups) {
awayStanding.wins++;
} else {
awayStanding.losses++;
}
}
}
allNonQualifiedTeams.push(...Array.from(standings.values()));
}
allNonQualifiedTeams.sort((a, b) => {
if (b.wins !== a.wins) return b.wins - a.wins;
if (b.cup_differential !== a.cup_differential) return b.cup_differential - a.cup_differential;
if (b.cups_for !== a.cups_for) return b.cups_for - a.cups_for;
return a.teamId.localeCompare(b.teamId);
});
const wildcardTeams = allNonQualifiedTeams.slice(0, wildcardsNeeded);
const wildcardTeamIds = wildcardTeams.map(t => t.teamId);
orderedTeamIds.push(...wildcardTeamIds);
logger.info('Added wildcard teams', {
wildcardTeams: wildcardTeams.map(t => ({
teamId: t.teamId,
wins: t.wins,
cupDiff: t.cup_differential,
cupsFor: t.cups_for
}))
});
}
logger.info('Ordered team IDs (with wildcards)', { orderedTeamIds, totalTeams: orderedTeamIds.length });
const tournament = await pbAdmin.getTournament(tournamentId);
const knockoutMatches = (tournament.matches || [])
.filter((m: Match) => m.round >= 0 && m.lid >= 0)
.sort((a: Match, b: Match) => a.lid - b.lid);
const seedToTeamId = new Map<number, string>();
orderedTeamIds.forEach((teamId, index) => {
seedToTeamId.set(index + 1, teamId);
});
logger.info('Seed to team mapping', {
seedToTeamId: Array.from(seedToTeamId.entries()),
orderedTeamIds
});
let updatedCount = 0;
for (const match of knockoutMatches) {
if (match.round === 0) {
const updates: any = {};
if (match.home_seed) {
const teamId = seedToTeamId.get(match.home_seed);
logger.info('Looking up home seed', {
matchId: match.id,
home_seed: match.home_seed,
teamId
});
if (teamId) {
updates.home = teamId;
}
}
if (match.away_seed) {
const teamId = seedToTeamId.get(match.away_seed);
logger.info('Looking up away seed', {
matchId: match.id,
away_seed: match.away_seed,
teamId
});
if (teamId) {
updates.away = teamId;
}
}
if (updates.home && updates.away) {
updates.status = "ready";
} else if (updates.home || updates.away) {
updates.status = "tbd";
}
if (Object.keys(updates).length > 0) {
logger.info('Updating match', { matchId: match.id, updates });
await pbAdmin.updateMatch(match.id, updates);
updatedCount++;
}
}
}
logger.info('Updated matches', { updatedCount, totalKnockoutMatches: knockoutMatches.length });
await pbAdmin.updateTournament(tournamentId, {
phase: "knockout"
});
logger.info('Knockout bracket populated successfully', { tournamentId });
}
const endMatchSchema = z.object({ const endMatchSchema = z.object({
matchId: z.string(), matchId: z.string(),
home_cups: z.number(), home_cups: z.number(),
@@ -190,19 +478,25 @@ export const endMatch = createServerFn()
ot_count, ot_count,
}); });
if (match.lid === -1) {
serverEvents.emit("match", {
type: "match",
matchId: match.id,
tournamentId: match.tournament.id
});
return match;
}
const matchWinner = home_cups > away_cups ? match.home : match.away; const matchWinner = home_cups > away_cups ? match.home : match.away;
const matchLoser = home_cups < away_cups ? match.home : match.away; const matchLoser = home_cups < away_cups ? match.home : match.away;
if (!matchWinner || !matchLoser) throw new Error("Something went wrong"); if (!matchWinner || !matchLoser) throw new Error("Something went wrong");
// winner -> where to send match winner to, loser same
const { winner, loser } = await pbAdmin.getChildMatches(matchId); const { winner, loser } = await pbAdmin.getChildMatches(matchId);
// reset match check
if (winner && winner.reset) { if (winner && winner.reset) {
const awayTeamWon = match.away === matchWinner; const awayTeamWon = match.away === matchWinner;
if (!awayTeamWon) { if (!awayTeamWon) {
// Reset match is not necessary
logger.info("Deleting reset match", { logger.info("Deleting reset match", {
resetMatchId: winner.id, resetMatchId: winner.id,
currentMatchId: match.id, currentMatchId: match.id,
@@ -214,7 +508,6 @@ export const endMatch = createServerFn()
} }
} }
// advance bracket
if (winner) { if (winner) {
await pbAdmin.updateMatch(winner.id, { await pbAdmin.updateMatch(winner.id, {
[winner.home_from_lid === match.lid ? "home" : "away"]: matchWinner.id, [winner.home_from_lid === match.lid ? "home" : "away"]: matchWinner.id,
@@ -347,3 +640,35 @@ export const getMatchReactions = createServerFn()
return reactions as Reaction[] return reactions as Reaction[]
}) })
); );
const matchesBetweenPlayersSchema = z.object({
player1Id: z.string(),
player2Id: z.string(),
});
export const getMatchesBetweenPlayers = createServerFn()
.inputValidator(matchesBetweenPlayersSchema)
.middleware([superTokensFunctionMiddleware])
.handler(async ({ data: { player1Id, player2Id } }) =>
toServerResult(async () => {
logger.info("Getting matches between players", { player1Id, player2Id });
const matches = await pbAdmin.getMatchesBetweenPlayers(player1Id, player2Id);
return matches;
})
);
const matchesBetweenTeamsSchema = z.object({
team1Id: z.string(),
team2Id: z.string(),
});
export const getMatchesBetweenTeams = createServerFn()
.inputValidator(matchesBetweenTeamsSchema)
.middleware([superTokensFunctionMiddleware])
.handler(async ({ data: { team1Id, team2Id } }) =>
toServerResult(async () => {
logger.info("Getting matches between teams", { team1Id, team2Id });
const matches = await pbAdmin.getMatchesBetweenTeams(team1Id, team2Id);
return matches;
})
);

View File

@@ -3,6 +3,7 @@ import { TeamInfo, Team } from "../teams/types";
import { TournamentInfo } from "../tournaments/types"; import { TournamentInfo } from "../tournaments/types";
export type MatchStatus = "tbd" | "ready" | "started" | "ended"; export type MatchStatus = "tbd" | "ready" | "started" | "ended";
export type MatchType = "group_stage" | "knockout" | "winners" | "losers" | "bracket";
export interface Match { export interface Match {
id: string; id: string;
@@ -29,6 +30,8 @@ export interface Match {
updated: string; updated: string;
home_seed?: number; home_seed?: number;
away_seed?: number; away_seed?: number;
match_type?: MatchType;
group?: string;
} }
export const matchInputSchema = z.object({ export const matchInputSchema = z.object({
@@ -53,6 +56,8 @@ export const matchInputSchema = z.object({
away: z.string().min(1).optional(), away: z.string().min(1).optional(),
home_seed: z.number().int().min(1).optional(), home_seed: z.number().int().min(1).optional(),
away_seed: z.number().int().min(1).optional(), away_seed: z.number().int().min(1).optional(),
match_type: z.enum(["group_stage", "knockout", "winners", "losers", "bracket"]).optional(),
group: z.string().optional(),
}); });
export type MatchInput = z.infer<typeof matchInputSchema>; export type MatchInput = z.infer<typeof matchInputSchema>;

View File

@@ -0,0 +1,276 @@
import { Stack, Text, TextInput, Box, Paper, Group, Divider, Center, ActionIcon, Badge } from "@mantine/core";
import { useState, useMemo } from "react";
import { MagnifyingGlassIcon, XIcon, ArrowRightIcon } from "@phosphor-icons/react";
import { useAllPlayerStats } from "../queries";
import { useSheet } from "@/hooks/use-sheet";
import Sheet from "@/components/sheet/sheet";
import PlayerHeadToHeadSheet from "./player-head-to-head-sheet";
import PlayerAvatar from "@/components/player-avatar";
const LeagueHeadToHead = () => {
const [player1Id, setPlayer1Id] = useState<string | null>(null);
const [player2Id, setPlayer2Id] = useState<string | null>(null);
const [search, setSearch] = useState("");
const { data: allPlayerStats } = useAllPlayerStats();
const h2hSheet = useSheet();
const player1Name = useMemo(() => {
if (!player1Id || !allPlayerStats) return "";
return allPlayerStats.find((p) => p.player_id === player1Id)?.player_name || "";
}, [player1Id, allPlayerStats]);
const player2Name = useMemo(() => {
if (!player2Id || !allPlayerStats) return "";
return allPlayerStats.find((p) => p.player_id === player2Id)?.player_name || "";
}, [player2Id, allPlayerStats]);
const filteredPlayers = useMemo(() => {
if (!allPlayerStats) return [];
return allPlayerStats
.filter((stat) => {
if (player1Id && stat.player_id === player1Id) return false;
if (player2Id && stat.player_id === player2Id) return false;
return true;
})
.filter((stat) =>
stat.player_name.toLowerCase().includes(search.toLowerCase())
)
.sort((a, b) => b.matches - a.matches);
}, [allPlayerStats, player1Id, player2Id, search]);
const handlePlayerClick = (playerId: string) => {
if (!player1Id) {
setPlayer1Id(playerId);
} else if (!player2Id) {
setPlayer2Id(playerId);
h2hSheet.open();
}
};
const handleClearPlayer1 = () => {
setPlayer1Id(null);
if (player2Id) {
setPlayer1Id(player2Id);
setPlayer2Id(null);
}
};
const handleClearPlayer2 = () => {
setPlayer2Id(null);
};
const activeStep = !player1Id ? 1 : !player2Id ? 2 : 0;
return (
<>
<Stack gap="md">
<Paper px="md" pt="md" pb="sm" withBorder shadow="sm">
<Stack gap="xs">
<Group gap="xs" wrap="nowrap">
<Paper
p="sm"
withBorder
style={{
flex: 1,
minHeight: 70,
display: "flex",
alignItems: "center",
justifyContent: "center",
position: "relative",
borderWidth: 2,
borderColor: activeStep === 1 ? "var(--mantine-primary-color-filled)" : undefined,
backgroundColor: player1Id && activeStep !== 1 ? "var(--mantine-color-default-hover)" : undefined,
cursor: player1Id && activeStep === 0 ? "pointer" : undefined,
transition: "all 150ms ease",
}}
onClick={player1Id && activeStep === 0 ? handleClearPlayer1 : undefined}
>
{player1Id ? (
<>
<Stack gap={4} align="center" style={{ flex: 1 }}>
<PlayerAvatar name={player1Name} size={36} disableFullscreen />
<Text size="xs" fw={600} ta="center" lineClamp={1}>
{player1Name}
</Text>
</Stack>
<ActionIcon
variant="light"
color="gray"
size="xs"
radius="xl"
onClick={(e) => {
e.stopPropagation();
handleClearPlayer1();
}}
style={{ position: "absolute", top: 4, right: 4 }}
>
<XIcon size={10} />
</ActionIcon>
</>
) : (
<Stack gap={4} align="center">
<PlayerAvatar size={36} disableFullscreen />
<Text size="xs" c="dimmed" fw={500}>
Player 1
</Text>
</Stack>
)}
</Paper>
<Center>
<Text size="xl" fw={700} c="dimmed">
VS
</Text>
</Center>
<Paper
p="sm"
withBorder
style={{
flex: 1,
minHeight: 70,
display: "flex",
alignItems: "center",
justifyContent: "center",
position: "relative",
borderWidth: 2,
borderColor: activeStep === 2 ? "var(--mantine-primary-color-filled)" : undefined,
backgroundColor: player2Id && activeStep !== 2 ? "var(--mantine-color-default-hover)" : undefined,
cursor: player2Id && activeStep === 0 ? "pointer" : undefined,
transition: "all 150ms ease",
}}
onClick={player2Id && activeStep === 0 ? handleClearPlayer2 : undefined}
>
{player2Id ? (
<>
<Stack gap={4} align="center" style={{ flex: 1 }}>
<PlayerAvatar name={player2Name} size={36} disableFullscreen />
<Text size="xs" fw={600} ta="center" lineClamp={1}>
{player2Name}
</Text>
</Stack>
<ActionIcon
variant="light"
color="gray"
size="xs"
radius="xl"
onClick={(e) => {
e.stopPropagation();
handleClearPlayer2();
}}
style={{ position: "absolute", top: 4, right: 4 }}
>
<XIcon size={10} />
</ActionIcon>
</>
) : (
<Stack gap={4} align="center">
<PlayerAvatar size={36} disableFullscreen />
<Text size="xs" c="dimmed" fw={500}>
Player 2
</Text>
</Stack>
)}
</Paper>
</Group>
{activeStep > 0 ? (
<Badge
variant="light"
size="sm"
radius="sm"
fullWidth
styles={{ label: { textTransform: "none" } }}
>
{activeStep === 1 && "Select first player"}
{activeStep === 2 && "Select second player"}
</Badge>
) : (
<Group justify="center">
<Text
size="xs"
c="dimmed"
style={{ cursor: "pointer" }}
onClick={() => {
setPlayer1Id(null);
setPlayer2Id(null);
}}
td="underline"
>
Clear both players
</Text>
</Group>
)}
</Stack>
</Paper>
<TextInput
placeholder="Search players"
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
leftSection={<MagnifyingGlassIcon size={16} />}
size="md"
px="md"
/>
<Box px="md" pb="md">
<Paper withBorder>
{filteredPlayers.length === 0 && (
<Text size="sm" c="dimmed" ta="center" py="xl">
{search ? `No players found matching "${search}"` : "No players available"}
</Text>
)}
{filteredPlayers.map((player, index) => (
<Box key={player.player_id}>
<Group
p="md"
gap="sm"
wrap="nowrap"
style={{
cursor: "pointer",
transition: "background-color 150ms ease",
}}
onClick={() => handlePlayerClick(player.player_id)}
styles={{
root: {
"&:hover": {
backgroundColor: "var(--mantine-color-default-hover)",
},
},
}}
>
<PlayerAvatar name={player.player_name} size={44} disableFullscreen />
<Box style={{ flex: 1, minWidth: 0 }}>
<Text size="sm" fw={600} truncate>
{player.player_name}
</Text>
</Box>
<ActionIcon variant="subtle" color="gray" size="lg" radius="xl">
<ArrowRightIcon size={18} />
</ActionIcon>
</Group>
{index < filteredPlayers.length - 1 && <Divider />}
</Box>
))}
</Paper>
</Box>
</Stack>
{player1Id && player2Id && (
<Sheet title="Head to Head" {...h2hSheet.props}>
<PlayerHeadToHeadSheet
player1Id={player1Id}
player1Name={player1Name}
player2Id={player2Id}
player2Name={player2Name}
isOpen={h2hSheet.props.opened}
/>
</Sheet>
)}
</>
);
};
export default LeagueHeadToHead;

View File

@@ -0,0 +1,279 @@
import { Stack, Text, Group, Box, Divider, Paper } from "@mantine/core";
import { usePlayerHeadToHead } from "@/features/matches/queries";
import { useMemo, useEffect, useState, Suspense } from "react";
import { CrownIcon } from "@phosphor-icons/react";
import MatchList from "@/features/matches/components/match-list";
import PlayerHeadToHeadSkeleton from "./player-head-to-head-skeleton";
interface PlayerHeadToHeadSheetProps {
player1Id: string;
player1Name: string;
player2Id: string;
player2Name: string;
isOpen?: boolean;
}
const PlayerHeadToHeadContent = ({
player1Id,
player1Name,
player2Id,
player2Name,
isOpen = true,
}: PlayerHeadToHeadSheetProps) => {
const [shouldFetch, setShouldFetch] = useState(false);
useEffect(() => {
if (isOpen && !shouldFetch) {
setShouldFetch(true);
}
}, [isOpen, shouldFetch]);
const { data: matches, isLoading } = usePlayerHeadToHead(player1Id, player2Id, shouldFetch);
const stats = useMemo(() => {
if (!matches || matches.length === 0) {
return {
player1Wins: 0,
player2Wins: 0,
player1CupsFor: 0,
player2CupsFor: 0,
player1CupsAgainst: 0,
player2CupsAgainst: 0,
player1AvgMargin: 0,
player2AvgMargin: 0,
};
}
let player1Wins = 0;
let player2Wins = 0;
let player1CupsFor = 0;
let player2CupsFor = 0;
let player1CupsAgainst = 0;
let player2CupsAgainst = 0;
let player1TotalWinMargin = 0;
let player2TotalWinMargin = 0;
matches.forEach((match) => {
const isPlayer1Home = match.home?.players?.some((p) => p.id === player1Id);
const player1Cups = isPlayer1Home ? match.home_cups : match.away_cups;
const player2Cups = isPlayer1Home ? match.away_cups : match.home_cups;
if (player1Cups > player2Cups) {
player1Wins++;
player1TotalWinMargin += (player1Cups - player2Cups);
} else if (player2Cups > player1Cups) {
player2Wins++;
player2TotalWinMargin += (player2Cups - player1Cups);
}
player1CupsFor += player1Cups;
player2CupsFor += player2Cups;
player1CupsAgainst += player2Cups;
player2CupsAgainst += player1Cups;
});
const player1AvgMargin =
player1Wins > 0 ? player1TotalWinMargin / player1Wins : 0;
const player2AvgMargin =
player2Wins > 0 ? player2TotalWinMargin / player2Wins : 0;
return {
player1Wins,
player2Wins,
player1CupsFor,
player2CupsFor,
player1CupsAgainst,
player2CupsAgainst,
player1AvgMargin,
player2AvgMargin,
};
}, [matches, player1Id]);
if (isLoading) {
return (
<Stack p="md" gap="md">
<Text size="sm" c="dimmed" ta="center">
Loading...
</Text>
</Stack>
);
}
if (!matches || matches.length === 0) {
return (
<Stack p="md" gap="md">
<Text size="sm" c="dimmed" ta="center">
These players have not faced each other yet.
</Text>
</Stack>
);
}
const totalMatches = stats.player1Wins + stats.player2Wins;
const leader =
stats.player1Wins > stats.player2Wins
? player1Name
: stats.player2Wins > stats.player1Wins
? player2Name
: null;
return (
<Stack gap="md">
<Paper p="md" withBorder radius="md">
<Stack gap="sm">
<Group justify="center" gap="xs">
<Text size="lg" fw={700}>
{player1Name}
</Text>
<Text size="sm" c="dimmed">
vs
</Text>
<Text size="lg" fw={700}>
{player2Name}
</Text>
</Group>
<Group justify="center" gap="lg">
<Stack gap={0} align="center">
<Text size="xl" fw={700}>
{stats.player1Wins}
</Text>
<Text size="xs" c="dimmed">
{player1Name}
</Text>
</Stack>
<Text size="md" c="dimmed">
-
</Text>
<Stack gap={0} align="center">
<Text size="xl" fw={700}>
{stats.player2Wins}
</Text>
<Text size="xs" c="dimmed">
{player2Name}
</Text>
</Stack>
</Group>
{leader && (
<Group justify="center" gap="xs">
<CrownIcon size={16} weight="fill" color="gold" />
<Text size="xs" c="dimmed">
{leader} leads the series
</Text>
</Group>
)}
{!leader && totalMatches > 0 && (
<Text size="xs" c="dimmed" ta="center">
Series is tied
</Text>
)}
</Stack>
</Paper>
<Stack gap={0}>
<Text size="sm" fw={600} px="md" mb="xs">
Stats Comparison
</Text>
<Paper withBorder>
<Stack gap={0}>
<Group justify="space-between" px="md" py="sm">
<Group gap="xs">
<Text size="sm" fw={600}>
{stats.player1CupsFor}
</Text>
<Text size="xs" c="dimmed">
cups
</Text>
</Group>
<Text size="xs" fw={500}>
Total Cups
</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">
cups
</Text>
<Text size="sm" fw={600}>
{stats.player2CupsFor}
</Text>
</Group>
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Group gap="xs">
<Text size="sm" fw={600}>
{totalMatches > 0
? (stats.player1CupsFor / totalMatches).toFixed(1)
: "0.0"}
</Text>
<Text size="xs" c="dimmed">
avg
</Text>
</Group>
<Text size="xs" fw={500}>
Avg Cups/Match
</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">
avg
</Text>
<Text size="sm" fw={600}>
{totalMatches > 0
? (stats.player2CupsFor / totalMatches).toFixed(1)
: "0.0"}
</Text>
</Group>
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Group gap="xs">
<Text size="sm" fw={600}>
{!isNaN(stats.player1AvgMargin)
? stats.player1AvgMargin.toFixed(1)
: "0.0"}
</Text>
<Text size="xs" c="dimmed">
margin
</Text>
</Group>
<Text size="xs" fw={500}>
Avg Win Margin
</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">
margin
</Text>
<Text size="sm" fw={600}>
{!isNaN(stats.player2AvgMargin)
? stats.player2AvgMargin.toFixed(1)
: "0.0"}
</Text>
</Group>
</Group>
</Stack>
</Paper>
</Stack>
<Stack gap="xs">
<Text size="sm" fw={600} px="md">
Match History ({totalMatches})
</Text>
<MatchList matches={matches} hideH2H />
</Stack>
</Stack>
);
};
const PlayerHeadToHeadSheet = (props: PlayerHeadToHeadSheetProps) => {
return (
<Suspense fallback={<PlayerHeadToHeadSkeleton />}>
<PlayerHeadToHeadContent {...props} />
</Suspense>
);
};
export default PlayerHeadToHeadSheet;

View File

@@ -0,0 +1,72 @@
import { Stack, Skeleton, Group, Paper, Divider } from "@mantine/core";
const PlayerHeadToHeadSkeleton = () => {
return (
<Stack gap="md">
<Paper p="md" withBorder radius="md">
<Stack gap="sm">
<Group justify="center" gap="xs">
<Skeleton height={28} width={120} />
<Skeleton height={20} width={20} />
<Skeleton height={28} width={120} />
</Group>
<Group justify="center" gap="lg">
<Stack gap={0} align="center">
<Skeleton height={32} width={40} />
<Skeleton height={16} width={80} mt={4} />
</Stack>
<Skeleton height={24} width={10} />
<Stack gap={0} align="center">
<Skeleton height={32} width={40} />
<Skeleton height={16} width={80} mt={4} />
</Stack>
</Group>
<Group justify="center">
<Skeleton height={16} width={150} />
</Group>
</Stack>
</Paper>
<Stack gap={0}>
<Skeleton height={18} width={130} ml="md" mb="xs" />
<Paper withBorder>
<Stack gap={0}>
<Group justify="space-between" px="md" py="sm">
<Skeleton height={20} width={60} />
<Skeleton height={16} width={80} />
<Skeleton height={20} width={60} />
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Skeleton height={20} width={60} />
<Skeleton height={16} width={100} />
<Skeleton height={20} width={60} />
</Group>
<Divider />
<Group justify="space-between" px="md" py="sm">
<Skeleton height={20} width={60} />
<Skeleton height={16} width={110} />
<Skeleton height={20} width={60} />
</Group>
</Stack>
</Paper>
</Stack>
<Stack gap="xs">
<Skeleton height={18} width={130} ml="md" />
<Stack gap="sm" p="md">
<Skeleton height={100} />
<Skeleton height={100} />
<Skeleton height={100} />
</Stack>
</Stack>
</Stack>
);
};
export default PlayerHeadToHeadSkeleton;

View File

@@ -1,6 +1,6 @@
import { List, ListItem, Skeleton, Text } from "@mantine/core"; import { List, ListItem, Skeleton, Text } from "@mantine/core";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import Avatar from "@/components/avatar"; import PlayerAvatar from "@/components/player-avatar";
import { Player } from "@/features/players/types"; import { Player } from "@/features/players/types";
import { useCallback } from "react"; import { useCallback } from "react";
@@ -29,7 +29,7 @@ const PlayerList = ({ players, loading = false }: PlayerListProps) => {
{players?.map((player) => ( {players?.map((player) => (
<ListItem key={player.id} <ListItem key={player.id}
py='xs' py='xs'
icon={<Avatar size={40} name={`${player.first_name} ${player.last_name}`} />} icon={<PlayerAvatar size={40} name={`${player.first_name} ${player.last_name}`} disableFullscreen />}
style={{ cursor: 'pointer' }} style={{ cursor: 'pointer' }}
onClick={() => handleClick(player.id)} onClick={() => handleClick(player.id)}
> >

View File

@@ -5,68 +5,86 @@ import {
Container, Container,
Divider, Divider,
Skeleton, Skeleton,
ScrollArea,
} from "@mantine/core"; } from "@mantine/core";
const PlayerListItemSkeleton = () => { const PlayerListItemSkeleton = () => {
return ( return (
<Box p="md"> <Box p="md">
<Group justify="space-between" align="center" w="100%"> <Group gap="sm" align="center" w="100%" wrap="nowrap" style={{ overflow: 'hidden' }}>
<Group gap="sm" align="center"> <Skeleton height={40} width={40} circle style={{ flexShrink: 0 }} />
<Skeleton height={45} circle /> <Stack gap={2} style={{ flexGrow: 1, overflow: 'hidden', minWidth: 0 }}>
<Stack gap={2}> <Group gap='xs'>
<Group gap='xs'> <Skeleton height={16} width={120} />
<Skeleton height={16} width={120} /> <Skeleton height={12} width={30} />
<Skeleton height={12} width={60} /> <Skeleton height={12} width={30} />
<Skeleton height={12} width={80} /> </Group>
</Group>
<Group gap="md" ta="center"> <ScrollArea type="never">
<Stack gap={0}> <Group gap='xs' wrap="nowrap">
<Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={25} /> <Skeleton height={10} width={25} />
<Skeleton height={10} width={30} /> <Skeleton height={10} width={30} />
</Stack> </Stack>
<Stack gap={0}> <Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={10} /> <Skeleton height={10} width={10} />
<Skeleton height={10} width={15} /> <Skeleton height={10} width={15} />
</Stack> </Stack>
<Stack gap={0}> <Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={10} /> <Skeleton height={10} width={10} />
<Skeleton height={10} width={15} /> <Skeleton height={10} width={15} />
</Stack> </Stack>
<Stack gap={0}> <Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={20} /> <Skeleton height={10} width={20} />
<Skeleton height={10} width={25} /> <Skeleton height={10} width={25} />
</Stack> </Stack>
<Stack gap={0}> <Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={25} /> <Skeleton height={10} width={25} />
<Skeleton height={10} width={20} /> <Skeleton height={10} width={20} />
</Stack> </Stack>
<Stack gap={0}> <Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={25} />
<Skeleton height={10} width={20} />
</Stack>
<Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={30} />
<Skeleton height={10} width={25} />
</Stack>
<Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={30} />
<Skeleton height={10} width={25} />
</Stack>
<Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={15} /> <Skeleton height={10} width={15} />
<Skeleton height={10} width={25} /> <Skeleton height={10} width={25} />
</Stack> </Stack>
<Stack gap={0}> <Stack gap={0} style={{ flexShrink: 0 }}>
<Skeleton height={10} width={15} /> <Skeleton height={10} width={15} />
<Skeleton height={10} width={25} /> <Skeleton height={10} width={25} />
</Stack> </Stack>
</Group> </Group>
</Stack> </ScrollArea>
</Group> </Stack>
</Group> </Group>
</Box> </Box>
); );
}; };
const PlayerStatsTableSkeleton = () => { interface PlayerStatsTableSkeletonProps {
hideFilters?: boolean;
}
const PlayerStatsTableSkeleton = ({ hideFilters = false }: PlayerStatsTableSkeletonProps) => {
return ( return (
<Container size="100%" px={0}> <Container size="100%" px={0}>
<Stack gap="xs"> <Stack gap="xs">
<Box px="md" pb="xs"> <Skeleton mx="md" height={12} width={100} />
<Box px="md" pb={4}>
<Skeleton height={40} /> <Skeleton height={40} />
</Box> </Box>
<Group px="md" justify="space-between" align="center"> <Group justify="space-between" align="center" w='100%'>
<Skeleton height={12} width={100} /> <Group ml="auto" gap="xs">
<Group gap="xs">
<Skeleton height={12} width={200} /> <Skeleton height={12} width={200} />
</Group> </Group>
</Group> </Group>

View File

@@ -1,4 +1,4 @@
import { useState, useMemo, useCallback, memo } from "react"; import { useState, useMemo, useCallback, memo, useRef, useEffect } from "react";
import { import {
Text, Text,
TextInput, TextInput,
@@ -12,6 +12,7 @@ import {
UnstyledButton, UnstyledButton,
Popover, Popover,
ActionIcon, ActionIcon,
ScrollArea,
} from "@mantine/core"; } from "@mantine/core";
import { import {
MagnifyingGlassIcon, MagnifyingGlassIcon,
@@ -21,7 +22,7 @@ import {
InfoIcon, InfoIcon,
} from "@phosphor-icons/react"; } from "@phosphor-icons/react";
import { PlayerStats } from "../types"; import { PlayerStats } from "../types";
import Avatar from "@/components/avatar"; import PlayerAvatar from "@/components/player-avatar";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { useAllPlayerStats } from "../queries"; import { useAllPlayerStats } from "../queries";
@@ -37,9 +38,41 @@ interface PlayerListItemProps {
stat: PlayerStats; stat: PlayerStats;
onPlayerClick: (playerId: string) => void; onPlayerClick: (playerId: string) => void;
mmr: number; mmr: number;
onRegisterViewport: (viewport: HTMLDivElement) => void;
onUnregisterViewport: (viewport: HTMLDivElement) => void;
} }
const PlayerListItem = memo(({ stat, onPlayerClick, mmr }: PlayerListItemProps) => { interface StatCellProps {
label: string;
value: string | number;
}
const StatCell = memo(({ label, value }: StatCellProps) => (
<Stack justify="center" gap={0} style={{ textAlign: 'center', flexShrink: 0 }}>
<Text size="xs" c="dimmed" fw={700}>
{label}
</Text>
<Text size="xs" c="dimmed">
{value}
</Text>
</Stack>
));
const PlayerListItem = memo(({ stat, onPlayerClick, mmr, onRegisterViewport, onUnregisterViewport }: PlayerListItemProps) => {
const viewportRef = useRef<HTMLDivElement>(null);
const avg_cups_against = useMemo(() => stat.total_cups_against / stat.matches || 0, [stat.total_cups_against, stat.matches]);
useEffect(() => {
if (viewportRef.current) {
onRegisterViewport(viewportRef.current);
return () => {
if (viewportRef.current) {
onUnregisterViewport(viewportRef.current);
}
};
}
}, [onRegisterViewport, onUnregisterViewport]);
return ( return (
<> <>
@@ -59,90 +92,62 @@ const PlayerListItem = memo(({ stat, onPlayerClick, mmr }: PlayerListItemProps)
}, },
}} }}
> >
<Group justify="space-between" align="center" w="100%"> <Group p={0} gap="sm" align="center" w="100%" wrap="nowrap" style={{ overflow: 'hidden' }}>
<Group gap="sm" align="center"> <PlayerAvatar name={stat.player_name} size={40} style={{ flexShrink: 0 }} disableFullscreen />
<Avatar name={stat.player_name} size={40} /> <Stack gap={2} style={{ flexGrow: 1, overflow: 'hidden', minWidth: 0 }}>
<Stack gap={2}> <Group gap='xs'>
<Group gap='xs'> <Text size="sm" fw={600}>
<Text size="sm" fw={600}> {stat.player_name}
{stat.player_name} </Text>
</Text> <Text size="xs" c="dimmed" ta="right">
<Text size="xs" c="dimmed" ta="right"> {stat.matches}
{stat.matches} matches <Text span fw={800}>M</Text>
</Text> </Text>
<Text size="xs" c="dimmed" ta="right"> <Text size="xs" c="dimmed" ta="right">
{stat.tournaments} tournaments {stat.tournaments}
</Text> <Text span fw={800}>T</Text>
</Group> </Text>
<Group gap="md" ta="center"> </Group>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
MMR
</Text>
<Text size="xs" c="dimmed">
{mmr.toFixed(1)}
</Text>
</Stack>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
W
</Text>
<Text size="xs" c="dimmed">
{stat.wins}
</Text>
</Stack>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
L
</Text>
<Text size="xs" c="dimmed">
{stat.losses}
</Text>
</Stack>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
W%
</Text>
<Text size="xs" c="dimmed">
{stat.win_percentage.toFixed(1)}%
</Text>
</Stack>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
AVG
</Text>
<Text size="xs" c="dimmed">
{stat.avg_cups_per_match.toFixed(1)}
</Text>
</Stack>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
CF
</Text>
<Text size="xs" c="dimmed">
{stat.total_cups_made}
</Text>
</Stack>
<Stack gap={0}>
<Text size="xs" c="dimmed" fw={700}>
CA
</Text>
<Text size="xs" c="dimmed">
{stat.total_cups_against}
</Text>
</Stack>
</Group>
</Stack>
</Group>
<ScrollArea
viewportRef={viewportRef}
type="never"
styles={{
viewport: {
WebkitOverflowScrolling: 'touch',
scrollBehavior: 'auto',
willChange: 'scroll-position',
transform: 'translateZ(0)',
backfaceVisibility: 'hidden',
},
}}
>
<Group gap='xs' wrap="nowrap">
<StatCell label="MMR" value={mmr.toFixed(1)} />
<StatCell label="W" value={stat.wins} />
<StatCell label="L" value={stat.losses} />
<StatCell label="W%" value={`${stat.win_percentage.toFixed(1)}%`} />
<StatCell label="AWM" value={stat.margin_of_victory?.toFixed(1) || 0} />
<StatCell label="ALM" value={stat.margin_of_loss?.toFixed(1) || 0} />
<StatCell label="AC" value={stat.avg_cups_per_match.toFixed(1)} />
<StatCell label="ACA" value={avg_cups_against?.toFixed(1) || 0} />
<StatCell label="CF" value={stat.total_cups_made} />
<StatCell label="CA" value={stat.total_cups_against} />
</Group>
</ScrollArea>
</Stack>
</Group> </Group>
</UnstyledButton> </UnstyledButton>
</> </>
); );
}); });
const PlayerStatsTable = () => { interface PlayerStatsTableProps {
const { data: playerStats } = useAllPlayerStats(); viewType?: 'all' | 'mainline' | 'regional';
}
const PlayerStatsTable = ({ viewType = 'all' }: PlayerStatsTableProps) => {
const { data: playerStats } = useAllPlayerStats(viewType);
const navigate = useNavigate(); const navigate = useNavigate();
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [sortConfig, setSortConfig] = useState<SortConfig>({ const [sortConfig, setSortConfig] = useState<SortConfig>({
@@ -150,6 +155,64 @@ const PlayerStatsTable = () => {
direction: "desc", direction: "desc",
}); });
const viewportsRef = useRef<Set<HTMLDivElement>>(new Set());
const scrollHandlersRef = useRef<Map<HTMLDivElement, (e: Event) => void>>(new Map());
const scrollLeaderRef = useRef<HTMLDivElement | null>(null);
const scrollTimeoutRef = useRef<number | null>(null);
const handleRegisterViewport = useCallback((viewport: HTMLDivElement) => {
viewportsRef.current.add(viewport);
const handleScrollStart = () => {
scrollLeaderRef.current = viewport;
};
const handleScroll = (e: Event) => {
const target = e.target as HTMLDivElement;
if (!scrollLeaderRef.current) {
scrollLeaderRef.current = target;
}
if (scrollLeaderRef.current !== target) {
return;
}
const scrollLeft = target.scrollLeft;
viewportsRef.current.forEach((vp) => {
if (vp !== target && Math.abs(vp.scrollLeft - scrollLeft) > 0.5) {
vp.scrollLeft = scrollLeft;
}
});
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current);
}
scrollTimeoutRef.current = window.setTimeout(() => {
scrollLeaderRef.current = null;
}, 150);
};
viewport.addEventListener('touchstart', handleScrollStart, { passive: true });
viewport.addEventListener('mousedown', handleScrollStart, { passive: true });
viewport.addEventListener('scroll', handleScroll, { passive: true });
scrollHandlersRef.current.set(viewport, handleScroll);
}, []);
const handleUnregisterViewport = useCallback((viewport: HTMLDivElement) => {
viewportsRef.current.delete(viewport);
const handler = scrollHandlersRef.current.get(viewport);
if (handler) {
viewport.removeEventListener('scroll', handler);
viewport.removeEventListener('touchstart', handler);
viewport.removeEventListener('mousedown', handler);
scrollHandlersRef.current.delete(viewport);
}
}, []);
const calculateMMR = (stat: PlayerStats): number => { const calculateMMR = (stat: PlayerStats): number => {
if (stat.matches === 0) return 0; if (stat.matches === 0) return 0;
@@ -233,22 +296,23 @@ const PlayerStatsTable = () => {
if (playerStats.length === 0) { if (playerStats.length === 0) {
return ( return (
<Container px={0} size="md"> <Stack align="center" gap="md" py="xl">
<Stack align="center" gap="md" py="xl"> <ThemeIcon size="xl" variant="light" radius="md">
<ThemeIcon size="xl" variant="light" radius="md"> <ChartBarIcon size={32} />
<ChartBarIcon size={32} /> </ThemeIcon>
</ThemeIcon> <Title order={3} c="dimmed">
<Title order={3} c="dimmed"> No Stats Available
No Stats Available </Title>
</Title> </Stack>
</Stack>
</Container>
); );
} }
return ( return (
<Container size="100%" px={0}> <Container size="100%" px={0}>
<Stack gap="xs"> <Stack gap="xs">
<Text px="md" size="10px" lh={0} c="dimmed">
Showing {filteredAndSortedStats.length} of {playerStats.length} players
</Text>
<TextInput <TextInput
placeholder="Search players" placeholder="Search players"
value={search} value={search}
@@ -259,11 +323,9 @@ const PlayerStatsTable = () => {
/> />
<Group px="md" justify="space-between" align="center"> <Group px="md" justify="space-between" align="center">
<Text size="10px" lh={0} c="dimmed"> <Group gap="xs" w="100%">
{filteredAndSortedStats.length} of {playerStats.length} players <div></div>
</Text> <Text ml='auto' size="xs" c="dimmed">Sort:</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">Sort:</Text>
<UnstyledButton <UnstyledButton
onClick={() => handleSort("mmr")} onClick={() => handleSort("mmr")}
style={{ display: "flex", alignItems: "center", gap: 4 }} style={{ display: "flex", alignItems: "center", gap: 4 }}
@@ -301,6 +363,48 @@ const PlayerStatsTable = () => {
</Popover.Target> </Popover.Target>
<Popover.Dropdown> <Popover.Dropdown>
<Box maw={280}> <Box maw={280}>
<Text size="sm" fw={500} mb="xs">
Stat Abbreviations:
</Text>
<Text size="xs" mb={2}>
<strong>M:</strong> Matches
</Text>
<Text size="xs" mb={2}>
<strong>T:</strong> Tournaments
</Text>
<Text size="xs" mb={2}>
<strong>MMR:</strong> Matchmaking Rating
</Text>
<Text size="xs" mb={2}>
<strong>W:</strong> Wins
</Text>
<Text size="xs" mb={2}>
<strong>L:</strong> Losses
</Text>
<Text size="xs" mb={2}>
<strong>W%:</strong> Win Percentage
</Text>
<Text size="xs" mb={2}>
<strong>AWM:</strong> Average Win Margin
</Text>
<Text size="xs" mb={2}>
<strong>ALM:</strong> Average Loss Margin
</Text>
<Text size="xs" mb={2}>
<strong>AC:</strong> Average Cups Per Match
</Text>
<Text size="xs" mb={2}>
<strong>ACA:</strong> Average Cups Against
</Text>
<Text size="xs" mb={2}>
<strong>CF:</strong> Cups For
</Text>
<Text size="xs" mb={2}>
<strong>CA:</strong> Cups Against
</Text>
<Divider my="sm" />
<Text size="sm" fw={500} mb="xs"> <Text size="sm" fw={500} mb="xs">
MMR Calculation: MMR Calculation:
</Text> </Text>
@@ -335,6 +439,8 @@ const PlayerStatsTable = () => {
stat={stat} stat={stat}
onPlayerClick={handlePlayerClick} onPlayerClick={handlePlayerClick}
mmr={stat.mmr} mmr={stat.mmr}
onRegisterViewport={handleRegisterViewport}
onUnregisterViewport={handleUnregisterViewport}
/> />
{index < filteredAndSortedStats.length - 1 && <Divider />} {index < filteredAndSortedStats.length - 1 && <Divider />}
</Box> </Box>

Some files were not shown because too many files have changed in this diff Show More