Compare commits

..

3 Commits

Author SHA1 Message Date
Viktor Rådberg
ef0870e1d0 simpler QR code 2025-11-13 21:39:35 +01:00
Viktor Rådberg
27287fd0f2 compress QR code more 2025-11-13 21:30:52 +01:00
Viktor Rådberg
02b5c9cdf9 working 2025-11-13 19:45:38 +01:00
36 changed files with 3845 additions and 4824 deletions

18
.eslintrc.cjs Normal file
View File

@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

View File

@@ -13,22 +13,14 @@ jobs:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Setup pnpm - name: Setup bun
uses: pnpm/action-setup@v4 uses: oven-sh/setup-bun@v1
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- name: Build, lint, and deploy - name: Build, lint, and deploy
run: | run: |
pnpm install bun install
pnpm run build bun run build
pnpm run lint bun run lint
- name: Deploy to Firebase Hosting - name: Deploy to Firebase Hosting
uses: FirebaseExtended/action-hosting-deploy@v0 uses: FirebaseExtended/action-hosting-deploy@v0
with: with:

View File

@@ -14,24 +14,22 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v2
- name: Setup pnpm - name: Set up Node.js
uses: pnpm/action-setup@v4 uses: actions/setup-node@v2
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 18
cache: 'pnpm'
- name: Set up bun
uses: oven-sh/setup-bun@v1
- name: Install dependencies - name: Install dependencies
run: pnpm install run: bun install
- name: Run lint - name: Run lint
run: pnpm run lint run: bun run lint
- name: Build project - name: Build project
run: pnpm run build run: bun run build

View File

@@ -1,26 +0,0 @@
import js from '@eslint/js';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
);

View File

@@ -1,7 +1,11 @@
{ {
"hosting": { "hosting": {
"public": "dist", "public": "dist",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [ "rewrites": [
{ {
"source": "**", "source": "**",

View File

@@ -1,7 +1,7 @@
{ {
"name": "life-trinket", "name": "life-trinket",
"private": true, "private": true,
"version": "1.0.5", "version": "1.0.1",
"type": "commonjs", "type": "commonjs",
"engines": { "engines": {
"node": ">=20", "node": ">=20",
@@ -11,45 +11,49 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc && vite build",
"lint": "eslint . --report-unused-disable-directives --max-warnings 0", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview", "preview": "vite preview",
"generate-icons": "npx @svgr/cli src/Icons/svgs", "generate-icons": "npx @svgr/cli src/Icons/svgs",
"force-deploy": "pnpm run build && firebase deploy --only hosting", "deploy": "bun run build && firebase deploy --only hosting"
"release": "bash scripts/create-release.sh"
}, },
"dependencies": { "dependencies": {
"firebase": "^12.6.0", "firebase": "^10.14.1",
"react": "^19.2.0", "ga-4-react": "^0.1.281",
"react-dom": "^19.2.0", "pako": "^2.1.0",
"react-screen-wake-lock": "^3.1.1", "qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-screen-wake-lock": "^3.0.2",
"react-swipeable": "^7.0.2", "react-swipeable": "^7.0.2",
"react-twc": "^1.5.1", "react-twc": "^1.4.2",
"semver": "^7.7.3", "semver": "^7.7.1",
"zod": "^4.1.12" "zod": "^3.24.2"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.1", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@savvywombat/tailwindcss-grid-areas": "^4.0.0",
"@svgr/cli": "^8.1.0", "@svgr/cli": "^8.1.0",
"@tailwindcss/postcss": "^4.1.17", "@types/pako": "^2.0.4",
"@types/prop-types": "^15.7.15", "@types/qrcode": "^1.5.6",
"@types/react": "^19.2.5", "@types/react": "^18.3.18",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^18.3.5",
"@types/semver": "^7.7.1", "@types/semver": "^7.5.8",
"@typescript-eslint/eslint-plugin": "^8.47.0", "@typescript-eslint/eslint-plugin": "^7.18.0",
"@typescript-eslint/parser": "^8.47.0", "@typescript-eslint/parser": "^7.18.0",
"@vitejs/plugin-react-swc": "^4.2.2", "@vitejs/plugin-react-swc": "^3.8.0",
"autoprefixer": "^10.4.22", "autoprefixer": "^10.4.20",
"eslint": "^9.39.1", "eslint": "^8.57.1",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.24", "eslint-plugin-react-refresh": "^0.4.19",
"firebase-tools": "^14.25.0", "firebase-tools": "^13.31.2",
"postcss": "^8.5.6", "install": "^0.13.0",
"prettier": "3.6.2", "postcss": "^8.5.3",
"prettier": "2.8.8",
"prop-types": "^15.8.1", "prop-types": "^15.8.1",
"tailwindcss": "^4.1.17", "tailwindcss": "^3.4.17",
"typescript": "^5.9.3", "typescript": "^5.7.3",
"typescript-eslint": "^8.47.0", "vite": "^5.4.14",
"vite": "^7.2.2", "vite-plugin-pwa": "^0.20.5"
"vite-plugin-pwa": "^1.1.0"
} }
} }

7267
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
module.exports = { module.exports = {
plugins: { plugins: {
'@tailwindcss/postcss': {}, tailwindcss: {},
autoprefixer: {}, autoprefixer: {},
}, },
} }

View File

@@ -1,74 +0,0 @@
# Release Scripts
## create-release.sh
This script automates the process of creating a new release for LifeTrinket.
### Usage
```bash
npm run release
# or
pnpm release
# or
bash scripts/create-release.sh
```
### What it does
1. **Reads the current version** from `package.json`
2. **Checks for existing tags** - If a tag with the current version already exists, it will prompt you to update the version in `package.json` first
3. **Warns about uncommitted changes** - Prompts for confirmation if you have uncommitted changes
4. **Prompts for release description** - You can enter a multi-line description for the release
5. **Creates an annotated git tag** with the version and description
6. **Pushes the tag to remote** - This triggers the GitHub Actions workflow that builds and deploys the app
### Workflow
When you push a tag, the following happens:
1. The `firebase-release.yml` workflow is triggered
2. The app is built and deployed to Firebase Hosting
3. A GitHub release is created with the version number
### Before running
Make sure to:
1. **Update the version** in `package.json` if needed
2. **Commit all changes** you want to include in the release
3. **Test the build** with `npm run build` to ensure everything works
### Example
```bash
# 1. Update version in package.json to 1.0.3
# 2. Commit your changes
git add .
git commit -m "feat: add new features for v1.0.3"
# 3. Run the release script
npm run release
# The script will:
# - Show current version: 1.0.3
# - Prompt for confirmation
# - Ask for release description
# - Create and push the tag
# - Trigger the deployment workflow
```
### Troubleshooting
**"Tag already exists" error:**
- Update the version in `package.json` before creating a new release
**"Failed to push tag" error:**
- Check your git remote permissions
- Try pushing manually: `git push origin <version>`
**Script won't run:**
- Make sure the script is executable: `chmod +x scripts/create-release.sh`

View File

@@ -1,87 +0,0 @@
#!/bin/bash
# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}=== LifeTrinket Release Script ===${NC}\n"
# Get current version from package.json
CURRENT_VERSION=$(node -p "require('./package.json').version")
if [ -z "$CURRENT_VERSION" ]; then
echo -e "${RED}Error: Could not read version from package.json${NC}"
exit 1
fi
echo -e "${BLUE}Current version in package.json:${NC} ${GREEN}$CURRENT_VERSION${NC}"
# Check if we're on a clean working tree
if [[ -n $(git status -s) ]]; then
echo -e "${YELLOW}Warning: You have uncommitted changes.${NC}"
fi
# Fetch latest tags from remote
echo -e "\n${BLUE}Fetching latest tags from remote...${NC}"
git fetch --tags
# Check if tag already exists locally or remotely
if git rev-parse "$CURRENT_VERSION" >/dev/null 2>&1; then
echo -e "${RED}Error: Tag '$CURRENT_VERSION' already exists!${NC}"
echo -e "${YELLOW}Please update the version in package.json before creating a new release.${NC}"
echo -e "${YELLOW}Current version: $CURRENT_VERSION${NC}"
exit 1
fi
# Get the latest tag (if any)
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null)
if [ -n "$LATEST_TAG" ]; then
echo -e "${BLUE}Latest existing tag:${NC} ${YELLOW}$LATEST_TAG${NC}"
# Compare versions
if [ "$LATEST_TAG" = "$CURRENT_VERSION" ]; then
echo -e "${RED}Error: Latest tag matches current version ($CURRENT_VERSION)${NC}"
echo -e "${YELLOW}Please update the version in package.json before creating a new release.${NC}"
exit 1
fi
else
echo -e "${YELLOW}No existing tags found. This will be the first release.${NC}"
fi
# Get release description from user
echo -e "\n${BLUE}Enter release description (optional, press Enter to skip):${NC}"
read -r RELEASE_DESCRIPTION
if [ -z "$RELEASE_DESCRIPTION" ]; then
RELEASE_DESCRIPTION="Release $CURRENT_VERSION"
fi
# Create annotated tag with description
echo -e "\n${BLUE}Creating tag '$CURRENT_VERSION'...${NC}"
git tag -a "$CURRENT_VERSION" -m "$RELEASE_DESCRIPTION"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to create tag${NC}"
exit 1
fi
echo -e "${GREEN}✓ Tag created successfully${NC}"
# Push tag to remote
echo -e "\n${BLUE}Pushing tag to remote...${NC}"
git push origin "$CURRENT_VERSION"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to push tag${NC}"
echo -e "${YELLOW}Tag was created locally. You can try pushing manually:${NC}"
echo -e " git push origin $CURRENT_VERSION"
exit 1
fi
echo -e "\n${GREEN}✓ Tag pushed successfully!${NC}"
echo -e "${BLUE}GitHub Actions will now build and deploy version $CURRENT_VERSION${NC}"
echo -e "${BLUE}Check the progress at:${NC} https://github.com/Vikeo/LifeTrinket/actions"

View File

@@ -19,10 +19,10 @@ const Container = twc.div<RotationDivProps>((props) => [
]); ]);
export const ExtraCountersGrid = twc.div<RotationDivProps>((props) => [ export const ExtraCountersGrid = twc.div<RotationDivProps>((props) => [
'flex absolute flex-grow pointer-events-none', 'flex absolute flex-row flex-grow pointer-events-none overflow-x-scroll overflow-y-hidden ',
props.$rotation === Rotation.SideFlipped || props.$rotation === Rotation.Side props.$rotation === Rotation.SideFlipped || props.$rotation === Rotation.Side
? 'flex-col h-full w-auto overflow-y-scroll overflow-x-hidden bottom-auto right-0' ? 'flex-col-reverse h-full w-auto bottom-auto right-0'
: 'flex-row w-full overflow-x-scroll overflow-y-hidden bottom-0', : 'w-full bottom-0',
]); ]);
type ExtraCountersBarProps = { type ExtraCountersBarProps = {

View File

@@ -1,3 +1,4 @@
import { useRef } from 'react';
import { twc } from 'react-twc'; import { twc } from 'react-twc';
import { useAnalytics } from '../../Hooks/useAnalytics'; import { useAnalytics } from '../../Hooks/useAnalytics';
import { useGlobalSettings } from '../../Hooks/useGlobalSettings'; import { useGlobalSettings } from '../../Hooks/useGlobalSettings';
@@ -7,6 +8,7 @@ import { Separator } from '../Misc/Separator';
import { Paragraph } from '../Misc/TextComponents'; import { Paragraph } from '../Misc/TextComponents';
import { ToggleButton } from '../Misc/ToggleButton'; import { ToggleButton } from '../Misc/ToggleButton';
import { Dialog } from './Dialog'; import { Dialog } from './Dialog';
import { ShareGameDialog } from './ShareGameDialog';
const SettingContainer = twc.div`w-full flex flex-col mb-2`; const SettingContainer = twc.div`w-full flex flex-col mb-2`;
@@ -24,6 +26,7 @@ export const SettingsDialog = ({
}) => { }) => {
const { settings, setSettings, isPWA, version } = useGlobalSettings(); const { settings, setSettings, isPWA, version } = useGlobalSettings();
const analytics = useAnalytics(); const analytics = useAnalytics();
const shareGameDialogRef = useRef<HTMLDialogElement | null>(null);
return ( return (
<Dialog id="settings" title="⚙️ Settings ⚙️" dialogRef={dialogRef}> <Dialog id="settings" title="⚙️ Settings ⚙️" dialogRef={dialogRef}>
@@ -242,25 +245,17 @@ export const SettingsDialog = ({
</ul> </ul>
</Description> </Description>
</SettingContainer> </SettingContainer>
<SettingContainer>
<ToggleContainer>
<label>Show Match Score</label>
<ToggleButton
checked={settings.showMatchScore}
onChange={() => {
setSettings({
...settings,
showMatchScore: !settings.showMatchScore,
});
}}
/>
</ToggleContainer>
<Description>
Shows a score badge on each player's card to track wins across multiple games.
</Description>
</SettingContainer>
<Separator height="1px" /> <Separator height="1px" />
<div className="flex w-full justify-center"> <div className="flex w-full justify-center gap-3">
<button
className="mt-1 mb-1 bg-secondary-main px-3 py-1 rounded-md duration-200 ease-in-out shadow-[1px_2px_4px_0px_rgba(0,0,0,0.3)] hover:bg-secondary-dark font-bold"
onClick={() => {
analytics.trackEvent('share_game_button_clicked');
shareGameDialogRef.current?.showModal();
}}
>
<span className="text-sm">Share Game</span>
</button>
<button <button
className="mt-1 mb-1 bg-primary-main px-3 py-1 rounded-md duration-200 ease-in-out shadow-[1px_2px_4px_0px_rgba(0,0,0,0.3)] hover:bg-primary-dark font-bold" className="mt-1 mb-1 bg-primary-main px-3 py-1 rounded-md duration-200 ease-in-out shadow-[1px_2px_4px_0px_rgba(0,0,0,0.3)] hover:bg-primary-dark font-bold"
onClick={() => { onClick={() => {
@@ -271,6 +266,7 @@ export const SettingsDialog = ({
<span className="text-sm">Save and Close</span> <span className="text-sm">Save and Close</span>
</button> </button>
</div> </div>
<ShareGameDialog dialogRef={shareGameDialogRef} />
{!isPWA && ( {!isPWA && (
<> <>
{window.isIOS && ( {window.isIOS && (

View File

@@ -0,0 +1,138 @@
import { useEffect, useState } from 'react';
import QRCode from 'qrcode';
import { Dialog } from './Dialog';
import { generateShareableUrl } from '../../Utils/gameStateSharing';
import { useAnalytics } from '../../Hooks/useAnalytics';
export const ShareGameDialog = ({
dialogRef,
}: {
dialogRef: React.MutableRefObject<HTMLDialogElement | null>;
}) => {
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const [shareableUrl, setShareableUrl] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string>('');
const [copied, setCopied] = useState(false);
const analytics = useAnalytics();
useEffect(() => {
// Generate QR code when dialog opens
const dialog = dialogRef.current;
if (!dialog) return;
const handleOpen = async () => {
setIsLoading(true);
setError('');
setCopied(false);
try {
// Small delay to ensure all localStorage writes from useEffect have completed
await new Promise((resolve) => setTimeout(resolve, 50));
// Generate the shareable URL
const url = generateShareableUrl();
setShareableUrl(url);
// Generate QR code with lower error correction for less detail
const qrDataUrl = await QRCode.toDataURL(url, {
width: 300,
margin: 2,
errorCorrectionLevel: 'L', // Low error correction = simpler QR code
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
setQrCodeUrl(qrDataUrl);
analytics.trackEvent('share_game_qr_generated');
} catch (err) {
console.error('Error generating QR code:', err);
setError('Failed to generate QR code. Please try again.');
analytics.trackEvent('share_game_qr_error');
} finally {
setIsLoading(false);
}
};
// Listen for dialog open events
const observer = new MutationObserver(() => {
if (dialog.open) {
handleOpen();
}
});
observer.observe(dialog, { attributes: true, attributeFilter: ['open'] });
return () => observer.disconnect();
}, [dialogRef, analytics]);
const handleCopyUrl = async () => {
try {
await navigator.clipboard.writeText(shareableUrl);
setCopied(true);
analytics.trackEvent('share_game_url_copied');
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Failed to copy URL:', err);
analytics.trackEvent('share_game_url_copy_error');
}
};
return (
<Dialog id="share-game" title="Share Game" dialogRef={dialogRef}>
<div className="flex flex-col items-center gap-4 py-4">
{isLoading && (
<div className="text-text-secondary">Generating QR code...</div>
)}
{error && (
<div className="text-red-500 text-sm text-center">{error}</div>
)}
{!isLoading && !error && qrCodeUrl && (
<>
<div className="bg-white p-4 rounded-lg">
<img src={qrCodeUrl} alt="QR Code" className="w-full h-auto" />
</div>
<div className="text-text-secondary text-sm text-center max-w-full">
Scan this QR code to share the current game state
</div>
<div className="w-full flex flex-col gap-2">
<div className="text-xs text-text-secondary text-center">
Or copy the link:
</div>
<div className="flex gap-2 items-center w-full">
<input
type="text"
value={shareableUrl}
readOnly
className="flex-1 bg-secondary-main text-text-primary text-xs px-2 py-1 rounded-md border-none outline-none overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<button
onClick={handleCopyUrl}
className="bg-primary-main px-3 py-1 rounded-md text-sm font-semibold hover:bg-primary-dark transition-colors"
>
{copied ? 'Copied!' : 'Copy'}
</button>
</div>
</div>
</>
)}
<button
className="mt-2 bg-primary-main px-4 py-2 rounded-md font-semibold hover:bg-primary-dark transition-colors"
onClick={() => {
analytics.trackEvent('share_game_dialog_closed');
dialogRef.current?.close();
}}
>
Close
</button>
</div>
</Dialog>
);
};

View File

@@ -1,85 +0,0 @@
import { twc } from 'react-twc';
import { Player } from '../../Types/Player';
const Overlay = twc.div`
fixed top-0 left-0 w-[100dvmax] h-[100dvmin]
bg-black/80 backdrop-blur-sm
flex items-center justify-center
z-50
`;
const Modal = twc.div`
bg-background-default
rounded-2xl p-8
max-w-md w-[90%]
shadow-2xl
flex flex-col gap-6
`;
const Title = twc.h2`
text-[7vmin] font-bold text-center
text-text-primary
-mb-4
`;
const ButtonContainer = twc.div`
flex flex-col gap-3
`;
const WinnerName = twc.div`
text-[6vmin] font-bold text-center
py-[2vmin] px-[3vmin] rounded-xl
text-white
mb-0
`;
const PrimaryButton = twc.button`
py-[2vmin] px-[3vmin] rounded-xl
text-[4vmin] font-semibold
bg-interface-primary
text-white
transition-all duration-200
hover:scale-105 active:scale-95
border-3 border-white/50
shadow-lg shadow-interface-primary/50
`;
const SecondaryButton = twc.button`
py-[2vmin] px-[3vmin] rounded-xl
text-[4vmin] font-semibold
bg-secondary-main
text-text-primary
transition-all duration-200
hover:scale-105 active:scale-95
border-3 border-primary-main
shadow-lg shadow-secondary-main/50
`;
type GameOverProps = {
winner: Player;
onStartNextGame: () => void;
onStay: () => void;
};
export const GameOver = ({
winner,
onStartNextGame,
onStay,
}: GameOverProps) => {
return (
<Overlay>
<Modal>
<Title>Winner</Title>
<WinnerName style={{ backgroundColor: winner.color }}>
{winner.name || `Player ${winner.index + 1}`}
</WinnerName>
<ButtonContainer>
<SecondaryButton onClick={onStartNextGame}>
Start Next Game
</SecondaryButton>
<PrimaryButton onClick={onStay}>Close</PrimaryButton>
</ButtonContainer>
</Modal>
</Overlay>
);
};

View File

@@ -24,27 +24,6 @@ const SettingsButtonTwc = twc.button<RotationButtonProps>((props) => [
: 'top-1/4 right-[1vmax]', : 'top-1/4 right-[1vmax]',
]); ]);
type MatchScoreBadgeProps = RotationDivProps & {
$useCommanderDamage: boolean;
};
const MatchScoreBadge = twc.div<MatchScoreBadgeProps>((props) => [
'absolute flex items-center justify-center',
'bg-black/70 backdrop-blur-sm',
'rounded-full',
'w-[5vmin] h-[5vmin]',
'text-white font-bold',
'text-[3vmin]',
'z-[1]',
'pointer-events-none',
'select-none webkit-user-select-none',
props.$rotation === Rotation.Side || props.$rotation === Rotation.SideFlipped
? `left-[6.5vmax] bottom-[1vmax]`
: props.$useCommanderDamage
? 'left-[0.5vmax] top-[11.5vmin]'
: 'left-[0.5vmax] top-[1vmax]',
]);
type SettingsButtonProps = { type SettingsButtonProps = {
onClick: () => void; onClick: () => void;
rotation: Rotation; rotation: Rotation;
@@ -119,12 +98,11 @@ type LifeCounterProps = {
player: Player; player: Player;
opponents: Player[]; opponents: Player[];
isStartingPlayer?: boolean; isStartingPlayer?: boolean;
matchScore?: number;
}; };
const RECENT_DIFFERENCE_TTL = 3_000; const RECENT_DIFFERENCE_TTL = 3_000;
const LifeCounter = ({ player, opponents, matchScore }: LifeCounterProps) => { const LifeCounter = ({ player, opponents }: LifeCounterProps) => {
const { updatePlayer, updateLifeTotal } = usePlayers(); const { updatePlayer, updateLifeTotal } = usePlayers();
const { settings, playing } = useGlobalSettings(); const { settings, playing } = useGlobalSettings();
const recentDifferenceTimerRef = useRef<NodeJS.Timeout | undefined>( const recentDifferenceTimerRef = useRef<NodeJS.Timeout | undefined>(
@@ -195,6 +173,9 @@ const LifeCounter = ({ player, opponents, matchScore }: LifeCounterProps) => {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [document.body.clientHeight, document.body.clientWidth]); }, [document.body.clientHeight, document.body.clientWidth]);
player.settings.rotation === Rotation.SideFlipped ||
player.settings.rotation === Rotation.Side;
const handleLifeChange = (updatedLifeTotal: number) => { const handleLifeChange = (updatedLifeTotal: number) => {
const difference = updateLifeTotal(player, updatedLifeTotal); const difference = updateLifeTotal(player, updatedLifeTotal);
setRecentDifference(recentDifference + difference); setRecentDifference(recentDifference + difference);
@@ -234,21 +215,6 @@ const LifeCounter = ({ player, opponents, matchScore }: LifeCounterProps) => {
key={player.index} key={player.index}
handleLifeChange={handleLifeChange} handleLifeChange={handleLifeChange}
/> />
{matchScore !== undefined && matchScore > 0 && (
<MatchScoreBadge
$rotation={player.settings.rotation}
$useCommanderDamage={player.settings.useCommanderDamage}
style={{
rotate:
player.settings.rotation === Rotation.Side ||
player.settings.rotation === Rotation.SideFlipped
? `-90deg`
: '0deg',
}}
>
{matchScore}
</MatchScoreBadge>
)}
{settings.showPlayerMenuCog && ( {settings.showPlayerMenuCog && (
<SettingsButton <SettingsButton
onClick={() => { onClick={() => {
@@ -278,8 +244,6 @@ const LifeCounter = ({ player, opponents, matchScore }: LifeCounterProps) => {
isShown={showPlayerMenu} isShown={showPlayerMenu}
player={player} player={player}
setShowPlayerMenu={setShowPlayerMenu} setShowPlayerMenu={setShowPlayerMenu}
onForfeit={toggleGameLost}
totalPlayers={opponents.length + 1}
/> />
</LifeCounterWrapper> </LifeCounterWrapper>
</LifeCounterContentWrapper> </LifeCounterContentWrapper>

View File

@@ -1,5 +1,7 @@
import { useEffect, useState } from 'react';
import { twc } from 'react-twc'; import { twc } from 'react-twc';
import { useGlobalSettings } from '../Hooks/useGlobalSettings'; import { useGlobalSettings } from '../Hooks/useGlobalSettings';
import { importGameState } from '../Utils/gameStateSharing';
import { Play } from './Views/Play'; import { Play } from './Views/Play';
import StartMenu from './Views/StartMenu/StartMenu'; import StartMenu from './Views/StartMenu/StartMenu';
@@ -26,8 +28,88 @@ const EmergencyResetButton = () => {
export const LifeTrinket = () => { export const LifeTrinket = () => {
const { showPlay, initialGameSettings } = useGlobalSettings(); const { showPlay, initialGameSettings } = useGlobalSettings();
// Check for query parameter immediately on every render
const urlParams = new URLSearchParams(window.location.search);
const gameStateParam = urlParams.get('gameStateToLoad');
const [showImportDialog, setShowImportDialog] = useState(!!gameStateParam);
const [importSuccess, setImportSuccess] = useState<boolean | null>(null);
useEffect(() => {
// Update dialog visibility if query parameter changes
if (gameStateParam && !showImportDialog) {
setShowImportDialog(true);
}
}, [gameStateParam, showImportDialog]);
const handleImportConfirm = () => {
const urlParams = new URLSearchParams(window.location.search);
const gameStateParam = urlParams.get('gameStateToLoad');
if (gameStateParam) {
// Import game state to localStorage
const success = importGameState(gameStateParam);
if (success) {
// Remove query parameter and reload the page
// This ensures providers pick up the new localStorage values
window.location.href =
window.location.origin + window.location.pathname;
} else {
// Show error and remove query parameter
setImportSuccess(false);
window.history.replaceState({}, '', window.location.pathname);
setShowImportDialog(false);
}
}
};
const handleImportCancel = () => {
// Remove the query parameter from URL
const newUrl = window.location.pathname;
window.history.replaceState({}, '', newUrl);
setShowImportDialog(false);
};
// If import dialog is shown, only render the dialog and nothing else
if (showImportDialog) {
return (
<div className="fixed inset-0 bg-background-backdrop backdrop-blur-sm z-[9999] flex items-center justify-center">
<div className="bg-background-default rounded-2xl p-8 max-w-md mx-4">
<h2 className="text-2xl text-text-primary font-bold mb-4 text-center">
Load Shared Game?
</h2>
<p className="text-text-secondary mb-6 text-center">
A shared game state has been detected. Would you like to load it?
This will replace your current game state.
</p>
<div className="flex gap-4 justify-center">
<button
onClick={handleImportCancel}
className="px-4 py-2 bg-secondary-main text-text-primary rounded-md font-semibold hover:bg-secondary-dark transition-colors"
>
Cancel
</button>
<button
onClick={handleImportConfirm}
className="px-4 py-2 bg-primary-main text-text-primary rounded-md font-semibold hover:bg-primary-dark transition-colors"
>
Load Game
</button>
</div>
</div>
</div>
);
}
return ( return (
<> <>
{importSuccess === false && (
<div className="fixed top-4 left-1/2 transform -translate-x-1/2 bg-red-500 text-white px-6 py-3 rounded-md z-[9999]">
Failed to load game state. The link may be corrupted.
</div>
)}
{showPlay && initialGameSettings ? ( {showPlay && initialGameSettings ? (
<PlayWrapper> <PlayWrapper>
<Play /> <Play />

View File

@@ -1,5 +1,3 @@
import { ReactElement } from 'react';
export const IconCheckbox = ({ export const IconCheckbox = ({
name, name,
icon, icon,
@@ -9,14 +7,14 @@ export const IconCheckbox = ({
className, className,
}: { }: {
name: string; name: string;
icon: ReactElement; icon: JSX.Element;
checkedIcon: ReactElement; checkedIcon: JSX.Element;
checked: boolean; checked: boolean;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
className?: string; className?: string;
}) => { }) => {
return ( return (
<div className={className}> <div className={className} >
<label> <label>
<input <input
name={name} name={name}

View File

@@ -1,8 +1,9 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { BeforeInstallPromptEvent } from '../../global'; import { BeforeInstallPromptEvent } from '../../global';
import { useAnalytics } from '../../Hooks/useAnalytics'; import { useAnalytics } from '../../Hooks/useAnalytics';
export const InstallPWAButton = () => { export const InstallPWAButton = () => {
const supportsPWARef = useRef<boolean>(false);
const [promptInstall, setPromptInstall] = const [promptInstall, setPromptInstall] =
useState<BeforeInstallPromptEvent | null>(null); useState<BeforeInstallPromptEvent | null>(null);
@@ -10,6 +11,7 @@ export const InstallPWAButton = () => {
const handler = (e: BeforeInstallPromptEvent) => { const handler = (e: BeforeInstallPromptEvent) => {
e.preventDefault(); e.preventDefault();
supportsPWARef.current = true;
setPromptInstall(e); setPromptInstall(e);
}; };
@@ -19,7 +21,7 @@ export const InstallPWAButton = () => {
return () => window.removeEventListener('transitionend', handler); return () => window.removeEventListener('transitionend', handler);
}, []); }, []);
if (!promptInstall) { if (!supportsPWARef.current) {
return null; return null;
} }

View File

@@ -2,7 +2,10 @@ import { Rotation } from '../../Types/Player';
import { twc } from 'react-twc'; import { twc } from 'react-twc';
//TODO Create provider for this //TODO Create provider for this
import { baseColors } from './../../../tailwind.config'; import tailwindConfig from './../../../tailwind.config';
import resolveConfig from 'tailwindcss/resolveConfig';
const fullConfig = resolveConfig(tailwindConfig);
const Container = twc.div` const Container = twc.div`
flex flex
@@ -56,12 +59,12 @@ export const OutlinedText: React.FC<OutlinedTextProps> = ({
fontSize, fontSize,
fontWeight, fontWeight,
strokeWidth: strokeWidth || '1vmin', strokeWidth: strokeWidth || '1vmin',
color: fillColor || baseColors.common.black, color: fillColor || fullConfig.theme.colors.common.black,
WebkitTextStroke: `${strokeWidth || '1vmin'} ${ WebkitTextStroke: `${strokeWidth || '1vmin'} ${
strokeColor || baseColors.common.white strokeColor || fullConfig.theme.colors.common.white
}`, }`,
WebkitTextFillColor: WebkitTextFillColor:
fillColor || baseColors.common.black, fillColor || fullConfig.theme.colors.common.black,
rotate: `${calcRotation}deg`, rotate: `${calcRotation}deg`,
}} }}
> >

View File

@@ -16,7 +16,6 @@ import {
PartnerTax, PartnerTax,
Poison, Poison,
ResetGame, ResetGame,
Skull,
} from '../../Icons/generated'; } from '../../Icons/generated';
import { Player, Rotation } from '../../Types/Player'; import { Player, Rotation } from '../../Types/Player';
import { PreStartMode } from '../../Types/Settings'; import { PreStartMode } from '../../Types/Settings';
@@ -91,21 +90,16 @@ type PlayerMenuProps = {
player: Player; player: Player;
setShowPlayerMenu: (showPlayerMenu: boolean) => void; setShowPlayerMenu: (showPlayerMenu: boolean) => void;
isShown: boolean; isShown: boolean;
onForfeit?: () => void;
totalPlayers: number;
}; };
const PlayerMenu = ({ const PlayerMenu = ({
player, player,
setShowPlayerMenu, setShowPlayerMenu,
isShown, isShown,
onForfeit,
totalPlayers,
}: PlayerMenuProps) => { }: PlayerMenuProps) => {
const settingsContainerRef = useRef<HTMLDivElement | null>(null); const settingsContainerRef = useRef<HTMLDivElement | null>(null);
const resetGameDialogRef = useRef<HTMLDialogElement | null>(null); const resetGameDialogRef = useRef<HTMLDialogElement | null>(null);
const endGameDialogRef = useRef<HTMLDialogElement | null>(null); const endGameDialogRef = useRef<HTMLDialogElement | null>(null);
const forfeitGameDialogRef = useRef<HTMLDialogElement | null>(null);
const { isSide } = useSafeRotate({ const { isSide } = useSafeRotate({
rotation: player.settings.rotation, rotation: player.settings.rotation,
@@ -123,7 +117,6 @@ const PlayerMenu = ({
saveCurrentGame, saveCurrentGame,
initialGameSettings, initialGameSettings,
setPreStartCompleted, setPreStartCompleted,
gameScore,
} = useGlobalSettings(); } = useGlobalSettings();
const analytics = useAnalytics(); const analytics = useAnalytics();
@@ -166,7 +159,7 @@ const PlayerMenu = ({
}; };
const handleGoToStart = () => { const handleGoToStart = () => {
saveCurrentGame({ players, initialGameSettings, gameScore }); saveCurrentGame({ players, initialGameSettings });
goToStart(); goToStart();
setRandomizingPlayer(true); setRandomizingPlayer(true);
}; };
@@ -486,32 +479,6 @@ const PlayerMenu = ({
> >
<ResetGame size={iconSize} /> <ResetGame size={iconSize} />
</button> </button>
<button
style={{
cursor: 'pointer',
userSelect: 'none',
fontSize: buttonFontSize,
padding: '2px',
}}
className="text-red-500"
onClick={() => {
if (totalPlayers === 2) {
forfeitGameDialogRef.current?.show();
} else {
if (onForfeit) {
analytics.trackEvent('forfeit_game', {
player: player.index,
});
onForfeit();
setShowPlayerMenu(false);
}
}
}}
aria-label="Forfeit Game"
>
<Skull size={iconSize} />
</button>
</ButtonsSections> </ButtonsSections>
</BetterRowContainer> </BetterRowContainer>
@@ -592,48 +559,6 @@ const PlayerMenu = ({
</div> </div>
</div> </div>
</dialog> </dialog>
<dialog
ref={forfeitGameDialogRef}
className="z-[999] size-full bg-background-settings overflow-y-scroll"
onClick={() => forfeitGameDialogRef.current?.close()}
>
<div className="flex size-full items-center justify-center">
<div className="flex flex-col justify-center p-4 gap-2 bg-background-default rounded-xl border-none">
<h1
className="text-center text-text-primary"
style={{ fontSize: extraCountersSize }}
>
Forfeit Game?
</h1>
<div className="flex justify-evenly gap-2">
<button
className="bg-primary-main border border-primary-dark text-text-primary rounded-lg flex-grow"
style={{ fontSize: iconSize }}
onClick={() => forfeitGameDialogRef.current?.close()}
>
No
</button>
<button
className="bg-primary-main border border-primary-dark text-text-primary rounded-lg flex-grow"
onClick={() => {
if (onForfeit) {
analytics.trackEvent('forfeit_game', {
player: player.index,
});
onForfeit();
setShowPlayerMenu(false);
forfeitGameDialogRef.current?.close();
}
}}
style={{ fontSize: iconSize }}
>
Yes
</button>
</div>
</div>
</div>
</dialog>
</SettingsContainer> </SettingsContainer>
</PlayerMenuWrapper> </PlayerMenuWrapper>
); );

View File

@@ -31,7 +31,7 @@ const PlayersWrapper = twc.div`w-full h-full bg-black`;
export const Players = ({ gridLayout }: { gridLayout: GridLayout }) => { export const Players = ({ gridLayout }: { gridLayout: GridLayout }) => {
const { players } = usePlayers(); const { players } = usePlayers();
const { playing, settings, preStartCompleted, gameScore } = useGlobalSettings(); const { playing, settings, preStartCompleted } = useGlobalSettings();
return ( return (
<PlayersWrapper> <PlayersWrapper>
@@ -48,11 +48,6 @@ export const Players = ({ gridLayout }: { gridLayout: GridLayout }) => {
opponents={players.filter( opponents={players.filter(
(opponent) => opponent.index !== player.index (opponent) => opponent.index !== player.index
)} )}
matchScore={
settings.showMatchScore
? gameScore[player.index]
: undefined
}
/> />
{settings.preStartMode === PreStartMode.RandomKing && {settings.preStartMode === PreStartMode.RandomKing &&

View File

@@ -107,7 +107,7 @@ export const Trivia = () => {
const { setPlaying, goToStart } = useGlobalSettings(); const { setPlaying, goToStart } = useGlobalSettings();
const [randomQuestion, setRandomQuestion] = useState( const [randomQuestion, setRandomQuestion] = useState(
() => questions[Math.floor(Math.random() * questions.length)] questions[Math.floor(Math.random() * questions.length)]
); );
const setUniqueRandomQuestion = () => { const setUniqueRandomQuestion = () => {

View File

@@ -1,71 +0,0 @@
import { twc } from 'react-twc';
import { Player } from '../../Types/Player';
import { GameScore } from '../../Contexts/GlobalSettingsContext';
const ScoreContainer = twc.div`
absolute bottom-4 left-1/2 -translate-x-1/2
bg-background-default/90 backdrop-blur-sm
rounded-lg p-4
shadow-lg
z-40
min-w-[200px]
`;
const Title = twc.h3`
text-sm font-semibold text-text-secondary
uppercase tracking-wide mb-3
`;
const ScoreList = twc.div`
flex flex-col gap-2
`;
const ScoreItem = twc.div`
flex items-center justify-between gap-4
`;
const PlayerInfo = twc.div`
flex items-center gap-2
`;
const PlayerColor = twc.div`
w-4 h-4 rounded-full
`;
const PlayerName = twc.span`
text-text-primary font-medium
`;
const Score = twc.span`
text-text-primary font-bold text-lg
`;
type ScoreDisplayProps = {
players: Player[];
gameScore: GameScore;
};
export const ScoreDisplay = ({ players, gameScore }: ScoreDisplayProps) => {
const hasAnyScore = Object.values(gameScore).some((score) => score > 0);
if (!hasAnyScore) {
return null;
}
return (
<ScoreContainer>
<Title>Match Score</Title>
<ScoreList>
{players.map((player) => (
<ScoreItem key={player.index}>
<PlayerInfo>
<PlayerColor style={{ backgroundColor: player.color }} />
<PlayerName>{player.name || `Player ${player.index + 1}`}</PlayerName>
</PlayerInfo>
<Score>{gameScore[player.index] || 0}</Score>
</ScoreItem>
))}
</ScoreList>
</ScoreContainer>
);
};

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'; import { useEffect } from 'react';
import { twc } from 'react-twc'; import { twc } from 'react-twc';
import { twGridTemplateAreas } from '../../../tailwind.config'; import { twGridTemplateAreas } from '../../../tailwind.config';
import { useGlobalSettings } from '../../Hooks/useGlobalSettings'; import { useGlobalSettings } from '../../Hooks/useGlobalSettings';
@@ -6,7 +6,6 @@ import { usePlayers } from '../../Hooks/usePlayers';
import { Orientation, PreStartMode } from '../../Types/Settings'; import { Orientation, PreStartMode } from '../../Types/Settings';
import { Players } from '../Players/Players'; import { Players } from '../Players/Players';
import { PreStart } from '../PreStartGame/PreStart'; import { PreStart } from '../PreStartGame/PreStart';
import { GameOver } from '../GameOver/GameOver';
const MainWrapper = twc.div`w-[100dvmax] h-[100dvmin] overflow-hidden, setPlayers`; const MainWrapper = twc.div`w-[100dvmax] h-[100dvmin] overflow-hidden, setPlayers`;
@@ -15,10 +14,9 @@ type GridTemplateAreasKeys = keyof typeof twGridTemplateAreas;
export type GridLayout = `grid-areas-${GridTemplateAreasKeys}`; export type GridLayout = `grid-areas-${GridTemplateAreasKeys}`;
export const Play = () => { export const Play = () => {
const { players, setPlayers, resetCurrentGame, setStartingPlayerIndex } = usePlayers(); const { players, setPlayers } = usePlayers();
const { initialGameSettings, playing, settings, preStartCompleted, gameScore, setGameScore } = const { initialGameSettings, playing, settings, preStartCompleted } =
useGlobalSettings(); useGlobalSettings();
const [winner, setWinner] = useState<number | null>(null);
let gridLayout: GridLayout; let gridLayout: GridLayout;
switch (players.length) { switch (players.length) {
@@ -96,57 +94,6 @@ export const Play = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
// Check for game over when only one player remains
useEffect(() => {
if (players.length < 2 || winner !== null || !settings.showMatchScore) {
return;
}
const activePlayers = players.filter((p) => !p.hasLost);
// If only one player is alive, they are the winner
if (activePlayers.length === 1) {
setWinner(activePlayers[0].index);
}
}, [players, winner, settings.showMatchScore]);
const handleStartNextGame = () => {
if (winner === null) return;
// Update score
const newScore = { ...gameScore };
newScore[winner] = (newScore[winner] || 0) + 1;
setGameScore(newScore);
// Set the loser as the starting player for next game
const loserIndex = players.find((p) => p.index !== winner)?.index ?? 0;
setStartingPlayerIndex(loserIndex);
// Reset game
resetCurrentGame();
setWinner(null);
};
const handleStay = () => {
if (winner === null) return;
// Update score
const newScore = { ...gameScore };
newScore[winner] = (newScore[winner] || 0) + 1;
setGameScore(newScore);
// Reset hasLost state for all players
setPlayers(
players.map((p) => ({
...p,
hasLost: false,
}))
);
// Clear winner to allow new game over detection
setWinner(null);
};
return ( return (
<MainWrapper> <MainWrapper>
{players.length > 1 && {players.length > 1 &&
@@ -156,14 +103,6 @@ export const Play = () => {
settings.showStartingPlayer && <PreStart />} settings.showStartingPlayer && <PreStart />}
<Players gridLayout={gridLayout} /> <Players gridLayout={gridLayout} />
{winner !== null && (
<GameOver
winner={players[winner]}
onStartNextGame={handleStartNextGame}
onStay={handleStay}
/>
)}
</MainWrapper> </MainWrapper>
); );
}; };

View File

@@ -18,7 +18,7 @@ import { Orientation } from '../../../Types/Settings';
const LayoutsRadioGroup = twc.div`flex flex-row justify-center items-center gap-4 self-center w-full`; const LayoutsRadioGroup = twc.div`flex flex-row justify-center items-center gap-4 self-center w-full`;
const Label = twc.label`flex flex-row relative max-w-[118px] hover:bg-white/[0.03] rounded-2xl cursor-pointer`; const Label = twc.label`flex flex-row relative max-w-[118px] hover:bg-primary-main hover:bg-opacity-5 rounded-2xl cursor-pointer`;
const Input = twc.input`peer sr-only`; const Input = twc.input`peer sr-only`;

View File

@@ -64,7 +64,6 @@ const Start = () => {
setPlaying, setPlaying,
savedGame, savedGame,
saveCurrentGame, saveCurrentGame,
setGameScore,
} = useGlobalSettings(); } = useGlobalSettings();
const infoDialogRef = useRef<HTMLDialogElement | null>(null); const infoDialogRef = useRef<HTMLDialogElement | null>(null);
@@ -214,9 +213,6 @@ const Start = () => {
setInitialGameSettings(savedGame.initialGameSettings); setInitialGameSettings(savedGame.initialGameSettings);
setPlayers(savedGame.players); setPlayers(savedGame.players);
if (savedGame.gameScore) {
setGameScore(savedGame.gameScore);
}
saveCurrentGame(null); saveCurrentGame(null);
setRandomizingPlayer(false); setRandomizingPlayer(false);
setShowPlay(true); setShowPlay(true);
@@ -415,27 +411,11 @@ const Start = () => {
duration-200 ease-in-out shadow-[1px_2px_4px_0px_rgba(0,0,0,0.3)] hover:bg-secondary-dark font-bold" duration-200 ease-in-out shadow-[1px_2px_4px_0px_rgba(0,0,0,0.3)] hover:bg-secondary-dark font-bold"
onClick={doResumeGame} onClick={doResumeGame}
> >
<div className="flex flex-col items-center"> RESUME&nbsp;
<div> <span className="text-xs">
RESUME&nbsp; ({savedGame.players.length}&nbsp;
<span className="text-xs"> {savedGame.players.length > 1 ? 'players' : 'player'})
({savedGame.players.length}&nbsp; </span>
{savedGame.players.length > 1 ? 'players' : 'player'})
</span>
</div>
{savedGame.gameScore && Object.keys(savedGame.gameScore).length > 0 && (
<div className="text-xs opacity-75">
Score: {Object.entries(savedGame.gameScore)
.map(([playerIndex, score]) => {
const player = savedGame.players.find(
(p) => p.index === Number(playerIndex)
);
return `${player?.name || `P${Number(playerIndex) + 1}`}: ${score}`;
})
.join(' | ')}
</div>
)}
</div>
</button> </button>
)} )}
</StartButtonFooter> </StartButtonFooter>

View File

@@ -12,13 +12,8 @@ type Version = {
export type SavedGame = { export type SavedGame = {
initialGameSettings: InitialGameSettings; initialGameSettings: InitialGameSettings;
players: Player[]; players: Player[];
gameScore?: GameScore;
} | null; } | null;
export type GameScore = {
[playerIndex: number]: number;
};
export type GlobalSettingsContextType = { export type GlobalSettingsContextType = {
fullscreen: { fullscreen: {
isFullscreen: boolean; isFullscreen: boolean;
@@ -50,9 +45,6 @@ export type GlobalSettingsContextType = {
version: Version; version: Version;
savedGame: SavedGame; savedGame: SavedGame;
saveCurrentGame: (currentGame: SavedGame) => void; saveCurrentGame: (currentGame: SavedGame) => void;
gameScore: GameScore;
setGameScore: (score: GameScore) => void;
resetGameScore: () => void;
}; };
export const GlobalSettingsContext = export const GlobalSettingsContext =

View File

@@ -1,30 +1,17 @@
import { initializeApp } from 'firebase/app'; import { initializeApp } from 'firebase/app';
import { Analytics, getAnalytics, logEvent } from 'firebase/analytics'; import { getAnalytics, logEvent } from 'firebase/analytics';
const firebaseConfig = { const firebaseConfig = {
apiKey: 'AIzaSyCZ1AHMb5zmWS4VoRnC-OBxTswUfrJ0mlY', apiKey: 'AIzaSyCZ1AHMb5zmWS4VoRnC-OBxTswUfrJ0mlY',
authDomain: 'life-trinket.firebaseapp.com', authDomain: 'life-trinket.firebaseapp.com',
projectId: 'life-trinket', projectId: 'life-trinket',
storageBucket: 'life-trinket.firebasestorage.app', storageBucket: 'life-trinket.appspot.com',
messagingSenderId: '508011650619', messagingSenderId: '508011650619',
appId: '1:508011650619:web:bdc7d0b6f8707b1f9e861e', appId: '1:508011650619:web:bdc7d0b6f8707b1f9e861e',
measurementId: 'G-BE86QSSG14',
}; };
const app = initializeApp(firebaseConfig); const app = initializeApp(firebaseConfig);
let analytics: Analytics | null = null; const analytics = getAnalytics(app);
const getAnalyticsInstance = () => {
if (!analytics) {
try {
analytics = getAnalytics(app);
} catch (error) {
console.error('Failed to initialize Firebase Analytics:', error);
return null;
}
}
return analytics;
};
export const useAnalytics = () => { export const useAnalytics = () => {
const trackEvent = ( const trackEvent = (
@@ -36,18 +23,12 @@ export const useAnalytics = () => {
return; return;
} }
const analyticsInstance = getAnalyticsInstance();
if (!analyticsInstance) {
console.warn('Analytics not available');
return;
}
const paramsWithVersion = { const paramsWithVersion = {
...eventParams, ...eventParams,
app_version: import.meta.env.VITE_APP_VERSION, app_version: import.meta.env.VITE_APP_VERSION,
}; };
logEvent(analyticsInstance, eventName, paramsWithVersion); logEvent(analytics, eventName, paramsWithVersion);
}; };
return { trackEvent }; return { trackEvent };

View File

@@ -1,7 +1,6 @@
import { ReactNode, useEffect, useMemo, useState } from 'react'; import { ReactNode, useEffect, useMemo, useState } from 'react';
import { useWakeLock } from 'react-screen-wake-lock'; import { useWakeLock } from 'react-screen-wake-lock';
import { import {
GameScore,
GlobalSettingsContext, GlobalSettingsContext,
GlobalSettingsContextType, GlobalSettingsContextType,
SavedGame, SavedGame,
@@ -62,20 +61,14 @@ export const GlobalSettingsProvider = ({
}; };
const savedSettings = localStorage.getItem('settings'); const savedSettings = localStorage.getItem('settings');
const [randomizingPlayer, setRandomizingPlayer] = useState<boolean>(() => { const [randomizingPlayer, setRandomizingPlayer] = useState<boolean>(
if (!savedSettings) return true; savedSettings
const parsed = JSON.parse(savedSettings); ? Boolean(JSON.parse(savedSettings).preStartMode === 'random-king')
return Boolean(parsed.preStartMode === 'random-king'); : true
}); );
const [settings, setSettings] = useState<Settings>(() => { const [settings, setSettings] = useState<Settings>(
if (!savedSettings) return defaultSettings; savedSettings ? JSON.parse(savedSettings) : defaultSettings
const parsed = settingsSchema.safeParse(JSON.parse(savedSettings)); );
if (!parsed.success) {
console.error('invalid settings, using default settings');
return defaultSettings;
}
return parsed.data;
});
const setSettingsAndLocalStorage = (settings: Settings) => { const setSettingsAndLocalStorage = (settings: Settings) => {
setSettings(settings); setSettings(settings);
@@ -85,17 +78,11 @@ export const GlobalSettingsProvider = ({
const savedGameSettings = localStorage.getItem('initialGameSettings'); const savedGameSettings = localStorage.getItem('initialGameSettings');
const [initialGameSettings, setInitialGameSettings] = const [initialGameSettings, setInitialGameSettings] =
useState<InitialGameSettings>(() => { useState<InitialGameSettings>(
if (!savedGameSettings) return defaultInitialGameSettings; savedGameSettings
const parsed = initialGameSettingsSchema.safeParse( ? JSON.parse(savedGameSettings)
JSON.parse(savedGameSettings) : defaultInitialGameSettings
); );
if (!parsed.success) {
console.error('invalid game settings, using default settings');
return defaultInitialGameSettings;
}
return parsed.data;
});
const setInitialGameSettingsAndLocalStorage = ( const setInitialGameSettingsAndLocalStorage = (
initialGameSettings: InitialGameSettings initialGameSettings: InitialGameSettings
@@ -107,18 +94,47 @@ export const GlobalSettingsProvider = ({
); );
}; };
const savedGameScore = localStorage.getItem('gameScore'); // Set settings if they are not valid
const [gameScore, setGameScore] = useState<GameScore>( useEffect(() => {
savedGameScore ? JSON.parse(savedGameScore) : {} // If there are no saved settings, set default settings
); if (!savedSettings) {
const setGameScoreAndLocalStorage = (score: GameScore) => { setSettingsAndLocalStorage(defaultSettings);
setGameScore(score); return;
localStorage.setItem('gameScore', JSON.stringify(score)); }
};
const resetGameScore = () => { const parsedSettings = settingsSchema.safeParse(JSON.parse(savedSettings));
setGameScore({});
localStorage.removeItem('gameScore'); // If saved settings are not valid, remove them
}; if (!parsedSettings.success) {
console.error('invalid settings, resetting to default settings');
setSettingsAndLocalStorage(defaultSettings);
return;
}
localStorage.setItem('settings', JSON.stringify(parsedSettings.data));
}, [settings, savedSettings]);
// Set initial game settings if they are not valid
useEffect(() => {
if (!savedGameSettings) {
setInitialGameSettingsAndLocalStorage(defaultInitialGameSettings);
return;
}
//parse existing game settings with zod schema
const parsedInitialGameSettings =
initialGameSettingsSchema.safeParse(initialGameSettings);
if (!parsedInitialGameSettings.success) {
console.error('invalid game settings, resetting to default settings');
setInitialGameSettingsAndLocalStorage(defaultInitialGameSettings);
return;
}
localStorage.setItem(
'initialGameSettings',
JSON.stringify(parsedInitialGameSettings.data)
);
}, [initialGameSettings, savedGameSettings]);
const [isFullscreen, setIsFullscreen] = useState(false); const [isFullscreen, setIsFullscreen] = useState(false);
@@ -155,13 +171,11 @@ export const GlobalSettingsProvider = ({
localStorage.removeItem('playing'); localStorage.removeItem('playing');
localStorage.removeItem('showPlay'); localStorage.removeItem('showPlay');
localStorage.removeItem('preStartComplete'); localStorage.removeItem('preStartComplete');
localStorage.removeItem('gameScore');
setPlaying(false); setPlaying(false);
setShowPlay(false); setShowPlay(false);
setPreStartCompleted(false); setPreStartCompleted(false);
setSettings({ ...settings, useMonarch: false }); setSettings({ ...settings, useMonarch: false });
setGameScore({});
}; };
const goToStart = async () => { const goToStart = async () => {
@@ -210,20 +224,17 @@ export const GlobalSettingsProvider = ({
async function checkForNewVersion(source: 'settings' | 'start_menu') { async function checkForNewVersion(source: 'settings' | 'start_menu') {
try { try {
const token = import.meta.env.VITE_REPO_READ_ACCESS_TOKEN;
const headers: HeadersInit = {
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
};
// Only add authorization if token is available
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const result = await fetch( const result = await fetch(
'https://api.github.com/repos/Vikeo/LifeTrinket/releases/latest', 'https://api.github.com/repos/Vikeo/LifeTrinket/releases/latest',
{ headers } {
headers: {
Authorization: `Bearer ${
import.meta.env.VITE_REPO_READ_ACCESS_TOKEN
}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
},
}
); );
const data = await result.json(); const data = await result.json();
@@ -272,7 +283,7 @@ export const GlobalSettingsProvider = ({
playing, playing,
setPlaying: setPlayingAndLocalStorage, setPlaying: setPlayingAndLocalStorage,
initialGameSettings, initialGameSettings,
setInitialGameSettings: setInitialGameSettingsAndLocalStorage, setInitialGameSettings,
settings, settings,
setSettings: setSettingsAndLocalStorage, setSettings: setSettingsAndLocalStorage,
randomizingPlayer, randomizingPlayer,
@@ -288,9 +299,6 @@ export const GlobalSettingsProvider = ({
isLatest: isLatestVersion, isLatest: isLatestVersion,
checkForNewVersion, checkForNewVersion,
}, },
gameScore,
setGameScore: setGameScoreAndLocalStorage,
resetGameScore,
}; };
}, [ }, [
isFullscreen, isFullscreen,
@@ -304,13 +312,11 @@ export const GlobalSettingsProvider = ({
initialGameSettings, initialGameSettings,
settings, settings,
randomizingPlayer, randomizingPlayer,
setRandomizingPlayer,
preStartCompleted, preStartCompleted,
savedGame, savedGame,
remoteVersion, remoteVersion,
isLatestVersion, isLatestVersion,
analytics, analytics,
gameScore,
]); ]);
return ( return (

View File

@@ -1,5 +1,6 @@
import { ReactNode, useCallback, useEffect, useMemo, useState } from 'react'; import { ReactNode, useEffect } from 'react';
import { Player } from '../Types/Player'; import { Player } from '../Types/Player';
import { useMemo, useState } from 'react';
import { PlayersContextType, PlayersContext } from '../Contexts/PlayersContext'; import { PlayersContextType, PlayersContext } from '../Contexts/PlayersContext';
import { InitialGameSettings } from '../Types/Settings'; import { InitialGameSettings } from '../Types/Settings';
@@ -12,10 +13,10 @@ export const PlayersProvider = ({ children }: { children: ReactNode }) => {
savedStartingPlayerIndex ? parseInt(savedStartingPlayerIndex) : -1 savedStartingPlayerIndex ? parseInt(savedStartingPlayerIndex) : -1
); );
const setStartingPlayerIndexAndLocalStorage = useCallback((index: number) => { const setStartingPlayerIndexAndLocalStorage = (index: number) => {
setStartingPlayerIndex(index); setStartingPlayerIndex(index);
localStorage.setItem('startingPlayerIndex', String(index)); localStorage.setItem('startingPlayerIndex', String(index));
}, []); };
const [players, setPlayers] = useState<Player[]>( const [players, setPlayers] = useState<Player[]>(
savedPlayers ? JSON.parse(savedPlayers) : [] savedPlayers ? JSON.parse(savedPlayers) : []
@@ -60,11 +61,7 @@ export const PlayersProvider = ({ children }: { children: ReactNode }) => {
return; return;
} }
// Use the saved starting player index if available, otherwise random const newStartingPlayerIndex = Math.floor(Math.random() * players.length);
const newStartingPlayerIndex =
startingPlayerIndex >= 0
? startingPlayerIndex
: Math.floor(Math.random() * players.length);
players.forEach((player: Player) => { players.forEach((player: Player) => {
player.commanderDamage.map((damage) => { player.commanderDamage.map((damage) => {
@@ -95,7 +92,7 @@ export const PlayersProvider = ({ children }: { children: ReactNode }) => {
startingPlayerIndex, startingPlayerIndex,
setStartingPlayerIndex: setStartingPlayerIndexAndLocalStorage, setStartingPlayerIndex: setStartingPlayerIndexAndLocalStorage,
}; };
}, [players, startingPlayerIndex, setStartingPlayerIndexAndLocalStorage]); }, [players, startingPlayerIndex]);
return ( return (
<PlayersContext.Provider value={ctxValue}> <PlayersContext.Provider value={ctxValue}>

View File

@@ -27,7 +27,6 @@ export type Settings = {
preStartMode: PreStartMode; preStartMode: PreStartMode;
showAnimations: boolean; showAnimations: boolean;
useMonarch: boolean; useMonarch: boolean;
showMatchScore: boolean;
}; };
export type InitialGameSettings = { export type InitialGameSettings = {
@@ -62,7 +61,6 @@ export const settingsSchema = z.object({
preStartMode: z.nativeEnum(PreStartMode), preStartMode: z.nativeEnum(PreStartMode),
showAnimations: z.boolean(), showAnimations: z.boolean(),
useMonarch: z.boolean().default(false), useMonarch: z.boolean().default(false),
showMatchScore: z.boolean().default(true),
}); });
export const defaultSettings: Settings = { export const defaultSettings: Settings = {
@@ -73,5 +71,4 @@ export const defaultSettings: Settings = {
preStartMode: PreStartMode.None, preStartMode: PreStartMode.None,
showAnimations: true, showAnimations: true,
useMonarch: false, useMonarch: false,
showMatchScore: true,
}; };

View File

@@ -0,0 +1,113 @@
import pako from 'pako';
export interface GameStateExport {
settings: string | null;
initialGameSettings: string | null;
players: string | null;
playing: string | null;
showPlay: string | null;
preStartComplete: string | null;
savedGame: string | null;
startingPlayerIndex: string | null;
}
/**
* Export all game state from localStorage, compress it, and encode for URL
*/
export function exportGameState(): string {
try {
// Only export essential data with very short keys
const compactState: Record<string, string> = {};
const s = localStorage.getItem('settings');
const i = localStorage.getItem('initialGameSettings');
const p = localStorage.getItem('players');
const si = localStorage.getItem('startingPlayerIndex');
// Only include non-null values
if (s) compactState.s = s;
if (i) compactState.i = i;
if (p) compactState.p = p;
if (si) compactState.si = si;
// Convert to JSON string
const jsonString = JSON.stringify(compactState);
// Compress using pako (gzip) with maximum compression
const compressed = pako.deflate(jsonString, { level: 9 });
// Convert to base64 for URL safety
const base64 = btoa(String.fromCharCode(...compressed));
// Make URL-safe by replacing characters
const urlSafe = base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
return urlSafe;
} catch (error) {
console.error('Error exporting game state:', error);
throw new Error('Failed to export game state');
}
}
/**
* Import game state from compressed URL parameter and load into localStorage
*/
export function importGameState(encodedData: string): boolean {
try {
// Restore base64 characters
let base64 = encodedData.replace(/-/g, '+').replace(/_/g, '/');
// Add padding if needed
while (base64.length % 4) {
base64 += '=';
}
// Decode from base64
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Decompress
const decompressed = pako.inflate(bytes, { to: 'string' });
// Parse JSON
const compactState: Record<string, string> = JSON.parse(decompressed);
// Validate that we have some data
if (!compactState || typeof compactState !== 'object') {
throw new Error('Invalid game state format');
}
// Map short keys back to full localStorage keys and load
if (compactState.s) localStorage.setItem('settings', compactState.s);
if (compactState.i)
localStorage.setItem('initialGameSettings', compactState.i);
if (compactState.p) localStorage.setItem('players', compactState.p);
if (compactState.si)
localStorage.setItem('startingPlayerIndex', compactState.si);
// Always set playing and showPlay to false after loading
// This ensures the user starts at the main menu and can review the state
localStorage.setItem('playing', 'false');
localStorage.setItem('showPlay', 'false');
return true;
} catch (error) {
console.error('Error importing game state:', error);
return false;
}
}
/**
* Generate shareable URL with game state
*/
export function generateShareableUrl(): string {
const encodedState = exportGameState();
const currentUrl = window.location.origin + window.location.pathname;
return `${currentUrl}?gameStateToLoad=${encodedState}`;
}

View File

@@ -1,32 +1,6 @@
@import 'tailwindcss'; @tailwind base;
@tailwind components;
@theme { @tailwind utilities;
--color-primary-main: #78A083;
--color-primary-dark: #608069;
--color-secondary-main: #5D7965;
--color-secondary-dark: #4a6151;
--color-background-default: #2E3041;
--color-background-spotlight: #777BA7;
--color-background-backdrop: rgba(0, 0, 0, 0.3);
--color-background-settings: rgba(0, 0, 0, 0.8);
--color-icons-dark: #000000;
--color-icons-light: #F9FFE3;
--color-icons-gold: #FFD700;
--color-text-primary: #F9FFE3;
--color-text-secondary: #c7ccb6;
--color-common-white: #F9FFE3;
--color-common-black: #000000;
--color-lifeCounter-text: rgba(0, 0, 0, 0.4);
--color-lifeCounter-lostWrapper: #000000;
--color-interface-loseButton-background: #43434380;
--color-interface-recentDifference-background: rgba(255, 255, 255, 0.6);
--color-interface-recentDifference-text: #333333;
--font-size-xxs: 0.625rem;
--line-height-xxs: 1rem;
--breakpoint-modalSm: 548px;
}
html { html {
overflow: hidden; overflow: hidden;
@@ -40,7 +14,7 @@ html,
body { body {
height: 100%; height: 100%;
position: relative; position: relative;
background-color: var(--color-background-default); background-color: theme('colors.background.default');
margin: 0; margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
@@ -57,7 +31,7 @@ code {
monospace; monospace;
} }
/* hide scrollbar globally */ // hide scrollbar globally
::-webkit-scrollbar { ::-webkit-scrollbar {
display: none; display: none;
} }
@@ -69,18 +43,18 @@ code {
/* Track */ /* Track */
::-webkit-scrollbar-track { ::-webkit-scrollbar-track {
background-color: var(--color-background-default); background-color: theme('colors.background.default');
} }
/* Handle */ /* Handle */
::-webkit-scrollbar-thumb { ::-webkit-scrollbar-thumb {
background: var(--color-primary-dark); background: theme('colors.primary.dark');
border-radius: 32px; border-radius: 32px;
} }
/* Handle on hover */ /* Handle on hover */
::-webkit-scrollbar-thumb:hover { ::-webkit-scrollbar-thumb:hover {
background: var(--color-primary-main); background: theme('colors.primary.main');
} }
* { * {
@@ -105,67 +79,6 @@ code {
scrollbar-width: auto; scrollbar-width: auto;
-ms-overflow-style: auto; -ms-overflow-style: auto;
} }
/* Grid template areas */
.grid-areas-onePlayerLandscape {
grid-template-areas: 'player0 player0';
}
.grid-areas-onePlayerPortrait {
grid-template-areas: 'player0' 'player0';
}
.grid-areas-twoPlayersOppositeLandscape {
grid-template-areas: 'player0' 'player1';
}
.grid-areas-twoPlayersOppositePortrait {
grid-template-areas: 'player0 player1' 'player0 player1';
}
.grid-areas-twoPlayersSameSideLandscape {
grid-template-areas: 'player0 player1';
}
.grid-areas-threePlayers {
grid-template-areas: 'player0 player0' 'player1 player2';
}
.grid-areas-threePlayersSide {
grid-template-areas: 'player0 player0 player0 player2' 'player1 player1 player1 player2';
}
.grid-areas-fourPlayerPortrait {
grid-template-areas: 'player0 player1 player1 player1 player1 player3' 'player0 player2 player2 player2 player2 player3';
}
.grid-areas-fourPlayer {
grid-template-areas: 'player0 player1' 'player2 player3';
}
.grid-areas-fivePlayers {
grid-template-areas: 'player0 player0 player0 player1 player1 player1' 'player2 player2 player3 player3 player4 player4';
}
.grid-areas-fivePlayersSide {
grid-template-areas: 'player0 player0 player0 player0 player0 player1 player1 player1 player1 player1 player2' 'player3 player3 player3 player3 player3 player4 player4 player4 player4 player4 player2';
}
.grid-areas-sixPlayers {
grid-template-areas: 'player0 player1 player2' 'player3 player4 player5';
}
.grid-areas-sixPlayersSide {
grid-template-areas: 'player0 player1 player1 player1 player1 player1 player1 player2 player2 player2 player2 player2 player2 player3' 'player0 player4 player4 player4 player4 player4 player4 player5 player5 player5 player5 player5 player5 player3';
}
/* Grid area assignments */
.grid-in-player0 {
grid-area: player0;
}
.grid-in-player1 {
grid-area: player1;
}
.grid-in-player2 {
grid-area: player2;
}
.grid-in-player3 {
grid-area: player3;
}
.grid-in-player4 {
grid-area: player4;
}
.grid-in-player5 {
grid-area: player5;
}
} }
@keyframes background-orb { @keyframes background-orb {
@@ -207,7 +120,7 @@ code {
} }
.spotlight1 { .spotlight1 {
background: var(--color-background-default); background: theme('colors.background.default');
position: fixed; position: fixed;
height: 10vmax; height: 10vmax;
@@ -229,7 +142,7 @@ code {
} }
.spotlight2 { .spotlight2 {
background: var(--color-background-default); background: theme('colors.background.default');
position: fixed; position: fixed;
height: 30vmax; height: 30vmax;
@@ -253,7 +166,7 @@ input[type='range'] {
transition: background 0ms ease-in; transition: background 0ms ease-in;
margin: 10px 0; margin: 10px 0;
width: 100%; width: 100%;
background: var(--color-secondary-main); background: theme('colors.secondary.main');
} }
input[type='range']:focus { input[type='range']:focus {
outline: none; outline: none;
@@ -274,7 +187,7 @@ input[type='range']::-webkit-slider-thumb {
height: 20px; height: 20px;
width: 20px; width: 20px;
border-radius: 100px; border-radius: 100px;
background: var(--color-primary-main); background: theme('colors.primary.main');
cursor: pointer; cursor: pointer;
margin-top: -3px; margin-top: -3px;
} }
@@ -294,7 +207,7 @@ input[type='range']::-moz-range-thumb {
height: 20px; height: 20px;
width: 20px; width: 20px;
border-radius: 100px; border-radius: 100px;
background: var(--color-primary-main); background: theme('colors.primary.main');
cursor: pointer; cursor: pointer;
} }
@@ -312,7 +225,7 @@ input[type='range']::-ms-thumb {
height: 20px; height: 20px;
width: 20px; width: 20px;
border-radius: 100px; border-radius: 100px;
background: var(--color-primary-main); background: theme('colors.primary.main');
cursor: pointer; cursor: pointer;
margin-top: -3px; margin-top: -3px;
} }

View File

@@ -1,3 +1,5 @@
/* eslint-disable no-undef */
/* eslint-disable-next-line no-undef */
module.exports = { module.exports = {
template: require('./template'), template: require('./template'),
titleProp: true, titleProp: true,

View File

@@ -1,3 +1,5 @@
//@ts-expect-error - tailwindcss-grid-areas does not have typescript support
import tailwindcssGridAreas from '@savvywombat/tailwindcss-grid-areas';
import type { Config } from 'tailwindcss'; import type { Config } from 'tailwindcss';
export const baseColors = { export const baseColors = {
@@ -105,6 +107,6 @@ export default {
}, },
}, },
}, },
plugins: [], plugins: [tailwindcssGridAreas],
} satisfies Config; } satisfies Config;
// #98FF98 // #98FF98

View File

@@ -34,5 +34,7 @@ const propTypesTemplate = (
export default ${title}`; export default ${title}`;
}; };
// eslint-disable-next-line no-undef
module.exports = propTypesTemplate; module.exports = propTypesTemplate;